]> Git Repo - binutils.git/blob - gdb/ada-lang.c
Handle type qualifier for enumeration name
[binutils.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3    Copyright (C) 1992-2021 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20
21 #include "defs.h"
22 #include <ctype.h>
23 #include "gdb_regex.h"
24 #include "frame.h"
25 #include "symtab.h"
26 #include "gdbtypes.h"
27 #include "gdbcmd.h"
28 #include "expression.h"
29 #include "parser-defs.h"
30 #include "language.h"
31 #include "varobj.h"
32 #include "inferior.h"
33 #include "symfile.h"
34 #include "objfiles.h"
35 #include "breakpoint.h"
36 #include "gdbcore.h"
37 #include "hashtab.h"
38 #include "gdb_obstack.h"
39 #include "ada-lang.h"
40 #include "completer.h"
41 #include "ui-out.h"
42 #include "block.h"
43 #include "infcall.h"
44 #include "annotate.h"
45 #include "valprint.h"
46 #include "source.h"
47 #include "observable.h"
48 #include "stack.h"
49 #include "typeprint.h"
50 #include "namespace.h"
51 #include "cli/cli-style.h"
52 #include "cli/cli-decode.h"
53
54 #include "value.h"
55 #include "mi/mi-common.h"
56 #include "arch-utils.h"
57 #include "cli/cli-utils.h"
58 #include "gdbsupport/function-view.h"
59 #include "gdbsupport/byte-vector.h"
60 #include <algorithm>
61 #include "ada-exp.h"
62
63 /* Define whether or not the C operator '/' truncates towards zero for
64    differently signed operands (truncation direction is undefined in C).
65    Copied from valarith.c.  */
66
67 #ifndef TRUNCATION_TOWARDS_ZERO
68 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
69 #endif
70
71 static struct type *desc_base_type (struct type *);
72
73 static struct type *desc_bounds_type (struct type *);
74
75 static struct value *desc_bounds (struct value *);
76
77 static int fat_pntr_bounds_bitpos (struct type *);
78
79 static int fat_pntr_bounds_bitsize (struct type *);
80
81 static struct type *desc_data_target_type (struct type *);
82
83 static struct value *desc_data (struct value *);
84
85 static int fat_pntr_data_bitpos (struct type *);
86
87 static int fat_pntr_data_bitsize (struct type *);
88
89 static struct value *desc_one_bound (struct value *, int, int);
90
91 static int desc_bound_bitpos (struct type *, int, int);
92
93 static int desc_bound_bitsize (struct type *, int, int);
94
95 static struct type *desc_index_type (struct type *, int);
96
97 static int desc_arity (struct type *);
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 (std::vector<struct block_symbol> &,
104                                    const struct block *,
105                                    const lookup_name_info &lookup_name,
106                                    domain_enum, struct objfile *);
107
108 static void ada_add_all_symbols (std::vector<struct block_symbol> &,
109                                  const struct block *,
110                                  const lookup_name_info &lookup_name,
111                                  domain_enum, int, int *);
112
113 static int is_nonfunction (const std::vector<struct block_symbol> &);
114
115 static void add_defn_to_vec (std::vector<struct block_symbol> &,
116                              struct symbol *,
117                              const struct block *);
118
119 static int possible_user_operator_p (enum exp_opcode, struct value **);
120
121 static const char *ada_decoded_op_name (enum exp_opcode);
122
123 static int numeric_type_p (struct type *);
124
125 static int integer_type_p (struct type *);
126
127 static int scalar_type_p (struct type *);
128
129 static int discrete_type_p (struct type *);
130
131 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
132                                                 int, int);
133
134 static struct type *ada_find_parallel_type_with_name (struct type *,
135                                                       const char *);
136
137 static int is_dynamic_field (struct type *, int);
138
139 static struct type *to_fixed_variant_branch_type (struct type *,
140                                                   const gdb_byte *,
141                                                   CORE_ADDR, struct value *);
142
143 static struct type *to_fixed_array_type (struct type *, struct value *, int);
144
145 static struct type *to_fixed_range_type (struct type *, struct value *);
146
147 static struct type *to_static_fixed_type (struct type *);
148 static struct type *static_unwrap_type (struct type *type);
149
150 static struct value *unwrap_value (struct value *);
151
152 static struct type *constrained_packed_array_type (struct type *, long *);
153
154 static struct type *decode_constrained_packed_array_type (struct type *);
155
156 static long decode_packed_array_bitsize (struct type *);
157
158 static struct value *decode_constrained_packed_array (struct value *);
159
160 static int ada_is_unconstrained_packed_array_type (struct type *);
161
162 static struct value *value_subscript_packed (struct value *, int,
163                                              struct value **);
164
165 static struct value *coerce_unspec_val_to_type (struct value *,
166                                                 struct type *);
167
168 static int lesseq_defined_than (struct symbol *, struct symbol *);
169
170 static int equiv_types (struct type *, struct type *);
171
172 static int is_name_suffix (const char *);
173
174 static int advance_wild_match (const char **, const char *, char);
175
176 static bool wild_match (const char *name, const char *patn);
177
178 static struct value *ada_coerce_ref (struct value *);
179
180 static LONGEST pos_atr (struct value *);
181
182 static struct value *val_atr (struct type *, LONGEST);
183
184 static struct symbol *standard_lookup (const char *, const struct block *,
185                                        domain_enum);
186
187 static struct value *ada_search_struct_field (const char *, struct value *, int,
188                                               struct type *);
189
190 static int find_struct_field (const char *, struct type *, int,
191                               struct type **, int *, int *, int *, int *);
192
193 static int ada_resolve_function (std::vector<struct block_symbol> &,
194                                  struct value **, int, const char *,
195                                  struct type *, bool);
196
197 static int ada_is_direct_array_type (struct type *);
198
199 static struct value *ada_index_struct_field (int, struct value *, int,
200                                              struct type *);
201
202 static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
203
204
205 static struct type *ada_find_any_type (const char *name);
206
207 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
208   (const lookup_name_info &lookup_name);
209
210 \f
211
212 /* The result of a symbol lookup to be stored in our symbol cache.  */
213
214 struct cache_entry
215 {
216   /* The name used to perform the lookup.  */
217   const char *name;
218   /* The namespace used during the lookup.  */
219   domain_enum domain;
220   /* The symbol returned by the lookup, or NULL if no matching symbol
221      was found.  */
222   struct symbol *sym;
223   /* The block where the symbol was found, or NULL if no matching
224      symbol was found.  */
225   const struct block *block;
226   /* A pointer to the next entry with the same hash.  */
227   struct cache_entry *next;
228 };
229
230 /* The Ada symbol cache, used to store the result of Ada-mode symbol
231    lookups in the course of executing the user's commands.
232
233    The cache is implemented using a simple, fixed-sized hash.
234    The size is fixed on the grounds that there are not likely to be
235    all that many symbols looked up during any given session, regardless
236    of the size of the symbol table.  If we decide to go to a resizable
237    table, let's just use the stuff from libiberty instead.  */
238
239 #define HASH_SIZE 1009
240
241 struct ada_symbol_cache
242 {
243   /* An obstack used to store the entries in our cache.  */
244   struct auto_obstack cache_space;
245
246   /* The root of the hash table used to implement our symbol cache.  */
247   struct cache_entry *root[HASH_SIZE] {};
248 };
249
250 /* Maximum-sized dynamic type.  */
251 static unsigned int varsize_limit;
252
253 static const char ada_completer_word_break_characters[] =
254 #ifdef VMS
255   " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
256 #else
257   " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
258 #endif
259
260 /* The name of the symbol to use to get the name of the main subprogram.  */
261 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
262   = "__gnat_ada_main_program_name";
263
264 /* Limit on the number of warnings to raise per expression evaluation.  */
265 static int warning_limit = 2;
266
267 /* Number of warning messages issued; reset to 0 by cleanups after
268    expression evaluation.  */
269 static int warnings_issued = 0;
270
271 static const char * const known_runtime_file_name_patterns[] = {
272   ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
273 };
274
275 static const char * const known_auxiliary_function_name_patterns[] = {
276   ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
277 };
278
279 /* Maintenance-related settings for this module.  */
280
281 static struct cmd_list_element *maint_set_ada_cmdlist;
282 static struct cmd_list_element *maint_show_ada_cmdlist;
283
284 /* The "maintenance ada set/show ignore-descriptive-type" value.  */
285
286 static bool ada_ignore_descriptive_types_p = false;
287
288                         /* Inferior-specific data.  */
289
290 /* Per-inferior data for this module.  */
291
292 struct ada_inferior_data
293 {
294   /* The ada__tags__type_specific_data type, which is used when decoding
295      tagged types.  With older versions of GNAT, this type was directly
296      accessible through a component ("tsd") in the object tag.  But this
297      is no longer the case, so we cache it for each inferior.  */
298   struct type *tsd_type = nullptr;
299
300   /* The exception_support_info data.  This data is used to determine
301      how to implement support for Ada exception catchpoints in a given
302      inferior.  */
303   const struct exception_support_info *exception_info = nullptr;
304 };
305
306 /* Our key to this module's inferior data.  */
307 static const struct inferior_key<ada_inferior_data> ada_inferior_data;
308
309 /* Return our inferior data for the given inferior (INF).
310
311    This function always returns a valid pointer to an allocated
312    ada_inferior_data structure.  If INF's inferior data has not
313    been previously set, this functions creates a new one with all
314    fields set to zero, sets INF's inferior to it, and then returns
315    a pointer to that newly allocated ada_inferior_data.  */
316
317 static struct ada_inferior_data *
318 get_ada_inferior_data (struct inferior *inf)
319 {
320   struct ada_inferior_data *data;
321
322   data = ada_inferior_data.get (inf);
323   if (data == NULL)
324     data = ada_inferior_data.emplace (inf);
325
326   return data;
327 }
328
329 /* Perform all necessary cleanups regarding our module's inferior data
330    that is required after the inferior INF just exited.  */
331
332 static void
333 ada_inferior_exit (struct inferior *inf)
334 {
335   ada_inferior_data.clear (inf);
336 }
337
338
339                         /* program-space-specific data.  */
340
341 /* This module's per-program-space data.  */
342 struct ada_pspace_data
343 {
344   /* The Ada symbol cache.  */
345   std::unique_ptr<ada_symbol_cache> sym_cache;
346 };
347
348 /* Key to our per-program-space data.  */
349 static const struct program_space_key<ada_pspace_data> ada_pspace_data_handle;
350
351 /* Return this module's data for the given program space (PSPACE).
352    If not is found, add a zero'ed one now.
353
354    This function always returns a valid object.  */
355
356 static struct ada_pspace_data *
357 get_ada_pspace_data (struct program_space *pspace)
358 {
359   struct ada_pspace_data *data;
360
361   data = ada_pspace_data_handle.get (pspace);
362   if (data == NULL)
363     data = ada_pspace_data_handle.emplace (pspace);
364
365   return data;
366 }
367
368                         /* Utilities */
369
370 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
371    all typedef layers have been peeled.  Otherwise, return TYPE.
372
373    Normally, we really expect a typedef type to only have 1 typedef layer.
374    In other words, we really expect the target type of a typedef type to be
375    a non-typedef type.  This is particularly true for Ada units, because
376    the language does not have a typedef vs not-typedef distinction.
377    In that respect, the Ada compiler has been trying to eliminate as many
378    typedef definitions in the debugging information, since they generally
379    do not bring any extra information (we still use typedef under certain
380    circumstances related mostly to the GNAT encoding).
381
382    Unfortunately, we have seen situations where the debugging information
383    generated by the compiler leads to such multiple typedef layers.  For
384    instance, consider the following example with stabs:
385
386      .stabs  "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
387      .stabs  "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
388
389    This is an error in the debugging information which causes type
390    pck__float_array___XUP to be defined twice, and the second time,
391    it is defined as a typedef of a typedef.
392
393    This is on the fringe of legality as far as debugging information is
394    concerned, and certainly unexpected.  But it is easy to handle these
395    situations correctly, so we can afford to be lenient in this case.  */
396
397 static struct type *
398 ada_typedef_target_type (struct type *type)
399 {
400   while (type->code () == TYPE_CODE_TYPEDEF)
401     type = TYPE_TARGET_TYPE (type);
402   return type;
403 }
404
405 /* Given DECODED_NAME a string holding a symbol name in its
406    decoded form (ie using the Ada dotted notation), returns
407    its unqualified name.  */
408
409 static const char *
410 ada_unqualified_name (const char *decoded_name)
411 {
412   const char *result;
413   
414   /* If the decoded name starts with '<', it means that the encoded
415      name does not follow standard naming conventions, and thus that
416      it is not your typical Ada symbol name.  Trying to unqualify it
417      is therefore pointless and possibly erroneous.  */
418   if (decoded_name[0] == '<')
419     return decoded_name;
420
421   result = strrchr (decoded_name, '.');
422   if (result != NULL)
423     result++;                   /* Skip the dot...  */
424   else
425     result = decoded_name;
426
427   return result;
428 }
429
430 /* Return a string starting with '<', followed by STR, and '>'.  */
431
432 static std::string
433 add_angle_brackets (const char *str)
434 {
435   return string_printf ("<%s>", str);
436 }
437
438 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
439    suffix of FIELD_NAME beginning "___".  */
440
441 static int
442 field_name_match (const char *field_name, const char *target)
443 {
444   int len = strlen (target);
445
446   return
447     (strncmp (field_name, target, len) == 0
448      && (field_name[len] == '\0'
449          || (startswith (field_name + len, "___")
450              && strcmp (field_name + strlen (field_name) - 6,
451                         "___XVN") != 0)));
452 }
453
454
455 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
456    a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
457    and return its index.  This function also handles fields whose name
458    have ___ suffixes because the compiler sometimes alters their name
459    by adding such a suffix to represent fields with certain constraints.
460    If the field could not be found, return a negative number if
461    MAYBE_MISSING is set.  Otherwise raise an error.  */
462
463 int
464 ada_get_field_index (const struct type *type, const char *field_name,
465                      int maybe_missing)
466 {
467   int fieldno;
468   struct type *struct_type = check_typedef ((struct type *) type);
469
470   for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
471     if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
472       return fieldno;
473
474   if (!maybe_missing)
475     error (_("Unable to find field %s in struct %s.  Aborting"),
476            field_name, struct_type->name ());
477
478   return -1;
479 }
480
481 /* The length of the prefix of NAME prior to any "___" suffix.  */
482
483 int
484 ada_name_prefix_len (const char *name)
485 {
486   if (name == NULL)
487     return 0;
488   else
489     {
490       const char *p = strstr (name, "___");
491
492       if (p == NULL)
493         return strlen (name);
494       else
495         return p - name;
496     }
497 }
498
499 /* Return non-zero if SUFFIX is a suffix of STR.
500    Return zero if STR is null.  */
501
502 static int
503 is_suffix (const char *str, const char *suffix)
504 {
505   int len1, len2;
506
507   if (str == NULL)
508     return 0;
509   len1 = strlen (str);
510   len2 = strlen (suffix);
511   return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
512 }
513
514 /* The contents of value VAL, treated as a value of type TYPE.  The
515    result is an lval in memory if VAL is.  */
516
517 static struct value *
518 coerce_unspec_val_to_type (struct value *val, struct type *type)
519 {
520   type = ada_check_typedef (type);
521   if (value_type (val) == type)
522     return val;
523   else
524     {
525       struct value *result;
526
527       /* Make sure that the object size is not unreasonable before
528          trying to allocate some memory for it.  */
529       ada_ensure_varsize_limit (type);
530
531       if (value_optimized_out (val))
532         result = allocate_optimized_out_value (type);
533       else if (value_lazy (val)
534                /* Be careful not to make a lazy not_lval value.  */
535                || (VALUE_LVAL (val) != not_lval
536                    && TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val))))
537         result = allocate_value_lazy (type);
538       else
539         {
540           result = allocate_value (type);
541           value_contents_copy (result, 0, val, 0, TYPE_LENGTH (type));
542         }
543       set_value_component_location (result, val);
544       set_value_bitsize (result, value_bitsize (val));
545       set_value_bitpos (result, value_bitpos (val));
546       if (VALUE_LVAL (result) == lval_memory)
547         set_value_address (result, value_address (val));
548       return result;
549     }
550 }
551
552 static const gdb_byte *
553 cond_offset_host (const gdb_byte *valaddr, long offset)
554 {
555   if (valaddr == NULL)
556     return NULL;
557   else
558     return valaddr + offset;
559 }
560
561 static CORE_ADDR
562 cond_offset_target (CORE_ADDR address, long offset)
563 {
564   if (address == 0)
565     return 0;
566   else
567     return address + offset;
568 }
569
570 /* Issue a warning (as for the definition of warning in utils.c, but
571    with exactly one argument rather than ...), unless the limit on the
572    number of warnings has passed during the evaluation of the current
573    expression.  */
574
575 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
576    provided by "complaint".  */
577 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
578
579 static void
580 lim_warning (const char *format, ...)
581 {
582   va_list args;
583
584   va_start (args, format);
585   warnings_issued += 1;
586   if (warnings_issued <= warning_limit)
587     vwarning (format, args);
588
589   va_end (args);
590 }
591
592 /* Issue an error if the size of an object of type T is unreasonable,
593    i.e. if it would be a bad idea to allocate a value of this type in
594    GDB.  */
595
596 void
597 ada_ensure_varsize_limit (const struct type *type)
598 {
599   if (TYPE_LENGTH (type) > varsize_limit)
600     error (_("object size is larger than varsize-limit"));
601 }
602
603 /* Maximum value of a SIZE-byte signed integer type.  */
604 static LONGEST
605 max_of_size (int size)
606 {
607   LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
608
609   return top_bit | (top_bit - 1);
610 }
611
612 /* Minimum value of a SIZE-byte signed integer type.  */
613 static LONGEST
614 min_of_size (int size)
615 {
616   return -max_of_size (size) - 1;
617 }
618
619 /* Maximum value of a SIZE-byte unsigned integer type.  */
620 static ULONGEST
621 umax_of_size (int size)
622 {
623   ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
624
625   return top_bit | (top_bit - 1);
626 }
627
628 /* Maximum value of integral type T, as a signed quantity.  */
629 static LONGEST
630 max_of_type (struct type *t)
631 {
632   if (t->is_unsigned ())
633     return (LONGEST) umax_of_size (TYPE_LENGTH (t));
634   else
635     return max_of_size (TYPE_LENGTH (t));
636 }
637
638 /* Minimum value of integral type T, as a signed quantity.  */
639 static LONGEST
640 min_of_type (struct type *t)
641 {
642   if (t->is_unsigned ())
643     return 0;
644   else
645     return min_of_size (TYPE_LENGTH (t));
646 }
647
648 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
649 LONGEST
650 ada_discrete_type_high_bound (struct type *type)
651 {
652   type = resolve_dynamic_type (type, {}, 0);
653   switch (type->code ())
654     {
655     case TYPE_CODE_RANGE:
656       {
657         const dynamic_prop &high = type->bounds ()->high;
658
659         if (high.kind () == PROP_CONST)
660           return high.const_val ();
661         else
662           {
663             gdb_assert (high.kind () == PROP_UNDEFINED);
664
665             /* This happens when trying to evaluate a type's dynamic bound
666                without a live target.  There is nothing relevant for us to
667                return here, so return 0.  */
668             return 0;
669           }
670       }
671     case TYPE_CODE_ENUM:
672       return TYPE_FIELD_ENUMVAL (type, type->num_fields () - 1);
673     case TYPE_CODE_BOOL:
674       return 1;
675     case TYPE_CODE_CHAR:
676     case TYPE_CODE_INT:
677       return max_of_type (type);
678     default:
679       error (_("Unexpected type in ada_discrete_type_high_bound."));
680     }
681 }
682
683 /* The smallest value in the domain of TYPE, a discrete type, as an integer.  */
684 LONGEST
685 ada_discrete_type_low_bound (struct type *type)
686 {
687   type = resolve_dynamic_type (type, {}, 0);
688   switch (type->code ())
689     {
690     case TYPE_CODE_RANGE:
691       {
692         const dynamic_prop &low = type->bounds ()->low;
693
694         if (low.kind () == PROP_CONST)
695           return low.const_val ();
696         else
697           {
698             gdb_assert (low.kind () == PROP_UNDEFINED);
699
700             /* This happens when trying to evaluate a type's dynamic bound
701                without a live target.  There is nothing relevant for us to
702                return here, so return 0.  */
703             return 0;
704           }
705       }
706     case TYPE_CODE_ENUM:
707       return TYPE_FIELD_ENUMVAL (type, 0);
708     case TYPE_CODE_BOOL:
709       return 0;
710     case TYPE_CODE_CHAR:
711     case TYPE_CODE_INT:
712       return min_of_type (type);
713     default:
714       error (_("Unexpected type in ada_discrete_type_low_bound."));
715     }
716 }
717
718 /* The identity on non-range types.  For range types, the underlying
719    non-range scalar type.  */
720
721 static struct type *
722 get_base_type (struct type *type)
723 {
724   while (type != NULL && type->code () == TYPE_CODE_RANGE)
725     {
726       if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
727         return type;
728       type = TYPE_TARGET_TYPE (type);
729     }
730   return type;
731 }
732
733 /* Return a decoded version of the given VALUE.  This means returning
734    a value whose type is obtained by applying all the GNAT-specific
735    encodings, making the resulting type a static but standard description
736    of the initial type.  */
737
738 struct value *
739 ada_get_decoded_value (struct value *value)
740 {
741   struct type *type = ada_check_typedef (value_type (value));
742
743   if (ada_is_array_descriptor_type (type)
744       || (ada_is_constrained_packed_array_type (type)
745           && type->code () != TYPE_CODE_PTR))
746     {
747       if (type->code () == TYPE_CODE_TYPEDEF)  /* array access type.  */
748         value = ada_coerce_to_simple_array_ptr (value);
749       else
750         value = ada_coerce_to_simple_array (value);
751     }
752   else
753     value = ada_to_fixed_value (value);
754
755   return value;
756 }
757
758 /* Same as ada_get_decoded_value, but with the given TYPE.
759    Because there is no associated actual value for this type,
760    the resulting type might be a best-effort approximation in
761    the case of dynamic types.  */
762
763 struct type *
764 ada_get_decoded_type (struct type *type)
765 {
766   type = to_static_fixed_type (type);
767   if (ada_is_constrained_packed_array_type (type))
768     type = ada_coerce_to_simple_array_type (type);
769   return type;
770 }
771
772 \f
773
774                                 /* Language Selection */
775
776 /* If the main program is in Ada, return language_ada, otherwise return LANG
777    (the main program is in Ada iif the adainit symbol is found).  */
778
779 static enum language
780 ada_update_initial_language (enum language lang)
781 {
782   if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
783     return language_ada;
784
785   return lang;
786 }
787
788 /* If the main procedure is written in Ada, then return its name.
789    The result is good until the next call.  Return NULL if the main
790    procedure doesn't appear to be in Ada.  */
791
792 char *
793 ada_main_name (void)
794 {
795   struct bound_minimal_symbol msym;
796   static gdb::unique_xmalloc_ptr<char> main_program_name;
797
798   /* For Ada, the name of the main procedure is stored in a specific
799      string constant, generated by the binder.  Look for that symbol,
800      extract its address, and then read that string.  If we didn't find
801      that string, then most probably the main procedure is not written
802      in Ada.  */
803   msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
804
805   if (msym.minsym != NULL)
806     {
807       CORE_ADDR main_program_name_addr = BMSYMBOL_VALUE_ADDRESS (msym);
808       if (main_program_name_addr == 0)
809         error (_("Invalid address for Ada main program name."));
810
811       main_program_name = target_read_string (main_program_name_addr, 1024);
812       return main_program_name.get ();
813     }
814
815   /* The main procedure doesn't seem to be in Ada.  */
816   return NULL;
817 }
818 \f
819                                 /* Symbols */
820
821 /* Table of Ada operators and their GNAT-encoded names.  Last entry is pair
822    of NULLs.  */
823
824 const struct ada_opname_map ada_opname_table[] = {
825   {"Oadd", "\"+\"", BINOP_ADD},
826   {"Osubtract", "\"-\"", BINOP_SUB},
827   {"Omultiply", "\"*\"", BINOP_MUL},
828   {"Odivide", "\"/\"", BINOP_DIV},
829   {"Omod", "\"mod\"", BINOP_MOD},
830   {"Orem", "\"rem\"", BINOP_REM},
831   {"Oexpon", "\"**\"", BINOP_EXP},
832   {"Olt", "\"<\"", BINOP_LESS},
833   {"Ole", "\"<=\"", BINOP_LEQ},
834   {"Ogt", "\">\"", BINOP_GTR},
835   {"Oge", "\">=\"", BINOP_GEQ},
836   {"Oeq", "\"=\"", BINOP_EQUAL},
837   {"One", "\"/=\"", BINOP_NOTEQUAL},
838   {"Oand", "\"and\"", BINOP_BITWISE_AND},
839   {"Oor", "\"or\"", BINOP_BITWISE_IOR},
840   {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
841   {"Oconcat", "\"&\"", BINOP_CONCAT},
842   {"Oabs", "\"abs\"", UNOP_ABS},
843   {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
844   {"Oadd", "\"+\"", UNOP_PLUS},
845   {"Osubtract", "\"-\"", UNOP_NEG},
846   {NULL, NULL}
847 };
848
849 /* The "encoded" form of DECODED, according to GNAT conventions.  If
850    THROW_ERRORS, throw an error if invalid operator name is found.
851    Otherwise, return the empty string in that case.  */
852
853 static std::string
854 ada_encode_1 (const char *decoded, bool throw_errors)
855 {
856   if (decoded == NULL)
857     return {};
858
859   std::string encoding_buffer;
860   for (const char *p = decoded; *p != '\0'; p += 1)
861     {
862       if (*p == '.')
863         encoding_buffer.append ("__");
864       else if (*p == '"')
865         {
866           const struct ada_opname_map *mapping;
867
868           for (mapping = ada_opname_table;
869                mapping->encoded != NULL
870                && !startswith (p, mapping->decoded); mapping += 1)
871             ;
872           if (mapping->encoded == NULL)
873             {
874               if (throw_errors)
875                 error (_("invalid Ada operator name: %s"), p);
876               else
877                 return {};
878             }
879           encoding_buffer.append (mapping->encoded);
880           break;
881         }
882       else
883         encoding_buffer.push_back (*p);
884     }
885
886   return encoding_buffer;
887 }
888
889 /* The "encoded" form of DECODED, according to GNAT conventions.  */
890
891 std::string
892 ada_encode (const char *decoded)
893 {
894   return ada_encode_1 (decoded, true);
895 }
896
897 /* Return NAME folded to lower case, or, if surrounded by single
898    quotes, unfolded, but with the quotes stripped away.  Result good
899    to next call.  */
900
901 static const char *
902 ada_fold_name (gdb::string_view name)
903 {
904   static std::string fold_storage;
905
906   if (!name.empty () && name[0] == '\'')
907     fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
908   else
909     {
910       fold_storage = gdb::to_string (name);
911       for (int i = 0; i < name.size (); i += 1)
912         fold_storage[i] = tolower (fold_storage[i]);
913     }
914
915   return fold_storage.c_str ();
916 }
917
918 /* Return nonzero if C is either a digit or a lowercase alphabet character.  */
919
920 static int
921 is_lower_alphanum (const char c)
922 {
923   return (isdigit (c) || (isalpha (c) && islower (c)));
924 }
925
926 /* ENCODED is the linkage name of a symbol and LEN contains its length.
927    This function saves in LEN the length of that same symbol name but
928    without either of these suffixes:
929      . .{DIGIT}+
930      . ${DIGIT}+
931      . ___{DIGIT}+
932      . __{DIGIT}+.
933
934    These are suffixes introduced by the compiler for entities such as
935    nested subprogram for instance, in order to avoid name clashes.
936    They do not serve any purpose for the debugger.  */
937
938 static void
939 ada_remove_trailing_digits (const char *encoded, int *len)
940 {
941   if (*len > 1 && isdigit (encoded[*len - 1]))
942     {
943       int i = *len - 2;
944
945       while (i > 0 && isdigit (encoded[i]))
946         i--;
947       if (i >= 0 && encoded[i] == '.')
948         *len = i;
949       else if (i >= 0 && encoded[i] == '$')
950         *len = i;
951       else if (i >= 2 && startswith (encoded + i - 2, "___"))
952         *len = i - 2;
953       else if (i >= 1 && startswith (encoded + i - 1, "__"))
954         *len = i - 1;
955     }
956 }
957
958 /* Remove the suffix introduced by the compiler for protected object
959    subprograms.  */
960
961 static void
962 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
963 {
964   /* Remove trailing N.  */
965
966   /* Protected entry subprograms are broken into two
967      separate subprograms: The first one is unprotected, and has
968      a 'N' suffix; the second is the protected version, and has
969      the 'P' suffix.  The second calls the first one after handling
970      the protection.  Since the P subprograms are internally generated,
971      we leave these names undecoded, giving the user a clue that this
972      entity is internal.  */
973
974   if (*len > 1
975       && encoded[*len - 1] == 'N'
976       && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
977     *len = *len - 1;
978 }
979
980 /* See ada-lang.h.  */
981
982 std::string
983 ada_decode (const char *encoded, bool wrap)
984 {
985   int i, j;
986   int len0;
987   const char *p;
988   int at_start_name;
989   std::string decoded;
990
991   /* With function descriptors on PPC64, the value of a symbol named
992      ".FN", if it exists, is the entry point of the function "FN".  */
993   if (encoded[0] == '.')
994     encoded += 1;
995
996   /* The name of the Ada main procedure starts with "_ada_".
997      This prefix is not part of the decoded name, so skip this part
998      if we see this prefix.  */
999   if (startswith (encoded, "_ada_"))
1000     encoded += 5;
1001
1002   /* If the name starts with '_', then it is not a properly encoded
1003      name, so do not attempt to decode it.  Similarly, if the name
1004      starts with '<', the name should not be decoded.  */
1005   if (encoded[0] == '_' || encoded[0] == '<')
1006     goto Suppress;
1007
1008   len0 = strlen (encoded);
1009
1010   ada_remove_trailing_digits (encoded, &len0);
1011   ada_remove_po_subprogram_suffix (encoded, &len0);
1012
1013   /* Remove the ___X.* suffix if present.  Do not forget to verify that
1014      the suffix is located before the current "end" of ENCODED.  We want
1015      to avoid re-matching parts of ENCODED that have previously been
1016      marked as discarded (by decrementing LEN0).  */
1017   p = strstr (encoded, "___");
1018   if (p != NULL && p - encoded < len0 - 3)
1019     {
1020       if (p[3] == 'X')
1021         len0 = p - encoded;
1022       else
1023         goto Suppress;
1024     }
1025
1026   /* Remove any trailing TKB suffix.  It tells us that this symbol
1027      is for the body of a task, but that information does not actually
1028      appear in the decoded name.  */
1029
1030   if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1031     len0 -= 3;
1032
1033   /* Remove any trailing TB suffix.  The TB suffix is slightly different
1034      from the TKB suffix because it is used for non-anonymous task
1035      bodies.  */
1036
1037   if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1038     len0 -= 2;
1039
1040   /* Remove trailing "B" suffixes.  */
1041   /* FIXME: brobecker/2006-04-19: Not sure what this are used for...  */
1042
1043   if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1044     len0 -= 1;
1045
1046   /* Make decoded big enough for possible expansion by operator name.  */
1047
1048   decoded.resize (2 * len0 + 1, 'X');
1049
1050   /* Remove trailing __{digit}+ or trailing ${digit}+.  */
1051
1052   if (len0 > 1 && isdigit (encoded[len0 - 1]))
1053     {
1054       i = len0 - 2;
1055       while ((i >= 0 && isdigit (encoded[i]))
1056              || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1057         i -= 1;
1058       if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1059         len0 = i - 1;
1060       else if (encoded[i] == '$')
1061         len0 = i;
1062     }
1063
1064   /* The first few characters that are not alphabetic are not part
1065      of any encoding we use, so we can copy them over verbatim.  */
1066
1067   for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
1068     decoded[j] = encoded[i];
1069
1070   at_start_name = 1;
1071   while (i < len0)
1072     {
1073       /* Is this a symbol function?  */
1074       if (at_start_name && encoded[i] == 'O')
1075         {
1076           int k;
1077
1078           for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1079             {
1080               int op_len = strlen (ada_opname_table[k].encoded);
1081               if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1082                             op_len - 1) == 0)
1083                   && !isalnum (encoded[i + op_len]))
1084                 {
1085                   strcpy (&decoded.front() + j, ada_opname_table[k].decoded);
1086                   at_start_name = 0;
1087                   i += op_len;
1088                   j += strlen (ada_opname_table[k].decoded);
1089                   break;
1090                 }
1091             }
1092           if (ada_opname_table[k].encoded != NULL)
1093             continue;
1094         }
1095       at_start_name = 0;
1096
1097       /* Replace "TK__" with "__", which will eventually be translated
1098          into "." (just below).  */
1099
1100       if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1101         i += 2;
1102
1103       /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1104          be translated into "." (just below).  These are internal names
1105          generated for anonymous blocks inside which our symbol is nested.  */
1106
1107       if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1108           && encoded [i+2] == 'B' && encoded [i+3] == '_'
1109           && isdigit (encoded [i+4]))
1110         {
1111           int k = i + 5;
1112           
1113           while (k < len0 && isdigit (encoded[k]))
1114             k++;  /* Skip any extra digit.  */
1115
1116           /* Double-check that the "__B_{DIGITS}+" sequence we found
1117              is indeed followed by "__".  */
1118           if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1119             i = k;
1120         }
1121
1122       /* Remove _E{DIGITS}+[sb] */
1123
1124       /* Just as for protected object subprograms, there are 2 categories
1125          of subprograms created by the compiler for each entry.  The first
1126          one implements the actual entry code, and has a suffix following
1127          the convention above; the second one implements the barrier and
1128          uses the same convention as above, except that the 'E' is replaced
1129          by a 'B'.
1130
1131          Just as above, we do not decode the name of barrier functions
1132          to give the user a clue that the code he is debugging has been
1133          internally generated.  */
1134
1135       if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1136           && isdigit (encoded[i+2]))
1137         {
1138           int k = i + 3;
1139
1140           while (k < len0 && isdigit (encoded[k]))
1141             k++;
1142
1143           if (k < len0
1144               && (encoded[k] == 'b' || encoded[k] == 's'))
1145             {
1146               k++;
1147               /* Just as an extra precaution, make sure that if this
1148                  suffix is followed by anything else, it is a '_'.
1149                  Otherwise, we matched this sequence by accident.  */
1150               if (k == len0
1151                   || (k < len0 && encoded[k] == '_'))
1152                 i = k;
1153             }
1154         }
1155
1156       /* Remove trailing "N" in [a-z0-9]+N__.  The N is added by
1157          the GNAT front-end in protected object subprograms.  */
1158
1159       if (i < len0 + 3
1160           && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1161         {
1162           /* Backtrack a bit up until we reach either the begining of
1163              the encoded name, or "__".  Make sure that we only find
1164              digits or lowercase characters.  */
1165           const char *ptr = encoded + i - 1;
1166
1167           while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1168             ptr--;
1169           if (ptr < encoded
1170               || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1171             i++;
1172         }
1173
1174       if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1175         {
1176           /* This is a X[bn]* sequence not separated from the previous
1177              part of the name with a non-alpha-numeric character (in other
1178              words, immediately following an alpha-numeric character), then
1179              verify that it is placed at the end of the encoded name.  If
1180              not, then the encoding is not valid and we should abort the
1181              decoding.  Otherwise, just skip it, it is used in body-nested
1182              package names.  */
1183           do
1184             i += 1;
1185           while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1186           if (i < len0)
1187             goto Suppress;
1188         }
1189       else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1190         {
1191          /* Replace '__' by '.'.  */
1192           decoded[j] = '.';
1193           at_start_name = 1;
1194           i += 2;
1195           j += 1;
1196         }
1197       else
1198         {
1199           /* It's a character part of the decoded name, so just copy it
1200              over.  */
1201           decoded[j] = encoded[i];
1202           i += 1;
1203           j += 1;
1204         }
1205     }
1206   decoded.resize (j);
1207
1208   /* Decoded names should never contain any uppercase character.
1209      Double-check this, and abort the decoding if we find one.  */
1210
1211   for (i = 0; i < decoded.length(); ++i)
1212     if (isupper (decoded[i]) || decoded[i] == ' ')
1213       goto Suppress;
1214
1215   return decoded;
1216
1217 Suppress:
1218   if (!wrap)
1219     return {};
1220
1221   if (encoded[0] == '<')
1222     decoded = encoded;
1223   else
1224     decoded = '<' + std::string(encoded) + '>';
1225   return decoded;
1226 }
1227
1228 /* Table for keeping permanent unique copies of decoded names.  Once
1229    allocated, names in this table are never released.  While this is a
1230    storage leak, it should not be significant unless there are massive
1231    changes in the set of decoded names in successive versions of a 
1232    symbol table loaded during a single session.  */
1233 static struct htab *decoded_names_store;
1234
1235 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1236    in the language-specific part of GSYMBOL, if it has not been
1237    previously computed.  Tries to save the decoded name in the same
1238    obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1239    in any case, the decoded symbol has a lifetime at least that of
1240    GSYMBOL).
1241    The GSYMBOL parameter is "mutable" in the C++ sense: logically
1242    const, but nevertheless modified to a semantically equivalent form
1243    when a decoded name is cached in it.  */
1244
1245 const char *
1246 ada_decode_symbol (const struct general_symbol_info *arg)
1247 {
1248   struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1249   const char **resultp =
1250     &gsymbol->language_specific.demangled_name;
1251
1252   if (!gsymbol->ada_mangled)
1253     {
1254       std::string decoded = ada_decode (gsymbol->linkage_name ());
1255       struct obstack *obstack = gsymbol->language_specific.obstack;
1256
1257       gsymbol->ada_mangled = 1;
1258
1259       if (obstack != NULL)
1260         *resultp = obstack_strdup (obstack, decoded.c_str ());
1261       else
1262         {
1263           /* Sometimes, we can't find a corresponding objfile, in
1264              which case, we put the result on the heap.  Since we only
1265              decode when needed, we hope this usually does not cause a
1266              significant memory leak (FIXME).  */
1267
1268           char **slot = (char **) htab_find_slot (decoded_names_store,
1269                                                   decoded.c_str (), INSERT);
1270
1271           if (*slot == NULL)
1272             *slot = xstrdup (decoded.c_str ());
1273           *resultp = *slot;
1274         }
1275     }
1276
1277   return *resultp;
1278 }
1279
1280 static char *
1281 ada_la_decode (const char *encoded, int options)
1282 {
1283   return xstrdup (ada_decode (encoded).c_str ());
1284 }
1285
1286 \f
1287
1288                                 /* Arrays */
1289
1290 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1291    generated by the GNAT compiler to describe the index type used
1292    for each dimension of an array, check whether it follows the latest
1293    known encoding.  If not, fix it up to conform to the latest encoding.
1294    Otherwise, do nothing.  This function also does nothing if
1295    INDEX_DESC_TYPE is NULL.
1296
1297    The GNAT encoding used to describe the array index type evolved a bit.
1298    Initially, the information would be provided through the name of each
1299    field of the structure type only, while the type of these fields was
1300    described as unspecified and irrelevant.  The debugger was then expected
1301    to perform a global type lookup using the name of that field in order
1302    to get access to the full index type description.  Because these global
1303    lookups can be very expensive, the encoding was later enhanced to make
1304    the global lookup unnecessary by defining the field type as being
1305    the full index type description.
1306
1307    The purpose of this routine is to allow us to support older versions
1308    of the compiler by detecting the use of the older encoding, and by
1309    fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1310    we essentially replace each field's meaningless type by the associated
1311    index subtype).  */
1312
1313 void
1314 ada_fixup_array_indexes_type (struct type *index_desc_type)
1315 {
1316   int i;
1317
1318   if (index_desc_type == NULL)
1319     return;
1320   gdb_assert (index_desc_type->num_fields () > 0);
1321
1322   /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1323      to check one field only, no need to check them all).  If not, return
1324      now.
1325
1326      If our INDEX_DESC_TYPE was generated using the older encoding,
1327      the field type should be a meaningless integer type whose name
1328      is not equal to the field name.  */
1329   if (index_desc_type->field (0).type ()->name () != NULL
1330       && strcmp (index_desc_type->field (0).type ()->name (),
1331                  TYPE_FIELD_NAME (index_desc_type, 0)) == 0)
1332     return;
1333
1334   /* Fixup each field of INDEX_DESC_TYPE.  */
1335   for (i = 0; i < index_desc_type->num_fields (); i++)
1336    {
1337      const char *name = TYPE_FIELD_NAME (index_desc_type, i);
1338      struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1339
1340      if (raw_type)
1341        index_desc_type->field (i).set_type (raw_type);
1342    }
1343 }
1344
1345 /* The desc_* routines return primitive portions of array descriptors
1346    (fat pointers).  */
1347
1348 /* The descriptor or array type, if any, indicated by TYPE; removes
1349    level of indirection, if needed.  */
1350
1351 static struct type *
1352 desc_base_type (struct type *type)
1353 {
1354   if (type == NULL)
1355     return NULL;
1356   type = ada_check_typedef (type);
1357   if (type->code () == TYPE_CODE_TYPEDEF)
1358     type = ada_typedef_target_type (type);
1359
1360   if (type != NULL
1361       && (type->code () == TYPE_CODE_PTR
1362           || type->code () == TYPE_CODE_REF))
1363     return ada_check_typedef (TYPE_TARGET_TYPE (type));
1364   else
1365     return type;
1366 }
1367
1368 /* True iff TYPE indicates a "thin" array pointer type.  */
1369
1370 static int
1371 is_thin_pntr (struct type *type)
1372 {
1373   return
1374     is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1375     || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1376 }
1377
1378 /* The descriptor type for thin pointer type TYPE.  */
1379
1380 static struct type *
1381 thin_descriptor_type (struct type *type)
1382 {
1383   struct type *base_type = desc_base_type (type);
1384
1385   if (base_type == NULL)
1386     return NULL;
1387   if (is_suffix (ada_type_name (base_type), "___XVE"))
1388     return base_type;
1389   else
1390     {
1391       struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1392
1393       if (alt_type == NULL)
1394         return base_type;
1395       else
1396         return alt_type;
1397     }
1398 }
1399
1400 /* A pointer to the array data for thin-pointer value VAL.  */
1401
1402 static struct value *
1403 thin_data_pntr (struct value *val)
1404 {
1405   struct type *type = ada_check_typedef (value_type (val));
1406   struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1407
1408   data_type = lookup_pointer_type (data_type);
1409
1410   if (type->code () == TYPE_CODE_PTR)
1411     return value_cast (data_type, value_copy (val));
1412   else
1413     return value_from_longest (data_type, value_address (val));
1414 }
1415
1416 /* True iff TYPE indicates a "thick" array pointer type.  */
1417
1418 static int
1419 is_thick_pntr (struct type *type)
1420 {
1421   type = desc_base_type (type);
1422   return (type != NULL && type->code () == TYPE_CODE_STRUCT
1423           && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1424 }
1425
1426 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1427    pointer to one, the type of its bounds data; otherwise, NULL.  */
1428
1429 static struct type *
1430 desc_bounds_type (struct type *type)
1431 {
1432   struct type *r;
1433
1434   type = desc_base_type (type);
1435
1436   if (type == NULL)
1437     return NULL;
1438   else if (is_thin_pntr (type))
1439     {
1440       type = thin_descriptor_type (type);
1441       if (type == NULL)
1442         return NULL;
1443       r = lookup_struct_elt_type (type, "BOUNDS", 1);
1444       if (r != NULL)
1445         return ada_check_typedef (r);
1446     }
1447   else if (type->code () == TYPE_CODE_STRUCT)
1448     {
1449       r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1450       if (r != NULL)
1451         return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1452     }
1453   return NULL;
1454 }
1455
1456 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1457    one, a pointer to its bounds data.   Otherwise NULL.  */
1458
1459 static struct value *
1460 desc_bounds (struct value *arr)
1461 {
1462   struct type *type = ada_check_typedef (value_type (arr));
1463
1464   if (is_thin_pntr (type))
1465     {
1466       struct type *bounds_type =
1467         desc_bounds_type (thin_descriptor_type (type));
1468       LONGEST addr;
1469
1470       if (bounds_type == NULL)
1471         error (_("Bad GNAT array descriptor"));
1472
1473       /* NOTE: The following calculation is not really kosher, but
1474          since desc_type is an XVE-encoded type (and shouldn't be),
1475          the correct calculation is a real pain.  FIXME (and fix GCC).  */
1476       if (type->code () == TYPE_CODE_PTR)
1477         addr = value_as_long (arr);
1478       else
1479         addr = value_address (arr);
1480
1481       return
1482         value_from_longest (lookup_pointer_type (bounds_type),
1483                             addr - TYPE_LENGTH (bounds_type));
1484     }
1485
1486   else if (is_thick_pntr (type))
1487     {
1488       struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1489                                                _("Bad GNAT array descriptor"));
1490       struct type *p_bounds_type = value_type (p_bounds);
1491
1492       if (p_bounds_type
1493           && p_bounds_type->code () == TYPE_CODE_PTR)
1494         {
1495           struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
1496
1497           if (target_type->is_stub ())
1498             p_bounds = value_cast (lookup_pointer_type
1499                                    (ada_check_typedef (target_type)),
1500                                    p_bounds);
1501         }
1502       else
1503         error (_("Bad GNAT array descriptor"));
1504
1505       return p_bounds;
1506     }
1507   else
1508     return NULL;
1509 }
1510
1511 /* If TYPE is the type of an array-descriptor (fat pointer),  the bit
1512    position of the field containing the address of the bounds data.  */
1513
1514 static int
1515 fat_pntr_bounds_bitpos (struct type *type)
1516 {
1517   return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
1518 }
1519
1520 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1521    size of the field containing the address of the bounds data.  */
1522
1523 static int
1524 fat_pntr_bounds_bitsize (struct type *type)
1525 {
1526   type = desc_base_type (type);
1527
1528   if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1529     return TYPE_FIELD_BITSIZE (type, 1);
1530   else
1531     return 8 * TYPE_LENGTH (ada_check_typedef (type->field (1).type ()));
1532 }
1533
1534 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1535    pointer to one, the type of its array data (a array-with-no-bounds type);
1536    otherwise, NULL.  Use ada_type_of_array to get an array type with bounds
1537    data.  */
1538
1539 static struct type *
1540 desc_data_target_type (struct type *type)
1541 {
1542   type = desc_base_type (type);
1543
1544   /* NOTE: The following is bogus; see comment in desc_bounds.  */
1545   if (is_thin_pntr (type))
1546     return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1547   else if (is_thick_pntr (type))
1548     {
1549       struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1550
1551       if (data_type
1552           && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1553         return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
1554     }
1555
1556   return NULL;
1557 }
1558
1559 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1560    its array data.  */
1561
1562 static struct value *
1563 desc_data (struct value *arr)
1564 {
1565   struct type *type = value_type (arr);
1566
1567   if (is_thin_pntr (type))
1568     return thin_data_pntr (arr);
1569   else if (is_thick_pntr (type))
1570     return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1571                              _("Bad GNAT array descriptor"));
1572   else
1573     return NULL;
1574 }
1575
1576
1577 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1578    position of the field containing the address of the data.  */
1579
1580 static int
1581 fat_pntr_data_bitpos (struct type *type)
1582 {
1583   return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
1584 }
1585
1586 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1587    size of the field containing the address of the data.  */
1588
1589 static int
1590 fat_pntr_data_bitsize (struct type *type)
1591 {
1592   type = desc_base_type (type);
1593
1594   if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1595     return TYPE_FIELD_BITSIZE (type, 0);
1596   else
1597     return TARGET_CHAR_BIT * TYPE_LENGTH (type->field (0).type ());
1598 }
1599
1600 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1601    the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1602    bound, if WHICH is 1.  The first bound is I=1.  */
1603
1604 static struct value *
1605 desc_one_bound (struct value *bounds, int i, int which)
1606 {
1607   char bound_name[20];
1608   xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1609              which ? 'U' : 'L', i - 1);
1610   return value_struct_elt (&bounds, {}, bound_name, NULL,
1611                            _("Bad GNAT array descriptor bounds"));
1612 }
1613
1614 /* If BOUNDS is an array-bounds structure type, return the bit position
1615    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1616    bound, if WHICH is 1.  The first bound is I=1.  */
1617
1618 static int
1619 desc_bound_bitpos (struct type *type, int i, int which)
1620 {
1621   return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
1622 }
1623
1624 /* If BOUNDS is an array-bounds structure type, return the bit field size
1625    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1626    bound, if WHICH is 1.  The first bound is I=1.  */
1627
1628 static int
1629 desc_bound_bitsize (struct type *type, int i, int which)
1630 {
1631   type = desc_base_type (type);
1632
1633   if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1634     return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1635   else
1636     return 8 * TYPE_LENGTH (type->field (2 * i + which - 2).type ());
1637 }
1638
1639 /* If TYPE is the type of an array-bounds structure, the type of its
1640    Ith bound (numbering from 1).  Otherwise, NULL.  */
1641
1642 static struct type *
1643 desc_index_type (struct type *type, int i)
1644 {
1645   type = desc_base_type (type);
1646
1647   if (type->code () == TYPE_CODE_STRUCT)
1648     {
1649       char bound_name[20];
1650       xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
1651       return lookup_struct_elt_type (type, bound_name, 1);
1652     }
1653   else
1654     return NULL;
1655 }
1656
1657 /* The number of index positions in the array-bounds type TYPE.
1658    Return 0 if TYPE is NULL.  */
1659
1660 static int
1661 desc_arity (struct type *type)
1662 {
1663   type = desc_base_type (type);
1664
1665   if (type != NULL)
1666     return type->num_fields () / 2;
1667   return 0;
1668 }
1669
1670 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or 
1671    an array descriptor type (representing an unconstrained array
1672    type).  */
1673
1674 static int
1675 ada_is_direct_array_type (struct type *type)
1676 {
1677   if (type == NULL)
1678     return 0;
1679   type = ada_check_typedef (type);
1680   return (type->code () == TYPE_CODE_ARRAY
1681           || ada_is_array_descriptor_type (type));
1682 }
1683
1684 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
1685  * to one.  */
1686
1687 static int
1688 ada_is_array_type (struct type *type)
1689 {
1690   while (type != NULL
1691          && (type->code () == TYPE_CODE_PTR
1692              || type->code () == TYPE_CODE_REF))
1693     type = TYPE_TARGET_TYPE (type);
1694   return ada_is_direct_array_type (type);
1695 }
1696
1697 /* Non-zero iff TYPE is a simple array type or pointer to one.  */
1698
1699 int
1700 ada_is_simple_array_type (struct type *type)
1701 {
1702   if (type == NULL)
1703     return 0;
1704   type = ada_check_typedef (type);
1705   return (type->code () == TYPE_CODE_ARRAY
1706           || (type->code () == TYPE_CODE_PTR
1707               && (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ()
1708                   == TYPE_CODE_ARRAY)));
1709 }
1710
1711 /* Non-zero iff TYPE belongs to a GNAT array descriptor.  */
1712
1713 int
1714 ada_is_array_descriptor_type (struct type *type)
1715 {
1716   struct type *data_type = desc_data_target_type (type);
1717
1718   if (type == NULL)
1719     return 0;
1720   type = ada_check_typedef (type);
1721   return (data_type != NULL
1722           && data_type->code () == TYPE_CODE_ARRAY
1723           && desc_arity (desc_bounds_type (type)) > 0);
1724 }
1725
1726 /* Non-zero iff type is a partially mal-formed GNAT array
1727    descriptor.  FIXME: This is to compensate for some problems with
1728    debugging output from GNAT.  Re-examine periodically to see if it
1729    is still needed.  */
1730
1731 int
1732 ada_is_bogus_array_descriptor (struct type *type)
1733 {
1734   return
1735     type != NULL
1736     && type->code () == TYPE_CODE_STRUCT
1737     && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1738         || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1739     && !ada_is_array_descriptor_type (type);
1740 }
1741
1742
1743 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1744    (fat pointer) returns the type of the array data described---specifically,
1745    a pointer-to-array type.  If BOUNDS is non-zero, the bounds data are filled
1746    in from the descriptor; otherwise, they are left unspecified.  If
1747    the ARR denotes a null array descriptor and BOUNDS is non-zero,
1748    returns NULL.  The result is simply the type of ARR if ARR is not
1749    a descriptor.  */
1750
1751 static struct type *
1752 ada_type_of_array (struct value *arr, int bounds)
1753 {
1754   if (ada_is_constrained_packed_array_type (value_type (arr)))
1755     return decode_constrained_packed_array_type (value_type (arr));
1756
1757   if (!ada_is_array_descriptor_type (value_type (arr)))
1758     return value_type (arr);
1759
1760   if (!bounds)
1761     {
1762       struct type *array_type =
1763         ada_check_typedef (desc_data_target_type (value_type (arr)));
1764
1765       if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1766         TYPE_FIELD_BITSIZE (array_type, 0) =
1767           decode_packed_array_bitsize (value_type (arr));
1768       
1769       return array_type;
1770     }
1771   else
1772     {
1773       struct type *elt_type;
1774       int arity;
1775       struct value *descriptor;
1776
1777       elt_type = ada_array_element_type (value_type (arr), -1);
1778       arity = ada_array_arity (value_type (arr));
1779
1780       if (elt_type == NULL || arity == 0)
1781         return ada_check_typedef (value_type (arr));
1782
1783       descriptor = desc_bounds (arr);
1784       if (value_as_long (descriptor) == 0)
1785         return NULL;
1786       while (arity > 0)
1787         {
1788           struct type *range_type = alloc_type_copy (value_type (arr));
1789           struct type *array_type = alloc_type_copy (value_type (arr));
1790           struct value *low = desc_one_bound (descriptor, arity, 0);
1791           struct value *high = desc_one_bound (descriptor, arity, 1);
1792
1793           arity -= 1;
1794           create_static_range_type (range_type, value_type (low),
1795                                     longest_to_int (value_as_long (low)),
1796                                     longest_to_int (value_as_long (high)));
1797           elt_type = create_array_type (array_type, elt_type, range_type);
1798
1799           if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1800             {
1801               /* We need to store the element packed bitsize, as well as
1802                  recompute the array size, because it was previously
1803                  computed based on the unpacked element size.  */
1804               LONGEST lo = value_as_long (low);
1805               LONGEST hi = value_as_long (high);
1806
1807               TYPE_FIELD_BITSIZE (elt_type, 0) =
1808                 decode_packed_array_bitsize (value_type (arr));
1809               /* If the array has no element, then the size is already
1810                  zero, and does not need to be recomputed.  */
1811               if (lo < hi)
1812                 {
1813                   int array_bitsize =
1814                         (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
1815
1816                   TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
1817                 }
1818             }
1819         }
1820
1821       return lookup_pointer_type (elt_type);
1822     }
1823 }
1824
1825 /* If ARR does not represent an array, returns ARR unchanged.
1826    Otherwise, returns either a standard GDB array with bounds set
1827    appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
1828    GDB array.  Returns NULL if ARR is a null fat pointer.  */
1829
1830 struct value *
1831 ada_coerce_to_simple_array_ptr (struct value *arr)
1832 {
1833   if (ada_is_array_descriptor_type (value_type (arr)))
1834     {
1835       struct type *arrType = ada_type_of_array (arr, 1);
1836
1837       if (arrType == NULL)
1838         return NULL;
1839       return value_cast (arrType, value_copy (desc_data (arr)));
1840     }
1841   else if (ada_is_constrained_packed_array_type (value_type (arr)))
1842     return decode_constrained_packed_array (arr);
1843   else
1844     return arr;
1845 }
1846
1847 /* If ARR does not represent an array, returns ARR unchanged.
1848    Otherwise, returns a standard GDB array describing ARR (which may
1849    be ARR itself if it already is in the proper form).  */
1850
1851 struct value *
1852 ada_coerce_to_simple_array (struct value *arr)
1853 {
1854   if (ada_is_array_descriptor_type (value_type (arr)))
1855     {
1856       struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
1857
1858       if (arrVal == NULL)
1859         error (_("Bounds unavailable for null array pointer."));
1860       ada_ensure_varsize_limit (TYPE_TARGET_TYPE (value_type (arrVal)));
1861       return value_ind (arrVal);
1862     }
1863   else if (ada_is_constrained_packed_array_type (value_type (arr)))
1864     return decode_constrained_packed_array (arr);
1865   else
1866     return arr;
1867 }
1868
1869 /* If TYPE represents a GNAT array type, return it translated to an
1870    ordinary GDB array type (possibly with BITSIZE fields indicating
1871    packing).  For other types, is the identity.  */
1872
1873 struct type *
1874 ada_coerce_to_simple_array_type (struct type *type)
1875 {
1876   if (ada_is_constrained_packed_array_type (type))
1877     return decode_constrained_packed_array_type (type);
1878
1879   if (ada_is_array_descriptor_type (type))
1880     return ada_check_typedef (desc_data_target_type (type));
1881
1882   return type;
1883 }
1884
1885 /* Non-zero iff TYPE represents a standard GNAT packed-array type.  */
1886
1887 static int
1888 ada_is_gnat_encoded_packed_array_type  (struct type *type)
1889 {
1890   if (type == NULL)
1891     return 0;
1892   type = desc_base_type (type);
1893   type = ada_check_typedef (type);
1894   return
1895     ada_type_name (type) != NULL
1896     && strstr (ada_type_name (type), "___XP") != NULL;
1897 }
1898
1899 /* Non-zero iff TYPE represents a standard GNAT constrained
1900    packed-array type.  */
1901
1902 int
1903 ada_is_constrained_packed_array_type (struct type *type)
1904 {
1905   return ada_is_gnat_encoded_packed_array_type (type)
1906     && !ada_is_array_descriptor_type (type);
1907 }
1908
1909 /* Non-zero iff TYPE represents an array descriptor for a
1910    unconstrained packed-array type.  */
1911
1912 static int
1913 ada_is_unconstrained_packed_array_type (struct type *type)
1914 {
1915   if (!ada_is_array_descriptor_type (type))
1916     return 0;
1917
1918   if (ada_is_gnat_encoded_packed_array_type (type))
1919     return 1;
1920
1921   /* If we saw GNAT encodings, then the above code is sufficient.
1922      However, with minimal encodings, we will just have a thick
1923      pointer instead.  */
1924   if (is_thick_pntr (type))
1925     {
1926       type = desc_base_type (type);
1927       /* The structure's first field is a pointer to an array, so this
1928          fetches the array type.  */
1929       type = TYPE_TARGET_TYPE (type->field (0).type ());
1930       /* Now we can see if the array elements are packed.  */
1931       return TYPE_FIELD_BITSIZE (type, 0) > 0;
1932     }
1933
1934   return 0;
1935 }
1936
1937 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
1938    type, or if it is an ordinary (non-Gnat-encoded) packed array.  */
1939
1940 static bool
1941 ada_is_any_packed_array_type (struct type *type)
1942 {
1943   return (ada_is_constrained_packed_array_type (type)
1944           || (type->code () == TYPE_CODE_ARRAY
1945               && TYPE_FIELD_BITSIZE (type, 0) % 8 != 0));
1946 }
1947
1948 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
1949    return the size of its elements in bits.  */
1950
1951 static long
1952 decode_packed_array_bitsize (struct type *type)
1953 {
1954   const char *raw_name;
1955   const char *tail;
1956   long bits;
1957
1958   /* Access to arrays implemented as fat pointers are encoded as a typedef
1959      of the fat pointer type.  We need the name of the fat pointer type
1960      to do the decoding, so strip the typedef layer.  */
1961   if (type->code () == TYPE_CODE_TYPEDEF)
1962     type = ada_typedef_target_type (type);
1963
1964   raw_name = ada_type_name (ada_check_typedef (type));
1965   if (!raw_name)
1966     raw_name = ada_type_name (desc_base_type (type));
1967
1968   if (!raw_name)
1969     return 0;
1970
1971   tail = strstr (raw_name, "___XP");
1972   if (tail == nullptr)
1973     {
1974       gdb_assert (is_thick_pntr (type));
1975       /* The structure's first field is a pointer to an array, so this
1976          fetches the array type.  */
1977       type = TYPE_TARGET_TYPE (type->field (0).type ());
1978       /* Now we can see if the array elements are packed.  */
1979       return TYPE_FIELD_BITSIZE (type, 0);
1980     }
1981
1982   if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
1983     {
1984       lim_warning
1985         (_("could not understand bit size information on packed array"));
1986       return 0;
1987     }
1988
1989   return bits;
1990 }
1991
1992 /* Given that TYPE is a standard GDB array type with all bounds filled
1993    in, and that the element size of its ultimate scalar constituents
1994    (that is, either its elements, or, if it is an array of arrays, its
1995    elements' elements, etc.) is *ELT_BITS, return an identical type,
1996    but with the bit sizes of its elements (and those of any
1997    constituent arrays) recorded in the BITSIZE components of its
1998    TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
1999    in bits.
2000
2001    Note that, for arrays whose index type has an XA encoding where
2002    a bound references a record discriminant, getting that discriminant,
2003    and therefore the actual value of that bound, is not possible
2004    because none of the given parameters gives us access to the record.
2005    This function assumes that it is OK in the context where it is being
2006    used to return an array whose bounds are still dynamic and where
2007    the length is arbitrary.  */
2008
2009 static struct type *
2010 constrained_packed_array_type (struct type *type, long *elt_bits)
2011 {
2012   struct type *new_elt_type;
2013   struct type *new_type;
2014   struct type *index_type_desc;
2015   struct type *index_type;
2016   LONGEST low_bound, high_bound;
2017
2018   type = ada_check_typedef (type);
2019   if (type->code () != TYPE_CODE_ARRAY)
2020     return type;
2021
2022   index_type_desc = ada_find_parallel_type (type, "___XA");
2023   if (index_type_desc)
2024     index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2025                                       NULL);
2026   else
2027     index_type = type->index_type ();
2028
2029   new_type = alloc_type_copy (type);
2030   new_elt_type =
2031     constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
2032                                    elt_bits);
2033   create_array_type (new_type, new_elt_type, index_type);
2034   TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2035   new_type->set_name (ada_type_name (type));
2036
2037   if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2038        && is_dynamic_type (check_typedef (index_type)))
2039       || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2040     low_bound = high_bound = 0;
2041   if (high_bound < low_bound)
2042     *elt_bits = TYPE_LENGTH (new_type) = 0;
2043   else
2044     {
2045       *elt_bits *= (high_bound - low_bound + 1);
2046       TYPE_LENGTH (new_type) =
2047         (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2048     }
2049
2050   new_type->set_is_fixed_instance (true);
2051   return new_type;
2052 }
2053
2054 /* The array type encoded by TYPE, where
2055    ada_is_constrained_packed_array_type (TYPE).  */
2056
2057 static struct type *
2058 decode_constrained_packed_array_type (struct type *type)
2059 {
2060   const char *raw_name = ada_type_name (ada_check_typedef (type));
2061   char *name;
2062   const char *tail;
2063   struct type *shadow_type;
2064   long bits;
2065
2066   if (!raw_name)
2067     raw_name = ada_type_name (desc_base_type (type));
2068
2069   if (!raw_name)
2070     return NULL;
2071
2072   name = (char *) alloca (strlen (raw_name) + 1);
2073   tail = strstr (raw_name, "___XP");
2074   type = desc_base_type (type);
2075
2076   memcpy (name, raw_name, tail - raw_name);
2077   name[tail - raw_name] = '\000';
2078
2079   shadow_type = ada_find_parallel_type_with_name (type, name);
2080
2081   if (shadow_type == NULL)
2082     {
2083       lim_warning (_("could not find bounds information on packed array"));
2084       return NULL;
2085     }
2086   shadow_type = check_typedef (shadow_type);
2087
2088   if (shadow_type->code () != TYPE_CODE_ARRAY)
2089     {
2090       lim_warning (_("could not understand bounds "
2091                      "information on packed array"));
2092       return NULL;
2093     }
2094
2095   bits = decode_packed_array_bitsize (type);
2096   return constrained_packed_array_type (shadow_type, &bits);
2097 }
2098
2099 /* Helper function for decode_constrained_packed_array.  Set the field
2100    bitsize on a series of packed arrays.  Returns the number of
2101    elements in TYPE.  */
2102
2103 static LONGEST
2104 recursively_update_array_bitsize (struct type *type)
2105 {
2106   gdb_assert (type->code () == TYPE_CODE_ARRAY);
2107
2108   LONGEST low, high;
2109   if (!get_discrete_bounds (type->index_type (), &low, &high)
2110       || low > high)
2111     return 0;
2112   LONGEST our_len = high - low + 1;
2113
2114   struct type *elt_type = TYPE_TARGET_TYPE (type);
2115   if (elt_type->code () == TYPE_CODE_ARRAY)
2116     {
2117       LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2118       LONGEST elt_bitsize = elt_len * TYPE_FIELD_BITSIZE (elt_type, 0);
2119       TYPE_FIELD_BITSIZE (type, 0) = elt_bitsize;
2120
2121       TYPE_LENGTH (type) = ((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2122                             / HOST_CHAR_BIT);
2123     }
2124
2125   return our_len;
2126 }
2127
2128 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2129    array, returns a simple array that denotes that array.  Its type is a
2130    standard GDB array type except that the BITSIZEs of the array
2131    target types are set to the number of bits in each element, and the
2132    type length is set appropriately.  */
2133
2134 static struct value *
2135 decode_constrained_packed_array (struct value *arr)
2136 {
2137   struct type *type;
2138
2139   /* If our value is a pointer, then dereference it. Likewise if
2140      the value is a reference.  Make sure that this operation does not
2141      cause the target type to be fixed, as this would indirectly cause
2142      this array to be decoded.  The rest of the routine assumes that
2143      the array hasn't been decoded yet, so we use the basic "coerce_ref"
2144      and "value_ind" routines to perform the dereferencing, as opposed
2145      to using "ada_coerce_ref" or "ada_value_ind".  */
2146   arr = coerce_ref (arr);
2147   if (ada_check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2148     arr = value_ind (arr);
2149
2150   type = decode_constrained_packed_array_type (value_type (arr));
2151   if (type == NULL)
2152     {
2153       error (_("can't unpack array"));
2154       return NULL;
2155     }
2156
2157   /* Decoding the packed array type could not correctly set the field
2158      bitsizes for any dimension except the innermost, because the
2159      bounds may be variable and were not passed to that function.  So,
2160      we further resolve the array bounds here and then update the
2161      sizes.  */
2162   const gdb_byte *valaddr = value_contents_for_printing (arr);
2163   CORE_ADDR address = value_address (arr);
2164   gdb::array_view<const gdb_byte> view
2165     = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
2166   type = resolve_dynamic_type (type, view, address);
2167   recursively_update_array_bitsize (type);
2168
2169   if (type_byte_order (value_type (arr)) == BFD_ENDIAN_BIG
2170       && ada_is_modular_type (value_type (arr)))
2171     {
2172        /* This is a (right-justified) modular type representing a packed
2173           array with no wrapper.  In order to interpret the value through
2174           the (left-justified) packed array type we just built, we must
2175           first left-justify it.  */
2176       int bit_size, bit_pos;
2177       ULONGEST mod;
2178
2179       mod = ada_modulus (value_type (arr)) - 1;
2180       bit_size = 0;
2181       while (mod > 0)
2182         {
2183           bit_size += 1;
2184           mod >>= 1;
2185         }
2186       bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
2187       arr = ada_value_primitive_packed_val (arr, NULL,
2188                                             bit_pos / HOST_CHAR_BIT,
2189                                             bit_pos % HOST_CHAR_BIT,
2190                                             bit_size,
2191                                             type);
2192     }
2193
2194   return coerce_unspec_val_to_type (arr, type);
2195 }
2196
2197
2198 /* The value of the element of packed array ARR at the ARITY indices
2199    given in IND.   ARR must be a simple array.  */
2200
2201 static struct value *
2202 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2203 {
2204   int i;
2205   int bits, elt_off, bit_off;
2206   long elt_total_bit_offset;
2207   struct type *elt_type;
2208   struct value *v;
2209
2210   bits = 0;
2211   elt_total_bit_offset = 0;
2212   elt_type = ada_check_typedef (value_type (arr));
2213   for (i = 0; i < arity; i += 1)
2214     {
2215       if (elt_type->code () != TYPE_CODE_ARRAY
2216           || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2217         error
2218           (_("attempt to do packed indexing of "
2219              "something other than a packed array"));
2220       else
2221         {
2222           struct type *range_type = elt_type->index_type ();
2223           LONGEST lowerbound, upperbound;
2224           LONGEST idx;
2225
2226           if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2227             {
2228               lim_warning (_("don't know bounds of array"));
2229               lowerbound = upperbound = 0;
2230             }
2231
2232           idx = pos_atr (ind[i]);
2233           if (idx < lowerbound || idx > upperbound)
2234             lim_warning (_("packed array index %ld out of bounds"),
2235                          (long) idx);
2236           bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2237           elt_total_bit_offset += (idx - lowerbound) * bits;
2238           elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
2239         }
2240     }
2241   elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2242   bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2243
2244   v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2245                                       bits, elt_type);
2246   return v;
2247 }
2248
2249 /* Non-zero iff TYPE includes negative integer values.  */
2250
2251 static int
2252 has_negatives (struct type *type)
2253 {
2254   switch (type->code ())
2255     {
2256     default:
2257       return 0;
2258     case TYPE_CODE_INT:
2259       return !type->is_unsigned ();
2260     case TYPE_CODE_RANGE:
2261       return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2262     }
2263 }
2264
2265 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2266    unpack that data into UNPACKED.  UNPACKED_LEN is the size in bytes of
2267    the unpacked buffer.
2268
2269    The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2270    enough to contain at least BIT_OFFSET bits.  If not, an error is raised.
2271
2272    IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2273    zero otherwise.
2274
2275    IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2276
2277    IS_SCALAR is nonzero if the data corresponds to a signed type.  */
2278
2279 static void
2280 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2281                           gdb_byte *unpacked, int unpacked_len,
2282                           int is_big_endian, int is_signed_type,
2283                           int is_scalar)
2284 {
2285   int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2286   int src_idx;                  /* Index into the source area */
2287   int src_bytes_left;           /* Number of source bytes left to process.  */
2288   int srcBitsLeft;              /* Number of source bits left to move */
2289   int unusedLS;                 /* Number of bits in next significant
2290                                    byte of source that are unused */
2291
2292   int unpacked_idx;             /* Index into the unpacked buffer */
2293   int unpacked_bytes_left;      /* Number of bytes left to set in unpacked.  */
2294
2295   unsigned long accum;          /* Staging area for bits being transferred */
2296   int accumSize;                /* Number of meaningful bits in accum */
2297   unsigned char sign;
2298
2299   /* Transmit bytes from least to most significant; delta is the direction
2300      the indices move.  */
2301   int delta = is_big_endian ? -1 : 1;
2302
2303   /* Make sure that unpacked is large enough to receive the BIT_SIZE
2304      bits from SRC.  .*/
2305   if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2306     error (_("Cannot unpack %d bits into buffer of %d bytes"),
2307            bit_size, unpacked_len);
2308
2309   srcBitsLeft = bit_size;
2310   src_bytes_left = src_len;
2311   unpacked_bytes_left = unpacked_len;
2312   sign = 0;
2313
2314   if (is_big_endian)
2315     {
2316       src_idx = src_len - 1;
2317       if (is_signed_type
2318           && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2319         sign = ~0;
2320
2321       unusedLS =
2322         (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2323         % HOST_CHAR_BIT;
2324
2325       if (is_scalar)
2326         {
2327           accumSize = 0;
2328           unpacked_idx = unpacked_len - 1;
2329         }
2330       else
2331         {
2332           /* Non-scalar values must be aligned at a byte boundary...  */
2333           accumSize =
2334             (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2335           /* ... And are placed at the beginning (most-significant) bytes
2336              of the target.  */
2337           unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2338           unpacked_bytes_left = unpacked_idx + 1;
2339         }
2340     }
2341   else
2342     {
2343       int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2344
2345       src_idx = unpacked_idx = 0;
2346       unusedLS = bit_offset;
2347       accumSize = 0;
2348
2349       if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2350         sign = ~0;
2351     }
2352
2353   accum = 0;
2354   while (src_bytes_left > 0)
2355     {
2356       /* Mask for removing bits of the next source byte that are not
2357          part of the value.  */
2358       unsigned int unusedMSMask =
2359         (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2360         1;
2361       /* Sign-extend bits for this byte.  */
2362       unsigned int signMask = sign & ~unusedMSMask;
2363
2364       accum |=
2365         (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2366       accumSize += HOST_CHAR_BIT - unusedLS;
2367       if (accumSize >= HOST_CHAR_BIT)
2368         {
2369           unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2370           accumSize -= HOST_CHAR_BIT;
2371           accum >>= HOST_CHAR_BIT;
2372           unpacked_bytes_left -= 1;
2373           unpacked_idx += delta;
2374         }
2375       srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2376       unusedLS = 0;
2377       src_bytes_left -= 1;
2378       src_idx += delta;
2379     }
2380   while (unpacked_bytes_left > 0)
2381     {
2382       accum |= sign << accumSize;
2383       unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2384       accumSize -= HOST_CHAR_BIT;
2385       if (accumSize < 0)
2386         accumSize = 0;
2387       accum >>= HOST_CHAR_BIT;
2388       unpacked_bytes_left -= 1;
2389       unpacked_idx += delta;
2390     }
2391 }
2392
2393 /* Create a new value of type TYPE from the contents of OBJ starting
2394    at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2395    proceeding for BIT_SIZE bits.  If OBJ is an lval in memory, then
2396    assigning through the result will set the field fetched from.
2397    VALADDR is ignored unless OBJ is NULL, in which case,
2398    VALADDR+OFFSET must address the start of storage containing the 
2399    packed value.  The value returned  in this case is never an lval.
2400    Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT.  */
2401
2402 struct value *
2403 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2404                                 long offset, int bit_offset, int bit_size,
2405                                 struct type *type)
2406 {
2407   struct value *v;
2408   const gdb_byte *src;                /* First byte containing data to unpack */
2409   gdb_byte *unpacked;
2410   const int is_scalar = is_scalar_type (type);
2411   const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2412   gdb::byte_vector staging;
2413
2414   type = ada_check_typedef (type);
2415
2416   if (obj == NULL)
2417     src = valaddr + offset;
2418   else
2419     src = value_contents (obj) + offset;
2420
2421   if (is_dynamic_type (type))
2422     {
2423       /* The length of TYPE might by dynamic, so we need to resolve
2424          TYPE in order to know its actual size, which we then use
2425          to create the contents buffer of the value we return.
2426          The difficulty is that the data containing our object is
2427          packed, and therefore maybe not at a byte boundary.  So, what
2428          we do, is unpack the data into a byte-aligned buffer, and then
2429          use that buffer as our object's value for resolving the type.  */
2430       int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2431       staging.resize (staging_len);
2432
2433       ada_unpack_from_contents (src, bit_offset, bit_size,
2434                                 staging.data (), staging.size (),
2435                                 is_big_endian, has_negatives (type),
2436                                 is_scalar);
2437       type = resolve_dynamic_type (type, staging, 0);
2438       if (TYPE_LENGTH (type) < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2439         {
2440           /* This happens when the length of the object is dynamic,
2441              and is actually smaller than the space reserved for it.
2442              For instance, in an array of variant records, the bit_size
2443              we're given is the array stride, which is constant and
2444              normally equal to the maximum size of its element.
2445              But, in reality, each element only actually spans a portion
2446              of that stride.  */
2447           bit_size = TYPE_LENGTH (type) * HOST_CHAR_BIT;
2448         }
2449     }
2450
2451   if (obj == NULL)
2452     {
2453       v = allocate_value (type);
2454       src = valaddr + offset;
2455     }
2456   else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2457     {
2458       int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2459       gdb_byte *buf;
2460
2461       v = value_at (type, value_address (obj) + offset);
2462       buf = (gdb_byte *) alloca (src_len);
2463       read_memory (value_address (v), buf, src_len);
2464       src = buf;
2465     }
2466   else
2467     {
2468       v = allocate_value (type);
2469       src = value_contents (obj) + offset;
2470     }
2471
2472   if (obj != NULL)
2473     {
2474       long new_offset = offset;
2475
2476       set_value_component_location (v, obj);
2477       set_value_bitpos (v, bit_offset + value_bitpos (obj));
2478       set_value_bitsize (v, bit_size);
2479       if (value_bitpos (v) >= HOST_CHAR_BIT)
2480         {
2481           ++new_offset;
2482           set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2483         }
2484       set_value_offset (v, new_offset);
2485
2486       /* Also set the parent value.  This is needed when trying to
2487          assign a new value (in inferior memory).  */
2488       set_value_parent (v, obj);
2489     }
2490   else
2491     set_value_bitsize (v, bit_size);
2492   unpacked = value_contents_writeable (v);
2493
2494   if (bit_size == 0)
2495     {
2496       memset (unpacked, 0, TYPE_LENGTH (type));
2497       return v;
2498     }
2499
2500   if (staging.size () == TYPE_LENGTH (type))
2501     {
2502       /* Small short-cut: If we've unpacked the data into a buffer
2503          of the same size as TYPE's length, then we can reuse that,
2504          instead of doing the unpacking again.  */
2505       memcpy (unpacked, staging.data (), staging.size ());
2506     }
2507   else
2508     ada_unpack_from_contents (src, bit_offset, bit_size,
2509                               unpacked, TYPE_LENGTH (type),
2510                               is_big_endian, has_negatives (type), is_scalar);
2511
2512   return v;
2513 }
2514
2515 /* Store the contents of FROMVAL into the location of TOVAL.
2516    Return a new value with the location of TOVAL and contents of
2517    FROMVAL.   Handles assignment into packed fields that have
2518    floating-point or non-scalar types.  */
2519
2520 static struct value *
2521 ada_value_assign (struct value *toval, struct value *fromval)
2522 {
2523   struct type *type = value_type (toval);
2524   int bits = value_bitsize (toval);
2525
2526   toval = ada_coerce_ref (toval);
2527   fromval = ada_coerce_ref (fromval);
2528
2529   if (ada_is_direct_array_type (value_type (toval)))
2530     toval = ada_coerce_to_simple_array (toval);
2531   if (ada_is_direct_array_type (value_type (fromval)))
2532     fromval = ada_coerce_to_simple_array (fromval);
2533
2534   if (!deprecated_value_modifiable (toval))
2535     error (_("Left operand of assignment is not a modifiable lvalue."));
2536
2537   if (VALUE_LVAL (toval) == lval_memory
2538       && bits > 0
2539       && (type->code () == TYPE_CODE_FLT
2540           || type->code () == TYPE_CODE_STRUCT))
2541     {
2542       int len = (value_bitpos (toval)
2543                  + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2544       int from_size;
2545       gdb_byte *buffer = (gdb_byte *) alloca (len);
2546       struct value *val;
2547       CORE_ADDR to_addr = value_address (toval);
2548
2549       if (type->code () == TYPE_CODE_FLT)
2550         fromval = value_cast (type, fromval);
2551
2552       read_memory (to_addr, buffer, len);
2553       from_size = value_bitsize (fromval);
2554       if (from_size == 0)
2555         from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2556
2557       const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2558       ULONGEST from_offset = 0;
2559       if (is_big_endian && is_scalar_type (value_type (fromval)))
2560         from_offset = from_size - bits;
2561       copy_bitwise (buffer, value_bitpos (toval),
2562                     value_contents (fromval), from_offset,
2563                     bits, is_big_endian);
2564       write_memory_with_notification (to_addr, buffer, len);
2565
2566       val = value_copy (toval);
2567       memcpy (value_contents_raw (val), value_contents (fromval),
2568               TYPE_LENGTH (type));
2569       deprecated_set_value_type (val, type);
2570
2571       return val;
2572     }
2573
2574   return value_assign (toval, fromval);
2575 }
2576
2577
2578 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2579    CONTAINER, assign the contents of VAL to COMPONENTS's place in
2580    CONTAINER.  Modifies the VALUE_CONTENTS of CONTAINER only, not
2581    COMPONENT, and not the inferior's memory.  The current contents
2582    of COMPONENT are ignored.
2583
2584    Although not part of the initial design, this function also works
2585    when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2586    had a null address, and COMPONENT had an address which is equal to
2587    its offset inside CONTAINER.  */
2588
2589 static void
2590 value_assign_to_component (struct value *container, struct value *component,
2591                            struct value *val)
2592 {
2593   LONGEST offset_in_container =
2594     (LONGEST)  (value_address (component) - value_address (container));
2595   int bit_offset_in_container =
2596     value_bitpos (component) - value_bitpos (container);
2597   int bits;
2598
2599   val = value_cast (value_type (component), val);
2600
2601   if (value_bitsize (component) == 0)
2602     bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2603   else
2604     bits = value_bitsize (component);
2605
2606   if (type_byte_order (value_type (container)) == BFD_ENDIAN_BIG)
2607     {
2608       int src_offset;
2609
2610       if (is_scalar_type (check_typedef (value_type (component))))
2611         src_offset
2612           = TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits;
2613       else
2614         src_offset = 0;
2615       copy_bitwise (value_contents_writeable (container) + offset_in_container,
2616                     value_bitpos (container) + bit_offset_in_container,
2617                     value_contents (val), src_offset, bits, 1);
2618     }
2619   else
2620     copy_bitwise (value_contents_writeable (container) + offset_in_container,
2621                   value_bitpos (container) + bit_offset_in_container,
2622                   value_contents (val), 0, bits, 0);
2623 }
2624
2625 /* Determine if TYPE is an access to an unconstrained array.  */
2626
2627 bool
2628 ada_is_access_to_unconstrained_array (struct type *type)
2629 {
2630   return (type->code () == TYPE_CODE_TYPEDEF
2631           && is_thick_pntr (ada_typedef_target_type (type)));
2632 }
2633
2634 /* The value of the element of array ARR at the ARITY indices given in IND.
2635    ARR may be either a simple array, GNAT array descriptor, or pointer
2636    thereto.  */
2637
2638 struct value *
2639 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2640 {
2641   int k;
2642   struct value *elt;
2643   struct type *elt_type;
2644
2645   elt = ada_coerce_to_simple_array (arr);
2646
2647   elt_type = ada_check_typedef (value_type (elt));
2648   if (elt_type->code () == TYPE_CODE_ARRAY
2649       && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2650     return value_subscript_packed (elt, arity, ind);
2651
2652   for (k = 0; k < arity; k += 1)
2653     {
2654       struct type *saved_elt_type = TYPE_TARGET_TYPE (elt_type);
2655
2656       if (elt_type->code () != TYPE_CODE_ARRAY)
2657         error (_("too many subscripts (%d expected)"), k);
2658
2659       elt = value_subscript (elt, pos_atr (ind[k]));
2660
2661       if (ada_is_access_to_unconstrained_array (saved_elt_type)
2662           && value_type (elt)->code () != TYPE_CODE_TYPEDEF)
2663         {
2664           /* The element is a typedef to an unconstrained array,
2665              except that the value_subscript call stripped the
2666              typedef layer.  The typedef layer is GNAT's way to
2667              specify that the element is, at the source level, an
2668              access to the unconstrained array, rather than the
2669              unconstrained array.  So, we need to restore that
2670              typedef layer, which we can do by forcing the element's
2671              type back to its original type. Otherwise, the returned
2672              value is going to be printed as the array, rather
2673              than as an access.  Another symptom of the same issue
2674              would be that an expression trying to dereference the
2675              element would also be improperly rejected.  */
2676           deprecated_set_value_type (elt, saved_elt_type);
2677         }
2678
2679       elt_type = ada_check_typedef (value_type (elt));
2680     }
2681
2682   return elt;
2683 }
2684
2685 /* Assuming ARR is a pointer to a GDB array, the value of the element
2686    of *ARR at the ARITY indices given in IND.
2687    Does not read the entire array into memory.
2688
2689    Note: Unlike what one would expect, this function is used instead of
2690    ada_value_subscript for basically all non-packed array types.  The reason
2691    for this is that a side effect of doing our own pointer arithmetics instead
2692    of relying on value_subscript is that there is no implicit typedef peeling.
2693    This is important for arrays of array accesses, where it allows us to
2694    preserve the fact that the array's element is an array access, where the
2695    access part os encoded in a typedef layer.  */
2696
2697 static struct value *
2698 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
2699 {
2700   int k;
2701   struct value *array_ind = ada_value_ind (arr);
2702   struct type *type
2703     = check_typedef (value_enclosing_type (array_ind));
2704
2705   if (type->code () == TYPE_CODE_ARRAY
2706       && TYPE_FIELD_BITSIZE (type, 0) > 0)
2707     return value_subscript_packed (array_ind, arity, ind);
2708
2709   for (k = 0; k < arity; k += 1)
2710     {
2711       LONGEST lwb, upb;
2712
2713       if (type->code () != TYPE_CODE_ARRAY)
2714         error (_("too many subscripts (%d expected)"), k);
2715       arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2716                         value_copy (arr));
2717       get_discrete_bounds (type->index_type (), &lwb, &upb);
2718       arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
2719       type = TYPE_TARGET_TYPE (type);
2720     }
2721
2722   return value_ind (arr);
2723 }
2724
2725 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2726    actual type of ARRAY_PTR is ignored), returns the Ada slice of
2727    HIGH'Pos-LOW'Pos+1 elements starting at index LOW.  The lower bound of
2728    this array is LOW, as per Ada rules.  */
2729 static struct value *
2730 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
2731                           int low, int high)
2732 {
2733   struct type *type0 = ada_check_typedef (type);
2734   struct type *base_index_type = TYPE_TARGET_TYPE (type0->index_type ());
2735   struct type *index_type
2736     = create_static_range_type (NULL, base_index_type, low, high);
2737   struct type *slice_type = create_array_type_with_stride
2738                               (NULL, TYPE_TARGET_TYPE (type0), index_type,
2739                                type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
2740                                TYPE_FIELD_BITSIZE (type0, 0));
2741   int base_low =  ada_discrete_type_low_bound (type0->index_type ());
2742   gdb::optional<LONGEST> base_low_pos, low_pos;
2743   CORE_ADDR base;
2744
2745   low_pos = discrete_position (base_index_type, low);
2746   base_low_pos = discrete_position (base_index_type, base_low);
2747
2748   if (!low_pos.has_value () || !base_low_pos.has_value ())
2749     {
2750       warning (_("unable to get positions in slice, use bounds instead"));
2751       low_pos = low;
2752       base_low_pos = base_low;
2753     }
2754
2755   ULONGEST stride = TYPE_FIELD_BITSIZE (slice_type, 0) / 8;
2756   if (stride == 0)
2757     stride = TYPE_LENGTH (TYPE_TARGET_TYPE (type0));
2758
2759   base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
2760   return value_at_lazy (slice_type, base);
2761 }
2762
2763
2764 static struct value *
2765 ada_value_slice (struct value *array, int low, int high)
2766 {
2767   struct type *type = ada_check_typedef (value_type (array));
2768   struct type *base_index_type = TYPE_TARGET_TYPE (type->index_type ());
2769   struct type *index_type
2770     = create_static_range_type (NULL, type->index_type (), low, high);
2771   struct type *slice_type = create_array_type_with_stride
2772                               (NULL, TYPE_TARGET_TYPE (type), index_type,
2773                                type->dyn_prop (DYN_PROP_BYTE_STRIDE),
2774                                TYPE_FIELD_BITSIZE (type, 0));
2775   gdb::optional<LONGEST> low_pos, high_pos;
2776
2777
2778   low_pos = discrete_position (base_index_type, low);
2779   high_pos = discrete_position (base_index_type, high);
2780
2781   if (!low_pos.has_value () || !high_pos.has_value ())
2782     {
2783       warning (_("unable to get positions in slice, use bounds instead"));
2784       low_pos = low;
2785       high_pos = high;
2786     }
2787
2788   return value_cast (slice_type,
2789                      value_slice (array, low, *high_pos - *low_pos + 1));
2790 }
2791
2792 /* If type is a record type in the form of a standard GNAT array
2793    descriptor, returns the number of dimensions for type.  If arr is a
2794    simple array, returns the number of "array of"s that prefix its
2795    type designation.  Otherwise, returns 0.  */
2796
2797 int
2798 ada_array_arity (struct type *type)
2799 {
2800   int arity;
2801
2802   if (type == NULL)
2803     return 0;
2804
2805   type = desc_base_type (type);
2806
2807   arity = 0;
2808   if (type->code () == TYPE_CODE_STRUCT)
2809     return desc_arity (desc_bounds_type (type));
2810   else
2811     while (type->code () == TYPE_CODE_ARRAY)
2812       {
2813         arity += 1;
2814         type = ada_check_typedef (TYPE_TARGET_TYPE (type));
2815       }
2816
2817   return arity;
2818 }
2819
2820 /* If TYPE is a record type in the form of a standard GNAT array
2821    descriptor or a simple array type, returns the element type for
2822    TYPE after indexing by NINDICES indices, or by all indices if
2823    NINDICES is -1.  Otherwise, returns NULL.  */
2824
2825 struct type *
2826 ada_array_element_type (struct type *type, int nindices)
2827 {
2828   type = desc_base_type (type);
2829
2830   if (type->code () == TYPE_CODE_STRUCT)
2831     {
2832       int k;
2833       struct type *p_array_type;
2834
2835       p_array_type = desc_data_target_type (type);
2836
2837       k = ada_array_arity (type);
2838       if (k == 0)
2839         return NULL;
2840
2841       /* Initially p_array_type = elt_type(*)[]...(k times)...[].  */
2842       if (nindices >= 0 && k > nindices)
2843         k = nindices;
2844       while (k > 0 && p_array_type != NULL)
2845         {
2846           p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
2847           k -= 1;
2848         }
2849       return p_array_type;
2850     }
2851   else if (type->code () == TYPE_CODE_ARRAY)
2852     {
2853       while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
2854         {
2855           type = TYPE_TARGET_TYPE (type);
2856           nindices -= 1;
2857         }
2858       return type;
2859     }
2860
2861   return NULL;
2862 }
2863
2864 /* See ada-lang.h.  */
2865
2866 struct type *
2867 ada_index_type (struct type *type, int n, const char *name)
2868 {
2869   struct type *result_type;
2870
2871   type = desc_base_type (type);
2872
2873   if (n < 0 || n > ada_array_arity (type))
2874     error (_("invalid dimension number to '%s"), name);
2875
2876   if (ada_is_simple_array_type (type))
2877     {
2878       int i;
2879
2880       for (i = 1; i < n; i += 1)
2881         {
2882           type = ada_check_typedef (type);
2883           type = TYPE_TARGET_TYPE (type);
2884         }
2885       result_type = TYPE_TARGET_TYPE (ada_check_typedef (type)->index_type ());
2886       /* FIXME: The stabs type r(0,0);bound;bound in an array type
2887          has a target type of TYPE_CODE_UNDEF.  We compensate here, but
2888          perhaps stabsread.c would make more sense.  */
2889       if (result_type && result_type->code () == TYPE_CODE_UNDEF)
2890         result_type = NULL;
2891     }
2892   else
2893     {
2894       result_type = desc_index_type (desc_bounds_type (type), n);
2895       if (result_type == NULL)
2896         error (_("attempt to take bound of something that is not an array"));
2897     }
2898
2899   return result_type;
2900 }
2901
2902 /* Given that arr is an array type, returns the lower bound of the
2903    Nth index (numbering from 1) if WHICH is 0, and the upper bound if
2904    WHICH is 1.  This returns bounds 0 .. -1 if ARR_TYPE is an
2905    array-descriptor type.  It works for other arrays with bounds supplied
2906    by run-time quantities other than discriminants.  */
2907
2908 static LONGEST
2909 ada_array_bound_from_type (struct type *arr_type, int n, int which)
2910 {
2911   struct type *type, *index_type_desc, *index_type;
2912   int i;
2913
2914   gdb_assert (which == 0 || which == 1);
2915
2916   if (ada_is_constrained_packed_array_type (arr_type))
2917     arr_type = decode_constrained_packed_array_type (arr_type);
2918
2919   if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
2920     return (LONGEST) - which;
2921
2922   if (arr_type->code () == TYPE_CODE_PTR)
2923     type = TYPE_TARGET_TYPE (arr_type);
2924   else
2925     type = arr_type;
2926
2927   if (type->is_fixed_instance ())
2928     {
2929       /* The array has already been fixed, so we do not need to
2930          check the parallel ___XA type again.  That encoding has
2931          already been applied, so ignore it now.  */
2932       index_type_desc = NULL;
2933     }
2934   else
2935     {
2936       index_type_desc = ada_find_parallel_type (type, "___XA");
2937       ada_fixup_array_indexes_type (index_type_desc);
2938     }
2939
2940   if (index_type_desc != NULL)
2941     index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
2942                                       NULL);
2943   else
2944     {
2945       struct type *elt_type = check_typedef (type);
2946
2947       for (i = 1; i < n; i++)
2948         elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
2949
2950       index_type = elt_type->index_type ();
2951     }
2952
2953   return
2954     (LONGEST) (which == 0
2955                ? ada_discrete_type_low_bound (index_type)
2956                : ada_discrete_type_high_bound (index_type));
2957 }
2958
2959 /* Given that arr is an array value, returns the lower bound of the
2960    nth index (numbering from 1) if WHICH is 0, and the upper bound if
2961    WHICH is 1.  This routine will also work for arrays with bounds
2962    supplied by run-time quantities other than discriminants.  */
2963
2964 static LONGEST
2965 ada_array_bound (struct value *arr, int n, int which)
2966 {
2967   struct type *arr_type;
2968
2969   if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2970     arr = value_ind (arr);
2971   arr_type = value_enclosing_type (arr);
2972
2973   if (ada_is_constrained_packed_array_type (arr_type))
2974     return ada_array_bound (decode_constrained_packed_array (arr), n, which);
2975   else if (ada_is_simple_array_type (arr_type))
2976     return ada_array_bound_from_type (arr_type, n, which);
2977   else
2978     return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
2979 }
2980
2981 /* Given that arr is an array value, returns the length of the
2982    nth index.  This routine will also work for arrays with bounds
2983    supplied by run-time quantities other than discriminants.
2984    Does not work for arrays indexed by enumeration types with representation
2985    clauses at the moment.  */
2986
2987 static LONGEST
2988 ada_array_length (struct value *arr, int n)
2989 {
2990   struct type *arr_type, *index_type;
2991   int low, high;
2992
2993   if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2994     arr = value_ind (arr);
2995   arr_type = value_enclosing_type (arr);
2996
2997   if (ada_is_constrained_packed_array_type (arr_type))
2998     return ada_array_length (decode_constrained_packed_array (arr), n);
2999
3000   if (ada_is_simple_array_type (arr_type))
3001     {
3002       low = ada_array_bound_from_type (arr_type, n, 0);
3003       high = ada_array_bound_from_type (arr_type, n, 1);
3004     }
3005   else
3006     {
3007       low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3008       high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3009     }
3010
3011   arr_type = check_typedef (arr_type);
3012   index_type = ada_index_type (arr_type, n, "length");
3013   if (index_type != NULL)
3014     {
3015       struct type *base_type;
3016       if (index_type->code () == TYPE_CODE_RANGE)
3017         base_type = TYPE_TARGET_TYPE (index_type);
3018       else
3019         base_type = index_type;
3020
3021       low = pos_atr (value_from_longest (base_type, low));
3022       high = pos_atr (value_from_longest (base_type, high));
3023     }
3024   return high - low + 1;
3025 }
3026
3027 /* An array whose type is that of ARR_TYPE (an array type), with
3028    bounds LOW to HIGH, but whose contents are unimportant.  If HIGH is
3029    less than LOW, then LOW-1 is used.  */
3030
3031 static struct value *
3032 empty_array (struct type *arr_type, int low, int high)
3033 {
3034   struct type *arr_type0 = ada_check_typedef (arr_type);
3035   struct type *index_type
3036     = create_static_range_type
3037         (NULL, TYPE_TARGET_TYPE (arr_type0->index_type ()), low,
3038          high < low ? low - 1 : high);
3039   struct type *elt_type = ada_array_element_type (arr_type0, 1);
3040
3041   return allocate_value (create_array_type (NULL, elt_type, index_type));
3042 }
3043 \f
3044
3045                                 /* Name resolution */
3046
3047 /* The "decoded" name for the user-definable Ada operator corresponding
3048    to OP.  */
3049
3050 static const char *
3051 ada_decoded_op_name (enum exp_opcode op)
3052 {
3053   int i;
3054
3055   for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3056     {
3057       if (ada_opname_table[i].op == op)
3058         return ada_opname_table[i].decoded;
3059     }
3060   error (_("Could not find operator name for opcode"));
3061 }
3062
3063 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3064    in a listing of choices during disambiguation (see sort_choices, below).
3065    The idea is that overloadings of a subprogram name from the
3066    same package should sort in their source order.  We settle for ordering
3067    such symbols by their trailing number (__N  or $N).  */
3068
3069 static int
3070 encoded_ordered_before (const char *N0, const char *N1)
3071 {
3072   if (N1 == NULL)
3073     return 0;
3074   else if (N0 == NULL)
3075     return 1;
3076   else
3077     {
3078       int k0, k1;
3079
3080       for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3081         ;
3082       for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3083         ;
3084       if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3085           && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3086         {
3087           int n0, n1;
3088
3089           n0 = k0;
3090           while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3091             n0 -= 1;
3092           n1 = k1;
3093           while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3094             n1 -= 1;
3095           if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3096             return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3097         }
3098       return (strcmp (N0, N1) < 0);
3099     }
3100 }
3101
3102 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3103    encoded names.  */
3104
3105 static void
3106 sort_choices (struct block_symbol syms[], int nsyms)
3107 {
3108   int i;
3109
3110   for (i = 1; i < nsyms; i += 1)
3111     {
3112       struct block_symbol sym = syms[i];
3113       int j;
3114
3115       for (j = i - 1; j >= 0; j -= 1)
3116         {
3117           if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3118                                       sym.symbol->linkage_name ()))
3119             break;
3120           syms[j + 1] = syms[j];
3121         }
3122       syms[j + 1] = sym;
3123     }
3124 }
3125
3126 /* Whether GDB should display formals and return types for functions in the
3127    overloads selection menu.  */
3128 static bool print_signatures = true;
3129
3130 /* Print the signature for SYM on STREAM according to the FLAGS options.  For
3131    all but functions, the signature is just the name of the symbol.  For
3132    functions, this is the name of the function, the list of types for formals
3133    and the return type (if any).  */
3134
3135 static void
3136 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3137                             const struct type_print_options *flags)
3138 {
3139   struct type *type = SYMBOL_TYPE (sym);
3140
3141   fprintf_filtered (stream, "%s", sym->print_name ());
3142   if (!print_signatures
3143       || type == NULL
3144       || type->code () != TYPE_CODE_FUNC)
3145     return;
3146
3147   if (type->num_fields () > 0)
3148     {
3149       int i;
3150
3151       fprintf_filtered (stream, " (");
3152       for (i = 0; i < type->num_fields (); ++i)
3153         {
3154           if (i > 0)
3155             fprintf_filtered (stream, "; ");
3156           ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3157                           flags);
3158         }
3159       fprintf_filtered (stream, ")");
3160     }
3161   if (TYPE_TARGET_TYPE (type) != NULL
3162       && TYPE_TARGET_TYPE (type)->code () != TYPE_CODE_VOID)
3163     {
3164       fprintf_filtered (stream, " return ");
3165       ada_print_type (TYPE_TARGET_TYPE (type), NULL, stream, -1, 0, flags);
3166     }
3167 }
3168
3169 /* Read and validate a set of numeric choices from the user in the
3170    range 0 .. N_CHOICES-1.  Place the results in increasing
3171    order in CHOICES[0 .. N-1], and return N.
3172
3173    The user types choices as a sequence of numbers on one line
3174    separated by blanks, encoding them as follows:
3175
3176      + A choice of 0 means to cancel the selection, throwing an error.
3177      + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3178      + The user chooses k by typing k+IS_ALL_CHOICE+1.
3179
3180    The user is not allowed to choose more than MAX_RESULTS values.
3181
3182    ANNOTATION_SUFFIX, if present, is used to annotate the input
3183    prompts (for use with the -f switch).  */
3184
3185 static int
3186 get_selections (int *choices, int n_choices, int max_results,
3187                 int is_all_choice, const char *annotation_suffix)
3188 {
3189   const char *args;
3190   const char *prompt;
3191   int n_chosen;
3192   int first_choice = is_all_choice ? 2 : 1;
3193
3194   prompt = getenv ("PS2");
3195   if (prompt == NULL)
3196     prompt = "> ";
3197
3198   args = command_line_input (prompt, annotation_suffix);
3199
3200   if (args == NULL)
3201     error_no_arg (_("one or more choice numbers"));
3202
3203   n_chosen = 0;
3204
3205   /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3206      order, as given in args.  Choices are validated.  */
3207   while (1)
3208     {
3209       char *args2;
3210       int choice, j;
3211
3212       args = skip_spaces (args);
3213       if (*args == '\0' && n_chosen == 0)
3214         error_no_arg (_("one or more choice numbers"));
3215       else if (*args == '\0')
3216         break;
3217
3218       choice = strtol (args, &args2, 10);
3219       if (args == args2 || choice < 0
3220           || choice > n_choices + first_choice - 1)
3221         error (_("Argument must be choice number"));
3222       args = args2;
3223
3224       if (choice == 0)
3225         error (_("cancelled"));
3226
3227       if (choice < first_choice)
3228         {
3229           n_chosen = n_choices;
3230           for (j = 0; j < n_choices; j += 1)
3231             choices[j] = j;
3232           break;
3233         }
3234       choice -= first_choice;
3235
3236       for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3237         {
3238         }
3239
3240       if (j < 0 || choice != choices[j])
3241         {
3242           int k;
3243
3244           for (k = n_chosen - 1; k > j; k -= 1)
3245             choices[k + 1] = choices[k];
3246           choices[j + 1] = choice;
3247           n_chosen += 1;
3248         }
3249     }
3250
3251   if (n_chosen > max_results)
3252     error (_("Select no more than %d of the above"), max_results);
3253
3254   return n_chosen;
3255 }
3256
3257 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3258    by asking the user (if necessary), returning the number selected,
3259    and setting the first elements of SYMS items.  Error if no symbols
3260    selected.  */
3261
3262 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3263    to be re-integrated one of these days.  */
3264
3265 static int
3266 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3267 {
3268   int i;
3269   int *chosen = XALLOCAVEC (int , nsyms);
3270   int n_chosen;
3271   int first_choice = (max_results == 1) ? 1 : 2;
3272   const char *select_mode = multiple_symbols_select_mode ();
3273
3274   if (max_results < 1)
3275     error (_("Request to select 0 symbols!"));
3276   if (nsyms <= 1)
3277     return nsyms;
3278
3279   if (select_mode == multiple_symbols_cancel)
3280     error (_("\
3281 canceled because the command is ambiguous\n\
3282 See set/show multiple-symbol."));
3283
3284   /* If select_mode is "all", then return all possible symbols.
3285      Only do that if more than one symbol can be selected, of course.
3286      Otherwise, display the menu as usual.  */
3287   if (select_mode == multiple_symbols_all && max_results > 1)
3288     return nsyms;
3289
3290   printf_filtered (_("[0] cancel\n"));
3291   if (max_results > 1)
3292     printf_filtered (_("[1] all\n"));
3293
3294   sort_choices (syms, nsyms);
3295
3296   for (i = 0; i < nsyms; i += 1)
3297     {
3298       if (syms[i].symbol == NULL)
3299         continue;
3300
3301       if (SYMBOL_CLASS (syms[i].symbol) == LOC_BLOCK)
3302         {
3303           struct symtab_and_line sal =
3304             find_function_start_sal (syms[i].symbol, 1);
3305
3306           printf_filtered ("[%d] ", i + first_choice);
3307           ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3308                                       &type_print_raw_options);
3309           if (sal.symtab == NULL)
3310             printf_filtered (_(" at %p[<no source file available>%p]:%d\n"),
3311                              metadata_style.style ().ptr (), nullptr, sal.line);
3312           else
3313             printf_filtered
3314               (_(" at %ps:%d\n"),
3315                styled_string (file_name_style.style (),
3316                               symtab_to_filename_for_display (sal.symtab)),
3317                sal.line);
3318           continue;
3319         }
3320       else
3321         {
3322           int is_enumeral =
3323             (SYMBOL_CLASS (syms[i].symbol) == LOC_CONST
3324              && SYMBOL_TYPE (syms[i].symbol) != NULL
3325              && SYMBOL_TYPE (syms[i].symbol)->code () == TYPE_CODE_ENUM);
3326           struct symtab *symtab = NULL;
3327
3328           if (SYMBOL_OBJFILE_OWNED (syms[i].symbol))
3329             symtab = symbol_symtab (syms[i].symbol);
3330
3331           if (SYMBOL_LINE (syms[i].symbol) != 0 && symtab != NULL)
3332             {
3333               printf_filtered ("[%d] ", i + first_choice);
3334               ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3335                                           &type_print_raw_options);
3336               printf_filtered (_(" at %s:%d\n"),
3337                                symtab_to_filename_for_display (symtab),
3338                                SYMBOL_LINE (syms[i].symbol));
3339             }
3340           else if (is_enumeral
3341                    && SYMBOL_TYPE (syms[i].symbol)->name () != NULL)
3342             {
3343               printf_filtered (("[%d] "), i + first_choice);
3344               ada_print_type (SYMBOL_TYPE (syms[i].symbol), NULL,
3345                               gdb_stdout, -1, 0, &type_print_raw_options);
3346               printf_filtered (_("'(%s) (enumeral)\n"),
3347                                syms[i].symbol->print_name ());
3348             }
3349           else
3350             {
3351               printf_filtered ("[%d] ", i + first_choice);
3352               ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3353                                           &type_print_raw_options);
3354
3355               if (symtab != NULL)
3356                 printf_filtered (is_enumeral
3357                                  ? _(" in %s (enumeral)\n")
3358                                  : _(" at %s:?\n"),
3359                                  symtab_to_filename_for_display (symtab));
3360               else
3361                 printf_filtered (is_enumeral
3362                                  ? _(" (enumeral)\n")
3363                                  : _(" at ?\n"));
3364             }
3365         }
3366     }
3367
3368   n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3369                              "overload-choice");
3370
3371   for (i = 0; i < n_chosen; i += 1)
3372     syms[i] = syms[chosen[i]];
3373
3374   return n_chosen;
3375 }
3376
3377 /* See ada-lang.h.  */
3378
3379 block_symbol
3380 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3381                           int nargs, value *argvec[])
3382 {
3383   if (possible_user_operator_p (op, argvec))
3384     {
3385       std::vector<struct block_symbol> candidates
3386         = ada_lookup_symbol_list (ada_decoded_op_name (op),
3387                                   NULL, VAR_DOMAIN);
3388
3389       int i = ada_resolve_function (candidates, argvec,
3390                                     nargs, ada_decoded_op_name (op), NULL,
3391                                     parse_completion);
3392       if (i >= 0)
3393         return candidates[i];
3394     }
3395   return {};
3396 }
3397
3398 /* See ada-lang.h.  */
3399
3400 block_symbol
3401 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3402                      struct type *context_type,
3403                      bool parse_completion,
3404                      int nargs, value *argvec[],
3405                      innermost_block_tracker *tracker)
3406 {
3407   std::vector<struct block_symbol> candidates
3408     = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3409
3410   int i;
3411   if (candidates.size () == 1)
3412     i = 0;
3413   else
3414     {
3415       i = ada_resolve_function
3416         (candidates,
3417          argvec, nargs,
3418          sym->linkage_name (),
3419          context_type, parse_completion);
3420       if (i < 0)
3421         error (_("Could not find a match for %s"), sym->print_name ());
3422     }
3423
3424   tracker->update (candidates[i]);
3425   return candidates[i];
3426 }
3427
3428 /* Resolve a mention of a name where the context type is an
3429    enumeration type.  */
3430
3431 static int
3432 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3433                   const char *name, struct type *context_type,
3434                   bool parse_completion)
3435 {
3436   gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3437   context_type = ada_check_typedef (context_type);
3438
3439   for (int i = 0; i < syms.size (); ++i)
3440     {
3441       /* We already know the name matches, so we're just looking for
3442          an element of the correct enum type.  */
3443       if (ada_check_typedef (SYMBOL_TYPE (syms[i].symbol)) == context_type)
3444         return i;
3445     }
3446
3447   error (_("No name '%s' in enumeration type '%s'"), name,
3448          ada_type_name (context_type));
3449 }
3450
3451 /* See ada-lang.h.  */
3452
3453 block_symbol
3454 ada_resolve_variable (struct symbol *sym, const struct block *block,
3455                       struct type *context_type,
3456                       bool parse_completion,
3457                       int deprocedure_p,
3458                       innermost_block_tracker *tracker)
3459 {
3460   std::vector<struct block_symbol> candidates
3461     = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3462
3463   if (std::any_of (candidates.begin (),
3464                    candidates.end (),
3465                    [] (block_symbol &bsym)
3466                    {
3467                      switch (SYMBOL_CLASS (bsym.symbol))
3468                        {
3469                        case LOC_REGISTER:
3470                        case LOC_ARG:
3471                        case LOC_REF_ARG:
3472                        case LOC_REGPARM_ADDR:
3473                        case LOC_LOCAL:
3474                        case LOC_COMPUTED:
3475                          return true;
3476                        default:
3477                          return false;
3478                        }
3479                    }))
3480     {
3481       /* Types tend to get re-introduced locally, so if there
3482          are any local symbols that are not types, first filter
3483          out all types.  */
3484       candidates.erase
3485         (std::remove_if
3486          (candidates.begin (),
3487           candidates.end (),
3488           [] (block_symbol &bsym)
3489           {
3490             return SYMBOL_CLASS (bsym.symbol) == LOC_TYPEDEF;
3491           }),
3492          candidates.end ());
3493     }
3494
3495   int i;
3496   if (candidates.empty ())
3497     error (_("No definition found for %s"), sym->print_name ());
3498   else if (candidates.size () == 1)
3499     i = 0;
3500   else if (context_type != nullptr
3501            && context_type->code () == TYPE_CODE_ENUM)
3502     i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3503                           parse_completion);
3504   else if (deprocedure_p && !is_nonfunction (candidates))
3505     {
3506       i = ada_resolve_function
3507         (candidates, NULL, 0,
3508          sym->linkage_name (),
3509          context_type, parse_completion);
3510       if (i < 0)
3511         error (_("Could not find a match for %s"), sym->print_name ());
3512     }
3513   else
3514     {
3515       printf_filtered (_("Multiple matches for %s\n"), sym->print_name ());
3516       user_select_syms (candidates.data (), candidates.size (), 1);
3517       i = 0;
3518     }
3519
3520   tracker->update (candidates[i]);
3521   return candidates[i];
3522 }
3523
3524 /* Return non-zero if formal type FTYPE matches actual type ATYPE.  */
3525 /* The term "match" here is rather loose.  The match is heuristic and
3526    liberal.  */
3527
3528 static int
3529 ada_type_match (struct type *ftype, struct type *atype)
3530 {
3531   ftype = ada_check_typedef (ftype);
3532   atype = ada_check_typedef (atype);
3533
3534   if (ftype->code () == TYPE_CODE_REF)
3535     ftype = TYPE_TARGET_TYPE (ftype);
3536   if (atype->code () == TYPE_CODE_REF)
3537     atype = TYPE_TARGET_TYPE (atype);
3538
3539   switch (ftype->code ())
3540     {
3541     default:
3542       return ftype->code () == atype->code ();
3543     case TYPE_CODE_PTR:
3544       if (atype->code () != TYPE_CODE_PTR)
3545         return 0;
3546       atype = TYPE_TARGET_TYPE (atype);
3547       /* This can only happen if the actual argument is 'null'.  */
3548       if (atype->code () == TYPE_CODE_INT && TYPE_LENGTH (atype) == 0)
3549         return 1;
3550       return ada_type_match (TYPE_TARGET_TYPE (ftype), atype);
3551     case TYPE_CODE_INT:
3552     case TYPE_CODE_ENUM:
3553     case TYPE_CODE_RANGE:
3554       switch (atype->code ())
3555         {
3556         case TYPE_CODE_INT:
3557         case TYPE_CODE_ENUM:
3558         case TYPE_CODE_RANGE:
3559           return 1;
3560         default:
3561           return 0;
3562         }
3563
3564     case TYPE_CODE_ARRAY:
3565       return (atype->code () == TYPE_CODE_ARRAY
3566               || ada_is_array_descriptor_type (atype));
3567
3568     case TYPE_CODE_STRUCT:
3569       if (ada_is_array_descriptor_type (ftype))
3570         return (atype->code () == TYPE_CODE_ARRAY
3571                 || ada_is_array_descriptor_type (atype));
3572       else
3573         return (atype->code () == TYPE_CODE_STRUCT
3574                 && !ada_is_array_descriptor_type (atype));
3575
3576     case TYPE_CODE_UNION:
3577     case TYPE_CODE_FLT:
3578       return (atype->code () == ftype->code ());
3579     }
3580 }
3581
3582 /* Return non-zero if the formals of FUNC "sufficiently match" the
3583    vector of actual argument types ACTUALS of size N_ACTUALS.  FUNC
3584    may also be an enumeral, in which case it is treated as a 0-
3585    argument function.  */
3586
3587 static int
3588 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3589 {
3590   int i;
3591   struct type *func_type = SYMBOL_TYPE (func);
3592
3593   if (SYMBOL_CLASS (func) == LOC_CONST
3594       && func_type->code () == TYPE_CODE_ENUM)
3595     return (n_actuals == 0);
3596   else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
3597     return 0;
3598
3599   if (func_type->num_fields () != n_actuals)
3600     return 0;
3601
3602   for (i = 0; i < n_actuals; i += 1)
3603     {
3604       if (actuals[i] == NULL)
3605         return 0;
3606       else
3607         {
3608           struct type *ftype = ada_check_typedef (func_type->field (i).type ());
3609           struct type *atype = ada_check_typedef (value_type (actuals[i]));
3610
3611           if (!ada_type_match (ftype, atype))
3612             return 0;
3613         }
3614     }
3615   return 1;
3616 }
3617
3618 /* False iff function type FUNC_TYPE definitely does not produce a value
3619    compatible with type CONTEXT_TYPE.  Conservatively returns 1 if
3620    FUNC_TYPE is not a valid function type with a non-null return type
3621    or an enumerated type.  A null CONTEXT_TYPE indicates any non-void type.  */
3622
3623 static int
3624 return_match (struct type *func_type, struct type *context_type)
3625 {
3626   struct type *return_type;
3627
3628   if (func_type == NULL)
3629     return 1;
3630
3631   if (func_type->code () == TYPE_CODE_FUNC)
3632     return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
3633   else
3634     return_type = get_base_type (func_type);
3635   if (return_type == NULL)
3636     return 1;
3637
3638   context_type = get_base_type (context_type);
3639
3640   if (return_type->code () == TYPE_CODE_ENUM)
3641     return context_type == NULL || return_type == context_type;
3642   else if (context_type == NULL)
3643     return return_type->code () != TYPE_CODE_VOID;
3644   else
3645     return return_type->code () == context_type->code ();
3646 }
3647
3648
3649 /* Returns the index in SYMS that contains the symbol for the
3650    function (if any) that matches the types of the NARGS arguments in
3651    ARGS.  If CONTEXT_TYPE is non-null and there is at least one match
3652    that returns that type, then eliminate matches that don't.  If
3653    CONTEXT_TYPE is void and there is at least one match that does not
3654    return void, eliminate all matches that do.
3655
3656    Asks the user if there is more than one match remaining.  Returns -1
3657    if there is no such symbol or none is selected.  NAME is used
3658    solely for messages.  May re-arrange and modify SYMS in
3659    the process; the index returned is for the modified vector.  */
3660
3661 static int
3662 ada_resolve_function (std::vector<struct block_symbol> &syms,
3663                       struct value **args, int nargs,
3664                       const char *name, struct type *context_type,
3665                       bool parse_completion)
3666 {
3667   int fallback;
3668   int k;
3669   int m;                        /* Number of hits */
3670
3671   m = 0;
3672   /* In the first pass of the loop, we only accept functions matching
3673      context_type.  If none are found, we add a second pass of the loop
3674      where every function is accepted.  */
3675   for (fallback = 0; m == 0 && fallback < 2; fallback++)
3676     {
3677       for (k = 0; k < syms.size (); k += 1)
3678         {
3679           struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].symbol));
3680
3681           if (ada_args_match (syms[k].symbol, args, nargs)
3682               && (fallback || return_match (type, context_type)))
3683             {
3684               syms[m] = syms[k];
3685               m += 1;
3686             }
3687         }
3688     }
3689
3690   /* If we got multiple matches, ask the user which one to use.  Don't do this
3691      interactive thing during completion, though, as the purpose of the
3692      completion is providing a list of all possible matches.  Prompting the
3693      user to filter it down would be completely unexpected in this case.  */
3694   if (m == 0)
3695     return -1;
3696   else if (m > 1 && !parse_completion)
3697     {
3698       printf_filtered (_("Multiple matches for %s\n"), name);
3699       user_select_syms (syms.data (), m, 1);
3700       return 0;
3701     }
3702   return 0;
3703 }
3704
3705 /* Type-class predicates */
3706
3707 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
3708    or FLOAT).  */
3709
3710 static int
3711 numeric_type_p (struct type *type)
3712 {
3713   if (type == NULL)
3714     return 0;
3715   else
3716     {
3717       switch (type->code ())
3718         {
3719         case TYPE_CODE_INT:
3720         case TYPE_CODE_FLT:
3721         case TYPE_CODE_FIXED_POINT:
3722           return 1;
3723         case TYPE_CODE_RANGE:
3724           return (type == TYPE_TARGET_TYPE (type)
3725                   || numeric_type_p (TYPE_TARGET_TYPE (type)));
3726         default:
3727           return 0;
3728         }
3729     }
3730 }
3731
3732 /* True iff TYPE is integral (an INT or RANGE of INTs).  */
3733
3734 static int
3735 integer_type_p (struct type *type)
3736 {
3737   if (type == NULL)
3738     return 0;
3739   else
3740     {
3741       switch (type->code ())
3742         {
3743         case TYPE_CODE_INT:
3744           return 1;
3745         case TYPE_CODE_RANGE:
3746           return (type == TYPE_TARGET_TYPE (type)
3747                   || integer_type_p (TYPE_TARGET_TYPE (type)));
3748         default:
3749           return 0;
3750         }
3751     }
3752 }
3753
3754 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM).  */
3755
3756 static int
3757 scalar_type_p (struct type *type)
3758 {
3759   if (type == NULL)
3760     return 0;
3761   else
3762     {
3763       switch (type->code ())
3764         {
3765         case TYPE_CODE_INT:
3766         case TYPE_CODE_RANGE:
3767         case TYPE_CODE_ENUM:
3768         case TYPE_CODE_FLT:
3769         case TYPE_CODE_FIXED_POINT:
3770           return 1;
3771         default:
3772           return 0;
3773         }
3774     }
3775 }
3776
3777 /* True iff TYPE is discrete (INT, RANGE, ENUM).  */
3778
3779 static int
3780 discrete_type_p (struct type *type)
3781 {
3782   if (type == NULL)
3783     return 0;
3784   else
3785     {
3786       switch (type->code ())
3787         {
3788         case TYPE_CODE_INT:
3789         case TYPE_CODE_RANGE:
3790         case TYPE_CODE_ENUM:
3791         case TYPE_CODE_BOOL:
3792           return 1;
3793         default:
3794           return 0;
3795         }
3796     }
3797 }
3798
3799 /* Returns non-zero if OP with operands in the vector ARGS could be
3800    a user-defined function.  Errs on the side of pre-defined operators
3801    (i.e., result 0).  */
3802
3803 static int
3804 possible_user_operator_p (enum exp_opcode op, struct value *args[])
3805 {
3806   struct type *type0 =
3807     (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
3808   struct type *type1 =
3809     (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
3810
3811   if (type0 == NULL)
3812     return 0;
3813
3814   switch (op)
3815     {
3816     default:
3817       return 0;
3818
3819     case BINOP_ADD:
3820     case BINOP_SUB:
3821     case BINOP_MUL:
3822     case BINOP_DIV:
3823       return (!(numeric_type_p (type0) && numeric_type_p (type1)));
3824
3825     case BINOP_REM:
3826     case BINOP_MOD:
3827     case BINOP_BITWISE_AND:
3828     case BINOP_BITWISE_IOR:
3829     case BINOP_BITWISE_XOR:
3830       return (!(integer_type_p (type0) && integer_type_p (type1)));
3831
3832     case BINOP_EQUAL:
3833     case BINOP_NOTEQUAL:
3834     case BINOP_LESS:
3835     case BINOP_GTR:
3836     case BINOP_LEQ:
3837     case BINOP_GEQ:
3838       return (!(scalar_type_p (type0) && scalar_type_p (type1)));
3839
3840     case BINOP_CONCAT:
3841       return !ada_is_array_type (type0) || !ada_is_array_type (type1);
3842
3843     case BINOP_EXP:
3844       return (!(numeric_type_p (type0) && integer_type_p (type1)));
3845
3846     case UNOP_NEG:
3847     case UNOP_PLUS:
3848     case UNOP_LOGICAL_NOT:
3849     case UNOP_ABS:
3850       return (!numeric_type_p (type0));
3851
3852     }
3853 }
3854 \f
3855                                 /* Renaming */
3856
3857 /* NOTES: 
3858
3859    1. In the following, we assume that a renaming type's name may
3860       have an ___XD suffix.  It would be nice if this went away at some
3861       point.
3862    2. We handle both the (old) purely type-based representation of 
3863       renamings and the (new) variable-based encoding.  At some point,
3864       it is devoutly to be hoped that the former goes away 
3865       (FIXME: hilfinger-2007-07-09).
3866    3. Subprogram renamings are not implemented, although the XRS
3867       suffix is recognized (FIXME: hilfinger-2007-07-09).  */
3868
3869 /* If SYM encodes a renaming, 
3870
3871        <renaming> renames <renamed entity>,
3872
3873    sets *LEN to the length of the renamed entity's name,
3874    *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
3875    the string describing the subcomponent selected from the renamed
3876    entity.  Returns ADA_NOT_RENAMING if SYM does not encode a renaming
3877    (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
3878    are undefined).  Otherwise, returns a value indicating the category
3879    of entity renamed: an object (ADA_OBJECT_RENAMING), exception
3880    (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
3881    subprogram (ADA_SUBPROGRAM_RENAMING).  Does no allocation; the
3882    strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
3883    deallocated.  The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
3884    may be NULL, in which case they are not assigned.
3885
3886    [Currently, however, GCC does not generate subprogram renamings.]  */
3887
3888 enum ada_renaming_category
3889 ada_parse_renaming (struct symbol *sym,
3890                     const char **renamed_entity, int *len, 
3891                     const char **renaming_expr)
3892 {
3893   enum ada_renaming_category kind;
3894   const char *info;
3895   const char *suffix;
3896
3897   if (sym == NULL)
3898     return ADA_NOT_RENAMING;
3899   switch (SYMBOL_CLASS (sym)) 
3900     {
3901     default:
3902       return ADA_NOT_RENAMING;
3903     case LOC_LOCAL:
3904     case LOC_STATIC:
3905     case LOC_COMPUTED:
3906     case LOC_OPTIMIZED_OUT:
3907       info = strstr (sym->linkage_name (), "___XR");
3908       if (info == NULL)
3909         return ADA_NOT_RENAMING;
3910       switch (info[5])
3911         {
3912         case '_':
3913           kind = ADA_OBJECT_RENAMING;
3914           info += 6;
3915           break;
3916         case 'E':
3917           kind = ADA_EXCEPTION_RENAMING;
3918           info += 7;
3919           break;
3920         case 'P':
3921           kind = ADA_PACKAGE_RENAMING;
3922           info += 7;
3923           break;
3924         case 'S':
3925           kind = ADA_SUBPROGRAM_RENAMING;
3926           info += 7;
3927           break;
3928         default:
3929           return ADA_NOT_RENAMING;
3930         }
3931     }
3932
3933   if (renamed_entity != NULL)
3934     *renamed_entity = info;
3935   suffix = strstr (info, "___XE");
3936   if (suffix == NULL || suffix == info)
3937     return ADA_NOT_RENAMING;
3938   if (len != NULL)
3939     *len = strlen (info) - strlen (suffix);
3940   suffix += 5;
3941   if (renaming_expr != NULL)
3942     *renaming_expr = suffix;
3943   return kind;
3944 }
3945
3946 /* Compute the value of the given RENAMING_SYM, which is expected to
3947    be a symbol encoding a renaming expression.  BLOCK is the block
3948    used to evaluate the renaming.  */
3949
3950 static struct value *
3951 ada_read_renaming_var_value (struct symbol *renaming_sym,
3952                              const struct block *block)
3953 {
3954   const char *sym_name;
3955
3956   sym_name = renaming_sym->linkage_name ();
3957   expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
3958   return evaluate_expression (expr.get ());
3959 }
3960 \f
3961
3962                                 /* Evaluation: Function Calls */
3963
3964 /* Return an lvalue containing the value VAL.  This is the identity on
3965    lvalues, and otherwise has the side-effect of allocating memory
3966    in the inferior where a copy of the value contents is copied.  */
3967
3968 static struct value *
3969 ensure_lval (struct value *val)
3970 {
3971   if (VALUE_LVAL (val) == not_lval
3972       || VALUE_LVAL (val) == lval_internalvar)
3973     {
3974       int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
3975       const CORE_ADDR addr =
3976         value_as_long (value_allocate_space_in_inferior (len));
3977
3978       VALUE_LVAL (val) = lval_memory;
3979       set_value_address (val, addr);
3980       write_memory (addr, value_contents (val), len);
3981     }
3982
3983   return val;
3984 }
3985
3986 /* Given ARG, a value of type (pointer or reference to a)*
3987    structure/union, extract the component named NAME from the ultimate
3988    target structure/union and return it as a value with its
3989    appropriate type.
3990
3991    The routine searches for NAME among all members of the structure itself
3992    and (recursively) among all members of any wrapper members
3993    (e.g., '_parent').
3994
3995    If NO_ERR, then simply return NULL in case of error, rather than
3996    calling error.  */
3997
3998 static struct value *
3999 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4000 {
4001   struct type *t, *t1;
4002   struct value *v;
4003   int check_tag;
4004
4005   v = NULL;
4006   t1 = t = ada_check_typedef (value_type (arg));
4007   if (t->code () == TYPE_CODE_REF)
4008     {
4009       t1 = TYPE_TARGET_TYPE (t);
4010       if (t1 == NULL)
4011         goto BadValue;
4012       t1 = ada_check_typedef (t1);
4013       if (t1->code () == TYPE_CODE_PTR)
4014         {
4015           arg = coerce_ref (arg);
4016           t = t1;
4017         }
4018     }
4019
4020   while (t->code () == TYPE_CODE_PTR)
4021     {
4022       t1 = TYPE_TARGET_TYPE (t);
4023       if (t1 == NULL)
4024         goto BadValue;
4025       t1 = ada_check_typedef (t1);
4026       if (t1->code () == TYPE_CODE_PTR)
4027         {
4028           arg = value_ind (arg);
4029           t = t1;
4030         }
4031       else
4032         break;
4033     }
4034
4035   if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4036     goto BadValue;
4037
4038   if (t1 == t)
4039     v = ada_search_struct_field (name, arg, 0, t);
4040   else
4041     {
4042       int bit_offset, bit_size, byte_offset;
4043       struct type *field_type;
4044       CORE_ADDR address;
4045
4046       if (t->code () == TYPE_CODE_PTR)
4047         address = value_address (ada_value_ind (arg));
4048       else
4049         address = value_address (ada_coerce_ref (arg));
4050
4051       /* Check to see if this is a tagged type.  We also need to handle
4052          the case where the type is a reference to a tagged type, but
4053          we have to be careful to exclude pointers to tagged types.
4054          The latter should be shown as usual (as a pointer), whereas
4055          a reference should mostly be transparent to the user.  */
4056
4057       if (ada_is_tagged_type (t1, 0)
4058           || (t1->code () == TYPE_CODE_REF
4059               && ada_is_tagged_type (TYPE_TARGET_TYPE (t1), 0)))
4060         {
4061           /* We first try to find the searched field in the current type.
4062              If not found then let's look in the fixed type.  */
4063
4064           if (!find_struct_field (name, t1, 0,
4065                                   &field_type, &byte_offset, &bit_offset,
4066                                   &bit_size, NULL))
4067             check_tag = 1;
4068           else
4069             check_tag = 0;
4070         }
4071       else
4072         check_tag = 0;
4073
4074       /* Convert to fixed type in all cases, so that we have proper
4075          offsets to each field in unconstrained record types.  */
4076       t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4077                               address, NULL, check_tag);
4078
4079       /* Resolve the dynamic type as well.  */
4080       arg = value_from_contents_and_address (t1, nullptr, address);
4081       t1 = value_type (arg);
4082
4083       if (find_struct_field (name, t1, 0,
4084                              &field_type, &byte_offset, &bit_offset,
4085                              &bit_size, NULL))
4086         {
4087           if (bit_size != 0)
4088             {
4089               if (t->code () == TYPE_CODE_REF)
4090                 arg = ada_coerce_ref (arg);
4091               else
4092                 arg = ada_value_ind (arg);
4093               v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4094                                                   bit_offset, bit_size,
4095                                                   field_type);
4096             }
4097           else
4098             v = value_at_lazy (field_type, address + byte_offset);
4099         }
4100     }
4101
4102   if (v != NULL || no_err)
4103     return v;
4104   else
4105     error (_("There is no member named %s."), name);
4106
4107  BadValue:
4108   if (no_err)
4109     return NULL;
4110   else
4111     error (_("Attempt to extract a component of "
4112              "a value that is not a record."));
4113 }
4114
4115 /* Return the value ACTUAL, converted to be an appropriate value for a
4116    formal of type FORMAL_TYPE.  Use *SP as a stack pointer for
4117    allocating any necessary descriptors (fat pointers), or copies of
4118    values not residing in memory, updating it as needed.  */
4119
4120 struct value *
4121 ada_convert_actual (struct value *actual, struct type *formal_type0)
4122 {
4123   struct type *actual_type = ada_check_typedef (value_type (actual));
4124   struct type *formal_type = ada_check_typedef (formal_type0);
4125   struct type *formal_target =
4126     formal_type->code () == TYPE_CODE_PTR
4127     ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
4128   struct type *actual_target =
4129     actual_type->code () == TYPE_CODE_PTR
4130     ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
4131
4132   if (ada_is_array_descriptor_type (formal_target)
4133       && actual_target->code () == TYPE_CODE_ARRAY)
4134     return make_array_descriptor (formal_type, actual);
4135   else if (formal_type->code () == TYPE_CODE_PTR
4136            || formal_type->code () == TYPE_CODE_REF)
4137     {
4138       struct value *result;
4139
4140       if (formal_target->code () == TYPE_CODE_ARRAY
4141           && ada_is_array_descriptor_type (actual_target))
4142         result = desc_data (actual);
4143       else if (formal_type->code () != TYPE_CODE_PTR)
4144         {
4145           if (VALUE_LVAL (actual) != lval_memory)
4146             {
4147               struct value *val;
4148
4149               actual_type = ada_check_typedef (value_type (actual));
4150               val = allocate_value (actual_type);
4151               memcpy ((char *) value_contents_raw (val),
4152                       (char *) value_contents (actual),
4153                       TYPE_LENGTH (actual_type));
4154               actual = ensure_lval (val);
4155             }
4156           result = value_addr (actual);
4157         }
4158       else
4159         return actual;
4160       return value_cast_pointers (formal_type, result, 0);
4161     }
4162   else if (actual_type->code () == TYPE_CODE_PTR)
4163     return ada_value_ind (actual);
4164   else if (ada_is_aligner_type (formal_type))
4165     {
4166       /* We need to turn this parameter into an aligner type
4167          as well.  */
4168       struct value *aligner = allocate_value (formal_type);
4169       struct value *component = ada_value_struct_elt (aligner, "F", 0);
4170
4171       value_assign_to_component (aligner, component, actual);
4172       return aligner;
4173     }
4174
4175   return actual;
4176 }
4177
4178 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4179    type TYPE.  This is usually an inefficient no-op except on some targets
4180    (such as AVR) where the representation of a pointer and an address
4181    differs.  */
4182
4183 static CORE_ADDR
4184 value_pointer (struct value *value, struct type *type)
4185 {
4186   unsigned len = TYPE_LENGTH (type);
4187   gdb_byte *buf = (gdb_byte *) alloca (len);
4188   CORE_ADDR addr;
4189
4190   addr = value_address (value);
4191   gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4192   addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4193   return addr;
4194 }
4195
4196
4197 /* Push a descriptor of type TYPE for array value ARR on the stack at
4198    *SP, updating *SP to reflect the new descriptor.  Return either
4199    an lvalue representing the new descriptor, or (if TYPE is a pointer-
4200    to-descriptor type rather than a descriptor type), a struct value *
4201    representing a pointer to this descriptor.  */
4202
4203 static struct value *
4204 make_array_descriptor (struct type *type, struct value *arr)
4205 {
4206   struct type *bounds_type = desc_bounds_type (type);
4207   struct type *desc_type = desc_base_type (type);
4208   struct value *descriptor = allocate_value (desc_type);
4209   struct value *bounds = allocate_value (bounds_type);
4210   int i;
4211
4212   for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4213        i > 0; i -= 1)
4214     {
4215       modify_field (value_type (bounds), value_contents_writeable (bounds),
4216                     ada_array_bound (arr, i, 0),
4217                     desc_bound_bitpos (bounds_type, i, 0),
4218                     desc_bound_bitsize (bounds_type, i, 0));
4219       modify_field (value_type (bounds), value_contents_writeable (bounds),
4220                     ada_array_bound (arr, i, 1),
4221                     desc_bound_bitpos (bounds_type, i, 1),
4222                     desc_bound_bitsize (bounds_type, i, 1));
4223     }
4224
4225   bounds = ensure_lval (bounds);
4226
4227   modify_field (value_type (descriptor),
4228                 value_contents_writeable (descriptor),
4229                 value_pointer (ensure_lval (arr),
4230                                desc_type->field (0).type ()),
4231                 fat_pntr_data_bitpos (desc_type),
4232                 fat_pntr_data_bitsize (desc_type));
4233
4234   modify_field (value_type (descriptor),
4235                 value_contents_writeable (descriptor),
4236                 value_pointer (bounds,
4237                                desc_type->field (1).type ()),
4238                 fat_pntr_bounds_bitpos (desc_type),
4239                 fat_pntr_bounds_bitsize (desc_type));
4240
4241   descriptor = ensure_lval (descriptor);
4242
4243   if (type->code () == TYPE_CODE_PTR)
4244     return value_addr (descriptor);
4245   else
4246     return descriptor;
4247 }
4248 \f
4249                                 /* Symbol Cache Module */
4250
4251 /* Performance measurements made as of 2010-01-15 indicate that
4252    this cache does bring some noticeable improvements.  Depending
4253    on the type of entity being printed, the cache can make it as much
4254    as an order of magnitude faster than without it.
4255
4256    The descriptive type DWARF extension has significantly reduced
4257    the need for this cache, at least when DWARF is being used.  However,
4258    even in this case, some expensive name-based symbol searches are still
4259    sometimes necessary - to find an XVZ variable, mostly.  */
4260
4261 /* Return the symbol cache associated to the given program space PSPACE.
4262    If not allocated for this PSPACE yet, allocate and initialize one.  */
4263
4264 static struct ada_symbol_cache *
4265 ada_get_symbol_cache (struct program_space *pspace)
4266 {
4267   struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4268
4269   if (pspace_data->sym_cache == nullptr)
4270     pspace_data->sym_cache.reset (new ada_symbol_cache);
4271
4272   return pspace_data->sym_cache.get ();
4273 }
4274
4275 /* Clear all entries from the symbol cache.  */
4276
4277 static void
4278 ada_clear_symbol_cache ()
4279 {
4280   struct ada_pspace_data *pspace_data
4281     = get_ada_pspace_data (current_program_space);
4282
4283   if (pspace_data->sym_cache != nullptr)
4284     pspace_data->sym_cache.reset ();
4285 }
4286
4287 /* Search our cache for an entry matching NAME and DOMAIN.
4288    Return it if found, or NULL otherwise.  */
4289
4290 static struct cache_entry **
4291 find_entry (const char *name, domain_enum domain)
4292 {
4293   struct ada_symbol_cache *sym_cache
4294     = ada_get_symbol_cache (current_program_space);
4295   int h = msymbol_hash (name) % HASH_SIZE;
4296   struct cache_entry **e;
4297
4298   for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4299     {
4300       if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4301         return e;
4302     }
4303   return NULL;
4304 }
4305
4306 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4307    Return 1 if found, 0 otherwise.
4308
4309    If an entry was found and SYM is not NULL, set *SYM to the entry's
4310    SYM.  Same principle for BLOCK if not NULL.  */
4311
4312 static int
4313 lookup_cached_symbol (const char *name, domain_enum domain,
4314                       struct symbol **sym, const struct block **block)
4315 {
4316   struct cache_entry **e = find_entry (name, domain);
4317
4318   if (e == NULL)
4319     return 0;
4320   if (sym != NULL)
4321     *sym = (*e)->sym;
4322   if (block != NULL)
4323     *block = (*e)->block;
4324   return 1;
4325 }
4326
4327 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4328    in domain DOMAIN, save this result in our symbol cache.  */
4329
4330 static void
4331 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4332               const struct block *block)
4333 {
4334   struct ada_symbol_cache *sym_cache
4335     = ada_get_symbol_cache (current_program_space);
4336   int h;
4337   struct cache_entry *e;
4338
4339   /* Symbols for builtin types don't have a block.
4340      For now don't cache such symbols.  */
4341   if (sym != NULL && !SYMBOL_OBJFILE_OWNED (sym))
4342     return;
4343
4344   /* If the symbol is a local symbol, then do not cache it, as a search
4345      for that symbol depends on the context.  To determine whether
4346      the symbol is local or not, we check the block where we found it
4347      against the global and static blocks of its associated symtab.  */
4348   if (sym
4349       && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4350                             GLOBAL_BLOCK) != block
4351       && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4352                             STATIC_BLOCK) != block)
4353     return;
4354
4355   h = msymbol_hash (name) % HASH_SIZE;
4356   e = XOBNEW (&sym_cache->cache_space, cache_entry);
4357   e->next = sym_cache->root[h];
4358   sym_cache->root[h] = e;
4359   e->name = obstack_strdup (&sym_cache->cache_space, name);
4360   e->sym = sym;
4361   e->domain = domain;
4362   e->block = block;
4363 }
4364 \f
4365                                 /* Symbol Lookup */
4366
4367 /* Return the symbol name match type that should be used used when
4368    searching for all symbols matching LOOKUP_NAME.
4369
4370    LOOKUP_NAME is expected to be a symbol name after transformation
4371    for Ada lookups.  */
4372
4373 static symbol_name_match_type
4374 name_match_type_from_name (const char *lookup_name)
4375 {
4376   return (strstr (lookup_name, "__") == NULL
4377           ? symbol_name_match_type::WILD
4378           : symbol_name_match_type::FULL);
4379 }
4380
4381 /* Return the result of a standard (literal, C-like) lookup of NAME in
4382    given DOMAIN, visible from lexical block BLOCK.  */
4383
4384 static struct symbol *
4385 standard_lookup (const char *name, const struct block *block,
4386                  domain_enum domain)
4387 {
4388   /* Initialize it just to avoid a GCC false warning.  */
4389   struct block_symbol sym = {};
4390
4391   if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4392     return sym.symbol;
4393   ada_lookup_encoded_symbol (name, block, domain, &sym);
4394   cache_symbol (name, domain, sym.symbol, sym.block);
4395   return sym.symbol;
4396 }
4397
4398
4399 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4400    in the symbol fields of SYMS.  We treat enumerals as functions, 
4401    since they contend in overloading in the same way.  */
4402 static int
4403 is_nonfunction (const std::vector<struct block_symbol> &syms)
4404 {
4405   for (const block_symbol &sym : syms)
4406     if (SYMBOL_TYPE (sym.symbol)->code () != TYPE_CODE_FUNC
4407         && (SYMBOL_TYPE (sym.symbol)->code () != TYPE_CODE_ENUM
4408             || SYMBOL_CLASS (sym.symbol) != LOC_CONST))
4409       return 1;
4410
4411   return 0;
4412 }
4413
4414 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4415    struct types.  Otherwise, they may not.  */
4416
4417 static int
4418 equiv_types (struct type *type0, struct type *type1)
4419 {
4420   if (type0 == type1)
4421     return 1;
4422   if (type0 == NULL || type1 == NULL
4423       || type0->code () != type1->code ())
4424     return 0;
4425   if ((type0->code () == TYPE_CODE_STRUCT
4426        || type0->code () == TYPE_CODE_ENUM)
4427       && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4428       && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4429     return 1;
4430
4431   return 0;
4432 }
4433
4434 /* True iff SYM0 represents the same entity as SYM1, or one that is
4435    no more defined than that of SYM1.  */
4436
4437 static int
4438 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4439 {
4440   if (sym0 == sym1)
4441     return 1;
4442   if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
4443       || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
4444     return 0;
4445
4446   switch (SYMBOL_CLASS (sym0))
4447     {
4448     case LOC_UNDEF:
4449       return 1;
4450     case LOC_TYPEDEF:
4451       {
4452         struct type *type0 = SYMBOL_TYPE (sym0);
4453         struct type *type1 = SYMBOL_TYPE (sym1);
4454         const char *name0 = sym0->linkage_name ();
4455         const char *name1 = sym1->linkage_name ();
4456         int len0 = strlen (name0);
4457
4458         return
4459           type0->code () == type1->code ()
4460           && (equiv_types (type0, type1)
4461               || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4462                   && startswith (name1 + len0, "___XV")));
4463       }
4464     case LOC_CONST:
4465       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
4466         && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
4467
4468     case LOC_STATIC:
4469       {
4470         const char *name0 = sym0->linkage_name ();
4471         const char *name1 = sym1->linkage_name ();
4472         return (strcmp (name0, name1) == 0
4473                 && SYMBOL_VALUE_ADDRESS (sym0) == SYMBOL_VALUE_ADDRESS (sym1));
4474       }
4475
4476     default:
4477       return 0;
4478     }
4479 }
4480
4481 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4482    records in RESULT.  Do nothing if SYM is a duplicate.  */
4483
4484 static void
4485 add_defn_to_vec (std::vector<struct block_symbol> &result,
4486                  struct symbol *sym,
4487                  const struct block *block)
4488 {
4489   /* Do not try to complete stub types, as the debugger is probably
4490      already scanning all symbols matching a certain name at the
4491      time when this function is called.  Trying to replace the stub
4492      type by its associated full type will cause us to restart a scan
4493      which may lead to an infinite recursion.  Instead, the client
4494      collecting the matching symbols will end up collecting several
4495      matches, with at least one of them complete.  It can then filter
4496      out the stub ones if needed.  */
4497
4498   for (int i = result.size () - 1; i >= 0; i -= 1)
4499     {
4500       if (lesseq_defined_than (sym, result[i].symbol))
4501         return;
4502       else if (lesseq_defined_than (result[i].symbol, sym))
4503         {
4504           result[i].symbol = sym;
4505           result[i].block = block;
4506           return;
4507         }
4508     }
4509
4510   struct block_symbol info;
4511   info.symbol = sym;
4512   info.block = block;
4513   result.push_back (info);
4514 }
4515
4516 /* Return a bound minimal symbol matching NAME according to Ada
4517    decoding rules.  Returns an invalid symbol if there is no such
4518    minimal symbol.  Names prefixed with "standard__" are handled
4519    specially: "standard__" is first stripped off, and only static and
4520    global symbols are searched.  */
4521
4522 struct bound_minimal_symbol
4523 ada_lookup_simple_minsym (const char *name)
4524 {
4525   struct bound_minimal_symbol result;
4526
4527   memset (&result, 0, sizeof (result));
4528
4529   symbol_name_match_type match_type = name_match_type_from_name (name);
4530   lookup_name_info lookup_name (name, match_type);
4531
4532   symbol_name_matcher_ftype *match_name
4533     = ada_get_symbol_name_matcher (lookup_name);
4534
4535   for (objfile *objfile : current_program_space->objfiles ())
4536     {
4537       for (minimal_symbol *msymbol : objfile->msymbols ())
4538         {
4539           if (match_name (msymbol->linkage_name (), lookup_name, NULL)
4540               && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4541             {
4542               result.minsym = msymbol;
4543               result.objfile = objfile;
4544               break;
4545             }
4546         }
4547     }
4548
4549   return result;
4550 }
4551
4552 /* True if TYPE is definitely an artificial type supplied to a symbol
4553    for which no debugging information was given in the symbol file.  */
4554
4555 static int
4556 is_nondebugging_type (struct type *type)
4557 {
4558   const char *name = ada_type_name (type);
4559
4560   return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4561 }
4562
4563 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4564    that are deemed "identical" for practical purposes.
4565
4566    This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4567    types and that their number of enumerals is identical (in other
4568    words, type1->num_fields () == type2->num_fields ()).  */
4569
4570 static int
4571 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4572 {
4573   int i;
4574
4575   /* The heuristic we use here is fairly conservative.  We consider
4576      that 2 enumerate types are identical if they have the same
4577      number of enumerals and that all enumerals have the same
4578      underlying value and name.  */
4579
4580   /* All enums in the type should have an identical underlying value.  */
4581   for (i = 0; i < type1->num_fields (); i++)
4582     if (TYPE_FIELD_ENUMVAL (type1, i) != TYPE_FIELD_ENUMVAL (type2, i))
4583       return 0;
4584
4585   /* All enumerals should also have the same name (modulo any numerical
4586      suffix).  */
4587   for (i = 0; i < type1->num_fields (); i++)
4588     {
4589       const char *name_1 = TYPE_FIELD_NAME (type1, i);
4590       const char *name_2 = TYPE_FIELD_NAME (type2, i);
4591       int len_1 = strlen (name_1);
4592       int len_2 = strlen (name_2);
4593
4594       ada_remove_trailing_digits (TYPE_FIELD_NAME (type1, i), &len_1);
4595       ada_remove_trailing_digits (TYPE_FIELD_NAME (type2, i), &len_2);
4596       if (len_1 != len_2
4597           || strncmp (TYPE_FIELD_NAME (type1, i),
4598                       TYPE_FIELD_NAME (type2, i),
4599                       len_1) != 0)
4600         return 0;
4601     }
4602
4603   return 1;
4604 }
4605
4606 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4607    that are deemed "identical" for practical purposes.  Sometimes,
4608    enumerals are not strictly identical, but their types are so similar
4609    that they can be considered identical.
4610
4611    For instance, consider the following code:
4612
4613       type Color is (Black, Red, Green, Blue, White);
4614       type RGB_Color is new Color range Red .. Blue;
4615
4616    Type RGB_Color is a subrange of an implicit type which is a copy
4617    of type Color. If we call that implicit type RGB_ColorB ("B" is
4618    for "Base Type"), then type RGB_ColorB is a copy of type Color.
4619    As a result, when an expression references any of the enumeral
4620    by name (Eg. "print green"), the expression is technically
4621    ambiguous and the user should be asked to disambiguate. But
4622    doing so would only hinder the user, since it wouldn't matter
4623    what choice he makes, the outcome would always be the same.
4624    So, for practical purposes, we consider them as the same.  */
4625
4626 static int
4627 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
4628 {
4629   int i;
4630
4631   /* Before performing a thorough comparison check of each type,
4632      we perform a series of inexpensive checks.  We expect that these
4633      checks will quickly fail in the vast majority of cases, and thus
4634      help prevent the unnecessary use of a more expensive comparison.
4635      Said comparison also expects us to make some of these checks
4636      (see ada_identical_enum_types_p).  */
4637
4638   /* Quick check: All symbols should have an enum type.  */
4639   for (i = 0; i < syms.size (); i++)
4640     if (SYMBOL_TYPE (syms[i].symbol)->code () != TYPE_CODE_ENUM)
4641       return 0;
4642
4643   /* Quick check: They should all have the same value.  */
4644   for (i = 1; i < syms.size (); i++)
4645     if (SYMBOL_VALUE (syms[i].symbol) != SYMBOL_VALUE (syms[0].symbol))
4646       return 0;
4647
4648   /* Quick check: They should all have the same number of enumerals.  */
4649   for (i = 1; i < syms.size (); i++)
4650     if (SYMBOL_TYPE (syms[i].symbol)->num_fields ()
4651         != SYMBOL_TYPE (syms[0].symbol)->num_fields ())
4652       return 0;
4653
4654   /* All the sanity checks passed, so we might have a set of
4655      identical enumeration types.  Perform a more complete
4656      comparison of the type of each symbol.  */
4657   for (i = 1; i < syms.size (); i++)
4658     if (!ada_identical_enum_types_p (SYMBOL_TYPE (syms[i].symbol),
4659                                      SYMBOL_TYPE (syms[0].symbol)))
4660       return 0;
4661
4662   return 1;
4663 }
4664
4665 /* Remove any non-debugging symbols in SYMS that definitely
4666    duplicate other symbols in the list (The only case I know of where
4667    this happens is when object files containing stabs-in-ecoff are
4668    linked with files containing ordinary ecoff debugging symbols (or no
4669    debugging symbols)).  Modifies SYMS to squeeze out deleted entries.  */
4670
4671 static void
4672 remove_extra_symbols (std::vector<struct block_symbol> *syms)
4673 {
4674   int i, j;
4675
4676   /* We should never be called with less than 2 symbols, as there
4677      cannot be any extra symbol in that case.  But it's easy to
4678      handle, since we have nothing to do in that case.  */
4679   if (syms->size () < 2)
4680     return;
4681
4682   i = 0;
4683   while (i < syms->size ())
4684     {
4685       int remove_p = 0;
4686
4687       /* If two symbols have the same name and one of them is a stub type,
4688          the get rid of the stub.  */
4689
4690       if (SYMBOL_TYPE ((*syms)[i].symbol)->is_stub ()
4691           && (*syms)[i].symbol->linkage_name () != NULL)
4692         {
4693           for (j = 0; j < syms->size (); j++)
4694             {
4695               if (j != i
4696                   && !SYMBOL_TYPE ((*syms)[j].symbol)->is_stub ()
4697                   && (*syms)[j].symbol->linkage_name () != NULL
4698                   && strcmp ((*syms)[i].symbol->linkage_name (),
4699                              (*syms)[j].symbol->linkage_name ()) == 0)
4700                 remove_p = 1;
4701             }
4702         }
4703
4704       /* Two symbols with the same name, same class and same address
4705          should be identical.  */
4706
4707       else if ((*syms)[i].symbol->linkage_name () != NULL
4708           && SYMBOL_CLASS ((*syms)[i].symbol) == LOC_STATIC
4709           && is_nondebugging_type (SYMBOL_TYPE ((*syms)[i].symbol)))
4710         {
4711           for (j = 0; j < syms->size (); j += 1)
4712             {
4713               if (i != j
4714                   && (*syms)[j].symbol->linkage_name () != NULL
4715                   && strcmp ((*syms)[i].symbol->linkage_name (),
4716                              (*syms)[j].symbol->linkage_name ()) == 0
4717                   && SYMBOL_CLASS ((*syms)[i].symbol)
4718                        == SYMBOL_CLASS ((*syms)[j].symbol)
4719                   && SYMBOL_VALUE_ADDRESS ((*syms)[i].symbol)
4720                   == SYMBOL_VALUE_ADDRESS ((*syms)[j].symbol))
4721                 remove_p = 1;
4722             }
4723         }
4724       
4725       if (remove_p)
4726         syms->erase (syms->begin () + i);
4727       else
4728         i += 1;
4729     }
4730
4731   /* If all the remaining symbols are identical enumerals, then
4732      just keep the first one and discard the rest.
4733
4734      Unlike what we did previously, we do not discard any entry
4735      unless they are ALL identical.  This is because the symbol
4736      comparison is not a strict comparison, but rather a practical
4737      comparison.  If all symbols are considered identical, then
4738      we can just go ahead and use the first one and discard the rest.
4739      But if we cannot reduce the list to a single element, we have
4740      to ask the user to disambiguate anyways.  And if we have to
4741      present a multiple-choice menu, it's less confusing if the list
4742      isn't missing some choices that were identical and yet distinct.  */
4743   if (symbols_are_identical_enums (*syms))
4744     syms->resize (1);
4745 }
4746
4747 /* Given a type that corresponds to a renaming entity, use the type name
4748    to extract the scope (package name or function name, fully qualified,
4749    and following the GNAT encoding convention) where this renaming has been
4750    defined.  */
4751
4752 static std::string
4753 xget_renaming_scope (struct type *renaming_type)
4754 {
4755   /* The renaming types adhere to the following convention:
4756      <scope>__<rename>___<XR extension>.
4757      So, to extract the scope, we search for the "___XR" extension,
4758      and then backtrack until we find the first "__".  */
4759
4760   const char *name = renaming_type->name ();
4761   const char *suffix = strstr (name, "___XR");
4762   const char *last;
4763
4764   /* Now, backtrack a bit until we find the first "__".  Start looking
4765      at suffix - 3, as the <rename> part is at least one character long.  */
4766
4767   for (last = suffix - 3; last > name; last--)
4768     if (last[0] == '_' && last[1] == '_')
4769       break;
4770
4771   /* Make a copy of scope and return it.  */
4772   return std::string (name, last);
4773 }
4774
4775 /* Return nonzero if NAME corresponds to a package name.  */
4776
4777 static int
4778 is_package_name (const char *name)
4779 {
4780   /* Here, We take advantage of the fact that no symbols are generated
4781      for packages, while symbols are generated for each function.
4782      So the condition for NAME represent a package becomes equivalent
4783      to NAME not existing in our list of symbols.  There is only one
4784      small complication with library-level functions (see below).  */
4785
4786   /* If it is a function that has not been defined at library level,
4787      then we should be able to look it up in the symbols.  */
4788   if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
4789     return 0;
4790
4791   /* Library-level function names start with "_ada_".  See if function
4792      "_ada_" followed by NAME can be found.  */
4793
4794   /* Do a quick check that NAME does not contain "__", since library-level
4795      functions names cannot contain "__" in them.  */
4796   if (strstr (name, "__") != NULL)
4797     return 0;
4798
4799   std::string fun_name = string_printf ("_ada_%s", name);
4800
4801   return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
4802 }
4803
4804 /* Return nonzero if SYM corresponds to a renaming entity that is
4805    not visible from FUNCTION_NAME.  */
4806
4807 static int
4808 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
4809 {
4810   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
4811     return 0;
4812
4813   std::string scope = xget_renaming_scope (SYMBOL_TYPE (sym));
4814
4815   /* If the rename has been defined in a package, then it is visible.  */
4816   if (is_package_name (scope.c_str ()))
4817     return 0;
4818
4819   /* Check that the rename is in the current function scope by checking
4820      that its name starts with SCOPE.  */
4821
4822   /* If the function name starts with "_ada_", it means that it is
4823      a library-level function.  Strip this prefix before doing the
4824      comparison, as the encoding for the renaming does not contain
4825      this prefix.  */
4826   if (startswith (function_name, "_ada_"))
4827     function_name += 5;
4828
4829   return !startswith (function_name, scope.c_str ());
4830 }
4831
4832 /* Remove entries from SYMS that corresponds to a renaming entity that
4833    is not visible from the function associated with CURRENT_BLOCK or
4834    that is superfluous due to the presence of more specific renaming
4835    information.  Places surviving symbols in the initial entries of
4836    SYMS.
4837
4838    Rationale:
4839    First, in cases where an object renaming is implemented as a
4840    reference variable, GNAT may produce both the actual reference
4841    variable and the renaming encoding.  In this case, we discard the
4842    latter.
4843
4844    Second, GNAT emits a type following a specified encoding for each renaming
4845    entity.  Unfortunately, STABS currently does not support the definition
4846    of types that are local to a given lexical block, so all renamings types
4847    are emitted at library level.  As a consequence, if an application
4848    contains two renaming entities using the same name, and a user tries to
4849    print the value of one of these entities, the result of the ada symbol
4850    lookup will also contain the wrong renaming type.
4851
4852    This function partially covers for this limitation by attempting to
4853    remove from the SYMS list renaming symbols that should be visible
4854    from CURRENT_BLOCK.  However, there does not seem be a 100% reliable
4855    method with the current information available.  The implementation
4856    below has a couple of limitations (FIXME: brobecker-2003-05-12):  
4857    
4858       - When the user tries to print a rename in a function while there
4859         is another rename entity defined in a package:  Normally, the
4860         rename in the function has precedence over the rename in the
4861         package, so the latter should be removed from the list.  This is
4862         currently not the case.
4863         
4864       - This function will incorrectly remove valid renames if
4865         the CURRENT_BLOCK corresponds to a function which symbol name
4866         has been changed by an "Export" pragma.  As a consequence,
4867         the user will be unable to print such rename entities.  */
4868
4869 static void
4870 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
4871                              const struct block *current_block)
4872 {
4873   struct symbol *current_function;
4874   const char *current_function_name;
4875   int i;
4876   int is_new_style_renaming;
4877
4878   /* If there is both a renaming foo___XR... encoded as a variable and
4879      a simple variable foo in the same block, discard the latter.
4880      First, zero out such symbols, then compress.  */
4881   is_new_style_renaming = 0;
4882   for (i = 0; i < syms->size (); i += 1)
4883     {
4884       struct symbol *sym = (*syms)[i].symbol;
4885       const struct block *block = (*syms)[i].block;
4886       const char *name;
4887       const char *suffix;
4888
4889       if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
4890         continue;
4891       name = sym->linkage_name ();
4892       suffix = strstr (name, "___XR");
4893
4894       if (suffix != NULL)
4895         {
4896           int name_len = suffix - name;
4897           int j;
4898
4899           is_new_style_renaming = 1;
4900           for (j = 0; j < syms->size (); j += 1)
4901             if (i != j && (*syms)[j].symbol != NULL
4902                 && strncmp (name, (*syms)[j].symbol->linkage_name (),
4903                             name_len) == 0
4904                 && block == (*syms)[j].block)
4905               (*syms)[j].symbol = NULL;
4906         }
4907     }
4908   if (is_new_style_renaming)
4909     {
4910       int j, k;
4911
4912       for (j = k = 0; j < syms->size (); j += 1)
4913         if ((*syms)[j].symbol != NULL)
4914             {
4915               (*syms)[k] = (*syms)[j];
4916               k += 1;
4917             }
4918       syms->resize (k);
4919       return;
4920     }
4921
4922   /* Extract the function name associated to CURRENT_BLOCK.
4923      Abort if unable to do so.  */
4924
4925   if (current_block == NULL)
4926     return;
4927
4928   current_function = block_linkage_function (current_block);
4929   if (current_function == NULL)
4930     return;
4931
4932   current_function_name = current_function->linkage_name ();
4933   if (current_function_name == NULL)
4934     return;
4935
4936   /* Check each of the symbols, and remove it from the list if it is
4937      a type corresponding to a renaming that is out of the scope of
4938      the current block.  */
4939
4940   i = 0;
4941   while (i < syms->size ())
4942     {
4943       if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
4944           == ADA_OBJECT_RENAMING
4945           && old_renaming_is_invisible ((*syms)[i].symbol,
4946                                         current_function_name))
4947         syms->erase (syms->begin () + i);
4948       else
4949         i += 1;
4950     }
4951 }
4952
4953 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
4954    whose name and domain match LOOKUP_NAME and DOMAIN respectively.
4955
4956    Note: This function assumes that RESULT is empty.  */
4957
4958 static void
4959 ada_add_local_symbols (std::vector<struct block_symbol> &result,
4960                        const lookup_name_info &lookup_name,
4961                        const struct block *block, domain_enum domain)
4962 {
4963   while (block != NULL)
4964     {
4965       ada_add_block_symbols (result, block, lookup_name, domain, NULL);
4966
4967       /* If we found a non-function match, assume that's the one.  We
4968          only check this when finding a function boundary, so that we
4969          can accumulate all results from intervening blocks first.  */
4970       if (BLOCK_FUNCTION (block) != nullptr && is_nonfunction (result))
4971         return;
4972
4973       block = BLOCK_SUPERBLOCK (block);
4974     }
4975 }
4976
4977 /* An object of this type is used as the callback argument when
4978    calling the map_matching_symbols method.  */
4979
4980 struct match_data
4981 {
4982   explicit match_data (std::vector<struct block_symbol> *rp)
4983     : resultp (rp)
4984   {
4985   }
4986   DISABLE_COPY_AND_ASSIGN (match_data);
4987
4988   bool operator() (struct block_symbol *bsym);
4989
4990   struct objfile *objfile = nullptr;
4991   std::vector<struct block_symbol> *resultp;
4992   struct symbol *arg_sym = nullptr;
4993   bool found_sym = false;
4994 };
4995
4996 /* A callback for add_nonlocal_symbols that adds symbol, found in
4997    BSYM, to a list of symbols.  */
4998
4999 bool
5000 match_data::operator() (struct block_symbol *bsym)
5001 {
5002   const struct block *block = bsym->block;
5003   struct symbol *sym = bsym->symbol;
5004
5005   if (sym == NULL)
5006     {
5007       if (!found_sym && arg_sym != NULL)
5008         add_defn_to_vec (*resultp,
5009                          fixup_symbol_section (arg_sym, objfile),
5010                          block);
5011       found_sym = false;
5012       arg_sym = NULL;
5013     }
5014   else 
5015     {
5016       if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
5017         return true;
5018       else if (SYMBOL_IS_ARGUMENT (sym))
5019         arg_sym = sym;
5020       else
5021         {
5022           found_sym = true;
5023           add_defn_to_vec (*resultp,
5024                            fixup_symbol_section (sym, objfile),
5025                            block);
5026         }
5027     }
5028   return true;
5029 }
5030
5031 /* Helper for add_nonlocal_symbols.  Find symbols in DOMAIN which are
5032    targeted by renamings matching LOOKUP_NAME in BLOCK.  Add these
5033    symbols to RESULT.  Return whether we found such symbols.  */
5034
5035 static int
5036 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5037                          const struct block *block,
5038                          const lookup_name_info &lookup_name,
5039                          domain_enum domain)
5040 {
5041   struct using_direct *renaming;
5042   int defns_mark = result.size ();
5043
5044   symbol_name_matcher_ftype *name_match
5045     = ada_get_symbol_name_matcher (lookup_name);
5046
5047   for (renaming = block_using (block);
5048        renaming != NULL;
5049        renaming = renaming->next)
5050     {
5051       const char *r_name;
5052
5053       /* Avoid infinite recursions: skip this renaming if we are actually
5054          already traversing it.
5055
5056          Currently, symbol lookup in Ada don't use the namespace machinery from
5057          C++/Fortran support: skip namespace imports that use them.  */
5058       if (renaming->searched
5059           || (renaming->import_src != NULL
5060               && renaming->import_src[0] != '\0')
5061           || (renaming->import_dest != NULL
5062               && renaming->import_dest[0] != '\0'))
5063         continue;
5064       renaming->searched = 1;
5065
5066       /* TODO: here, we perform another name-based symbol lookup, which can
5067          pull its own multiple overloads.  In theory, we should be able to do
5068          better in this case since, in DWARF, DW_AT_import is a DIE reference,
5069          not a simple name.  But in order to do this, we would need to enhance
5070          the DWARF reader to associate a symbol to this renaming, instead of a
5071          name.  So, for now, we do something simpler: re-use the C++/Fortran
5072          namespace machinery.  */
5073       r_name = (renaming->alias != NULL
5074                 ? renaming->alias
5075                 : renaming->declaration);
5076       if (name_match (r_name, lookup_name, NULL))
5077         {
5078           lookup_name_info decl_lookup_name (renaming->declaration,
5079                                              lookup_name.match_type ());
5080           ada_add_all_symbols (result, block, decl_lookup_name, domain,
5081                                1, NULL);
5082         }
5083       renaming->searched = 0;
5084     }
5085   return result.size () != defns_mark;
5086 }
5087
5088 /* Implements compare_names, but only applying the comparision using
5089    the given CASING.  */
5090
5091 static int
5092 compare_names_with_case (const char *string1, const char *string2,
5093                          enum case_sensitivity casing)
5094 {
5095   while (*string1 != '\0' && *string2 != '\0')
5096     {
5097       char c1, c2;
5098
5099       if (isspace (*string1) || isspace (*string2))
5100         return strcmp_iw_ordered (string1, string2);
5101
5102       if (casing == case_sensitive_off)
5103         {
5104           c1 = tolower (*string1);
5105           c2 = tolower (*string2);
5106         }
5107       else
5108         {
5109           c1 = *string1;
5110           c2 = *string2;
5111         }
5112       if (c1 != c2)
5113         break;
5114
5115       string1 += 1;
5116       string2 += 1;
5117     }
5118
5119   switch (*string1)
5120     {
5121     case '(':
5122       return strcmp_iw_ordered (string1, string2);
5123     case '_':
5124       if (*string2 == '\0')
5125         {
5126           if (is_name_suffix (string1))
5127             return 0;
5128           else
5129             return 1;
5130         }
5131       /* FALLTHROUGH */
5132     default:
5133       if (*string2 == '(')
5134         return strcmp_iw_ordered (string1, string2);
5135       else
5136         {
5137           if (casing == case_sensitive_off)
5138             return tolower (*string1) - tolower (*string2);
5139           else
5140             return *string1 - *string2;
5141         }
5142     }
5143 }
5144
5145 /* Compare STRING1 to STRING2, with results as for strcmp.
5146    Compatible with strcmp_iw_ordered in that...
5147
5148        strcmp_iw_ordered (STRING1, STRING2) <= 0
5149
5150    ... implies...
5151
5152        compare_names (STRING1, STRING2) <= 0
5153
5154    (they may differ as to what symbols compare equal).  */
5155
5156 static int
5157 compare_names (const char *string1, const char *string2)
5158 {
5159   int result;
5160
5161   /* Similar to what strcmp_iw_ordered does, we need to perform
5162      a case-insensitive comparison first, and only resort to
5163      a second, case-sensitive, comparison if the first one was
5164      not sufficient to differentiate the two strings.  */
5165
5166   result = compare_names_with_case (string1, string2, case_sensitive_off);
5167   if (result == 0)
5168     result = compare_names_with_case (string1, string2, case_sensitive_on);
5169
5170   return result;
5171 }
5172
5173 /* Convenience function to get at the Ada encoded lookup name for
5174    LOOKUP_NAME, as a C string.  */
5175
5176 static const char *
5177 ada_lookup_name (const lookup_name_info &lookup_name)
5178 {
5179   return lookup_name.ada ().lookup_name ().c_str ();
5180 }
5181
5182 /* A helper for add_nonlocal_symbols.  Call expand_matching_symbols
5183    for OBJFILE, then walk the objfile's symtabs and update the
5184    results.  */
5185
5186 static void
5187 map_matching_symbols (struct objfile *objfile,
5188                       const lookup_name_info &lookup_name,
5189                       bool is_wild_match,
5190                       domain_enum domain,
5191                       int global,
5192                       match_data &data)
5193 {
5194   data.objfile = objfile;
5195   objfile->expand_matching_symbols (lookup_name, domain, global,
5196                                     is_wild_match ? nullptr : compare_names);
5197
5198   const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5199   for (compunit_symtab *symtab : objfile->compunits ())
5200     {
5201       const struct block *block
5202         = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (symtab), block_kind);
5203       if (!iterate_over_symbols_terminated (block, lookup_name,
5204                                             domain, data))
5205         break;
5206     }
5207 }
5208
5209 /* Add to RESULT all non-local symbols whose name and domain match
5210    LOOKUP_NAME and DOMAIN respectively.  The search is performed on
5211    GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5212    symbols otherwise.  */
5213
5214 static void
5215 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5216                       const lookup_name_info &lookup_name,
5217                       domain_enum domain, int global)
5218 {
5219   struct match_data data (&result);
5220
5221   bool is_wild_match = lookup_name.ada ().wild_match_p ();
5222
5223   for (objfile *objfile : current_program_space->objfiles ())
5224     {
5225       map_matching_symbols (objfile, lookup_name, is_wild_match, domain,
5226                             global, data);
5227
5228       for (compunit_symtab *cu : objfile->compunits ())
5229         {
5230           const struct block *global_block
5231             = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cu), GLOBAL_BLOCK);
5232
5233           if (ada_add_block_renamings (result, global_block, lookup_name,
5234                                        domain))
5235             data.found_sym = true;
5236         }
5237     }
5238
5239   if (result.empty () && global && !is_wild_match)
5240     {
5241       const char *name = ada_lookup_name (lookup_name);
5242       std::string bracket_name = std::string ("<_ada_") + name + '>';
5243       lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5244
5245       for (objfile *objfile : current_program_space->objfiles ())
5246         map_matching_symbols (objfile, name1, false, domain, global, data);
5247     }
5248 }
5249
5250 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5251    FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5252    returning the number of matches.  Add these to RESULT.
5253
5254    When FULL_SEARCH is non-zero, any non-function/non-enumeral
5255    symbol match within the nest of blocks whose innermost member is BLOCK,
5256    is the one match returned (no other matches in that or
5257    enclosing blocks is returned).  If there are any matches in or
5258    surrounding BLOCK, then these alone are returned.
5259
5260    Names prefixed with "standard__" are handled specially:
5261    "standard__" is first stripped off (by the lookup_name
5262    constructor), and only static and global symbols are searched.
5263
5264    If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5265    to lookup global symbols.  */
5266
5267 static void
5268 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5269                      const struct block *block,
5270                      const lookup_name_info &lookup_name,
5271                      domain_enum domain,
5272                      int full_search,
5273                      int *made_global_lookup_p)
5274 {
5275   struct symbol *sym;
5276
5277   if (made_global_lookup_p)
5278     *made_global_lookup_p = 0;
5279
5280   /* Special case: If the user specifies a symbol name inside package
5281      Standard, do a non-wild matching of the symbol name without
5282      the "standard__" prefix.  This was primarily introduced in order
5283      to allow the user to specifically access the standard exceptions
5284      using, for instance, Standard.Constraint_Error when Constraint_Error
5285      is ambiguous (due to the user defining its own Constraint_Error
5286      entity inside its program).  */
5287   if (lookup_name.ada ().standard_p ())
5288     block = NULL;
5289
5290   /* Check the non-global symbols.  If we have ANY match, then we're done.  */
5291
5292   if (block != NULL)
5293     {
5294       if (full_search)
5295         ada_add_local_symbols (result, lookup_name, block, domain);
5296       else
5297         {
5298           /* In the !full_search case we're are being called by
5299              iterate_over_symbols, and we don't want to search
5300              superblocks.  */
5301           ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5302         }
5303       if (!result.empty () || !full_search)
5304         return;
5305     }
5306
5307   /* No non-global symbols found.  Check our cache to see if we have
5308      already performed this search before.  If we have, then return
5309      the same result.  */
5310
5311   if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5312                             domain, &sym, &block))
5313     {
5314       if (sym != NULL)
5315         add_defn_to_vec (result, sym, block);
5316       return;
5317     }
5318
5319   if (made_global_lookup_p)
5320     *made_global_lookup_p = 1;
5321
5322   /* Search symbols from all global blocks.  */
5323  
5324   add_nonlocal_symbols (result, lookup_name, domain, 1);
5325
5326   /* Now add symbols from all per-file blocks if we've gotten no hits
5327      (not strictly correct, but perhaps better than an error).  */
5328
5329   if (result.empty ())
5330     add_nonlocal_symbols (result, lookup_name, domain, 0);
5331 }
5332
5333 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5334    is non-zero, enclosing scope and in global scopes.
5335
5336    Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5337    blocks and symbol tables (if any) in which they were found.
5338
5339    When full_search is non-zero, any non-function/non-enumeral
5340    symbol match within the nest of blocks whose innermost member is BLOCK,
5341    is the one match returned (no other matches in that or
5342    enclosing blocks is returned).  If there are any matches in or
5343    surrounding BLOCK, then these alone are returned.
5344
5345    Names prefixed with "standard__" are handled specially: "standard__"
5346    is first stripped off, and only static and global symbols are searched.  */
5347
5348 static std::vector<struct block_symbol>
5349 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5350                                const struct block *block,
5351                                domain_enum domain,
5352                                int full_search)
5353 {
5354   int syms_from_global_search;
5355   std::vector<struct block_symbol> results;
5356
5357   ada_add_all_symbols (results, block, lookup_name,
5358                        domain, full_search, &syms_from_global_search);
5359
5360   remove_extra_symbols (&results);
5361
5362   if (results.empty () && full_search && syms_from_global_search)
5363     cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5364
5365   if (results.size () == 1 && full_search && syms_from_global_search)
5366     cache_symbol (ada_lookup_name (lookup_name), domain,
5367                   results[0].symbol, results[0].block);
5368
5369   remove_irrelevant_renamings (&results, block);
5370   return results;
5371 }
5372
5373 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5374    in global scopes, returning (SYM,BLOCK) tuples.
5375
5376    See ada_lookup_symbol_list_worker for further details.  */
5377
5378 std::vector<struct block_symbol>
5379 ada_lookup_symbol_list (const char *name, const struct block *block,
5380                         domain_enum domain)
5381 {
5382   symbol_name_match_type name_match_type = name_match_type_from_name (name);
5383   lookup_name_info lookup_name (name, name_match_type);
5384
5385   return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5386 }
5387
5388 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5389    to 1, but choosing the first symbol found if there are multiple
5390    choices.
5391
5392    The result is stored in *INFO, which must be non-NULL.
5393    If no match is found, INFO->SYM is set to NULL.  */
5394
5395 void
5396 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5397                            domain_enum domain,
5398                            struct block_symbol *info)
5399 {
5400   /* Since we already have an encoded name, wrap it in '<>' to force a
5401      verbatim match.  Otherwise, if the name happens to not look like
5402      an encoded name (because it doesn't include a "__"),
5403      ada_lookup_name_info would re-encode/fold it again, and that
5404      would e.g., incorrectly lowercase object renaming names like
5405      "R28b" -> "r28b".  */
5406   std::string verbatim = add_angle_brackets (name);
5407
5408   gdb_assert (info != NULL);
5409   *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5410 }
5411
5412 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5413    scope and in global scopes, or NULL if none.  NAME is folded and
5414    encoded first.  Otherwise, the result is as for ada_lookup_symbol_list,
5415    choosing the first symbol if there are multiple choices.  */
5416
5417 struct block_symbol
5418 ada_lookup_symbol (const char *name, const struct block *block0,
5419                    domain_enum domain)
5420 {
5421   std::vector<struct block_symbol> candidates
5422     = ada_lookup_symbol_list (name, block0, domain);
5423
5424   if (candidates.empty ())
5425     return {};
5426
5427   block_symbol info = candidates[0];
5428   info.symbol = fixup_symbol_section (info.symbol, NULL);
5429   return info;
5430 }
5431
5432
5433 /* True iff STR is a possible encoded suffix of a normal Ada name
5434    that is to be ignored for matching purposes.  Suffixes of parallel
5435    names (e.g., XVE) are not included here.  Currently, the possible suffixes
5436    are given by any of the regular expressions:
5437
5438    [.$][0-9]+       [nested subprogram suffix, on platforms such as GNU/Linux]
5439    ___[0-9]+        [nested subprogram suffix, on platforms such as HP/UX]
5440    TKB              [subprogram suffix for task bodies]
5441    _E[0-9]+[bs]$    [protected object entry suffixes]
5442    (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5443
5444    Also, any leading "__[0-9]+" sequence is skipped before the suffix
5445    match is performed.  This sequence is used to differentiate homonyms,
5446    is an optional part of a valid name suffix.  */
5447
5448 static int
5449 is_name_suffix (const char *str)
5450 {
5451   int k;
5452   const char *matching;
5453   const int len = strlen (str);
5454
5455   /* Skip optional leading __[0-9]+.  */
5456
5457   if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5458     {
5459       str += 3;
5460       while (isdigit (str[0]))
5461         str += 1;
5462     }
5463   
5464   /* [.$][0-9]+ */
5465
5466   if (str[0] == '.' || str[0] == '$')
5467     {
5468       matching = str + 1;
5469       while (isdigit (matching[0]))
5470         matching += 1;
5471       if (matching[0] == '\0')
5472         return 1;
5473     }
5474
5475   /* ___[0-9]+ */
5476
5477   if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5478     {
5479       matching = str + 3;
5480       while (isdigit (matching[0]))
5481         matching += 1;
5482       if (matching[0] == '\0')
5483         return 1;
5484     }
5485
5486   /* "TKB" suffixes are used for subprograms implementing task bodies.  */
5487
5488   if (strcmp (str, "TKB") == 0)
5489     return 1;
5490
5491 #if 0
5492   /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5493      with a N at the end.  Unfortunately, the compiler uses the same
5494      convention for other internal types it creates.  So treating
5495      all entity names that end with an "N" as a name suffix causes
5496      some regressions.  For instance, consider the case of an enumerated
5497      type.  To support the 'Image attribute, it creates an array whose
5498      name ends with N.
5499      Having a single character like this as a suffix carrying some
5500      information is a bit risky.  Perhaps we should change the encoding
5501      to be something like "_N" instead.  In the meantime, do not do
5502      the following check.  */
5503   /* Protected Object Subprograms */
5504   if (len == 1 && str [0] == 'N')
5505     return 1;
5506 #endif
5507
5508   /* _E[0-9]+[bs]$ */
5509   if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5510     {
5511       matching = str + 3;
5512       while (isdigit (matching[0]))
5513         matching += 1;
5514       if ((matching[0] == 'b' || matching[0] == 's')
5515           && matching [1] == '\0')
5516         return 1;
5517     }
5518
5519   /* ??? We should not modify STR directly, as we are doing below.  This
5520      is fine in this case, but may become problematic later if we find
5521      that this alternative did not work, and want to try matching
5522      another one from the begining of STR.  Since we modified it, we
5523      won't be able to find the begining of the string anymore!  */
5524   if (str[0] == 'X')
5525     {
5526       str += 1;
5527       while (str[0] != '_' && str[0] != '\0')
5528         {
5529           if (str[0] != 'n' && str[0] != 'b')
5530             return 0;
5531           str += 1;
5532         }
5533     }
5534
5535   if (str[0] == '\000')
5536     return 1;
5537
5538   if (str[0] == '_')
5539     {
5540       if (str[1] != '_' || str[2] == '\000')
5541         return 0;
5542       if (str[2] == '_')
5543         {
5544           if (strcmp (str + 3, "JM") == 0)
5545             return 1;
5546           /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5547              the LJM suffix in favor of the JM one.  But we will
5548              still accept LJM as a valid suffix for a reasonable
5549              amount of time, just to allow ourselves to debug programs
5550              compiled using an older version of GNAT.  */
5551           if (strcmp (str + 3, "LJM") == 0)
5552             return 1;
5553           if (str[3] != 'X')
5554             return 0;
5555           if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5556               || str[4] == 'U' || str[4] == 'P')
5557             return 1;
5558           if (str[4] == 'R' && str[5] != 'T')
5559             return 1;
5560           return 0;
5561         }
5562       if (!isdigit (str[2]))
5563         return 0;
5564       for (k = 3; str[k] != '\0'; k += 1)
5565         if (!isdigit (str[k]) && str[k] != '_')
5566           return 0;
5567       return 1;
5568     }
5569   if (str[0] == '$' && isdigit (str[1]))
5570     {
5571       for (k = 2; str[k] != '\0'; k += 1)
5572         if (!isdigit (str[k]) && str[k] != '_')
5573           return 0;
5574       return 1;
5575     }
5576   return 0;
5577 }
5578
5579 /* Return non-zero if the string starting at NAME and ending before
5580    NAME_END contains no capital letters.  */
5581
5582 static int
5583 is_valid_name_for_wild_match (const char *name0)
5584 {
5585   std::string decoded_name = ada_decode (name0);
5586   int i;
5587
5588   /* If the decoded name starts with an angle bracket, it means that
5589      NAME0 does not follow the GNAT encoding format.  It should then
5590      not be allowed as a possible wild match.  */
5591   if (decoded_name[0] == '<')
5592     return 0;
5593
5594   for (i=0; decoded_name[i] != '\0'; i++)
5595     if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5596       return 0;
5597
5598   return 1;
5599 }
5600
5601 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5602    character which could start a simple name.  Assumes that *NAMEP points
5603    somewhere inside the string beginning at NAME0.  */
5604
5605 static int
5606 advance_wild_match (const char **namep, const char *name0, char target0)
5607 {
5608   const char *name = *namep;
5609
5610   while (1)
5611     {
5612       char t0, t1;
5613
5614       t0 = *name;
5615       if (t0 == '_')
5616         {
5617           t1 = name[1];
5618           if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5619             {
5620               name += 1;
5621               if (name == name0 + 5 && startswith (name0, "_ada"))
5622                 break;
5623               else
5624                 name += 1;
5625             }
5626           else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5627                                  || name[2] == target0))
5628             {
5629               name += 2;
5630               break;
5631             }
5632           else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5633             {
5634               /* Names like "pkg__B_N__name", where N is a number, are
5635                  block-local.  We can handle these by simply skipping
5636                  the "B_" here.  */
5637               name += 4;
5638             }
5639           else
5640             return 0;
5641         }
5642       else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5643         name += 1;
5644       else
5645         return 0;
5646     }
5647
5648   *namep = name;
5649   return 1;
5650 }
5651
5652 /* Return true iff NAME encodes a name of the form prefix.PATN.
5653    Ignores any informational suffixes of NAME (i.e., for which
5654    is_name_suffix is true).  Assumes that PATN is a lower-cased Ada
5655    simple name.  */
5656
5657 static bool
5658 wild_match (const char *name, const char *patn)
5659 {
5660   const char *p;
5661   const char *name0 = name;
5662
5663   while (1)
5664     {
5665       const char *match = name;
5666
5667       if (*name == *patn)
5668         {
5669           for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5670             if (*p != *name)
5671               break;
5672           if (*p == '\0' && is_name_suffix (name))
5673             return match == name0 || is_valid_name_for_wild_match (name0);
5674
5675           if (name[-1] == '_')
5676             name -= 1;
5677         }
5678       if (!advance_wild_match (&name, name0, *patn))
5679         return false;
5680     }
5681 }
5682
5683 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
5684    necessary).  OBJFILE is the section containing BLOCK.  */
5685
5686 static void
5687 ada_add_block_symbols (std::vector<struct block_symbol> &result,
5688                        const struct block *block,
5689                        const lookup_name_info &lookup_name,
5690                        domain_enum domain, struct objfile *objfile)
5691 {
5692   struct block_iterator iter;
5693   /* A matching argument symbol, if any.  */
5694   struct symbol *arg_sym;
5695   /* Set true when we find a matching non-argument symbol.  */
5696   bool found_sym;
5697   struct symbol *sym;
5698
5699   arg_sym = NULL;
5700   found_sym = false;
5701   for (sym = block_iter_match_first (block, lookup_name, &iter);
5702        sym != NULL;
5703        sym = block_iter_match_next (lookup_name, &iter))
5704     {
5705       if (symbol_matches_domain (sym->language (), SYMBOL_DOMAIN (sym), domain))
5706         {
5707           if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
5708             {
5709               if (SYMBOL_IS_ARGUMENT (sym))
5710                 arg_sym = sym;
5711               else
5712                 {
5713                   found_sym = true;
5714                   add_defn_to_vec (result,
5715                                    fixup_symbol_section (sym, objfile),
5716                                    block);
5717                 }
5718             }
5719         }
5720     }
5721
5722   /* Handle renamings.  */
5723
5724   if (ada_add_block_renamings (result, block, lookup_name, domain))
5725     found_sym = true;
5726
5727   if (!found_sym && arg_sym != NULL)
5728     {
5729       add_defn_to_vec (result,
5730                        fixup_symbol_section (arg_sym, objfile),
5731                        block);
5732     }
5733
5734   if (!lookup_name.ada ().wild_match_p ())
5735     {
5736       arg_sym = NULL;
5737       found_sym = false;
5738       const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
5739       const char *name = ada_lookup_name.c_str ();
5740       size_t name_len = ada_lookup_name.size ();
5741
5742       ALL_BLOCK_SYMBOLS (block, iter, sym)
5743       {
5744         if (symbol_matches_domain (sym->language (),
5745                                    SYMBOL_DOMAIN (sym), domain))
5746           {
5747             int cmp;
5748
5749             cmp = (int) '_' - (int) sym->linkage_name ()[0];
5750             if (cmp == 0)
5751               {
5752                 cmp = !startswith (sym->linkage_name (), "_ada_");
5753                 if (cmp == 0)
5754                   cmp = strncmp (name, sym->linkage_name () + 5,
5755                                  name_len);
5756               }
5757
5758             if (cmp == 0
5759                 && is_name_suffix (sym->linkage_name () + name_len + 5))
5760               {
5761                 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
5762                   {
5763                     if (SYMBOL_IS_ARGUMENT (sym))
5764                       arg_sym = sym;
5765                     else
5766                       {
5767                         found_sym = true;
5768                         add_defn_to_vec (result,
5769                                          fixup_symbol_section (sym, objfile),
5770                                          block);
5771                       }
5772                   }
5773               }
5774           }
5775       }
5776
5777       /* NOTE: This really shouldn't be needed for _ada_ symbols.
5778          They aren't parameters, right?  */
5779       if (!found_sym && arg_sym != NULL)
5780         {
5781           add_defn_to_vec (result,
5782                            fixup_symbol_section (arg_sym, objfile),
5783                            block);
5784         }
5785     }
5786 }
5787 \f
5788
5789                                 /* Symbol Completion */
5790
5791 /* See symtab.h.  */
5792
5793 bool
5794 ada_lookup_name_info::matches
5795   (const char *sym_name,
5796    symbol_name_match_type match_type,
5797    completion_match_result *comp_match_res) const
5798 {
5799   bool match = false;
5800   const char *text = m_encoded_name.c_str ();
5801   size_t text_len = m_encoded_name.size ();
5802
5803   /* First, test against the fully qualified name of the symbol.  */
5804
5805   if (strncmp (sym_name, text, text_len) == 0)
5806     match = true;
5807
5808   std::string decoded_name = ada_decode (sym_name);
5809   if (match && !m_encoded_p)
5810     {
5811       /* One needed check before declaring a positive match is to verify
5812          that iff we are doing a verbatim match, the decoded version
5813          of the symbol name starts with '<'.  Otherwise, this symbol name
5814          is not a suitable completion.  */
5815
5816       bool has_angle_bracket = (decoded_name[0] == '<');
5817       match = (has_angle_bracket == m_verbatim_p);
5818     }
5819
5820   if (match && !m_verbatim_p)
5821     {
5822       /* When doing non-verbatim match, another check that needs to
5823          be done is to verify that the potentially matching symbol name
5824          does not include capital letters, because the ada-mode would
5825          not be able to understand these symbol names without the
5826          angle bracket notation.  */
5827       const char *tmp;
5828
5829       for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
5830       if (*tmp != '\0')
5831         match = false;
5832     }
5833
5834   /* Second: Try wild matching...  */
5835
5836   if (!match && m_wild_match_p)
5837     {
5838       /* Since we are doing wild matching, this means that TEXT
5839          may represent an unqualified symbol name.  We therefore must
5840          also compare TEXT against the unqualified name of the symbol.  */
5841       sym_name = ada_unqualified_name (decoded_name.c_str ());
5842
5843       if (strncmp (sym_name, text, text_len) == 0)
5844         match = true;
5845     }
5846
5847   /* Finally: If we found a match, prepare the result to return.  */
5848
5849   if (!match)
5850     return false;
5851
5852   if (comp_match_res != NULL)
5853     {
5854       std::string &match_str = comp_match_res->match.storage ();
5855
5856       if (!m_encoded_p)
5857         match_str = ada_decode (sym_name);
5858       else
5859         {
5860           if (m_verbatim_p)
5861             match_str = add_angle_brackets (sym_name);
5862           else
5863             match_str = sym_name;
5864
5865         }
5866
5867       comp_match_res->set_match (match_str.c_str ());
5868     }
5869
5870   return true;
5871 }
5872
5873                                 /* Field Access */
5874
5875 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
5876    for tagged types.  */
5877
5878 static int
5879 ada_is_dispatch_table_ptr_type (struct type *type)
5880 {
5881   const char *name;
5882
5883   if (type->code () != TYPE_CODE_PTR)
5884     return 0;
5885
5886   name = TYPE_TARGET_TYPE (type)->name ();
5887   if (name == NULL)
5888     return 0;
5889
5890   return (strcmp (name, "ada__tags__dispatch_table") == 0);
5891 }
5892
5893 /* Return non-zero if TYPE is an interface tag.  */
5894
5895 static int
5896 ada_is_interface_tag (struct type *type)
5897 {
5898   const char *name = type->name ();
5899
5900   if (name == NULL)
5901     return 0;
5902
5903   return (strcmp (name, "ada__tags__interface_tag") == 0);
5904 }
5905
5906 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
5907    to be invisible to users.  */
5908
5909 int
5910 ada_is_ignored_field (struct type *type, int field_num)
5911 {
5912   if (field_num < 0 || field_num > type->num_fields ())
5913     return 1;
5914
5915   /* Check the name of that field.  */
5916   {
5917     const char *name = TYPE_FIELD_NAME (type, field_num);
5918
5919     /* Anonymous field names should not be printed.
5920        brobecker/2007-02-20: I don't think this can actually happen
5921        but we don't want to print the value of anonymous fields anyway.  */
5922     if (name == NULL)
5923       return 1;
5924
5925     /* Normally, fields whose name start with an underscore ("_")
5926        are fields that have been internally generated by the compiler,
5927        and thus should not be printed.  The "_parent" field is special,
5928        however: This is a field internally generated by the compiler
5929        for tagged types, and it contains the components inherited from
5930        the parent type.  This field should not be printed as is, but
5931        should not be ignored either.  */
5932     if (name[0] == '_' && !startswith (name, "_parent"))
5933       return 1;
5934   }
5935
5936   /* If this is the dispatch table of a tagged type or an interface tag,
5937      then ignore.  */
5938   if (ada_is_tagged_type (type, 1)
5939       && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
5940           || ada_is_interface_tag (type->field (field_num).type ())))
5941     return 1;
5942
5943   /* Not a special field, so it should not be ignored.  */
5944   return 0;
5945 }
5946
5947 /* True iff TYPE has a tag field.  If REFOK, then TYPE may also be a
5948    pointer or reference type whose ultimate target has a tag field.  */
5949
5950 int
5951 ada_is_tagged_type (struct type *type, int refok)
5952 {
5953   return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
5954 }
5955
5956 /* True iff TYPE represents the type of X'Tag */
5957
5958 int
5959 ada_is_tag_type (struct type *type)
5960 {
5961   type = ada_check_typedef (type);
5962
5963   if (type == NULL || type->code () != TYPE_CODE_PTR)
5964     return 0;
5965   else
5966     {
5967       const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
5968
5969       return (name != NULL
5970               && strcmp (name, "ada__tags__dispatch_table") == 0);
5971     }
5972 }
5973
5974 /* The type of the tag on VAL.  */
5975
5976 static struct type *
5977 ada_tag_type (struct value *val)
5978 {
5979   return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0);
5980 }
5981
5982 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
5983    retired at Ada 05).  */
5984
5985 static int
5986 is_ada95_tag (struct value *tag)
5987 {
5988   return ada_value_struct_elt (tag, "tsd", 1) != NULL;
5989 }
5990
5991 /* The value of the tag on VAL.  */
5992
5993 static struct value *
5994 ada_value_tag (struct value *val)
5995 {
5996   return ada_value_struct_elt (val, "_tag", 0);
5997 }
5998
5999 /* The value of the tag on the object of type TYPE whose contents are
6000    saved at VALADDR, if it is non-null, or is at memory address
6001    ADDRESS.  */
6002
6003 static struct value *
6004 value_tag_from_contents_and_address (struct type *type,
6005                                      const gdb_byte *valaddr,
6006                                      CORE_ADDR address)
6007 {
6008   int tag_byte_offset;
6009   struct type *tag_type;
6010
6011   if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
6012                          NULL, NULL, NULL))
6013     {
6014       const gdb_byte *valaddr1 = ((valaddr == NULL)
6015                                   ? NULL
6016                                   : valaddr + tag_byte_offset);
6017       CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6018
6019       return value_from_contents_and_address (tag_type, valaddr1, address1);
6020     }
6021   return NULL;
6022 }
6023
6024 static struct type *
6025 type_from_tag (struct value *tag)
6026 {
6027   gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6028
6029   if (type_name != NULL)
6030     return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6031   return NULL;
6032 }
6033
6034 /* Given a value OBJ of a tagged type, return a value of this
6035    type at the base address of the object.  The base address, as
6036    defined in Ada.Tags, it is the address of the primary tag of
6037    the object, and therefore where the field values of its full
6038    view can be fetched.  */
6039
6040 struct value *
6041 ada_tag_value_at_base_address (struct value *obj)
6042 {
6043   struct value *val;
6044   LONGEST offset_to_top = 0;
6045   struct type *ptr_type, *obj_type;
6046   struct value *tag;
6047   CORE_ADDR base_address;
6048
6049   obj_type = value_type (obj);
6050
6051   /* It is the responsability of the caller to deref pointers.  */
6052
6053   if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6054     return obj;
6055
6056   tag = ada_value_tag (obj);
6057   if (!tag)
6058     return obj;
6059
6060   /* Base addresses only appeared with Ada 05 and multiple inheritance.  */
6061
6062   if (is_ada95_tag (tag))
6063     return obj;
6064
6065   ptr_type = language_lookup_primitive_type
6066     (language_def (language_ada), target_gdbarch(), "storage_offset");
6067   ptr_type = lookup_pointer_type (ptr_type);
6068   val = value_cast (ptr_type, tag);
6069   if (!val)
6070     return obj;
6071
6072   /* It is perfectly possible that an exception be raised while
6073      trying to determine the base address, just like for the tag;
6074      see ada_tag_name for more details.  We do not print the error
6075      message for the same reason.  */
6076
6077   try
6078     {
6079       offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6080     }
6081
6082   catch (const gdb_exception_error &e)
6083     {
6084       return obj;
6085     }
6086
6087   /* If offset is null, nothing to do.  */
6088
6089   if (offset_to_top == 0)
6090     return obj;
6091
6092   /* -1 is a special case in Ada.Tags; however, what should be done
6093      is not quite clear from the documentation.  So do nothing for
6094      now.  */
6095
6096   if (offset_to_top == -1)
6097     return obj;
6098
6099   /* OFFSET_TO_TOP used to be a positive value to be subtracted
6100      from the base address.  This was however incompatible with
6101      C++ dispatch table: C++ uses a *negative* value to *add*
6102      to the base address.  Ada's convention has therefore been
6103      changed in GNAT 19.0w 20171023: since then, C++ and Ada
6104      use the same convention.  Here, we support both cases by
6105      checking the sign of OFFSET_TO_TOP.  */
6106
6107   if (offset_to_top > 0)
6108     offset_to_top = -offset_to_top;
6109
6110   base_address = value_address (obj) + offset_to_top;
6111   tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6112
6113   /* Make sure that we have a proper tag at the new address.
6114      Otherwise, offset_to_top is bogus (which can happen when
6115      the object is not initialized yet).  */
6116
6117   if (!tag)
6118     return obj;
6119
6120   obj_type = type_from_tag (tag);
6121
6122   if (!obj_type)
6123     return obj;
6124
6125   return value_from_contents_and_address (obj_type, NULL, base_address);
6126 }
6127
6128 /* Return the "ada__tags__type_specific_data" type.  */
6129
6130 static struct type *
6131 ada_get_tsd_type (struct inferior *inf)
6132 {
6133   struct ada_inferior_data *data = get_ada_inferior_data (inf);
6134
6135   if (data->tsd_type == 0)
6136     data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6137   return data->tsd_type;
6138 }
6139
6140 /* Return the TSD (type-specific data) associated to the given TAG.
6141    TAG is assumed to be the tag of a tagged-type entity.
6142
6143    May return NULL if we are unable to get the TSD.  */
6144
6145 static struct value *
6146 ada_get_tsd_from_tag (struct value *tag)
6147 {
6148   struct value *val;
6149   struct type *type;
6150
6151   /* First option: The TSD is simply stored as a field of our TAG.
6152      Only older versions of GNAT would use this format, but we have
6153      to test it first, because there are no visible markers for
6154      the current approach except the absence of that field.  */
6155
6156   val = ada_value_struct_elt (tag, "tsd", 1);
6157   if (val)
6158     return val;
6159
6160   /* Try the second representation for the dispatch table (in which
6161      there is no explicit 'tsd' field in the referent of the tag pointer,
6162      and instead the tsd pointer is stored just before the dispatch
6163      table.  */
6164
6165   type = ada_get_tsd_type (current_inferior());
6166   if (type == NULL)
6167     return NULL;
6168   type = lookup_pointer_type (lookup_pointer_type (type));
6169   val = value_cast (type, tag);
6170   if (val == NULL)
6171     return NULL;
6172   return value_ind (value_ptradd (val, -1));
6173 }
6174
6175 /* Given the TSD of a tag (type-specific data), return a string
6176    containing the name of the associated type.
6177
6178    May return NULL if we are unable to determine the tag name.  */
6179
6180 static gdb::unique_xmalloc_ptr<char>
6181 ada_tag_name_from_tsd (struct value *tsd)
6182 {
6183   char *p;
6184   struct value *val;
6185
6186   val = ada_value_struct_elt (tsd, "expanded_name", 1);
6187   if (val == NULL)
6188     return NULL;
6189   gdb::unique_xmalloc_ptr<char> buffer
6190     = target_read_string (value_as_address (val), INT_MAX);
6191   if (buffer == nullptr)
6192     return nullptr;
6193
6194   for (p = buffer.get (); *p != '\0'; ++p)
6195     {
6196       if (isalpha (*p))
6197         *p = tolower (*p);
6198     }
6199
6200   return buffer;
6201 }
6202
6203 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6204    a C string.
6205
6206    Return NULL if the TAG is not an Ada tag, or if we were unable to
6207    determine the name of that tag.  */
6208
6209 gdb::unique_xmalloc_ptr<char>
6210 ada_tag_name (struct value *tag)
6211 {
6212   gdb::unique_xmalloc_ptr<char> name;
6213
6214   if (!ada_is_tag_type (value_type (tag)))
6215     return NULL;
6216
6217   /* It is perfectly possible that an exception be raised while trying
6218      to determine the TAG's name, even under normal circumstances:
6219      The associated variable may be uninitialized or corrupted, for
6220      instance. We do not let any exception propagate past this point.
6221      instead we return NULL.
6222
6223      We also do not print the error message either (which often is very
6224      low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6225      the caller print a more meaningful message if necessary.  */
6226   try
6227     {
6228       struct value *tsd = ada_get_tsd_from_tag (tag);
6229
6230       if (tsd != NULL)
6231         name = ada_tag_name_from_tsd (tsd);
6232     }
6233   catch (const gdb_exception_error &e)
6234     {
6235     }
6236
6237   return name;
6238 }
6239
6240 /* The parent type of TYPE, or NULL if none.  */
6241
6242 struct type *
6243 ada_parent_type (struct type *type)
6244 {
6245   int i;
6246
6247   type = ada_check_typedef (type);
6248
6249   if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6250     return NULL;
6251
6252   for (i = 0; i < type->num_fields (); i += 1)
6253     if (ada_is_parent_field (type, i))
6254       {
6255         struct type *parent_type = type->field (i).type ();
6256
6257         /* If the _parent field is a pointer, then dereference it.  */
6258         if (parent_type->code () == TYPE_CODE_PTR)
6259           parent_type = TYPE_TARGET_TYPE (parent_type);
6260         /* If there is a parallel XVS type, get the actual base type.  */
6261         parent_type = ada_get_base_type (parent_type);
6262
6263         return ada_check_typedef (parent_type);
6264       }
6265
6266   return NULL;
6267 }
6268
6269 /* True iff field number FIELD_NUM of structure type TYPE contains the
6270    parent-type (inherited) fields of a derived type.  Assumes TYPE is
6271    a structure type with at least FIELD_NUM+1 fields.  */
6272
6273 int
6274 ada_is_parent_field (struct type *type, int field_num)
6275 {
6276   const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);
6277
6278   return (name != NULL
6279           && (startswith (name, "PARENT")
6280               || startswith (name, "_parent")));
6281 }
6282
6283 /* True iff field number FIELD_NUM of structure type TYPE is a
6284    transparent wrapper field (which should be silently traversed when doing
6285    field selection and flattened when printing).  Assumes TYPE is a
6286    structure type with at least FIELD_NUM+1 fields.  Such fields are always
6287    structures.  */
6288
6289 int
6290 ada_is_wrapper_field (struct type *type, int field_num)
6291 {
6292   const char *name = TYPE_FIELD_NAME (type, field_num);
6293
6294   if (name != NULL && strcmp (name, "RETVAL") == 0)
6295     {
6296       /* This happens in functions with "out" or "in out" parameters
6297          which are passed by copy.  For such functions, GNAT describes
6298          the function's return type as being a struct where the return
6299          value is in a field called RETVAL, and where the other "out"
6300          or "in out" parameters are fields of that struct.  This is not
6301          a wrapper.  */
6302       return 0;
6303     }
6304
6305   return (name != NULL
6306           && (startswith (name, "PARENT")
6307               || strcmp (name, "REP") == 0
6308               || startswith (name, "_parent")
6309               || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6310 }
6311
6312 /* True iff field number FIELD_NUM of structure or union type TYPE
6313    is a variant wrapper.  Assumes TYPE is a structure type with at least
6314    FIELD_NUM+1 fields.  */
6315
6316 int
6317 ada_is_variant_part (struct type *type, int field_num)
6318 {
6319   /* Only Ada types are eligible.  */
6320   if (!ADA_TYPE_P (type))
6321     return 0;
6322
6323   struct type *field_type = type->field (field_num).type ();
6324
6325   return (field_type->code () == TYPE_CODE_UNION
6326           || (is_dynamic_field (type, field_num)
6327               && (TYPE_TARGET_TYPE (field_type)->code ()
6328                   == TYPE_CODE_UNION)));
6329 }
6330
6331 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6332    whose discriminants are contained in the record type OUTER_TYPE,
6333    returns the type of the controlling discriminant for the variant.
6334    May return NULL if the type could not be found.  */
6335
6336 struct type *
6337 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6338 {
6339   const char *name = ada_variant_discrim_name (var_type);
6340
6341   return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6342 }
6343
6344 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6345    valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6346    represents a 'when others' clause; otherwise 0.  */
6347
6348 static int
6349 ada_is_others_clause (struct type *type, int field_num)
6350 {
6351   const char *name = TYPE_FIELD_NAME (type, field_num);
6352
6353   return (name != NULL && name[0] == 'O');
6354 }
6355
6356 /* Assuming that TYPE0 is the type of the variant part of a record,
6357    returns the name of the discriminant controlling the variant.
6358    The value is valid until the next call to ada_variant_discrim_name.  */
6359
6360 const char *
6361 ada_variant_discrim_name (struct type *type0)
6362 {
6363   static std::string result;
6364   struct type *type;
6365   const char *name;
6366   const char *discrim_end;
6367   const char *discrim_start;
6368
6369   if (type0->code () == TYPE_CODE_PTR)
6370     type = TYPE_TARGET_TYPE (type0);
6371   else
6372     type = type0;
6373
6374   name = ada_type_name (type);
6375
6376   if (name == NULL || name[0] == '\000')
6377     return "";
6378
6379   for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6380        discrim_end -= 1)
6381     {
6382       if (startswith (discrim_end, "___XVN"))
6383         break;
6384     }
6385   if (discrim_end == name)
6386     return "";
6387
6388   for (discrim_start = discrim_end; discrim_start != name + 3;
6389        discrim_start -= 1)
6390     {
6391       if (discrim_start == name + 1)
6392         return "";
6393       if ((discrim_start > name + 3
6394            && startswith (discrim_start - 3, "___"))
6395           || discrim_start[-1] == '.')
6396         break;
6397     }
6398
6399   result = std::string (discrim_start, discrim_end - discrim_start);
6400   return result.c_str ();
6401 }
6402
6403 /* Scan STR for a subtype-encoded number, beginning at position K.
6404    Put the position of the character just past the number scanned in
6405    *NEW_K, if NEW_K!=NULL.  Put the scanned number in *R, if R!=NULL.
6406    Return 1 if there was a valid number at the given position, and 0
6407    otherwise.  A "subtype-encoded" number consists of the absolute value
6408    in decimal, followed by the letter 'm' to indicate a negative number.
6409    Assumes 0m does not occur.  */
6410
6411 int
6412 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6413 {
6414   ULONGEST RU;
6415
6416   if (!isdigit (str[k]))
6417     return 0;
6418
6419   /* Do it the hard way so as not to make any assumption about
6420      the relationship of unsigned long (%lu scan format code) and
6421      LONGEST.  */
6422   RU = 0;
6423   while (isdigit (str[k]))
6424     {
6425       RU = RU * 10 + (str[k] - '0');
6426       k += 1;
6427     }
6428
6429   if (str[k] == 'm')
6430     {
6431       if (R != NULL)
6432         *R = (-(LONGEST) (RU - 1)) - 1;
6433       k += 1;
6434     }
6435   else if (R != NULL)
6436     *R = (LONGEST) RU;
6437
6438   /* NOTE on the above: Technically, C does not say what the results of
6439      - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6440      number representable as a LONGEST (although either would probably work
6441      in most implementations).  When RU>0, the locution in the then branch
6442      above is always equivalent to the negative of RU.  */
6443
6444   if (new_k != NULL)
6445     *new_k = k;
6446   return 1;
6447 }
6448
6449 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6450    and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6451    in the range encoded by field FIELD_NUM of TYPE; otherwise 0.  */
6452
6453 static int
6454 ada_in_variant (LONGEST val, struct type *type, int field_num)
6455 {
6456   const char *name = TYPE_FIELD_NAME (type, field_num);
6457   int p;
6458
6459   p = 0;
6460   while (1)
6461     {
6462       switch (name[p])
6463         {
6464         case '\0':
6465           return 0;
6466         case 'S':
6467           {
6468             LONGEST W;
6469
6470             if (!ada_scan_number (name, p + 1, &W, &p))
6471               return 0;
6472             if (val == W)
6473               return 1;
6474             break;
6475           }
6476         case 'R':
6477           {
6478             LONGEST L, U;
6479
6480             if (!ada_scan_number (name, p + 1, &L, &p)
6481                 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6482               return 0;
6483             if (val >= L && val <= U)
6484               return 1;
6485             break;
6486           }
6487         case 'O':
6488           return 1;
6489         default:
6490           return 0;
6491         }
6492     }
6493 }
6494
6495 /* FIXME: Lots of redundancy below.  Try to consolidate.  */
6496
6497 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6498    ARG_TYPE, extract and return the value of one of its (non-static)
6499    fields.  FIELDNO says which field.   Differs from value_primitive_field
6500    only in that it can handle packed values of arbitrary type.  */
6501
6502 struct value *
6503 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6504                            struct type *arg_type)
6505 {
6506   struct type *type;
6507
6508   arg_type = ada_check_typedef (arg_type);
6509   type = arg_type->field (fieldno).type ();
6510
6511   /* Handle packed fields.  It might be that the field is not packed
6512      relative to its containing structure, but the structure itself is
6513      packed; in this case we must take the bit-field path.  */
6514   if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || value_bitpos (arg1) != 0)
6515     {
6516       int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
6517       int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6518
6519       return ada_value_primitive_packed_val (arg1, value_contents (arg1),
6520                                              offset + bit_pos / 8,
6521                                              bit_pos % 8, bit_size, type);
6522     }
6523   else
6524     return value_primitive_field (arg1, offset, fieldno, arg_type);
6525 }
6526
6527 /* Find field with name NAME in object of type TYPE.  If found, 
6528    set the following for each argument that is non-null:
6529     - *FIELD_TYPE_P to the field's type; 
6530     - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within 
6531       an object of that type;
6532     - *BIT_OFFSET_P to the bit offset modulo byte size of the field; 
6533     - *BIT_SIZE_P to its size in bits if the field is packed, and 
6534       0 otherwise;
6535    If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6536    fields up to but not including the desired field, or by the total
6537    number of fields if not found.   A NULL value of NAME never
6538    matches; the function just counts visible fields in this case.
6539    
6540    Notice that we need to handle when a tagged record hierarchy
6541    has some components with the same name, like in this scenario:
6542
6543       type Top_T is tagged record
6544          N : Integer := 1;
6545          U : Integer := 974;
6546          A : Integer := 48;
6547       end record;
6548
6549       type Middle_T is new Top.Top_T with record
6550          N : Character := 'a';
6551          C : Integer := 3;
6552       end record;
6553
6554      type Bottom_T is new Middle.Middle_T with record
6555         N : Float := 4.0;
6556         C : Character := '5';
6557         X : Integer := 6;
6558         A : Character := 'J';
6559      end record;
6560
6561    Let's say we now have a variable declared and initialized as follow:
6562
6563      TC : Top_A := new Bottom_T;
6564
6565    And then we use this variable to call this function
6566
6567      procedure Assign (Obj: in out Top_T; TV : Integer);
6568
6569    as follow:
6570
6571       Assign (Top_T (B), 12);
6572
6573    Now, we're in the debugger, and we're inside that procedure
6574    then and we want to print the value of obj.c:
6575
6576    Usually, the tagged record or one of the parent type owns the
6577    component to print and there's no issue but in this particular
6578    case, what does it mean to ask for Obj.C? Since the actual
6579    type for object is type Bottom_T, it could mean two things: type
6580    component C from the Middle_T view, but also component C from
6581    Bottom_T.  So in that "undefined" case, when the component is
6582    not found in the non-resolved type (which includes all the
6583    components of the parent type), then resolve it and see if we
6584    get better luck once expanded.
6585
6586    In the case of homonyms in the derived tagged type, we don't
6587    guaranty anything, and pick the one that's easiest for us
6588    to program.
6589
6590    Returns 1 if found, 0 otherwise.  */
6591
6592 static int
6593 find_struct_field (const char *name, struct type *type, int offset,
6594                    struct type **field_type_p,
6595                    int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6596                    int *index_p)
6597 {
6598   int i;
6599   int parent_offset = -1;
6600
6601   type = ada_check_typedef (type);
6602
6603   if (field_type_p != NULL)
6604     *field_type_p = NULL;
6605   if (byte_offset_p != NULL)
6606     *byte_offset_p = 0;
6607   if (bit_offset_p != NULL)
6608     *bit_offset_p = 0;
6609   if (bit_size_p != NULL)
6610     *bit_size_p = 0;
6611
6612   for (i = 0; i < type->num_fields (); i += 1)
6613     {
6614       int bit_pos = TYPE_FIELD_BITPOS (type, i);
6615       int fld_offset = offset + bit_pos / 8;
6616       const char *t_field_name = TYPE_FIELD_NAME (type, i);
6617
6618       if (t_field_name == NULL)
6619         continue;
6620
6621       else if (ada_is_parent_field (type, i))
6622         {
6623           /* This is a field pointing us to the parent type of a tagged
6624              type.  As hinted in this function's documentation, we give
6625              preference to fields in the current record first, so what
6626              we do here is just record the index of this field before
6627              we skip it.  If it turns out we couldn't find our field
6628              in the current record, then we'll get back to it and search
6629              inside it whether the field might exist in the parent.  */
6630
6631           parent_offset = i;
6632           continue;
6633         }
6634
6635       else if (name != NULL && field_name_match (t_field_name, name))
6636         {
6637           int bit_size = TYPE_FIELD_BITSIZE (type, i);
6638
6639           if (field_type_p != NULL)
6640             *field_type_p = type->field (i).type ();
6641           if (byte_offset_p != NULL)
6642             *byte_offset_p = fld_offset;
6643           if (bit_offset_p != NULL)
6644             *bit_offset_p = bit_pos % 8;
6645           if (bit_size_p != NULL)
6646             *bit_size_p = bit_size;
6647           return 1;
6648         }
6649       else if (ada_is_wrapper_field (type, i))
6650         {
6651           if (find_struct_field (name, type->field (i).type (), fld_offset,
6652                                  field_type_p, byte_offset_p, bit_offset_p,
6653                                  bit_size_p, index_p))
6654             return 1;
6655         }
6656       else if (ada_is_variant_part (type, i))
6657         {
6658           /* PNH: Wait.  Do we ever execute this section, or is ARG always of 
6659              fixed type?? */
6660           int j;
6661           struct type *field_type
6662             = ada_check_typedef (type->field (i).type ());
6663
6664           for (j = 0; j < field_type->num_fields (); j += 1)
6665             {
6666               if (find_struct_field (name, field_type->field (j).type (),
6667                                      fld_offset
6668                                      + TYPE_FIELD_BITPOS (field_type, j) / 8,
6669                                      field_type_p, byte_offset_p,
6670                                      bit_offset_p, bit_size_p, index_p))
6671                 return 1;
6672             }
6673         }
6674       else if (index_p != NULL)
6675         *index_p += 1;
6676     }
6677
6678   /* Field not found so far.  If this is a tagged type which
6679      has a parent, try finding that field in the parent now.  */
6680
6681   if (parent_offset != -1)
6682     {
6683       int bit_pos = TYPE_FIELD_BITPOS (type, parent_offset);
6684       int fld_offset = offset + bit_pos / 8;
6685
6686       if (find_struct_field (name, type->field (parent_offset).type (),
6687                              fld_offset, field_type_p, byte_offset_p,
6688                              bit_offset_p, bit_size_p, index_p))
6689         return 1;
6690     }
6691
6692   return 0;
6693 }
6694
6695 /* Number of user-visible fields in record type TYPE.  */
6696
6697 static int
6698 num_visible_fields (struct type *type)
6699 {
6700   int n;
6701
6702   n = 0;
6703   find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
6704   return n;
6705 }
6706
6707 /* Look for a field NAME in ARG.  Adjust the address of ARG by OFFSET bytes,
6708    and search in it assuming it has (class) type TYPE.
6709    If found, return value, else return NULL.
6710
6711    Searches recursively through wrapper fields (e.g., '_parent').
6712
6713    In the case of homonyms in the tagged types, please refer to the
6714    long explanation in find_struct_field's function documentation.  */
6715
6716 static struct value *
6717 ada_search_struct_field (const char *name, struct value *arg, int offset,
6718                          struct type *type)
6719 {
6720   int i;
6721   int parent_offset = -1;
6722
6723   type = ada_check_typedef (type);
6724   for (i = 0; i < type->num_fields (); i += 1)
6725     {
6726       const char *t_field_name = TYPE_FIELD_NAME (type, i);
6727
6728       if (t_field_name == NULL)
6729         continue;
6730
6731       else if (ada_is_parent_field (type, i))
6732         {
6733           /* This is a field pointing us to the parent type of a tagged
6734              type.  As hinted in this function's documentation, we give
6735              preference to fields in the current record first, so what
6736              we do here is just record the index of this field before
6737              we skip it.  If it turns out we couldn't find our field
6738              in the current record, then we'll get back to it and search
6739              inside it whether the field might exist in the parent.  */
6740
6741           parent_offset = i;
6742           continue;
6743         }
6744
6745       else if (field_name_match (t_field_name, name))
6746         return ada_value_primitive_field (arg, offset, i, type);
6747
6748       else if (ada_is_wrapper_field (type, i))
6749         {
6750           struct value *v =     /* Do not let indent join lines here.  */
6751             ada_search_struct_field (name, arg,
6752                                      offset + TYPE_FIELD_BITPOS (type, i) / 8,
6753                                      type->field (i).type ());
6754
6755           if (v != NULL)
6756             return v;
6757         }
6758
6759       else if (ada_is_variant_part (type, i))
6760         {
6761           /* PNH: Do we ever get here?  See find_struct_field.  */
6762           int j;
6763           struct type *field_type = ada_check_typedef (type->field (i).type ());
6764           int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
6765
6766           for (j = 0; j < field_type->num_fields (); j += 1)
6767             {
6768               struct value *v = ada_search_struct_field /* Force line
6769                                                            break.  */
6770                 (name, arg,
6771                  var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
6772                  field_type->field (j).type ());
6773
6774               if (v != NULL)
6775                 return v;
6776             }
6777         }
6778     }
6779
6780   /* Field not found so far.  If this is a tagged type which
6781      has a parent, try finding that field in the parent now.  */
6782
6783   if (parent_offset != -1)
6784     {
6785       struct value *v = ada_search_struct_field (
6786         name, arg, offset + TYPE_FIELD_BITPOS (type, parent_offset) / 8,
6787         type->field (parent_offset).type ());
6788
6789       if (v != NULL)
6790         return v;
6791     }
6792
6793   return NULL;
6794 }
6795
6796 static struct value *ada_index_struct_field_1 (int *, struct value *,
6797                                                int, struct type *);
6798
6799
6800 /* Return field #INDEX in ARG, where the index is that returned by
6801  * find_struct_field through its INDEX_P argument.  Adjust the address
6802  * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
6803  * If found, return value, else return NULL.  */
6804
6805 static struct value *
6806 ada_index_struct_field (int index, struct value *arg, int offset,
6807                         struct type *type)
6808 {
6809   return ada_index_struct_field_1 (&index, arg, offset, type);
6810 }
6811
6812
6813 /* Auxiliary function for ada_index_struct_field.  Like
6814  * ada_index_struct_field, but takes index from *INDEX_P and modifies
6815  * *INDEX_P.  */
6816
6817 static struct value *
6818 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
6819                           struct type *type)
6820 {
6821   int i;
6822   type = ada_check_typedef (type);
6823
6824   for (i = 0; i < type->num_fields (); i += 1)
6825     {
6826       if (TYPE_FIELD_NAME (type, i) == NULL)
6827         continue;
6828       else if (ada_is_wrapper_field (type, i))
6829         {
6830           struct value *v =     /* Do not let indent join lines here.  */
6831             ada_index_struct_field_1 (index_p, arg,
6832                                       offset + TYPE_FIELD_BITPOS (type, i) / 8,
6833                                       type->field (i).type ());
6834
6835           if (v != NULL)
6836             return v;
6837         }
6838
6839       else if (ada_is_variant_part (type, i))
6840         {
6841           /* PNH: Do we ever get here?  See ada_search_struct_field,
6842              find_struct_field.  */
6843           error (_("Cannot assign this kind of variant record"));
6844         }
6845       else if (*index_p == 0)
6846         return ada_value_primitive_field (arg, offset, i, type);
6847       else
6848         *index_p -= 1;
6849     }
6850   return NULL;
6851 }
6852
6853 /* Return a string representation of type TYPE.  */
6854
6855 static std::string
6856 type_as_string (struct type *type)
6857 {
6858   string_file tmp_stream;
6859
6860   type_print (type, "", &tmp_stream, -1);
6861
6862   return std::move (tmp_stream.string ());
6863 }
6864
6865 /* Given a type TYPE, look up the type of the component of type named NAME.
6866    If DISPP is non-null, add its byte displacement from the beginning of a
6867    structure (pointed to by a value) of type TYPE to *DISPP (does not
6868    work for packed fields).
6869
6870    Matches any field whose name has NAME as a prefix, possibly
6871    followed by "___".
6872
6873    TYPE can be either a struct or union.  If REFOK, TYPE may also 
6874    be a (pointer or reference)+ to a struct or union, and the
6875    ultimate target type will be searched.
6876
6877    Looks recursively into variant clauses and parent types.
6878
6879    In the case of homonyms in the tagged types, please refer to the
6880    long explanation in find_struct_field's function documentation.
6881
6882    If NOERR is nonzero, return NULL if NAME is not suitably defined or
6883    TYPE is not a type of the right kind.  */
6884
6885 static struct type *
6886 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
6887                             int noerr)
6888 {
6889   int i;
6890   int parent_offset = -1;
6891
6892   if (name == NULL)
6893     goto BadName;
6894
6895   if (refok && type != NULL)
6896     while (1)
6897       {
6898         type = ada_check_typedef (type);
6899         if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
6900           break;
6901         type = TYPE_TARGET_TYPE (type);
6902       }
6903
6904   if (type == NULL
6905       || (type->code () != TYPE_CODE_STRUCT
6906           && type->code () != TYPE_CODE_UNION))
6907     {
6908       if (noerr)
6909         return NULL;
6910
6911       error (_("Type %s is not a structure or union type"),
6912              type != NULL ? type_as_string (type).c_str () : _("(null)"));
6913     }
6914
6915   type = to_static_fixed_type (type);
6916
6917   for (i = 0; i < type->num_fields (); i += 1)
6918     {
6919       const char *t_field_name = TYPE_FIELD_NAME (type, i);
6920       struct type *t;
6921
6922       if (t_field_name == NULL)
6923         continue;
6924
6925       else if (ada_is_parent_field (type, i))
6926         {
6927           /* This is a field pointing us to the parent type of a tagged
6928              type.  As hinted in this function's documentation, we give
6929              preference to fields in the current record first, so what
6930              we do here is just record the index of this field before
6931              we skip it.  If it turns out we couldn't find our field
6932              in the current record, then we'll get back to it and search
6933              inside it whether the field might exist in the parent.  */
6934
6935           parent_offset = i;
6936           continue;
6937         }
6938
6939       else if (field_name_match (t_field_name, name))
6940         return type->field (i).type ();
6941
6942       else if (ada_is_wrapper_field (type, i))
6943         {
6944           t = ada_lookup_struct_elt_type (type->field (i).type (), name,
6945                                           0, 1);
6946           if (t != NULL)
6947             return t;
6948         }
6949
6950       else if (ada_is_variant_part (type, i))
6951         {
6952           int j;
6953           struct type *field_type = ada_check_typedef (type->field (i).type ());
6954
6955           for (j = field_type->num_fields () - 1; j >= 0; j -= 1)
6956             {
6957               /* FIXME pnh 2008/01/26: We check for a field that is
6958                  NOT wrapped in a struct, since the compiler sometimes
6959                  generates these for unchecked variant types.  Revisit
6960                  if the compiler changes this practice.  */
6961               const char *v_field_name = TYPE_FIELD_NAME (field_type, j);
6962
6963               if (v_field_name != NULL 
6964                   && field_name_match (v_field_name, name))
6965                 t = field_type->field (j).type ();
6966               else
6967                 t = ada_lookup_struct_elt_type (field_type->field (j).type (),
6968                                                 name, 0, 1);
6969
6970               if (t != NULL)
6971                 return t;
6972             }
6973         }
6974
6975     }
6976
6977     /* Field not found so far.  If this is a tagged type which
6978        has a parent, try finding that field in the parent now.  */
6979
6980     if (parent_offset != -1)
6981       {
6982         struct type *t;
6983
6984         t = ada_lookup_struct_elt_type (type->field (parent_offset).type (),
6985                                         name, 0, 1);
6986         if (t != NULL)
6987           return t;
6988       }
6989
6990 BadName:
6991   if (!noerr)
6992     {
6993       const char *name_str = name != NULL ? name : _("<null>");
6994
6995       error (_("Type %s has no component named %s"),
6996              type_as_string (type).c_str (), name_str);
6997     }
6998
6999   return NULL;
7000 }
7001
7002 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7003    within a value of type OUTER_TYPE, return true iff VAR_TYPE
7004    represents an unchecked union (that is, the variant part of a
7005    record that is named in an Unchecked_Union pragma).  */
7006
7007 static int
7008 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7009 {
7010   const char *discrim_name = ada_variant_discrim_name (var_type);
7011
7012   return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7013 }
7014
7015
7016 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7017    within OUTER, determine which variant clause (field number in VAR_TYPE,
7018    numbering from 0) is applicable.  Returns -1 if none are.  */
7019
7020 int
7021 ada_which_variant_applies (struct type *var_type, struct value *outer)
7022 {
7023   int others_clause;
7024   int i;
7025   const char *discrim_name = ada_variant_discrim_name (var_type);
7026   struct value *discrim;
7027   LONGEST discrim_val;
7028
7029   /* Using plain value_from_contents_and_address here causes problems
7030      because we will end up trying to resolve a type that is currently
7031      being constructed.  */
7032   discrim = ada_value_struct_elt (outer, discrim_name, 1);
7033   if (discrim == NULL)
7034     return -1;
7035   discrim_val = value_as_long (discrim);
7036
7037   others_clause = -1;
7038   for (i = 0; i < var_type->num_fields (); i += 1)
7039     {
7040       if (ada_is_others_clause (var_type, i))
7041         others_clause = i;
7042       else if (ada_in_variant (discrim_val, var_type, i))
7043         return i;
7044     }
7045
7046   return others_clause;
7047 }
7048 \f
7049
7050
7051                                 /* Dynamic-Sized Records */
7052
7053 /* Strategy: The type ostensibly attached to a value with dynamic size
7054    (i.e., a size that is not statically recorded in the debugging
7055    data) does not accurately reflect the size or layout of the value.
7056    Our strategy is to convert these values to values with accurate,
7057    conventional types that are constructed on the fly.  */
7058
7059 /* There is a subtle and tricky problem here.  In general, we cannot
7060    determine the size of dynamic records without its data.  However,
7061    the 'struct value' data structure, which GDB uses to represent
7062    quantities in the inferior process (the target), requires the size
7063    of the type at the time of its allocation in order to reserve space
7064    for GDB's internal copy of the data.  That's why the
7065    'to_fixed_xxx_type' routines take (target) addresses as parameters,
7066    rather than struct value*s.
7067
7068    However, GDB's internal history variables ($1, $2, etc.) are
7069    struct value*s containing internal copies of the data that are not, in
7070    general, the same as the data at their corresponding addresses in
7071    the target.  Fortunately, the types we give to these values are all
7072    conventional, fixed-size types (as per the strategy described
7073    above), so that we don't usually have to perform the
7074    'to_fixed_xxx_type' conversions to look at their values.
7075    Unfortunately, there is one exception: if one of the internal
7076    history variables is an array whose elements are unconstrained
7077    records, then we will need to create distinct fixed types for each
7078    element selected.  */
7079
7080 /* The upshot of all of this is that many routines take a (type, host
7081    address, target address) triple as arguments to represent a value.
7082    The host address, if non-null, is supposed to contain an internal
7083    copy of the relevant data; otherwise, the program is to consult the
7084    target at the target address.  */
7085
7086 /* Assuming that VAL0 represents a pointer value, the result of
7087    dereferencing it.  Differs from value_ind in its treatment of
7088    dynamic-sized types.  */
7089
7090 struct value *
7091 ada_value_ind (struct value *val0)
7092 {
7093   struct value *val = value_ind (val0);
7094
7095   if (ada_is_tagged_type (value_type (val), 0))
7096     val = ada_tag_value_at_base_address (val);
7097
7098   return ada_to_fixed_value (val);
7099 }
7100
7101 /* The value resulting from dereferencing any "reference to"
7102    qualifiers on VAL0.  */
7103
7104 static struct value *
7105 ada_coerce_ref (struct value *val0)
7106 {
7107   if (value_type (val0)->code () == TYPE_CODE_REF)
7108     {
7109       struct value *val = val0;
7110
7111       val = coerce_ref (val);
7112
7113       if (ada_is_tagged_type (value_type (val), 0))
7114         val = ada_tag_value_at_base_address (val);
7115
7116       return ada_to_fixed_value (val);
7117     }
7118   else
7119     return val0;
7120 }
7121
7122 /* Return the bit alignment required for field #F of template type TYPE.  */
7123
7124 static unsigned int
7125 field_alignment (struct type *type, int f)
7126 {
7127   const char *name = TYPE_FIELD_NAME (type, f);
7128   int len;
7129   int align_offset;
7130
7131   /* The field name should never be null, unless the debugging information
7132      is somehow malformed.  In this case, we assume the field does not
7133      require any alignment.  */
7134   if (name == NULL)
7135     return 1;
7136
7137   len = strlen (name);
7138
7139   if (!isdigit (name[len - 1]))
7140     return 1;
7141
7142   if (isdigit (name[len - 2]))
7143     align_offset = len - 2;
7144   else
7145     align_offset = len - 1;
7146
7147   if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7148     return TARGET_CHAR_BIT;
7149
7150   return atoi (name + align_offset) * TARGET_CHAR_BIT;
7151 }
7152
7153 /* Find a typedef or tag symbol named NAME.  Ignores ambiguity.  */
7154
7155 static struct symbol *
7156 ada_find_any_type_symbol (const char *name)
7157 {
7158   struct symbol *sym;
7159
7160   sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7161   if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
7162     return sym;
7163
7164   sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7165   return sym;
7166 }
7167
7168 /* Find a type named NAME.  Ignores ambiguity.  This routine will look
7169    solely for types defined by debug info, it will not search the GDB
7170    primitive types.  */
7171
7172 static struct type *
7173 ada_find_any_type (const char *name)
7174 {
7175   struct symbol *sym = ada_find_any_type_symbol (name);
7176
7177   if (sym != NULL)
7178     return SYMBOL_TYPE (sym);
7179
7180   return NULL;
7181 }
7182
7183 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7184    associated with NAME_SYM's name.  NAME_SYM may itself be a renaming
7185    symbol, in which case it is returned.  Otherwise, this looks for
7186    symbols whose name is that of NAME_SYM suffixed with  "___XR".
7187    Return symbol if found, and NULL otherwise.  */
7188
7189 static bool
7190 ada_is_renaming_symbol (struct symbol *name_sym)
7191 {
7192   const char *name = name_sym->linkage_name ();
7193   return strstr (name, "___XR") != NULL;
7194 }
7195
7196 /* Because of GNAT encoding conventions, several GDB symbols may match a
7197    given type name.  If the type denoted by TYPE0 is to be preferred to
7198    that of TYPE1 for purposes of type printing, return non-zero;
7199    otherwise return 0.  */
7200
7201 int
7202 ada_prefer_type (struct type *type0, struct type *type1)
7203 {
7204   if (type1 == NULL)
7205     return 1;
7206   else if (type0 == NULL)
7207     return 0;
7208   else if (type1->code () == TYPE_CODE_VOID)
7209     return 1;
7210   else if (type0->code () == TYPE_CODE_VOID)
7211     return 0;
7212   else if (type1->name () == NULL && type0->name () != NULL)
7213     return 1;
7214   else if (ada_is_constrained_packed_array_type (type0))
7215     return 1;
7216   else if (ada_is_array_descriptor_type (type0)
7217            && !ada_is_array_descriptor_type (type1))
7218     return 1;
7219   else
7220     {
7221       const char *type0_name = type0->name ();
7222       const char *type1_name = type1->name ();
7223
7224       if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7225           && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7226         return 1;
7227     }
7228   return 0;
7229 }
7230
7231 /* The name of TYPE, which is its TYPE_NAME.  Null if TYPE is
7232    null.  */
7233
7234 const char *
7235 ada_type_name (struct type *type)
7236 {
7237   if (type == NULL)
7238     return NULL;
7239   return type->name ();
7240 }
7241
7242 /* Search the list of "descriptive" types associated to TYPE for a type
7243    whose name is NAME.  */
7244
7245 static struct type *
7246 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7247 {
7248   struct type *result, *tmp;
7249
7250   if (ada_ignore_descriptive_types_p)
7251     return NULL;
7252
7253   /* If there no descriptive-type info, then there is no parallel type
7254      to be found.  */
7255   if (!HAVE_GNAT_AUX_INFO (type))
7256     return NULL;
7257
7258   result = TYPE_DESCRIPTIVE_TYPE (type);
7259   while (result != NULL)
7260     {
7261       const char *result_name = ada_type_name (result);
7262
7263       if (result_name == NULL)
7264         {
7265           warning (_("unexpected null name on descriptive type"));
7266           return NULL;
7267         }
7268
7269       /* If the names match, stop.  */
7270       if (strcmp (result_name, name) == 0)
7271         break;
7272
7273       /* Otherwise, look at the next item on the list, if any.  */
7274       if (HAVE_GNAT_AUX_INFO (result))
7275         tmp = TYPE_DESCRIPTIVE_TYPE (result);
7276       else
7277         tmp = NULL;
7278
7279       /* If not found either, try after having resolved the typedef.  */
7280       if (tmp != NULL)
7281         result = tmp;
7282       else
7283         {
7284           result = check_typedef (result);
7285           if (HAVE_GNAT_AUX_INFO (result))
7286             result = TYPE_DESCRIPTIVE_TYPE (result);
7287           else
7288             result = NULL;
7289         }
7290     }
7291
7292   /* If we didn't find a match, see whether this is a packed array.  With
7293      older compilers, the descriptive type information is either absent or
7294      irrelevant when it comes to packed arrays so the above lookup fails.
7295      Fall back to using a parallel lookup by name in this case.  */
7296   if (result == NULL && ada_is_constrained_packed_array_type (type))
7297     return ada_find_any_type (name);
7298
7299   return result;
7300 }
7301
7302 /* Find a parallel type to TYPE with the specified NAME, using the
7303    descriptive type taken from the debugging information, if available,
7304    and otherwise using the (slower) name-based method.  */
7305
7306 static struct type *
7307 ada_find_parallel_type_with_name (struct type *type, const char *name)
7308 {
7309   struct type *result = NULL;
7310
7311   if (HAVE_GNAT_AUX_INFO (type))
7312     result = find_parallel_type_by_descriptive_type (type, name);
7313   else
7314     result = ada_find_any_type (name);
7315
7316   return result;
7317 }
7318
7319 /* Same as above, but specify the name of the parallel type by appending
7320    SUFFIX to the name of TYPE.  */
7321
7322 struct type *
7323 ada_find_parallel_type (struct type *type, const char *suffix)
7324 {
7325   char *name;
7326   const char *type_name = ada_type_name (type);
7327   int len;
7328
7329   if (type_name == NULL)
7330     return NULL;
7331
7332   len = strlen (type_name);
7333
7334   name = (char *) alloca (len + strlen (suffix) + 1);
7335
7336   strcpy (name, type_name);
7337   strcpy (name + len, suffix);
7338
7339   return ada_find_parallel_type_with_name (type, name);
7340 }
7341
7342 /* If TYPE is a variable-size record type, return the corresponding template
7343    type describing its fields.  Otherwise, return NULL.  */
7344
7345 static struct type *
7346 dynamic_template_type (struct type *type)
7347 {
7348   type = ada_check_typedef (type);
7349
7350   if (type == NULL || type->code () != TYPE_CODE_STRUCT
7351       || ada_type_name (type) == NULL)
7352     return NULL;
7353   else
7354     {
7355       int len = strlen (ada_type_name (type));
7356
7357       if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7358         return type;
7359       else
7360         return ada_find_parallel_type (type, "___XVE");
7361     }
7362 }
7363
7364 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7365    non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size.  */
7366
7367 static int
7368 is_dynamic_field (struct type *templ_type, int field_num)
7369 {
7370   const char *name = TYPE_FIELD_NAME (templ_type, field_num);
7371
7372   return name != NULL
7373     && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7374     && strstr (name, "___XVL") != NULL;
7375 }
7376
7377 /* The index of the variant field of TYPE, or -1 if TYPE does not
7378    represent a variant record type.  */
7379
7380 static int
7381 variant_field_index (struct type *type)
7382 {
7383   int f;
7384
7385   if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7386     return -1;
7387
7388   for (f = 0; f < type->num_fields (); f += 1)
7389     {
7390       if (ada_is_variant_part (type, f))
7391         return f;
7392     }
7393   return -1;
7394 }
7395
7396 /* A record type with no fields.  */
7397
7398 static struct type *
7399 empty_record (struct type *templ)
7400 {
7401   struct type *type = alloc_type_copy (templ);
7402
7403   type->set_code (TYPE_CODE_STRUCT);
7404   INIT_NONE_SPECIFIC (type);
7405   type->set_name ("<empty>");
7406   TYPE_LENGTH (type) = 0;
7407   return type;
7408 }
7409
7410 /* An ordinary record type (with fixed-length fields) that describes
7411    the value of type TYPE at VALADDR or ADDRESS (see comments at
7412    the beginning of this section) VAL according to GNAT conventions.
7413    DVAL0 should describe the (portion of a) record that contains any
7414    necessary discriminants.  It should be NULL if value_type (VAL) is
7415    an outer-level type (i.e., as opposed to a branch of a variant.)  A
7416    variant field (unless unchecked) is replaced by a particular branch
7417    of the variant.
7418
7419    If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7420    length are not statically known are discarded.  As a consequence,
7421    VALADDR, ADDRESS and DVAL0 are ignored.
7422
7423    NOTE: Limitations: For now, we assume that dynamic fields and
7424    variants occupy whole numbers of bytes.  However, they need not be
7425    byte-aligned.  */
7426
7427 struct type *
7428 ada_template_to_fixed_record_type_1 (struct type *type,
7429                                      const gdb_byte *valaddr,
7430                                      CORE_ADDR address, struct value *dval0,
7431                                      int keep_dynamic_fields)
7432 {
7433   struct value *mark = value_mark ();
7434   struct value *dval;
7435   struct type *rtype;
7436   int nfields, bit_len;
7437   int variant_field;
7438   long off;
7439   int fld_bit_len;
7440   int f;
7441
7442   /* Compute the number of fields in this record type that are going
7443      to be processed: unless keep_dynamic_fields, this includes only
7444      fields whose position and length are static will be processed.  */
7445   if (keep_dynamic_fields)
7446     nfields = type->num_fields ();
7447   else
7448     {
7449       nfields = 0;
7450       while (nfields < type->num_fields ()
7451              && !ada_is_variant_part (type, nfields)
7452              && !is_dynamic_field (type, nfields))
7453         nfields++;
7454     }
7455
7456   rtype = alloc_type_copy (type);
7457   rtype->set_code (TYPE_CODE_STRUCT);
7458   INIT_NONE_SPECIFIC (rtype);
7459   rtype->set_num_fields (nfields);
7460   rtype->set_fields
7461    ((struct field *) TYPE_ZALLOC (rtype, nfields * sizeof (struct field)));
7462   rtype->set_name (ada_type_name (type));
7463   rtype->set_is_fixed_instance (true);
7464
7465   off = 0;
7466   bit_len = 0;
7467   variant_field = -1;
7468
7469   for (f = 0; f < nfields; f += 1)
7470     {
7471       off = align_up (off, field_alignment (type, f))
7472         + TYPE_FIELD_BITPOS (type, f);
7473       SET_FIELD_BITPOS (rtype->field (f), off);
7474       TYPE_FIELD_BITSIZE (rtype, f) = 0;
7475
7476       if (ada_is_variant_part (type, f))
7477         {
7478           variant_field = f;
7479           fld_bit_len = 0;
7480         }
7481       else if (is_dynamic_field (type, f))
7482         {
7483           const gdb_byte *field_valaddr = valaddr;
7484           CORE_ADDR field_address = address;
7485           struct type *field_type =
7486             TYPE_TARGET_TYPE (type->field (f).type ());
7487
7488           if (dval0 == NULL)
7489             {
7490               /* rtype's length is computed based on the run-time
7491                  value of discriminants.  If the discriminants are not
7492                  initialized, the type size may be completely bogus and
7493                  GDB may fail to allocate a value for it.  So check the
7494                  size first before creating the value.  */
7495               ada_ensure_varsize_limit (rtype);
7496               /* Using plain value_from_contents_and_address here
7497                  causes problems because we will end up trying to
7498                  resolve a type that is currently being
7499                  constructed.  */
7500               dval = value_from_contents_and_address_unresolved (rtype,
7501                                                                  valaddr,
7502                                                                  address);
7503               rtype = value_type (dval);
7504             }
7505           else
7506             dval = dval0;
7507
7508           /* If the type referenced by this field is an aligner type, we need
7509              to unwrap that aligner type, because its size might not be set.
7510              Keeping the aligner type would cause us to compute the wrong
7511              size for this field, impacting the offset of the all the fields
7512              that follow this one.  */
7513           if (ada_is_aligner_type (field_type))
7514             {
7515               long field_offset = TYPE_FIELD_BITPOS (field_type, f);
7516
7517               field_valaddr = cond_offset_host (field_valaddr, field_offset);
7518               field_address = cond_offset_target (field_address, field_offset);
7519               field_type = ada_aligned_type (field_type);
7520             }
7521
7522           field_valaddr = cond_offset_host (field_valaddr,
7523                                             off / TARGET_CHAR_BIT);
7524           field_address = cond_offset_target (field_address,
7525                                               off / TARGET_CHAR_BIT);
7526
7527           /* Get the fixed type of the field.  Note that, in this case,
7528              we do not want to get the real type out of the tag: if
7529              the current field is the parent part of a tagged record,
7530              we will get the tag of the object.  Clearly wrong: the real
7531              type of the parent is not the real type of the child.  We
7532              would end up in an infinite loop.  */
7533           field_type = ada_get_base_type (field_type);
7534           field_type = ada_to_fixed_type (field_type, field_valaddr,
7535                                           field_address, dval, 0);
7536           /* If the field size is already larger than the maximum
7537              object size, then the record itself will necessarily
7538              be larger than the maximum object size.  We need to make
7539              this check now, because the size might be so ridiculously
7540              large (due to an uninitialized variable in the inferior)
7541              that it would cause an overflow when adding it to the
7542              record size.  */
7543           ada_ensure_varsize_limit (field_type);
7544
7545           rtype->field (f).set_type (field_type);
7546           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7547           /* The multiplication can potentially overflow.  But because
7548              the field length has been size-checked just above, and
7549              assuming that the maximum size is a reasonable value,
7550              an overflow should not happen in practice.  So rather than
7551              adding overflow recovery code to this already complex code,
7552              we just assume that it's not going to happen.  */
7553           fld_bit_len =
7554             TYPE_LENGTH (rtype->field (f).type ()) * TARGET_CHAR_BIT;
7555         }
7556       else
7557         {
7558           /* Note: If this field's type is a typedef, it is important
7559              to preserve the typedef layer.
7560
7561              Otherwise, we might be transforming a typedef to a fat
7562              pointer (encoding a pointer to an unconstrained array),
7563              into a basic fat pointer (encoding an unconstrained
7564              array).  As both types are implemented using the same
7565              structure, the typedef is the only clue which allows us
7566              to distinguish between the two options.  Stripping it
7567              would prevent us from printing this field appropriately.  */
7568           rtype->field (f).set_type (type->field (f).type ());
7569           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
7570           if (TYPE_FIELD_BITSIZE (type, f) > 0)
7571             fld_bit_len =
7572               TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7573           else
7574             {
7575               struct type *field_type = type->field (f).type ();
7576
7577               /* We need to be careful of typedefs when computing
7578                  the length of our field.  If this is a typedef,
7579                  get the length of the target type, not the length
7580                  of the typedef.  */
7581               if (field_type->code () == TYPE_CODE_TYPEDEF)
7582                 field_type = ada_typedef_target_type (field_type);
7583
7584               fld_bit_len =
7585                 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
7586             }
7587         }
7588       if (off + fld_bit_len > bit_len)
7589         bit_len = off + fld_bit_len;
7590       off += fld_bit_len;
7591       TYPE_LENGTH (rtype) =
7592         align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7593     }
7594
7595   /* We handle the variant part, if any, at the end because of certain
7596      odd cases in which it is re-ordered so as NOT to be the last field of
7597      the record.  This can happen in the presence of representation
7598      clauses.  */
7599   if (variant_field >= 0)
7600     {
7601       struct type *branch_type;
7602
7603       off = TYPE_FIELD_BITPOS (rtype, variant_field);
7604
7605       if (dval0 == NULL)
7606         {
7607           /* Using plain value_from_contents_and_address here causes
7608              problems because we will end up trying to resolve a type
7609              that is currently being constructed.  */
7610           dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7611                                                              address);
7612           rtype = value_type (dval);
7613         }
7614       else
7615         dval = dval0;
7616
7617       branch_type =
7618         to_fixed_variant_branch_type
7619         (type->field (variant_field).type (),
7620          cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7621          cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7622       if (branch_type == NULL)
7623         {
7624           for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7625             rtype->field (f - 1) = rtype->field (f);
7626           rtype->set_num_fields (rtype->num_fields () - 1);
7627         }
7628       else
7629         {
7630           rtype->field (variant_field).set_type (branch_type);
7631           TYPE_FIELD_NAME (rtype, variant_field) = "S";
7632           fld_bit_len =
7633             TYPE_LENGTH (rtype->field (variant_field).type ()) *
7634             TARGET_CHAR_BIT;
7635           if (off + fld_bit_len > bit_len)
7636             bit_len = off + fld_bit_len;
7637           TYPE_LENGTH (rtype) =
7638             align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7639         }
7640     }
7641
7642   /* According to exp_dbug.ads, the size of TYPE for variable-size records
7643      should contain the alignment of that record, which should be a strictly
7644      positive value.  If null or negative, then something is wrong, most
7645      probably in the debug info.  In that case, we don't round up the size
7646      of the resulting type.  If this record is not part of another structure,
7647      the current RTYPE length might be good enough for our purposes.  */
7648   if (TYPE_LENGTH (type) <= 0)
7649     {
7650       if (rtype->name ())
7651         warning (_("Invalid type size for `%s' detected: %s."),
7652                  rtype->name (), pulongest (TYPE_LENGTH (type)));
7653       else
7654         warning (_("Invalid type size for <unnamed> detected: %s."),
7655                  pulongest (TYPE_LENGTH (type)));
7656     }
7657   else
7658     {
7659       TYPE_LENGTH (rtype) = align_up (TYPE_LENGTH (rtype),
7660                                       TYPE_LENGTH (type));
7661     }
7662
7663   value_free_to_mark (mark);
7664   if (TYPE_LENGTH (rtype) > varsize_limit)
7665     error (_("record type with dynamic size is larger than varsize-limit"));
7666   return rtype;
7667 }
7668
7669 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7670    of 1.  */
7671
7672 static struct type *
7673 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7674                                CORE_ADDR address, struct value *dval0)
7675 {
7676   return ada_template_to_fixed_record_type_1 (type, valaddr,
7677                                               address, dval0, 1);
7678 }
7679
7680 /* An ordinary record type in which ___XVL-convention fields and
7681    ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7682    static approximations, containing all possible fields.  Uses
7683    no runtime values.  Useless for use in values, but that's OK,
7684    since the results are used only for type determinations.   Works on both
7685    structs and unions.  Representation note: to save space, we memorize
7686    the result of this function in the TYPE_TARGET_TYPE of the
7687    template type.  */
7688
7689 static struct type *
7690 template_to_static_fixed_type (struct type *type0)
7691 {
7692   struct type *type;
7693   int nfields;
7694   int f;
7695
7696   /* No need no do anything if the input type is already fixed.  */
7697   if (type0->is_fixed_instance ())
7698     return type0;
7699
7700   /* Likewise if we already have computed the static approximation.  */
7701   if (TYPE_TARGET_TYPE (type0) != NULL)
7702     return TYPE_TARGET_TYPE (type0);
7703
7704   /* Don't clone TYPE0 until we are sure we are going to need a copy.  */
7705   type = type0;
7706   nfields = type0->num_fields ();
7707
7708   /* Whether or not we cloned TYPE0, cache the result so that we don't do
7709      recompute all over next time.  */
7710   TYPE_TARGET_TYPE (type0) = type;
7711
7712   for (f = 0; f < nfields; f += 1)
7713     {
7714       struct type *field_type = type0->field (f).type ();
7715       struct type *new_type;
7716
7717       if (is_dynamic_field (type0, f))
7718         {
7719           field_type = ada_check_typedef (field_type);
7720           new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
7721         }
7722       else
7723         new_type = static_unwrap_type (field_type);
7724
7725       if (new_type != field_type)
7726         {
7727           /* Clone TYPE0 only the first time we get a new field type.  */
7728           if (type == type0)
7729             {
7730               TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
7731               type->set_code (type0->code ());
7732               INIT_NONE_SPECIFIC (type);
7733               type->set_num_fields (nfields);
7734
7735               field *fields =
7736                 ((struct field *)
7737                  TYPE_ALLOC (type, nfields * sizeof (struct field)));
7738               memcpy (fields, type0->fields (),
7739                       sizeof (struct field) * nfields);
7740               type->set_fields (fields);
7741
7742               type->set_name (ada_type_name (type0));
7743               type->set_is_fixed_instance (true);
7744               TYPE_LENGTH (type) = 0;
7745             }
7746           type->field (f).set_type (new_type);
7747           TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
7748         }
7749     }
7750
7751   return type;
7752 }
7753
7754 /* Given an object of type TYPE whose contents are at VALADDR and
7755    whose address in memory is ADDRESS, returns a revision of TYPE,
7756    which should be a non-dynamic-sized record, in which the variant
7757    part, if any, is replaced with the appropriate branch.  Looks
7758    for discriminant values in DVAL0, which can be NULL if the record
7759    contains the necessary discriminant values.  */
7760
7761 static struct type *
7762 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
7763                                    CORE_ADDR address, struct value *dval0)
7764 {
7765   struct value *mark = value_mark ();
7766   struct value *dval;
7767   struct type *rtype;
7768   struct type *branch_type;
7769   int nfields = type->num_fields ();
7770   int variant_field = variant_field_index (type);
7771
7772   if (variant_field == -1)
7773     return type;
7774
7775   if (dval0 == NULL)
7776     {
7777       dval = value_from_contents_and_address (type, valaddr, address);
7778       type = value_type (dval);
7779     }
7780   else
7781     dval = dval0;
7782
7783   rtype = alloc_type_copy (type);
7784   rtype->set_code (TYPE_CODE_STRUCT);
7785   INIT_NONE_SPECIFIC (rtype);
7786   rtype->set_num_fields (nfields);
7787
7788   field *fields =
7789     (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
7790   memcpy (fields, type->fields (), sizeof (struct field) * nfields);
7791   rtype->set_fields (fields);
7792
7793   rtype->set_name (ada_type_name (type));
7794   rtype->set_is_fixed_instance (true);
7795   TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
7796
7797   branch_type = to_fixed_variant_branch_type
7798     (type->field (variant_field).type (),
7799      cond_offset_host (valaddr,
7800                        TYPE_FIELD_BITPOS (type, variant_field)
7801                        / TARGET_CHAR_BIT),
7802      cond_offset_target (address,
7803                          TYPE_FIELD_BITPOS (type, variant_field)
7804                          / TARGET_CHAR_BIT), dval);
7805   if (branch_type == NULL)
7806     {
7807       int f;
7808
7809       for (f = variant_field + 1; f < nfields; f += 1)
7810         rtype->field (f - 1) = rtype->field (f);
7811       rtype->set_num_fields (rtype->num_fields () - 1);
7812     }
7813   else
7814     {
7815       rtype->field (variant_field).set_type (branch_type);
7816       TYPE_FIELD_NAME (rtype, variant_field) = "S";
7817       TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
7818       TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
7819     }
7820   TYPE_LENGTH (rtype) -= TYPE_LENGTH (type->field (variant_field).type ());
7821
7822   value_free_to_mark (mark);
7823   return rtype;
7824 }
7825
7826 /* An ordinary record type (with fixed-length fields) that describes
7827    the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
7828    beginning of this section].   Any necessary discriminants' values
7829    should be in DVAL, a record value; it may be NULL if the object
7830    at ADDR itself contains any necessary discriminant values.
7831    Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
7832    values from the record are needed.  Except in the case that DVAL,
7833    VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
7834    unchecked) is replaced by a particular branch of the variant.
7835
7836    NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
7837    is questionable and may be removed.  It can arise during the
7838    processing of an unconstrained-array-of-record type where all the
7839    variant branches have exactly the same size.  This is because in
7840    such cases, the compiler does not bother to use the XVS convention
7841    when encoding the record.  I am currently dubious of this
7842    shortcut and suspect the compiler should be altered.  FIXME.  */
7843
7844 static struct type *
7845 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
7846                       CORE_ADDR address, struct value *dval)
7847 {
7848   struct type *templ_type;
7849
7850   if (type0->is_fixed_instance ())
7851     return type0;
7852
7853   templ_type = dynamic_template_type (type0);
7854
7855   if (templ_type != NULL)
7856     return template_to_fixed_record_type (templ_type, valaddr, address, dval);
7857   else if (variant_field_index (type0) >= 0)
7858     {
7859       if (dval == NULL && valaddr == NULL && address == 0)
7860         return type0;
7861       return to_record_with_fixed_variant_part (type0, valaddr, address,
7862                                                 dval);
7863     }
7864   else
7865     {
7866       type0->set_is_fixed_instance (true);
7867       return type0;
7868     }
7869
7870 }
7871
7872 /* An ordinary record type (with fixed-length fields) that describes
7873    the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
7874    union type.  Any necessary discriminants' values should be in DVAL,
7875    a record value.  That is, this routine selects the appropriate
7876    branch of the union at ADDR according to the discriminant value
7877    indicated in the union's type name.  Returns VAR_TYPE0 itself if
7878    it represents a variant subject to a pragma Unchecked_Union.  */
7879
7880 static struct type *
7881 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
7882                               CORE_ADDR address, struct value *dval)
7883 {
7884   int which;
7885   struct type *templ_type;
7886   struct type *var_type;
7887
7888   if (var_type0->code () == TYPE_CODE_PTR)
7889     var_type = TYPE_TARGET_TYPE (var_type0);
7890   else
7891     var_type = var_type0;
7892
7893   templ_type = ada_find_parallel_type (var_type, "___XVU");
7894
7895   if (templ_type != NULL)
7896     var_type = templ_type;
7897
7898   if (is_unchecked_variant (var_type, value_type (dval)))
7899       return var_type0;
7900   which = ada_which_variant_applies (var_type, dval);
7901
7902   if (which < 0)
7903     return empty_record (var_type);
7904   else if (is_dynamic_field (var_type, which))
7905     return to_fixed_record_type
7906       (TYPE_TARGET_TYPE (var_type->field (which).type ()),
7907        valaddr, address, dval);
7908   else if (variant_field_index (var_type->field (which).type ()) >= 0)
7909     return
7910       to_fixed_record_type
7911       (var_type->field (which).type (), valaddr, address, dval);
7912   else
7913     return var_type->field (which).type ();
7914 }
7915
7916 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
7917    ENCODING_TYPE, a type following the GNAT conventions for discrete
7918    type encodings, only carries redundant information.  */
7919
7920 static int
7921 ada_is_redundant_range_encoding (struct type *range_type,
7922                                  struct type *encoding_type)
7923 {
7924   const char *bounds_str;
7925   int n;
7926   LONGEST lo, hi;
7927
7928   gdb_assert (range_type->code () == TYPE_CODE_RANGE);
7929
7930   if (get_base_type (range_type)->code ()
7931       != get_base_type (encoding_type)->code ())
7932     {
7933       /* The compiler probably used a simple base type to describe
7934          the range type instead of the range's actual base type,
7935          expecting us to get the real base type from the encoding
7936          anyway.  In this situation, the encoding cannot be ignored
7937          as redundant.  */
7938       return 0;
7939     }
7940
7941   if (is_dynamic_type (range_type))
7942     return 0;
7943
7944   if (encoding_type->name () == NULL)
7945     return 0;
7946
7947   bounds_str = strstr (encoding_type->name (), "___XDLU_");
7948   if (bounds_str == NULL)
7949     return 0;
7950
7951   n = 8; /* Skip "___XDLU_".  */
7952   if (!ada_scan_number (bounds_str, n, &lo, &n))
7953     return 0;
7954   if (range_type->bounds ()->low.const_val () != lo)
7955     return 0;
7956
7957   n += 2; /* Skip the "__" separator between the two bounds.  */
7958   if (!ada_scan_number (bounds_str, n, &hi, &n))
7959     return 0;
7960   if (range_type->bounds ()->high.const_val () != hi)
7961     return 0;
7962
7963   return 1;
7964 }
7965
7966 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
7967    a type following the GNAT encoding for describing array type
7968    indices, only carries redundant information.  */
7969
7970 static int
7971 ada_is_redundant_index_type_desc (struct type *array_type,
7972                                   struct type *desc_type)
7973 {
7974   struct type *this_layer = check_typedef (array_type);
7975   int i;
7976
7977   for (i = 0; i < desc_type->num_fields (); i++)
7978     {
7979       if (!ada_is_redundant_range_encoding (this_layer->index_type (),
7980                                             desc_type->field (i).type ()))
7981         return 0;
7982       this_layer = check_typedef (TYPE_TARGET_TYPE (this_layer));
7983     }
7984
7985   return 1;
7986 }
7987
7988 /* Assuming that TYPE0 is an array type describing the type of a value
7989    at ADDR, and that DVAL describes a record containing any
7990    discriminants used in TYPE0, returns a type for the value that
7991    contains no dynamic components (that is, no components whose sizes
7992    are determined by run-time quantities).  Unless IGNORE_TOO_BIG is
7993    true, gives an error message if the resulting type's size is over
7994    varsize_limit.  */
7995
7996 static struct type *
7997 to_fixed_array_type (struct type *type0, struct value *dval,
7998                      int ignore_too_big)
7999 {
8000   struct type *index_type_desc;
8001   struct type *result;
8002   int constrained_packed_array_p;
8003   static const char *xa_suffix = "___XA";
8004
8005   type0 = ada_check_typedef (type0);
8006   if (type0->is_fixed_instance ())
8007     return type0;
8008
8009   constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8010   if (constrained_packed_array_p)
8011     {
8012       type0 = decode_constrained_packed_array_type (type0);
8013       if (type0 == nullptr)
8014         error (_("could not decode constrained packed array type"));
8015     }
8016
8017   index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8018
8019   /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8020      encoding suffixed with 'P' may still be generated.  If so,
8021      it should be used to find the XA type.  */
8022
8023   if (index_type_desc == NULL)
8024     {
8025       const char *type_name = ada_type_name (type0);
8026
8027       if (type_name != NULL)
8028         {
8029           const int len = strlen (type_name);
8030           char *name = (char *) alloca (len + strlen (xa_suffix));
8031
8032           if (type_name[len - 1] == 'P')
8033             {
8034               strcpy (name, type_name);
8035               strcpy (name + len - 1, xa_suffix);
8036               index_type_desc = ada_find_parallel_type_with_name (type0, name);
8037             }
8038         }
8039     }
8040
8041   ada_fixup_array_indexes_type (index_type_desc);
8042   if (index_type_desc != NULL
8043       && ada_is_redundant_index_type_desc (type0, index_type_desc))
8044     {
8045       /* Ignore this ___XA parallel type, as it does not bring any
8046          useful information.  This allows us to avoid creating fixed
8047          versions of the array's index types, which would be identical
8048          to the original ones.  This, in turn, can also help avoid
8049          the creation of fixed versions of the array itself.  */
8050       index_type_desc = NULL;
8051     }
8052
8053   if (index_type_desc == NULL)
8054     {
8055       struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
8056
8057       /* NOTE: elt_type---the fixed version of elt_type0---should never
8058          depend on the contents of the array in properly constructed
8059          debugging data.  */
8060       /* Create a fixed version of the array element type.
8061          We're not providing the address of an element here,
8062          and thus the actual object value cannot be inspected to do
8063          the conversion.  This should not be a problem, since arrays of
8064          unconstrained objects are not allowed.  In particular, all
8065          the elements of an array of a tagged type should all be of
8066          the same type specified in the debugging info.  No need to
8067          consult the object tag.  */
8068       struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8069
8070       /* Make sure we always create a new array type when dealing with
8071          packed array types, since we're going to fix-up the array
8072          type length and element bitsize a little further down.  */
8073       if (elt_type0 == elt_type && !constrained_packed_array_p)
8074         result = type0;
8075       else
8076         result = create_array_type (alloc_type_copy (type0),
8077                                     elt_type, type0->index_type ());
8078     }
8079   else
8080     {
8081       int i;
8082       struct type *elt_type0;
8083
8084       elt_type0 = type0;
8085       for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8086         elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8087
8088       /* NOTE: result---the fixed version of elt_type0---should never
8089          depend on the contents of the array in properly constructed
8090          debugging data.  */
8091       /* Create a fixed version of the array element type.
8092          We're not providing the address of an element here,
8093          and thus the actual object value cannot be inspected to do
8094          the conversion.  This should not be a problem, since arrays of
8095          unconstrained objects are not allowed.  In particular, all
8096          the elements of an array of a tagged type should all be of
8097          the same type specified in the debugging info.  No need to
8098          consult the object tag.  */
8099       result =
8100         ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8101
8102       elt_type0 = type0;
8103       for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8104         {
8105           struct type *range_type =
8106             to_fixed_range_type (index_type_desc->field (i).type (), dval);
8107
8108           result = create_array_type (alloc_type_copy (elt_type0),
8109                                       result, range_type);
8110           elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8111         }
8112       if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
8113         error (_("array type with dynamic size is larger than varsize-limit"));
8114     }
8115
8116   /* We want to preserve the type name.  This can be useful when
8117      trying to get the type name of a value that has already been
8118      printed (for instance, if the user did "print VAR; whatis $".  */
8119   result->set_name (type0->name ());
8120
8121   if (constrained_packed_array_p)
8122     {
8123       /* So far, the resulting type has been created as if the original
8124          type was a regular (non-packed) array type.  As a result, the
8125          bitsize of the array elements needs to be set again, and the array
8126          length needs to be recomputed based on that bitsize.  */
8127       int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
8128       int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8129
8130       TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8131       TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
8132       if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
8133         TYPE_LENGTH (result)++;
8134     }
8135
8136   result->set_is_fixed_instance (true);
8137   return result;
8138 }
8139
8140
8141 /* A standard type (containing no dynamically sized components)
8142    corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8143    DVAL describes a record containing any discriminants used in TYPE0,
8144    and may be NULL if there are none, or if the object of type TYPE at
8145    ADDRESS or in VALADDR contains these discriminants.
8146    
8147    If CHECK_TAG is not null, in the case of tagged types, this function
8148    attempts to locate the object's tag and use it to compute the actual
8149    type.  However, when ADDRESS is null, we cannot use it to determine the
8150    location of the tag, and therefore compute the tagged type's actual type.
8151    So we return the tagged type without consulting the tag.  */
8152    
8153 static struct type *
8154 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8155                    CORE_ADDR address, struct value *dval, int check_tag)
8156 {
8157   type = ada_check_typedef (type);
8158
8159   /* Only un-fixed types need to be handled here.  */
8160   if (!HAVE_GNAT_AUX_INFO (type))
8161     return type;
8162
8163   switch (type->code ())
8164     {
8165     default:
8166       return type;
8167     case TYPE_CODE_STRUCT:
8168       {
8169         struct type *static_type = to_static_fixed_type (type);
8170         struct type *fixed_record_type =
8171           to_fixed_record_type (type, valaddr, address, NULL);
8172
8173         /* If STATIC_TYPE is a tagged type and we know the object's address,
8174            then we can determine its tag, and compute the object's actual
8175            type from there.  Note that we have to use the fixed record
8176            type (the parent part of the record may have dynamic fields
8177            and the way the location of _tag is expressed may depend on
8178            them).  */
8179
8180         if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8181           {
8182             struct value *tag =
8183               value_tag_from_contents_and_address
8184               (fixed_record_type,
8185                valaddr,
8186                address);
8187             struct type *real_type = type_from_tag (tag);
8188             struct value *obj =
8189               value_from_contents_and_address (fixed_record_type,
8190                                                valaddr,
8191                                                address);
8192             fixed_record_type = value_type (obj);
8193             if (real_type != NULL)
8194               return to_fixed_record_type
8195                 (real_type, NULL,
8196                  value_address (ada_tag_value_at_base_address (obj)), NULL);
8197           }
8198
8199         /* Check to see if there is a parallel ___XVZ variable.
8200            If there is, then it provides the actual size of our type.  */
8201         else if (ada_type_name (fixed_record_type) != NULL)
8202           {
8203             const char *name = ada_type_name (fixed_record_type);
8204             char *xvz_name
8205               = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8206             bool xvz_found = false;
8207             LONGEST size;
8208
8209             xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8210             try
8211               {
8212                 xvz_found = get_int_var_value (xvz_name, size);
8213               }
8214             catch (const gdb_exception_error &except)
8215               {
8216                 /* We found the variable, but somehow failed to read
8217                    its value.  Rethrow the same error, but with a little
8218                    bit more information, to help the user understand
8219                    what went wrong (Eg: the variable might have been
8220                    optimized out).  */
8221                 throw_error (except.error,
8222                              _("unable to read value of %s (%s)"),
8223                              xvz_name, except.what ());
8224               }
8225
8226             if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
8227               {
8228                 fixed_record_type = copy_type (fixed_record_type);
8229                 TYPE_LENGTH (fixed_record_type) = size;
8230
8231                 /* The FIXED_RECORD_TYPE may have be a stub.  We have
8232                    observed this when the debugging info is STABS, and
8233                    apparently it is something that is hard to fix.
8234
8235                    In practice, we don't need the actual type definition
8236                    at all, because the presence of the XVZ variable allows us
8237                    to assume that there must be a XVS type as well, which we
8238                    should be able to use later, when we need the actual type
8239                    definition.
8240
8241                    In the meantime, pretend that the "fixed" type we are
8242                    returning is NOT a stub, because this can cause trouble
8243                    when using this type to create new types targeting it.
8244                    Indeed, the associated creation routines often check
8245                    whether the target type is a stub and will try to replace
8246                    it, thus using a type with the wrong size.  This, in turn,
8247                    might cause the new type to have the wrong size too.
8248                    Consider the case of an array, for instance, where the size
8249                    of the array is computed from the number of elements in
8250                    our array multiplied by the size of its element.  */
8251                 fixed_record_type->set_is_stub (false);
8252               }
8253           }
8254         return fixed_record_type;
8255       }
8256     case TYPE_CODE_ARRAY:
8257       return to_fixed_array_type (type, dval, 1);
8258     case TYPE_CODE_UNION:
8259       if (dval == NULL)
8260         return type;
8261       else
8262         return to_fixed_variant_branch_type (type, valaddr, address, dval);
8263     }
8264 }
8265
8266 /* The same as ada_to_fixed_type_1, except that it preserves the type
8267    if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8268
8269    The typedef layer needs be preserved in order to differentiate between
8270    arrays and array pointers when both types are implemented using the same
8271    fat pointer.  In the array pointer case, the pointer is encoded as
8272    a typedef of the pointer type.  For instance, considering:
8273
8274           type String_Access is access String;
8275           S1 : String_Access := null;
8276
8277    To the debugger, S1 is defined as a typedef of type String.  But
8278    to the user, it is a pointer.  So if the user tries to print S1,
8279    we should not dereference the array, but print the array address
8280    instead.
8281
8282    If we didn't preserve the typedef layer, we would lose the fact that
8283    the type is to be presented as a pointer (needs de-reference before
8284    being printed).  And we would also use the source-level type name.  */
8285
8286 struct type *
8287 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8288                    CORE_ADDR address, struct value *dval, int check_tag)
8289
8290 {
8291   struct type *fixed_type =
8292     ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8293
8294   /*  If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8295       then preserve the typedef layer.
8296
8297       Implementation note: We can only check the main-type portion of
8298       the TYPE and FIXED_TYPE, because eliminating the typedef layer
8299       from TYPE now returns a type that has the same instance flags
8300       as TYPE.  For instance, if TYPE is a "typedef const", and its
8301       target type is a "struct", then the typedef elimination will return
8302       a "const" version of the target type.  See check_typedef for more
8303       details about how the typedef layer elimination is done.
8304
8305       brobecker/2010-11-19: It seems to me that the only case where it is
8306       useful to preserve the typedef layer is when dealing with fat pointers.
8307       Perhaps, we could add a check for that and preserve the typedef layer
8308       only in that situation.  But this seems unnecessary so far, probably
8309       because we call check_typedef/ada_check_typedef pretty much everywhere.
8310       */
8311   if (type->code () == TYPE_CODE_TYPEDEF
8312       && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8313           == TYPE_MAIN_TYPE (fixed_type)))
8314     return type;
8315
8316   return fixed_type;
8317 }
8318
8319 /* A standard (static-sized) type corresponding as well as possible to
8320    TYPE0, but based on no runtime data.  */
8321
8322 static struct type *
8323 to_static_fixed_type (struct type *type0)
8324 {
8325   struct type *type;
8326
8327   if (type0 == NULL)
8328     return NULL;
8329
8330   if (type0->is_fixed_instance ())
8331     return type0;
8332
8333   type0 = ada_check_typedef (type0);
8334
8335   switch (type0->code ())
8336     {
8337     default:
8338       return type0;
8339     case TYPE_CODE_STRUCT:
8340       type = dynamic_template_type (type0);
8341       if (type != NULL)
8342         return template_to_static_fixed_type (type);
8343       else
8344         return template_to_static_fixed_type (type0);
8345     case TYPE_CODE_UNION:
8346       type = ada_find_parallel_type (type0, "___XVU");
8347       if (type != NULL)
8348         return template_to_static_fixed_type (type);
8349       else
8350         return template_to_static_fixed_type (type0);
8351     }
8352 }
8353
8354 /* A static approximation of TYPE with all type wrappers removed.  */
8355
8356 static struct type *
8357 static_unwrap_type (struct type *type)
8358 {
8359   if (ada_is_aligner_type (type))
8360     {
8361       struct type *type1 = ada_check_typedef (type)->field (0).type ();
8362       if (ada_type_name (type1) == NULL)
8363         type1->set_name (ada_type_name (type));
8364
8365       return static_unwrap_type (type1);
8366     }
8367   else
8368     {
8369       struct type *raw_real_type = ada_get_base_type (type);
8370
8371       if (raw_real_type == type)
8372         return type;
8373       else
8374         return to_static_fixed_type (raw_real_type);
8375     }
8376 }
8377
8378 /* In some cases, incomplete and private types require
8379    cross-references that are not resolved as records (for example,
8380       type Foo;
8381       type FooP is access Foo;
8382       V: FooP;
8383       type Foo is array ...;
8384    ).  In these cases, since there is no mechanism for producing
8385    cross-references to such types, we instead substitute for FooP a
8386    stub enumeration type that is nowhere resolved, and whose tag is
8387    the name of the actual type.  Call these types "non-record stubs".  */
8388
8389 /* A type equivalent to TYPE that is not a non-record stub, if one
8390    exists, otherwise TYPE.  */
8391
8392 struct type *
8393 ada_check_typedef (struct type *type)
8394 {
8395   if (type == NULL)
8396     return NULL;
8397
8398   /* If our type is an access to an unconstrained array, which is encoded
8399      as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8400      We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8401      what allows us to distinguish between fat pointers that represent
8402      array types, and fat pointers that represent array access types
8403      (in both cases, the compiler implements them as fat pointers).  */
8404   if (ada_is_access_to_unconstrained_array (type))
8405     return type;
8406
8407   type = check_typedef (type);
8408   if (type == NULL || type->code () != TYPE_CODE_ENUM
8409       || !type->is_stub ()
8410       || type->name () == NULL)
8411     return type;
8412   else
8413     {
8414       const char *name = type->name ();
8415       struct type *type1 = ada_find_any_type (name);
8416
8417       if (type1 == NULL)
8418         return type;
8419
8420       /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8421          stubs pointing to arrays, as we don't create symbols for array
8422          types, only for the typedef-to-array types).  If that's the case,
8423          strip the typedef layer.  */
8424       if (type1->code () == TYPE_CODE_TYPEDEF)
8425         type1 = ada_check_typedef (type1);
8426
8427       return type1;
8428     }
8429 }
8430
8431 /* A value representing the data at VALADDR/ADDRESS as described by
8432    type TYPE0, but with a standard (static-sized) type that correctly
8433    describes it.  If VAL0 is not NULL and TYPE0 already is a standard
8434    type, then return VAL0 [this feature is simply to avoid redundant
8435    creation of struct values].  */
8436
8437 static struct value *
8438 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8439                            struct value *val0)
8440 {
8441   struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8442
8443   if (type == type0 && val0 != NULL)
8444     return val0;
8445
8446   if (VALUE_LVAL (val0) != lval_memory)
8447     {
8448       /* Our value does not live in memory; it could be a convenience
8449          variable, for instance.  Create a not_lval value using val0's
8450          contents.  */
8451       return value_from_contents (type, value_contents (val0));
8452     }
8453
8454   return value_from_contents_and_address (type, 0, address);
8455 }
8456
8457 /* A value representing VAL, but with a standard (static-sized) type
8458    that correctly describes it.  Does not necessarily create a new
8459    value.  */
8460
8461 struct value *
8462 ada_to_fixed_value (struct value *val)
8463 {
8464   val = unwrap_value (val);
8465   val = ada_to_fixed_value_create (value_type (val), value_address (val), val);
8466   return val;
8467 }
8468 \f
8469
8470 /* Attributes */
8471
8472 /* Table mapping attribute numbers to names.
8473    NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h.  */
8474
8475 static const char * const attribute_names[] = {
8476   "<?>",
8477
8478   "first",
8479   "last",
8480   "length",
8481   "image",
8482   "max",
8483   "min",
8484   "modulus",
8485   "pos",
8486   "size",
8487   "tag",
8488   "val",
8489   0
8490 };
8491
8492 static const char *
8493 ada_attribute_name (enum exp_opcode n)
8494 {
8495   if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8496     return attribute_names[n - OP_ATR_FIRST + 1];
8497   else
8498     return attribute_names[0];
8499 }
8500
8501 /* Evaluate the 'POS attribute applied to ARG.  */
8502
8503 static LONGEST
8504 pos_atr (struct value *arg)
8505 {
8506   struct value *val = coerce_ref (arg);
8507   struct type *type = value_type (val);
8508
8509   if (!discrete_type_p (type))
8510     error (_("'POS only defined on discrete types"));
8511
8512   gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8513   if (!result.has_value ())
8514     error (_("enumeration value is invalid: can't find 'POS"));
8515
8516   return *result;
8517 }
8518
8519 struct value *
8520 ada_pos_atr (struct type *expect_type,
8521              struct expression *exp,
8522              enum noside noside, enum exp_opcode op,
8523              struct value *arg)
8524 {
8525   struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8526   if (noside == EVAL_AVOID_SIDE_EFFECTS)
8527     return value_zero (type, not_lval);
8528   return value_from_longest (type, pos_atr (arg));
8529 }
8530
8531 /* Evaluate the TYPE'VAL attribute applied to ARG.  */
8532
8533 static struct value *
8534 val_atr (struct type *type, LONGEST val)
8535 {
8536   gdb_assert (discrete_type_p (type));
8537   if (type->code () == TYPE_CODE_RANGE)
8538     type = TYPE_TARGET_TYPE (type);
8539   if (type->code () == TYPE_CODE_ENUM)
8540     {
8541       if (val < 0 || val >= type->num_fields ())
8542         error (_("argument to 'VAL out of range"));
8543       val = TYPE_FIELD_ENUMVAL (type, val);
8544     }
8545   return value_from_longest (type, val);
8546 }
8547
8548 struct value *
8549 ada_val_atr (enum noside noside, struct type *type, struct value *arg)
8550 {
8551   if (noside == EVAL_AVOID_SIDE_EFFECTS)
8552     return value_zero (type, not_lval);
8553
8554   if (!discrete_type_p (type))
8555     error (_("'VAL only defined on discrete types"));
8556   if (!integer_type_p (value_type (arg)))
8557     error (_("'VAL requires integral argument"));
8558
8559   return val_atr (type, value_as_long (arg));
8560 }
8561 \f
8562
8563                                 /* Evaluation */
8564
8565 /* True if TYPE appears to be an Ada character type.
8566    [At the moment, this is true only for Character and Wide_Character;
8567    It is a heuristic test that could stand improvement].  */
8568
8569 bool
8570 ada_is_character_type (struct type *type)
8571 {
8572   const char *name;
8573
8574   /* If the type code says it's a character, then assume it really is,
8575      and don't check any further.  */
8576   if (type->code () == TYPE_CODE_CHAR)
8577     return true;
8578   
8579   /* Otherwise, assume it's a character type iff it is a discrete type
8580      with a known character type name.  */
8581   name = ada_type_name (type);
8582   return (name != NULL
8583           && (type->code () == TYPE_CODE_INT
8584               || type->code () == TYPE_CODE_RANGE)
8585           && (strcmp (name, "character") == 0
8586               || strcmp (name, "wide_character") == 0
8587               || strcmp (name, "wide_wide_character") == 0
8588               || strcmp (name, "unsigned char") == 0));
8589 }
8590
8591 /* True if TYPE appears to be an Ada string type.  */
8592
8593 bool
8594 ada_is_string_type (struct type *type)
8595 {
8596   type = ada_check_typedef (type);
8597   if (type != NULL
8598       && type->code () != TYPE_CODE_PTR
8599       && (ada_is_simple_array_type (type)
8600           || ada_is_array_descriptor_type (type))
8601       && ada_array_arity (type) == 1)
8602     {
8603       struct type *elttype = ada_array_element_type (type, 1);
8604
8605       return ada_is_character_type (elttype);
8606     }
8607   else
8608     return false;
8609 }
8610
8611 /* The compiler sometimes provides a parallel XVS type for a given
8612    PAD type.  Normally, it is safe to follow the PAD type directly,
8613    but older versions of the compiler have a bug that causes the offset
8614    of its "F" field to be wrong.  Following that field in that case
8615    would lead to incorrect results, but this can be worked around
8616    by ignoring the PAD type and using the associated XVS type instead.
8617
8618    Set to True if the debugger should trust the contents of PAD types.
8619    Otherwise, ignore the PAD type if there is a parallel XVS type.  */
8620 static bool trust_pad_over_xvs = true;
8621
8622 /* True if TYPE is a struct type introduced by the compiler to force the
8623    alignment of a value.  Such types have a single field with a
8624    distinctive name.  */
8625
8626 int
8627 ada_is_aligner_type (struct type *type)
8628 {
8629   type = ada_check_typedef (type);
8630
8631   if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8632     return 0;
8633
8634   return (type->code () == TYPE_CODE_STRUCT
8635           && type->num_fields () == 1
8636           && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
8637 }
8638
8639 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8640    the parallel type.  */
8641
8642 struct type *
8643 ada_get_base_type (struct type *raw_type)
8644 {
8645   struct type *real_type_namer;
8646   struct type *raw_real_type;
8647
8648   if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8649     return raw_type;
8650
8651   if (ada_is_aligner_type (raw_type))
8652     /* The encoding specifies that we should always use the aligner type.
8653        So, even if this aligner type has an associated XVS type, we should
8654        simply ignore it.
8655
8656        According to the compiler gurus, an XVS type parallel to an aligner
8657        type may exist because of a stabs limitation.  In stabs, aligner
8658        types are empty because the field has a variable-sized type, and
8659        thus cannot actually be used as an aligner type.  As a result,
8660        we need the associated parallel XVS type to decode the type.
8661        Since the policy in the compiler is to not change the internal
8662        representation based on the debugging info format, we sometimes
8663        end up having a redundant XVS type parallel to the aligner type.  */
8664     return raw_type;
8665
8666   real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8667   if (real_type_namer == NULL
8668       || real_type_namer->code () != TYPE_CODE_STRUCT
8669       || real_type_namer->num_fields () != 1)
8670     return raw_type;
8671
8672   if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
8673     {
8674       /* This is an older encoding form where the base type needs to be
8675          looked up by name.  We prefer the newer encoding because it is
8676          more efficient.  */
8677       raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
8678       if (raw_real_type == NULL)
8679         return raw_type;
8680       else
8681         return raw_real_type;
8682     }
8683
8684   /* The field in our XVS type is a reference to the base type.  */
8685   return TYPE_TARGET_TYPE (real_type_namer->field (0).type ());
8686 }
8687
8688 /* The type of value designated by TYPE, with all aligners removed.  */
8689
8690 struct type *
8691 ada_aligned_type (struct type *type)
8692 {
8693   if (ada_is_aligner_type (type))
8694     return ada_aligned_type (type->field (0).type ());
8695   else
8696     return ada_get_base_type (type);
8697 }
8698
8699
8700 /* The address of the aligned value in an object at address VALADDR
8701    having type TYPE.  Assumes ada_is_aligner_type (TYPE).  */
8702
8703 const gdb_byte *
8704 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
8705 {
8706   if (ada_is_aligner_type (type))
8707     return ada_aligned_value_addr (type->field (0).type (),
8708                                    valaddr +
8709                                    TYPE_FIELD_BITPOS (type,
8710                                                       0) / TARGET_CHAR_BIT);
8711   else
8712     return valaddr;
8713 }
8714
8715
8716
8717 /* The printed representation of an enumeration literal with encoded
8718    name NAME.  The value is good to the next call of ada_enum_name.  */
8719 const char *
8720 ada_enum_name (const char *name)
8721 {
8722   static std::string storage;
8723   const char *tmp;
8724
8725   /* First, unqualify the enumeration name:
8726      1. Search for the last '.' character.  If we find one, then skip
8727      all the preceding characters, the unqualified name starts
8728      right after that dot.
8729      2. Otherwise, we may be debugging on a target where the compiler
8730      translates dots into "__".  Search forward for double underscores,
8731      but stop searching when we hit an overloading suffix, which is
8732      of the form "__" followed by digits.  */
8733
8734   tmp = strrchr (name, '.');
8735   if (tmp != NULL)
8736     name = tmp + 1;
8737   else
8738     {
8739       while ((tmp = strstr (name, "__")) != NULL)
8740         {
8741           if (isdigit (tmp[2]))
8742             break;
8743           else
8744             name = tmp + 2;
8745         }
8746     }
8747
8748   if (name[0] == 'Q')
8749     {
8750       int v;
8751
8752       if (name[1] == 'U' || name[1] == 'W')
8753         {
8754           if (sscanf (name + 2, "%x", &v) != 1)
8755             return name;
8756         }
8757       else if (((name[1] >= '0' && name[1] <= '9')
8758                 || (name[1] >= 'a' && name[1] <= 'z'))
8759                && name[2] == '\0')
8760         {
8761           storage = string_printf ("'%c'", name[1]);
8762           return storage.c_str ();
8763         }
8764       else
8765         return name;
8766
8767       if (isascii (v) && isprint (v))
8768         storage = string_printf ("'%c'", v);
8769       else if (name[1] == 'U')
8770         storage = string_printf ("[\"%02x\"]", v);
8771       else
8772         storage = string_printf ("[\"%04x\"]", v);
8773
8774       return storage.c_str ();
8775     }
8776   else
8777     {
8778       tmp = strstr (name, "__");
8779       if (tmp == NULL)
8780         tmp = strstr (name, "$");
8781       if (tmp != NULL)
8782         {
8783           storage = std::string (name, tmp - name);
8784           return storage.c_str ();
8785         }
8786
8787       return name;
8788     }
8789 }
8790
8791 /* If VAL is wrapped in an aligner or subtype wrapper, return the
8792    value it wraps.  */
8793
8794 static struct value *
8795 unwrap_value (struct value *val)
8796 {
8797   struct type *type = ada_check_typedef (value_type (val));
8798
8799   if (ada_is_aligner_type (type))
8800     {
8801       struct value *v = ada_value_struct_elt (val, "F", 0);
8802       struct type *val_type = ada_check_typedef (value_type (v));
8803
8804       if (ada_type_name (val_type) == NULL)
8805         val_type->set_name (ada_type_name (type));
8806
8807       return unwrap_value (v);
8808     }
8809   else
8810     {
8811       struct type *raw_real_type =
8812         ada_check_typedef (ada_get_base_type (type));
8813
8814       /* If there is no parallel XVS or XVE type, then the value is
8815          already unwrapped.  Return it without further modification.  */
8816       if ((type == raw_real_type)
8817           && ada_find_parallel_type (type, "___XVE") == NULL)
8818         return val;
8819
8820       return
8821         coerce_unspec_val_to_type
8822         (val, ada_to_fixed_type (raw_real_type, 0,
8823                                  value_address (val),
8824                                  NULL, 1));
8825     }
8826 }
8827
8828 /* Given two array types T1 and T2, return nonzero iff both arrays
8829    contain the same number of elements.  */
8830
8831 static int
8832 ada_same_array_size_p (struct type *t1, struct type *t2)
8833 {
8834   LONGEST lo1, hi1, lo2, hi2;
8835
8836   /* Get the array bounds in order to verify that the size of
8837      the two arrays match.  */
8838   if (!get_array_bounds (t1, &lo1, &hi1)
8839       || !get_array_bounds (t2, &lo2, &hi2))
8840     error (_("unable to determine array bounds"));
8841
8842   /* To make things easier for size comparison, normalize a bit
8843      the case of empty arrays by making sure that the difference
8844      between upper bound and lower bound is always -1.  */
8845   if (lo1 > hi1)
8846     hi1 = lo1 - 1;
8847   if (lo2 > hi2)
8848     hi2 = lo2 - 1;
8849
8850   return (hi1 - lo1 == hi2 - lo2);
8851 }
8852
8853 /* Assuming that VAL is an array of integrals, and TYPE represents
8854    an array with the same number of elements, but with wider integral
8855    elements, return an array "casted" to TYPE.  In practice, this
8856    means that the returned array is built by casting each element
8857    of the original array into TYPE's (wider) element type.  */
8858
8859 static struct value *
8860 ada_promote_array_of_integrals (struct type *type, struct value *val)
8861 {
8862   struct type *elt_type = TYPE_TARGET_TYPE (type);
8863   LONGEST lo, hi;
8864   struct value *res;
8865   LONGEST i;
8866
8867   /* Verify that both val and type are arrays of scalars, and
8868      that the size of val's elements is smaller than the size
8869      of type's element.  */
8870   gdb_assert (type->code () == TYPE_CODE_ARRAY);
8871   gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
8872   gdb_assert (value_type (val)->code () == TYPE_CODE_ARRAY);
8873   gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
8874   gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
8875               > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));
8876
8877   if (!get_array_bounds (type, &lo, &hi))
8878     error (_("unable to determine array bounds"));
8879
8880   res = allocate_value (type);
8881
8882   /* Promote each array element.  */
8883   for (i = 0; i < hi - lo + 1; i++)
8884     {
8885       struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
8886
8887       memcpy (value_contents_writeable (res) + (i * TYPE_LENGTH (elt_type)),
8888               value_contents_all (elt), TYPE_LENGTH (elt_type));
8889     }
8890
8891   return res;
8892 }
8893
8894 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
8895    return the converted value.  */
8896
8897 static struct value *
8898 coerce_for_assign (struct type *type, struct value *val)
8899 {
8900   struct type *type2 = value_type (val);
8901
8902   if (type == type2)
8903     return val;
8904
8905   type2 = ada_check_typedef (type2);
8906   type = ada_check_typedef (type);
8907
8908   if (type2->code () == TYPE_CODE_PTR
8909       && type->code () == TYPE_CODE_ARRAY)
8910     {
8911       val = ada_value_ind (val);
8912       type2 = value_type (val);
8913     }
8914
8915   if (type2->code () == TYPE_CODE_ARRAY
8916       && type->code () == TYPE_CODE_ARRAY)
8917     {
8918       if (!ada_same_array_size_p (type, type2))
8919         error (_("cannot assign arrays of different length"));
8920
8921       if (is_integral_type (TYPE_TARGET_TYPE (type))
8922           && is_integral_type (TYPE_TARGET_TYPE (type2))
8923           && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
8924                < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
8925         {
8926           /* Allow implicit promotion of the array elements to
8927              a wider type.  */
8928           return ada_promote_array_of_integrals (type, val);
8929         }
8930
8931       if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
8932           != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
8933         error (_("Incompatible types in assignment"));
8934       deprecated_set_value_type (val, type);
8935     }
8936   return val;
8937 }
8938
8939 static struct value *
8940 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
8941 {
8942   struct value *val;
8943   struct type *type1, *type2;
8944   LONGEST v, v1, v2;
8945
8946   arg1 = coerce_ref (arg1);
8947   arg2 = coerce_ref (arg2);
8948   type1 = get_base_type (ada_check_typedef (value_type (arg1)));
8949   type2 = get_base_type (ada_check_typedef (value_type (arg2)));
8950
8951   if (type1->code () != TYPE_CODE_INT
8952       || type2->code () != TYPE_CODE_INT)
8953     return value_binop (arg1, arg2, op);
8954
8955   switch (op)
8956     {
8957     case BINOP_MOD:
8958     case BINOP_DIV:
8959     case BINOP_REM:
8960       break;
8961     default:
8962       return value_binop (arg1, arg2, op);
8963     }
8964
8965   v2 = value_as_long (arg2);
8966   if (v2 == 0)
8967     {
8968       const char *name;
8969       if (op == BINOP_MOD)
8970         name = "mod";
8971       else if (op == BINOP_DIV)
8972         name = "/";
8973       else
8974         {
8975           gdb_assert (op == BINOP_REM);
8976           name = "rem";
8977         }
8978
8979       error (_("second operand of %s must not be zero."), name);
8980     }
8981
8982   if (type1->is_unsigned () || op == BINOP_MOD)
8983     return value_binop (arg1, arg2, op);
8984
8985   v1 = value_as_long (arg1);
8986   switch (op)
8987     {
8988     case BINOP_DIV:
8989       v = v1 / v2;
8990       if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
8991         v += v > 0 ? -1 : 1;
8992       break;
8993     case BINOP_REM:
8994       v = v1 % v2;
8995       if (v * v1 < 0)
8996         v -= v2;
8997       break;
8998     default:
8999       /* Should not reach this point.  */
9000       v = 0;
9001     }
9002
9003   val = allocate_value (type1);
9004   store_unsigned_integer (value_contents_raw (val),
9005                           TYPE_LENGTH (value_type (val)),
9006                           type_byte_order (type1), v);
9007   return val;
9008 }
9009
9010 static int
9011 ada_value_equal (struct value *arg1, struct value *arg2)
9012 {
9013   if (ada_is_direct_array_type (value_type (arg1))
9014       || ada_is_direct_array_type (value_type (arg2)))
9015     {
9016       struct type *arg1_type, *arg2_type;
9017
9018       /* Automatically dereference any array reference before
9019          we attempt to perform the comparison.  */
9020       arg1 = ada_coerce_ref (arg1);
9021       arg2 = ada_coerce_ref (arg2);
9022
9023       arg1 = ada_coerce_to_simple_array (arg1);
9024       arg2 = ada_coerce_to_simple_array (arg2);
9025
9026       arg1_type = ada_check_typedef (value_type (arg1));
9027       arg2_type = ada_check_typedef (value_type (arg2));
9028
9029       if (arg1_type->code () != TYPE_CODE_ARRAY
9030           || arg2_type->code () != TYPE_CODE_ARRAY)
9031         error (_("Attempt to compare array with non-array"));
9032       /* FIXME: The following works only for types whose
9033          representations use all bits (no padding or undefined bits)
9034          and do not have user-defined equality.  */
9035       return (TYPE_LENGTH (arg1_type) == TYPE_LENGTH (arg2_type)
9036               && memcmp (value_contents (arg1), value_contents (arg2),
9037                          TYPE_LENGTH (arg1_type)) == 0);
9038     }
9039   return value_equal (arg1, arg2);
9040 }
9041
9042 namespace expr
9043 {
9044
9045 bool
9046 check_objfile (const std::unique_ptr<ada_component> &comp,
9047                struct objfile *objfile)
9048 {
9049   return comp->uses_objfile (objfile);
9050 }
9051
9052 /* Assign the result of evaluating ARG starting at *POS to the INDEXth
9053    component of LHS (a simple array or a record).  Does not modify the
9054    inferior's memory, nor does it modify LHS (unless LHS ==
9055    CONTAINER).  */
9056
9057 static void
9058 assign_component (struct value *container, struct value *lhs, LONGEST index,
9059                   struct expression *exp, operation_up &arg)
9060 {
9061   scoped_value_mark mark;
9062
9063   struct value *elt;
9064   struct type *lhs_type = check_typedef (value_type (lhs));
9065
9066   if (lhs_type->code () == TYPE_CODE_ARRAY)
9067     {
9068       struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9069       struct value *index_val = value_from_longest (index_type, index);
9070
9071       elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9072     }
9073   else
9074     {
9075       elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9076       elt = ada_to_fixed_value (elt);
9077     }
9078
9079   ada_aggregate_operation *ag_op
9080     = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9081   if (ag_op != nullptr)
9082     ag_op->assign_aggregate (container, elt, exp);
9083   else
9084     value_assign_to_component (container, elt,
9085                                arg->evaluate (nullptr, exp,
9086                                               EVAL_NORMAL));
9087 }
9088
9089 bool
9090 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9091 {
9092   for (const auto &item : m_components)
9093     if (item->uses_objfile (objfile))
9094       return true;
9095   return false;
9096 }
9097
9098 void
9099 ada_aggregate_component::dump (ui_file *stream, int depth)
9100 {
9101   fprintf_filtered (stream, _("%*sAggregate\n"), depth, "");
9102   for (const auto &item : m_components)
9103     item->dump (stream, depth + 1);
9104 }
9105
9106 void
9107 ada_aggregate_component::assign (struct value *container,
9108                                  struct value *lhs, struct expression *exp,
9109                                  std::vector<LONGEST> &indices,
9110                                  LONGEST low, LONGEST high)
9111 {
9112   for (auto &item : m_components)
9113     item->assign (container, lhs, exp, indices, low, high);
9114 }
9115
9116 /* See ada-exp.h.  */
9117
9118 value *
9119 ada_aggregate_operation::assign_aggregate (struct value *container,
9120                                            struct value *lhs,
9121                                            struct expression *exp)
9122 {
9123   struct type *lhs_type;
9124   LONGEST low_index, high_index;
9125
9126   container = ada_coerce_ref (container);
9127   if (ada_is_direct_array_type (value_type (container)))
9128     container = ada_coerce_to_simple_array (container);
9129   lhs = ada_coerce_ref (lhs);
9130   if (!deprecated_value_modifiable (lhs))
9131     error (_("Left operand of assignment is not a modifiable lvalue."));
9132
9133   lhs_type = check_typedef (value_type (lhs));
9134   if (ada_is_direct_array_type (lhs_type))
9135     {
9136       lhs = ada_coerce_to_simple_array (lhs);
9137       lhs_type = check_typedef (value_type (lhs));
9138       low_index = lhs_type->bounds ()->low.const_val ();
9139       high_index = lhs_type->bounds ()->high.const_val ();
9140     }
9141   else if (lhs_type->code () == TYPE_CODE_STRUCT)
9142     {
9143       low_index = 0;
9144       high_index = num_visible_fields (lhs_type) - 1;
9145     }
9146   else
9147     error (_("Left-hand side must be array or record."));
9148
9149   std::vector<LONGEST> indices (4);
9150   indices[0] = indices[1] = low_index - 1;
9151   indices[2] = indices[3] = high_index + 1;
9152
9153   std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9154                                    low_index, high_index);
9155
9156   return container;
9157 }
9158
9159 bool
9160 ada_positional_component::uses_objfile (struct objfile *objfile)
9161 {
9162   return m_op->uses_objfile (objfile);
9163 }
9164
9165 void
9166 ada_positional_component::dump (ui_file *stream, int depth)
9167 {
9168   fprintf_filtered (stream, _("%*sPositional, index = %d\n"),
9169                     depth, "", m_index);
9170   m_op->dump (stream, depth + 1);
9171 }
9172
9173 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9174    construct, given that the positions are relative to lower bound
9175    LOW, where HIGH is the upper bound.  Record the position in
9176    INDICES.  CONTAINER is as for assign_aggregate.  */
9177 void
9178 ada_positional_component::assign (struct value *container,
9179                                   struct value *lhs, struct expression *exp,
9180                                   std::vector<LONGEST> &indices,
9181                                   LONGEST low, LONGEST high)
9182 {
9183   LONGEST ind = m_index + low;
9184
9185   if (ind - 1 == high)
9186     warning (_("Extra components in aggregate ignored."));
9187   if (ind <= high)
9188     {
9189       add_component_interval (ind, ind, indices);
9190       assign_component (container, lhs, ind, exp, m_op);
9191     }
9192 }
9193
9194 bool
9195 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9196 {
9197   return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9198 }
9199
9200 void
9201 ada_discrete_range_association::dump (ui_file *stream, int depth)
9202 {
9203   fprintf_filtered (stream, _("%*sDiscrete range:\n"), depth, "");
9204   m_low->dump (stream, depth + 1);
9205   m_high->dump (stream, depth + 1);
9206 }
9207
9208 void
9209 ada_discrete_range_association::assign (struct value *container,
9210                                         struct value *lhs,
9211                                         struct expression *exp,
9212                                         std::vector<LONGEST> &indices,
9213                                         LONGEST low, LONGEST high,
9214                                         operation_up &op)
9215 {
9216   LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9217   LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9218
9219   if (lower <= upper && (lower < low || upper > high))
9220     error (_("Index in component association out of bounds."));
9221
9222   add_component_interval (lower, upper, indices);
9223   while (lower <= upper)
9224     {
9225       assign_component (container, lhs, lower, exp, op);
9226       lower += 1;
9227     }
9228 }
9229
9230 bool
9231 ada_name_association::uses_objfile (struct objfile *objfile)
9232 {
9233   return m_val->uses_objfile (objfile);
9234 }
9235
9236 void
9237 ada_name_association::dump (ui_file *stream, int depth)
9238 {
9239   fprintf_filtered (stream, _("%*sName:\n"), depth, "");
9240   m_val->dump (stream, depth + 1);
9241 }
9242
9243 void
9244 ada_name_association::assign (struct value *container,
9245                               struct value *lhs,
9246                               struct expression *exp,
9247                               std::vector<LONGEST> &indices,
9248                               LONGEST low, LONGEST high,
9249                               operation_up &op)
9250 {
9251   int index;
9252
9253   if (ada_is_direct_array_type (value_type (lhs)))
9254     index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9255                                                             EVAL_NORMAL)));
9256   else
9257     {
9258       ada_string_operation *strop
9259         = dynamic_cast<ada_string_operation *> (m_val.get ());
9260
9261       const char *name;
9262       if (strop != nullptr)
9263         name = strop->get_name ();
9264       else
9265         {
9266           ada_var_value_operation *vvo
9267             = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9268           if (vvo != nullptr)
9269             error (_("Invalid record component association."));
9270           name = vvo->get_symbol ()->natural_name ();
9271         }
9272
9273       index = 0;
9274       if (! find_struct_field (name, value_type (lhs), 0,
9275                                NULL, NULL, NULL, NULL, &index))
9276         error (_("Unknown component name: %s."), name);
9277     }
9278
9279   add_component_interval (index, index, indices);
9280   assign_component (container, lhs, index, exp, op);
9281 }
9282
9283 bool
9284 ada_choices_component::uses_objfile (struct objfile *objfile)
9285 {
9286   if (m_op->uses_objfile (objfile))
9287     return true;
9288   for (const auto &item : m_assocs)
9289     if (item->uses_objfile (objfile))
9290       return true;
9291   return false;
9292 }
9293
9294 void
9295 ada_choices_component::dump (ui_file *stream, int depth)
9296 {
9297   fprintf_filtered (stream, _("%*sChoices:\n"), depth, "");
9298   m_op->dump (stream, depth + 1);
9299   for (const auto &item : m_assocs)
9300     item->dump (stream, depth + 1);
9301 }
9302
9303 /* Assign into the components of LHS indexed by the OP_CHOICES
9304    construct at *POS, updating *POS past the construct, given that
9305    the allowable indices are LOW..HIGH.  Record the indices assigned
9306    to in INDICES.  CONTAINER is as for assign_aggregate.  */
9307 void
9308 ada_choices_component::assign (struct value *container,
9309                                struct value *lhs, struct expression *exp,
9310                                std::vector<LONGEST> &indices,
9311                                LONGEST low, LONGEST high)
9312 {
9313   for (auto &item : m_assocs)
9314     item->assign (container, lhs, exp, indices, low, high, m_op);
9315 }
9316
9317 bool
9318 ada_others_component::uses_objfile (struct objfile *objfile)
9319 {
9320   return m_op->uses_objfile (objfile);
9321 }
9322
9323 void
9324 ada_others_component::dump (ui_file *stream, int depth)
9325 {
9326   fprintf_filtered (stream, _("%*sOthers:\n"), depth, "");
9327   m_op->dump (stream, depth + 1);
9328 }
9329
9330 /* Assign the value of the expression in the OP_OTHERS construct in
9331    EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9332    have not been previously assigned.  The index intervals already assigned
9333    are in INDICES.  CONTAINER is as for assign_aggregate.  */
9334 void
9335 ada_others_component::assign (struct value *container,
9336                               struct value *lhs, struct expression *exp,
9337                               std::vector<LONGEST> &indices,
9338                               LONGEST low, LONGEST high)
9339 {
9340   int num_indices = indices.size ();
9341   for (int i = 0; i < num_indices - 2; i += 2)
9342     {
9343       for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9344         assign_component (container, lhs, ind, exp, m_op);
9345     }
9346 }
9347
9348 struct value *
9349 ada_assign_operation::evaluate (struct type *expect_type,
9350                                 struct expression *exp,
9351                                 enum noside noside)
9352 {
9353   value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9354
9355   ada_aggregate_operation *ag_op
9356     = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9357   if (ag_op != nullptr)
9358     {
9359       if (noside != EVAL_NORMAL)
9360         return arg1;
9361
9362       arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9363       return ada_value_assign (arg1, arg1);
9364     }
9365   /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9366      except if the lhs of our assignment is a convenience variable.
9367      In the case of assigning to a convenience variable, the lhs
9368      should be exactly the result of the evaluation of the rhs.  */
9369   struct type *type = value_type (arg1);
9370   if (VALUE_LVAL (arg1) == lval_internalvar)
9371     type = NULL;
9372   value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9373   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9374     return arg1;
9375   if (VALUE_LVAL (arg1) == lval_internalvar)
9376     {
9377       /* Nothing.  */
9378     }
9379   else
9380     arg2 = coerce_for_assign (value_type (arg1), arg2);
9381   return ada_value_assign (arg1, arg2);
9382 }
9383
9384 } /* namespace expr */
9385
9386 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9387    [ INDICES[0] .. INDICES[1] ],...  The resulting intervals do not
9388    overlap.  */
9389 static void
9390 add_component_interval (LONGEST low, LONGEST high, 
9391                         std::vector<LONGEST> &indices)
9392 {
9393   int i, j;
9394
9395   int size = indices.size ();
9396   for (i = 0; i < size; i += 2) {
9397     if (high >= indices[i] && low <= indices[i + 1])
9398       {
9399         int kh;
9400
9401         for (kh = i + 2; kh < size; kh += 2)
9402           if (high < indices[kh])
9403             break;
9404         if (low < indices[i])
9405           indices[i] = low;
9406         indices[i + 1] = indices[kh - 1];
9407         if (high > indices[i + 1])
9408           indices[i + 1] = high;
9409         memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9410         indices.resize (kh - i - 2);
9411         return;
9412       }
9413     else if (high < indices[i])
9414       break;
9415   }
9416         
9417   indices.resize (indices.size () + 2);
9418   for (j = indices.size () - 1; j >= i + 2; j -= 1)
9419     indices[j] = indices[j - 2];
9420   indices[i] = low;
9421   indices[i + 1] = high;
9422 }
9423
9424 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9425    is different.  */
9426
9427 static struct value *
9428 ada_value_cast (struct type *type, struct value *arg2)
9429 {
9430   if (type == ada_check_typedef (value_type (arg2)))
9431     return arg2;
9432
9433   return value_cast (type, arg2);
9434 }
9435
9436 /*  Evaluating Ada expressions, and printing their result.
9437     ------------------------------------------------------
9438
9439     1. Introduction:
9440     ----------------
9441
9442     We usually evaluate an Ada expression in order to print its value.
9443     We also evaluate an expression in order to print its type, which
9444     happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9445     but we'll focus mostly on the EVAL_NORMAL phase.  In practice, the
9446     EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9447     the evaluation compared to the EVAL_NORMAL, but is otherwise very
9448     similar.
9449
9450     Evaluating expressions is a little more complicated for Ada entities
9451     than it is for entities in languages such as C.  The main reason for
9452     this is that Ada provides types whose definition might be dynamic.
9453     One example of such types is variant records.  Or another example
9454     would be an array whose bounds can only be known at run time.
9455
9456     The following description is a general guide as to what should be
9457     done (and what should NOT be done) in order to evaluate an expression
9458     involving such types, and when.  This does not cover how the semantic
9459     information is encoded by GNAT as this is covered separatly.  For the
9460     document used as the reference for the GNAT encoding, see exp_dbug.ads
9461     in the GNAT sources.
9462
9463     Ideally, we should embed each part of this description next to its
9464     associated code.  Unfortunately, the amount of code is so vast right
9465     now that it's hard to see whether the code handling a particular
9466     situation might be duplicated or not.  One day, when the code is
9467     cleaned up, this guide might become redundant with the comments
9468     inserted in the code, and we might want to remove it.
9469
9470     2. ``Fixing'' an Entity, the Simple Case:
9471     -----------------------------------------
9472
9473     When evaluating Ada expressions, the tricky issue is that they may
9474     reference entities whose type contents and size are not statically
9475     known.  Consider for instance a variant record:
9476
9477        type Rec (Empty : Boolean := True) is record
9478           case Empty is
9479              when True => null;
9480              when False => Value : Integer;
9481           end case;
9482        end record;
9483        Yes : Rec := (Empty => False, Value => 1);
9484        No  : Rec := (empty => True);
9485
9486     The size and contents of that record depends on the value of the
9487     descriminant (Rec.Empty).  At this point, neither the debugging
9488     information nor the associated type structure in GDB are able to
9489     express such dynamic types.  So what the debugger does is to create
9490     "fixed" versions of the type that applies to the specific object.
9491     We also informally refer to this operation as "fixing" an object,
9492     which means creating its associated fixed type.
9493
9494     Example: when printing the value of variable "Yes" above, its fixed
9495     type would look like this:
9496
9497        type Rec is record
9498           Empty : Boolean;
9499           Value : Integer;
9500        end record;
9501
9502     On the other hand, if we printed the value of "No", its fixed type
9503     would become:
9504
9505        type Rec is record
9506           Empty : Boolean;
9507        end record;
9508
9509     Things become a little more complicated when trying to fix an entity
9510     with a dynamic type that directly contains another dynamic type,
9511     such as an array of variant records, for instance.  There are
9512     two possible cases: Arrays, and records.
9513
9514     3. ``Fixing'' Arrays:
9515     ---------------------
9516
9517     The type structure in GDB describes an array in terms of its bounds,
9518     and the type of its elements.  By design, all elements in the array
9519     have the same type and we cannot represent an array of variant elements
9520     using the current type structure in GDB.  When fixing an array,
9521     we cannot fix the array element, as we would potentially need one
9522     fixed type per element of the array.  As a result, the best we can do
9523     when fixing an array is to produce an array whose bounds and size
9524     are correct (allowing us to read it from memory), but without having
9525     touched its element type.  Fixing each element will be done later,
9526     when (if) necessary.
9527
9528     Arrays are a little simpler to handle than records, because the same
9529     amount of memory is allocated for each element of the array, even if
9530     the amount of space actually used by each element differs from element
9531     to element.  Consider for instance the following array of type Rec:
9532
9533        type Rec_Array is array (1 .. 2) of Rec;
9534
9535     The actual amount of memory occupied by each element might be different
9536     from element to element, depending on the value of their discriminant.
9537     But the amount of space reserved for each element in the array remains
9538     fixed regardless.  So we simply need to compute that size using
9539     the debugging information available, from which we can then determine
9540     the array size (we multiply the number of elements of the array by
9541     the size of each element).
9542
9543     The simplest case is when we have an array of a constrained element
9544     type. For instance, consider the following type declarations:
9545
9546         type Bounded_String (Max_Size : Integer) is
9547            Length : Integer;
9548            Buffer : String (1 .. Max_Size);
9549         end record;
9550         type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9551
9552     In this case, the compiler describes the array as an array of
9553     variable-size elements (identified by its XVS suffix) for which
9554     the size can be read in the parallel XVZ variable.
9555
9556     In the case of an array of an unconstrained element type, the compiler
9557     wraps the array element inside a private PAD type.  This type should not
9558     be shown to the user, and must be "unwrap"'ed before printing.  Note
9559     that we also use the adjective "aligner" in our code to designate
9560     these wrapper types.
9561
9562     In some cases, the size allocated for each element is statically
9563     known.  In that case, the PAD type already has the correct size,
9564     and the array element should remain unfixed.
9565
9566     But there are cases when this size is not statically known.
9567     For instance, assuming that "Five" is an integer variable:
9568
9569         type Dynamic is array (1 .. Five) of Integer;
9570         type Wrapper (Has_Length : Boolean := False) is record
9571            Data : Dynamic;
9572            case Has_Length is
9573               when True => Length : Integer;
9574               when False => null;
9575            end case;
9576         end record;
9577         type Wrapper_Array is array (1 .. 2) of Wrapper;
9578
9579         Hello : Wrapper_Array := (others => (Has_Length => True,
9580                                              Data => (others => 17),
9581                                              Length => 1));
9582
9583
9584     The debugging info would describe variable Hello as being an
9585     array of a PAD type.  The size of that PAD type is not statically
9586     known, but can be determined using a parallel XVZ variable.
9587     In that case, a copy of the PAD type with the correct size should
9588     be used for the fixed array.
9589
9590     3. ``Fixing'' record type objects:
9591     ----------------------------------
9592
9593     Things are slightly different from arrays in the case of dynamic
9594     record types.  In this case, in order to compute the associated
9595     fixed type, we need to determine the size and offset of each of
9596     its components.  This, in turn, requires us to compute the fixed
9597     type of each of these components.
9598
9599     Consider for instance the example:
9600
9601         type Bounded_String (Max_Size : Natural) is record
9602            Str : String (1 .. Max_Size);
9603            Length : Natural;
9604         end record;
9605         My_String : Bounded_String (Max_Size => 10);
9606
9607     In that case, the position of field "Length" depends on the size
9608     of field Str, which itself depends on the value of the Max_Size
9609     discriminant.  In order to fix the type of variable My_String,
9610     we need to fix the type of field Str.  Therefore, fixing a variant
9611     record requires us to fix each of its components.
9612
9613     However, if a component does not have a dynamic size, the component
9614     should not be fixed.  In particular, fields that use a PAD type
9615     should not fixed.  Here is an example where this might happen
9616     (assuming type Rec above):
9617
9618        type Container (Big : Boolean) is record
9619           First : Rec;
9620           After : Integer;
9621           case Big is
9622              when True => Another : Integer;
9623              when False => null;
9624           end case;
9625        end record;
9626        My_Container : Container := (Big => False,
9627                                     First => (Empty => True),
9628                                     After => 42);
9629
9630     In that example, the compiler creates a PAD type for component First,
9631     whose size is constant, and then positions the component After just
9632     right after it.  The offset of component After is therefore constant
9633     in this case.
9634
9635     The debugger computes the position of each field based on an algorithm
9636     that uses, among other things, the actual position and size of the field
9637     preceding it.  Let's now imagine that the user is trying to print
9638     the value of My_Container.  If the type fixing was recursive, we would
9639     end up computing the offset of field After based on the size of the
9640     fixed version of field First.  And since in our example First has
9641     only one actual field, the size of the fixed type is actually smaller
9642     than the amount of space allocated to that field, and thus we would
9643     compute the wrong offset of field After.
9644
9645     To make things more complicated, we need to watch out for dynamic
9646     components of variant records (identified by the ___XVL suffix in
9647     the component name).  Even if the target type is a PAD type, the size
9648     of that type might not be statically known.  So the PAD type needs
9649     to be unwrapped and the resulting type needs to be fixed.  Otherwise,
9650     we might end up with the wrong size for our component.  This can be
9651     observed with the following type declarations:
9652
9653         type Octal is new Integer range 0 .. 7;
9654         type Octal_Array is array (Positive range <>) of Octal;
9655         pragma Pack (Octal_Array);
9656
9657         type Octal_Buffer (Size : Positive) is record
9658            Buffer : Octal_Array (1 .. Size);
9659            Length : Integer;
9660         end record;
9661
9662     In that case, Buffer is a PAD type whose size is unset and needs
9663     to be computed by fixing the unwrapped type.
9664
9665     4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
9666     ----------------------------------------------------------
9667
9668     Lastly, when should the sub-elements of an entity that remained unfixed
9669     thus far, be actually fixed?
9670
9671     The answer is: Only when referencing that element.  For instance
9672     when selecting one component of a record, this specific component
9673     should be fixed at that point in time.  Or when printing the value
9674     of a record, each component should be fixed before its value gets
9675     printed.  Similarly for arrays, the element of the array should be
9676     fixed when printing each element of the array, or when extracting
9677     one element out of that array.  On the other hand, fixing should
9678     not be performed on the elements when taking a slice of an array!
9679
9680     Note that one of the side effects of miscomputing the offset and
9681     size of each field is that we end up also miscomputing the size
9682     of the containing type.  This can have adverse results when computing
9683     the value of an entity.  GDB fetches the value of an entity based
9684     on the size of its type, and thus a wrong size causes GDB to fetch
9685     the wrong amount of memory.  In the case where the computed size is
9686     too small, GDB fetches too little data to print the value of our
9687     entity.  Results in this case are unpredictable, as we usually read
9688     past the buffer containing the data =:-o.  */
9689
9690 /* A helper function for TERNOP_IN_RANGE.  */
9691
9692 static value *
9693 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
9694                       enum noside noside,
9695                       value *arg1, value *arg2, value *arg3)
9696 {
9697   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9698   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9699   struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
9700   return
9701     value_from_longest (type,
9702                         (value_less (arg1, arg3)
9703                          || value_equal (arg1, arg3))
9704                         && (value_less (arg2, arg1)
9705                             || value_equal (arg2, arg1)));
9706 }
9707
9708 /* A helper function for UNOP_NEG.  */
9709
9710 value *
9711 ada_unop_neg (struct type *expect_type,
9712               struct expression *exp,
9713               enum noside noside, enum exp_opcode op,
9714               struct value *arg1)
9715 {
9716   unop_promote (exp->language_defn, exp->gdbarch, &arg1);
9717   return value_neg (arg1);
9718 }
9719
9720 /* A helper function for UNOP_IN_RANGE.  */
9721
9722 value *
9723 ada_unop_in_range (struct type *expect_type,
9724                    struct expression *exp,
9725                    enum noside noside, enum exp_opcode op,
9726                    struct value *arg1, struct type *type)
9727 {
9728   struct value *arg2, *arg3;
9729   switch (type->code ())
9730     {
9731     default:
9732       lim_warning (_("Membership test incompletely implemented; "
9733                      "always returns true"));
9734       type = language_bool_type (exp->language_defn, exp->gdbarch);
9735       return value_from_longest (type, (LONGEST) 1);
9736
9737     case TYPE_CODE_RANGE:
9738       arg2 = value_from_longest (type,
9739                                  type->bounds ()->low.const_val ());
9740       arg3 = value_from_longest (type,
9741                                  type->bounds ()->high.const_val ());
9742       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9743       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9744       type = language_bool_type (exp->language_defn, exp->gdbarch);
9745       return
9746         value_from_longest (type,
9747                             (value_less (arg1, arg3)
9748                              || value_equal (arg1, arg3))
9749                             && (value_less (arg2, arg1)
9750                                 || value_equal (arg2, arg1)));
9751     }
9752 }
9753
9754 /* A helper function for OP_ATR_TAG.  */
9755
9756 value *
9757 ada_atr_tag (struct type *expect_type,
9758              struct expression *exp,
9759              enum noside noside, enum exp_opcode op,
9760              struct value *arg1)
9761 {
9762   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9763     return value_zero (ada_tag_type (arg1), not_lval);
9764
9765   return ada_value_tag (arg1);
9766 }
9767
9768 /* A helper function for OP_ATR_SIZE.  */
9769
9770 value *
9771 ada_atr_size (struct type *expect_type,
9772               struct expression *exp,
9773               enum noside noside, enum exp_opcode op,
9774               struct value *arg1)
9775 {
9776   struct type *type = value_type (arg1);
9777
9778   /* If the argument is a reference, then dereference its type, since
9779      the user is really asking for the size of the actual object,
9780      not the size of the pointer.  */
9781   if (type->code () == TYPE_CODE_REF)
9782     type = TYPE_TARGET_TYPE (type);
9783
9784   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9785     return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
9786   else
9787     return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
9788                                TARGET_CHAR_BIT * TYPE_LENGTH (type));
9789 }
9790
9791 /* A helper function for UNOP_ABS.  */
9792
9793 value *
9794 ada_abs (struct type *expect_type,
9795          struct expression *exp,
9796          enum noside noside, enum exp_opcode op,
9797          struct value *arg1)
9798 {
9799   unop_promote (exp->language_defn, exp->gdbarch, &arg1);
9800   if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
9801     return value_neg (arg1);
9802   else
9803     return arg1;
9804 }
9805
9806 /* A helper function for BINOP_MUL.  */
9807
9808 value *
9809 ada_mult_binop (struct type *expect_type,
9810                 struct expression *exp,
9811                 enum noside noside, enum exp_opcode op,
9812                 struct value *arg1, struct value *arg2)
9813 {
9814   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9815     {
9816       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9817       return value_zero (value_type (arg1), not_lval);
9818     }
9819   else
9820     {
9821       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9822       return ada_value_binop (arg1, arg2, op);
9823     }
9824 }
9825
9826 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL.  */
9827
9828 value *
9829 ada_equal_binop (struct type *expect_type,
9830                  struct expression *exp,
9831                  enum noside noside, enum exp_opcode op,
9832                  struct value *arg1, struct value *arg2)
9833 {
9834   int tem;
9835   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9836     tem = 0;
9837   else
9838     {
9839       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9840       tem = ada_value_equal (arg1, arg2);
9841     }
9842   if (op == BINOP_NOTEQUAL)
9843     tem = !tem;
9844   struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
9845   return value_from_longest (type, (LONGEST) tem);
9846 }
9847
9848 /* A helper function for TERNOP_SLICE.  */
9849
9850 value *
9851 ada_ternop_slice (struct expression *exp,
9852                   enum noside noside,
9853                   struct value *array, struct value *low_bound_val,
9854                   struct value *high_bound_val)
9855 {
9856   LONGEST low_bound;
9857   LONGEST high_bound;
9858
9859   low_bound_val = coerce_ref (low_bound_val);
9860   high_bound_val = coerce_ref (high_bound_val);
9861   low_bound = value_as_long (low_bound_val);
9862   high_bound = value_as_long (high_bound_val);
9863
9864   /* If this is a reference to an aligner type, then remove all
9865      the aligners.  */
9866   if (value_type (array)->code () == TYPE_CODE_REF
9867       && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
9868     TYPE_TARGET_TYPE (value_type (array)) =
9869       ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
9870
9871   if (ada_is_any_packed_array_type (value_type (array)))
9872     error (_("cannot slice a packed array"));
9873
9874   /* If this is a reference to an array or an array lvalue,
9875      convert to a pointer.  */
9876   if (value_type (array)->code () == TYPE_CODE_REF
9877       || (value_type (array)->code () == TYPE_CODE_ARRAY
9878           && VALUE_LVAL (array) == lval_memory))
9879     array = value_addr (array);
9880
9881   if (noside == EVAL_AVOID_SIDE_EFFECTS
9882       && ada_is_array_descriptor_type (ada_check_typedef
9883                                        (value_type (array))))
9884     return empty_array (ada_type_of_array (array, 0), low_bound,
9885                         high_bound);
9886
9887   array = ada_coerce_to_simple_array_ptr (array);
9888
9889   /* If we have more than one level of pointer indirection,
9890      dereference the value until we get only one level.  */
9891   while (value_type (array)->code () == TYPE_CODE_PTR
9892          && (TYPE_TARGET_TYPE (value_type (array))->code ()
9893              == TYPE_CODE_PTR))
9894     array = value_ind (array);
9895
9896   /* Make sure we really do have an array type before going further,
9897      to avoid a SEGV when trying to get the index type or the target
9898      type later down the road if the debug info generated by
9899      the compiler is incorrect or incomplete.  */
9900   if (!ada_is_simple_array_type (value_type (array)))
9901     error (_("cannot take slice of non-array"));
9902
9903   if (ada_check_typedef (value_type (array))->code ()
9904       == TYPE_CODE_PTR)
9905     {
9906       struct type *type0 = ada_check_typedef (value_type (array));
9907
9908       if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
9909         return empty_array (TYPE_TARGET_TYPE (type0), low_bound, high_bound);
9910       else
9911         {
9912           struct type *arr_type0 =
9913             to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
9914
9915           return ada_value_slice_from_ptr (array, arr_type0,
9916                                            longest_to_int (low_bound),
9917                                            longest_to_int (high_bound));
9918         }
9919     }
9920   else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9921     return array;
9922   else if (high_bound < low_bound)
9923     return empty_array (value_type (array), low_bound, high_bound);
9924   else
9925     return ada_value_slice (array, longest_to_int (low_bound),
9926                             longest_to_int (high_bound));
9927 }
9928
9929 /* A helper function for BINOP_IN_BOUNDS.  */
9930
9931 value *
9932 ada_binop_in_bounds (struct expression *exp, enum noside noside,
9933                      struct value *arg1, struct value *arg2, int n)
9934 {
9935   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9936     {
9937       struct type *type = language_bool_type (exp->language_defn,
9938                                               exp->gdbarch);
9939       return value_zero (type, not_lval);
9940     }
9941
9942   struct type *type = ada_index_type (value_type (arg2), n, "range");
9943   if (!type)
9944     type = value_type (arg1);
9945
9946   value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
9947   arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
9948
9949   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9950   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9951   type = language_bool_type (exp->language_defn, exp->gdbarch);
9952   return value_from_longest (type,
9953                              (value_less (arg1, arg3)
9954                               || value_equal (arg1, arg3))
9955                              && (value_less (arg2, arg1)
9956                                  || value_equal (arg2, arg1)));
9957 }
9958
9959 /* A helper function for some attribute operations.  */
9960
9961 static value *
9962 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
9963               struct value *arg1, struct type *type_arg, int tem)
9964 {
9965   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9966     {
9967       if (type_arg == NULL)
9968         type_arg = value_type (arg1);
9969
9970       if (ada_is_constrained_packed_array_type (type_arg))
9971         type_arg = decode_constrained_packed_array_type (type_arg);
9972
9973       if (!discrete_type_p (type_arg))
9974         {
9975           switch (op)
9976             {
9977             default:          /* Should never happen.  */
9978               error (_("unexpected attribute encountered"));
9979             case OP_ATR_FIRST:
9980             case OP_ATR_LAST:
9981               type_arg = ada_index_type (type_arg, tem,
9982                                          ada_attribute_name (op));
9983               break;
9984             case OP_ATR_LENGTH:
9985               type_arg = builtin_type (exp->gdbarch)->builtin_int;
9986               break;
9987             }
9988         }
9989
9990       return value_zero (type_arg, not_lval);
9991     }
9992   else if (type_arg == NULL)
9993     {
9994       arg1 = ada_coerce_ref (arg1);
9995
9996       if (ada_is_constrained_packed_array_type (value_type (arg1)))
9997         arg1 = ada_coerce_to_simple_array (arg1);
9998
9999       struct type *type;
10000       if (op == OP_ATR_LENGTH)
10001         type = builtin_type (exp->gdbarch)->builtin_int;
10002       else
10003         {
10004           type = ada_index_type (value_type (arg1), tem,
10005                                  ada_attribute_name (op));
10006           if (type == NULL)
10007             type = builtin_type (exp->gdbarch)->builtin_int;
10008         }
10009
10010       switch (op)
10011         {
10012         default:          /* Should never happen.  */
10013           error (_("unexpected attribute encountered"));
10014         case OP_ATR_FIRST:
10015           return value_from_longest
10016             (type, ada_array_bound (arg1, tem, 0));
10017         case OP_ATR_LAST:
10018           return value_from_longest
10019             (type, ada_array_bound (arg1, tem, 1));
10020         case OP_ATR_LENGTH:
10021           return value_from_longest
10022             (type, ada_array_length (arg1, tem));
10023         }
10024     }
10025   else if (discrete_type_p (type_arg))
10026     {
10027       struct type *range_type;
10028       const char *name = ada_type_name (type_arg);
10029
10030       range_type = NULL;
10031       if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10032         range_type = to_fixed_range_type (type_arg, NULL);
10033       if (range_type == NULL)
10034         range_type = type_arg;
10035       switch (op)
10036         {
10037         default:
10038           error (_("unexpected attribute encountered"));
10039         case OP_ATR_FIRST:
10040           return value_from_longest 
10041             (range_type, ada_discrete_type_low_bound (range_type));
10042         case OP_ATR_LAST:
10043           return value_from_longest
10044             (range_type, ada_discrete_type_high_bound (range_type));
10045         case OP_ATR_LENGTH:
10046           error (_("the 'length attribute applies only to array types"));
10047         }
10048     }
10049   else if (type_arg->code () == TYPE_CODE_FLT)
10050     error (_("unimplemented type attribute"));
10051   else
10052     {
10053       LONGEST low, high;
10054
10055       if (ada_is_constrained_packed_array_type (type_arg))
10056         type_arg = decode_constrained_packed_array_type (type_arg);
10057
10058       struct type *type;
10059       if (op == OP_ATR_LENGTH)
10060         type = builtin_type (exp->gdbarch)->builtin_int;
10061       else
10062         {
10063           type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10064           if (type == NULL)
10065             type = builtin_type (exp->gdbarch)->builtin_int;
10066         }
10067
10068       switch (op)
10069         {
10070         default:
10071           error (_("unexpected attribute encountered"));
10072         case OP_ATR_FIRST:
10073           low = ada_array_bound_from_type (type_arg, tem, 0);
10074           return value_from_longest (type, low);
10075         case OP_ATR_LAST:
10076           high = ada_array_bound_from_type (type_arg, tem, 1);
10077           return value_from_longest (type, high);
10078         case OP_ATR_LENGTH:
10079           low = ada_array_bound_from_type (type_arg, tem, 0);
10080           high = ada_array_bound_from_type (type_arg, tem, 1);
10081           return value_from_longest (type, high - low + 1);
10082         }
10083     }
10084 }
10085
10086 /* A helper function for OP_ATR_MIN and OP_ATR_MAX.  */
10087
10088 struct value *
10089 ada_binop_minmax (struct type *expect_type,
10090                   struct expression *exp,
10091                   enum noside noside, enum exp_opcode op,
10092                   struct value *arg1, struct value *arg2)
10093 {
10094   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10095     return value_zero (value_type (arg1), not_lval);
10096   else
10097     {
10098       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10099       return value_binop (arg1, arg2, op);
10100     }
10101 }
10102
10103 /* A helper function for BINOP_EXP.  */
10104
10105 struct value *
10106 ada_binop_exp (struct type *expect_type,
10107                struct expression *exp,
10108                enum noside noside, enum exp_opcode op,
10109                struct value *arg1, struct value *arg2)
10110 {
10111   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10112     return value_zero (value_type (arg1), not_lval);
10113   else
10114     {
10115       /* For integer exponentiation operations,
10116          only promote the first argument.  */
10117       if (is_integral_type (value_type (arg2)))
10118         unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10119       else
10120         binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10121
10122       return value_binop (arg1, arg2, op);
10123     }
10124 }
10125
10126 namespace expr
10127 {
10128
10129 /* See ada-exp.h.  */
10130
10131 operation_up
10132 ada_resolvable::replace (operation_up &&owner,
10133                          struct expression *exp,
10134                          bool deprocedure_p,
10135                          bool parse_completion,
10136                          innermost_block_tracker *tracker,
10137                          struct type *context_type)
10138 {
10139   if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10140     return (make_operation<ada_funcall_operation>
10141             (std::move (owner),
10142              std::vector<operation_up> ()));
10143   return std::move (owner);
10144 }
10145
10146 /* Convert the character literal whose ASCII value would be VAL to the
10147    appropriate value of type TYPE, if there is a translation.
10148    Otherwise return VAL.  Hence, in an enumeration type ('A', 'B'),
10149    the literal 'A' (VAL == 65), returns 0.  */
10150
10151 static LONGEST
10152 convert_char_literal (struct type *type, LONGEST val)
10153 {
10154   char name[7];
10155   int f;
10156
10157   if (type == NULL)
10158     return val;
10159   type = check_typedef (type);
10160   if (type->code () != TYPE_CODE_ENUM)
10161     return val;
10162
10163   if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10164     xsnprintf (name, sizeof (name), "Q%c", (int) val);
10165   else
10166     xsnprintf (name, sizeof (name), "QU%02x", (int) val);
10167   size_t len = strlen (name);
10168   for (f = 0; f < type->num_fields (); f += 1)
10169     {
10170       /* Check the suffix because an enum constant in a package will
10171          have a name like "pkg__QUxx".  This is safe enough because we
10172          already have the correct type, and because mangling means
10173          there can't be clashes.  */
10174       const char *ename = TYPE_FIELD_NAME (type, f);
10175       size_t elen = strlen (ename);
10176
10177       if (elen >= len && strcmp (name, ename + elen - len) == 0)
10178         return TYPE_FIELD_ENUMVAL (type, f);
10179     }
10180   return val;
10181 }
10182
10183 /* See ada-exp.h.  */
10184
10185 operation_up
10186 ada_char_operation::replace (operation_up &&owner,
10187                              struct expression *exp,
10188                              bool deprocedure_p,
10189                              bool parse_completion,
10190                              innermost_block_tracker *tracker,
10191                              struct type *context_type)
10192 {
10193   operation_up result = std::move (owner);
10194
10195   if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10196     {
10197       gdb_assert (result.get () == this);
10198       std::get<0> (m_storage) = context_type;
10199       std::get<1> (m_storage)
10200         = convert_char_literal (context_type, std::get<1> (m_storage));
10201     }
10202
10203   return make_operation<ada_wrapped_operation> (std::move (result));
10204 }
10205
10206 value *
10207 ada_wrapped_operation::evaluate (struct type *expect_type,
10208                                  struct expression *exp,
10209                                  enum noside noside)
10210 {
10211   value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10212   if (noside == EVAL_NORMAL)
10213     result = unwrap_value (result);
10214
10215   /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10216      then we need to perform the conversion manually, because
10217      evaluate_subexp_standard doesn't do it.  This conversion is
10218      necessary in Ada because the different kinds of float/fixed
10219      types in Ada have different representations.
10220
10221      Similarly, we need to perform the conversion from OP_LONG
10222      ourselves.  */
10223   if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10224     result = ada_value_cast (expect_type, result);
10225
10226   return result;
10227 }
10228
10229 value *
10230 ada_string_operation::evaluate (struct type *expect_type,
10231                                 struct expression *exp,
10232                                 enum noside noside)
10233 {
10234   value *result = string_operation::evaluate (expect_type, exp, noside);
10235   /* The result type will have code OP_STRING, bashed there from 
10236      OP_ARRAY.  Bash it back.  */
10237   if (value_type (result)->code () == TYPE_CODE_STRING)
10238     value_type (result)->set_code (TYPE_CODE_ARRAY);
10239   return result;
10240 }
10241
10242 value *
10243 ada_qual_operation::evaluate (struct type *expect_type,
10244                               struct expression *exp,
10245                               enum noside noside)
10246 {
10247   struct type *type = std::get<1> (m_storage);
10248   return std::get<0> (m_storage)->evaluate (type, exp, noside);
10249 }
10250
10251 value *
10252 ada_ternop_range_operation::evaluate (struct type *expect_type,
10253                                       struct expression *exp,
10254                                       enum noside noside)
10255 {
10256   value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10257   value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10258   value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10259   return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10260 }
10261
10262 value *
10263 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10264                                       struct expression *exp,
10265                                       enum noside noside)
10266 {
10267   value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10268   value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10269
10270   auto do_op = [=] (LONGEST x, LONGEST y)
10271     {
10272       if (std::get<0> (m_storage) == BINOP_ADD)
10273         return x + y;
10274       return x - y;
10275     };
10276
10277   if (value_type (arg1)->code () == TYPE_CODE_PTR)
10278     return (value_from_longest
10279             (value_type (arg1),
10280              do_op (value_as_long (arg1), value_as_long (arg2))));
10281   if (value_type (arg2)->code () == TYPE_CODE_PTR)
10282     return (value_from_longest
10283             (value_type (arg2),
10284              do_op (value_as_long (arg1), value_as_long (arg2))));
10285   /* Preserve the original type for use by the range case below.
10286      We cannot cast the result to a reference type, so if ARG1 is
10287      a reference type, find its underlying type.  */
10288   struct type *type = value_type (arg1);
10289   while (type->code () == TYPE_CODE_REF)
10290     type = TYPE_TARGET_TYPE (type);
10291   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10292   arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10293   /* We need to special-case the result with a range.
10294      This is done for the benefit of "ptype".  gdb's Ada support
10295      historically used the LHS to set the result type here, so
10296      preserve this behavior.  */
10297   if (type->code () == TYPE_CODE_RANGE)
10298     arg1 = value_cast (type, arg1);
10299   return arg1;
10300 }
10301
10302 value *
10303 ada_unop_atr_operation::evaluate (struct type *expect_type,
10304                                   struct expression *exp,
10305                                   enum noside noside)
10306 {
10307   struct type *type_arg = nullptr;
10308   value *val = nullptr;
10309
10310   if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10311     {
10312       value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10313                                                       EVAL_AVOID_SIDE_EFFECTS);
10314       type_arg = value_type (tem);
10315     }
10316   else
10317     val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10318
10319   return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10320                        val, type_arg, std::get<2> (m_storage));
10321 }
10322
10323 value *
10324 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10325                                                  struct expression *exp,
10326                                                  enum noside noside)
10327 {
10328   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10329     return value_zero (expect_type, not_lval);
10330
10331   const bound_minimal_symbol &b = std::get<0> (m_storage);
10332   value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10333
10334   val = ada_value_cast (expect_type, val);
10335
10336   /* Follow the Ada language semantics that do not allow taking
10337      an address of the result of a cast (view conversion in Ada).  */
10338   if (VALUE_LVAL (val) == lval_memory)
10339     {
10340       if (value_lazy (val))
10341         value_fetch_lazy (val);
10342       VALUE_LVAL (val) = not_lval;
10343     }
10344   return val;
10345 }
10346
10347 value *
10348 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10349                                             struct expression *exp,
10350                                             enum noside noside)
10351 {
10352   value *val = evaluate_var_value (noside,
10353                                    std::get<0> (m_storage).block,
10354                                    std::get<0> (m_storage).symbol);
10355
10356   val = ada_value_cast (expect_type, val);
10357
10358   /* Follow the Ada language semantics that do not allow taking
10359      an address of the result of a cast (view conversion in Ada).  */
10360   if (VALUE_LVAL (val) == lval_memory)
10361     {
10362       if (value_lazy (val))
10363         value_fetch_lazy (val);
10364       VALUE_LVAL (val) = not_lval;
10365     }
10366   return val;
10367 }
10368
10369 value *
10370 ada_var_value_operation::evaluate (struct type *expect_type,
10371                                    struct expression *exp,
10372                                    enum noside noside)
10373 {
10374   symbol *sym = std::get<0> (m_storage).symbol;
10375
10376   if (SYMBOL_DOMAIN (sym) == UNDEF_DOMAIN)
10377     /* Only encountered when an unresolved symbol occurs in a
10378        context other than a function call, in which case, it is
10379        invalid.  */
10380     error (_("Unexpected unresolved symbol, %s, during evaluation"),
10381            sym->print_name ());
10382
10383   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10384     {
10385       struct type *type = static_unwrap_type (SYMBOL_TYPE (sym));
10386       /* Check to see if this is a tagged type.  We also need to handle
10387          the case where the type is a reference to a tagged type, but
10388          we have to be careful to exclude pointers to tagged types.
10389          The latter should be shown as usual (as a pointer), whereas
10390          a reference should mostly be transparent to the user.  */
10391       if (ada_is_tagged_type (type, 0)
10392           || (type->code () == TYPE_CODE_REF
10393               && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
10394         {
10395           /* Tagged types are a little special in the fact that the real
10396              type is dynamic and can only be determined by inspecting the
10397              object's tag.  This means that we need to get the object's
10398              value first (EVAL_NORMAL) and then extract the actual object
10399              type from its tag.
10400
10401              Note that we cannot skip the final step where we extract
10402              the object type from its tag, because the EVAL_NORMAL phase
10403              results in dynamic components being resolved into fixed ones.
10404              This can cause problems when trying to print the type
10405              description of tagged types whose parent has a dynamic size:
10406              We use the type name of the "_parent" component in order
10407              to print the name of the ancestor type in the type description.
10408              If that component had a dynamic size, the resolution into
10409              a fixed type would result in the loss of that type name,
10410              thus preventing us from printing the name of the ancestor
10411              type in the type description.  */
10412           value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10413
10414           if (type->code () != TYPE_CODE_REF)
10415             {
10416               struct type *actual_type;
10417
10418               actual_type = type_from_tag (ada_value_tag (arg1));
10419               if (actual_type == NULL)
10420                 /* If, for some reason, we were unable to determine
10421                    the actual type from the tag, then use the static
10422                    approximation that we just computed as a fallback.
10423                    This can happen if the debugging information is
10424                    incomplete, for instance.  */
10425                 actual_type = type;
10426               return value_zero (actual_type, not_lval);
10427             }
10428           else
10429             {
10430               /* In the case of a ref, ada_coerce_ref takes care
10431                  of determining the actual type.  But the evaluation
10432                  should return a ref as it should be valid to ask
10433                  for its address; so rebuild a ref after coerce.  */
10434               arg1 = ada_coerce_ref (arg1);
10435               return value_ref (arg1, TYPE_CODE_REF);
10436             }
10437         }
10438
10439       /* Records and unions for which GNAT encodings have been
10440          generated need to be statically fixed as well.
10441          Otherwise, non-static fixing produces a type where
10442          all dynamic properties are removed, which prevents "ptype"
10443          from being able to completely describe the type.
10444          For instance, a case statement in a variant record would be
10445          replaced by the relevant components based on the actual
10446          value of the discriminants.  */
10447       if ((type->code () == TYPE_CODE_STRUCT
10448            && dynamic_template_type (type) != NULL)
10449           || (type->code () == TYPE_CODE_UNION
10450               && ada_find_parallel_type (type, "___XVU") != NULL))
10451         return value_zero (to_static_fixed_type (type), not_lval);
10452     }
10453
10454   value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10455   return ada_to_fixed_value (arg1);
10456 }
10457
10458 bool
10459 ada_var_value_operation::resolve (struct expression *exp,
10460                                   bool deprocedure_p,
10461                                   bool parse_completion,
10462                                   innermost_block_tracker *tracker,
10463                                   struct type *context_type)
10464 {
10465   symbol *sym = std::get<0> (m_storage).symbol;
10466   if (SYMBOL_DOMAIN (sym) == UNDEF_DOMAIN)
10467     {
10468       block_symbol resolved
10469         = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10470                                 context_type, parse_completion,
10471                                 deprocedure_p, tracker);
10472       std::get<0> (m_storage) = resolved;
10473     }
10474
10475   if (deprocedure_p
10476       && (SYMBOL_TYPE (std::get<0> (m_storage).symbol)->code ()
10477           == TYPE_CODE_FUNC))
10478     return true;
10479
10480   return false;
10481 }
10482
10483 value *
10484 ada_atr_val_operation::evaluate (struct type *expect_type,
10485                                  struct expression *exp,
10486                                  enum noside noside)
10487 {
10488   value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10489   return ada_val_atr (noside, std::get<0> (m_storage), arg);
10490 }
10491
10492 value *
10493 ada_unop_ind_operation::evaluate (struct type *expect_type,
10494                                   struct expression *exp,
10495                                   enum noside noside)
10496 {
10497   value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10498
10499   struct type *type = ada_check_typedef (value_type (arg1));
10500   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10501     {
10502       if (ada_is_array_descriptor_type (type))
10503         /* GDB allows dereferencing GNAT array descriptors.  */
10504         {
10505           struct type *arrType = ada_type_of_array (arg1, 0);
10506
10507           if (arrType == NULL)
10508             error (_("Attempt to dereference null array pointer."));
10509           return value_at_lazy (arrType, 0);
10510         }
10511       else if (type->code () == TYPE_CODE_PTR
10512                || type->code () == TYPE_CODE_REF
10513                /* In C you can dereference an array to get the 1st elt.  */
10514                || type->code () == TYPE_CODE_ARRAY)
10515         {
10516           /* As mentioned in the OP_VAR_VALUE case, tagged types can
10517              only be determined by inspecting the object's tag.
10518              This means that we need to evaluate completely the
10519              expression in order to get its type.  */
10520
10521           if ((type->code () == TYPE_CODE_REF
10522                || type->code () == TYPE_CODE_PTR)
10523               && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
10524             {
10525               arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
10526                                                         EVAL_NORMAL);
10527               type = value_type (ada_value_ind (arg1));
10528             }
10529           else
10530             {
10531               type = to_static_fixed_type
10532                 (ada_aligned_type
10533                  (ada_check_typedef (TYPE_TARGET_TYPE (type))));
10534             }
10535           ada_ensure_varsize_limit (type);
10536           return value_zero (type, lval_memory);
10537         }
10538       else if (type->code () == TYPE_CODE_INT)
10539         {
10540           /* GDB allows dereferencing an int.  */
10541           if (expect_type == NULL)
10542             return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10543                                lval_memory);
10544           else
10545             {
10546               expect_type =
10547                 to_static_fixed_type (ada_aligned_type (expect_type));
10548               return value_zero (expect_type, lval_memory);
10549             }
10550         }
10551       else
10552         error (_("Attempt to take contents of a non-pointer value."));
10553     }
10554   arg1 = ada_coerce_ref (arg1);     /* FIXME: What is this for??  */
10555   type = ada_check_typedef (value_type (arg1));
10556
10557   if (type->code () == TYPE_CODE_INT)
10558     /* GDB allows dereferencing an int.  If we were given
10559        the expect_type, then use that as the target type.
10560        Otherwise, assume that the target type is an int.  */
10561     {
10562       if (expect_type != NULL)
10563         return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
10564                                           arg1));
10565       else
10566         return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
10567                               (CORE_ADDR) value_as_address (arg1));
10568     }
10569
10570   struct type *target_type = (to_static_fixed_type
10571                               (ada_aligned_type
10572                                (ada_check_typedef (TYPE_TARGET_TYPE (type)))));
10573   ada_ensure_varsize_limit (target_type);
10574
10575   if (ada_is_array_descriptor_type (type))
10576     /* GDB allows dereferencing GNAT array descriptors.  */
10577     return ada_coerce_to_simple_array (arg1);
10578   else
10579     return ada_value_ind (arg1);
10580 }
10581
10582 value *
10583 ada_structop_operation::evaluate (struct type *expect_type,
10584                                   struct expression *exp,
10585                                   enum noside noside)
10586 {
10587   value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10588   const char *str = std::get<1> (m_storage).c_str ();
10589   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10590     {
10591       struct type *type;
10592       struct type *type1 = value_type (arg1);
10593
10594       if (ada_is_tagged_type (type1, 1))
10595         {
10596           type = ada_lookup_struct_elt_type (type1, str, 1, 1);
10597
10598           /* If the field is not found, check if it exists in the
10599              extension of this object's type. This means that we
10600              need to evaluate completely the expression.  */
10601
10602           if (type == NULL)
10603             {
10604               arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
10605                                                         EVAL_NORMAL);
10606               arg1 = ada_value_struct_elt (arg1, str, 0);
10607               arg1 = unwrap_value (arg1);
10608               type = value_type (ada_to_fixed_value (arg1));
10609             }
10610         }
10611       else
10612         type = ada_lookup_struct_elt_type (type1, str, 1, 0);
10613
10614       return value_zero (ada_aligned_type (type), lval_memory);
10615     }
10616   else
10617     {
10618       arg1 = ada_value_struct_elt (arg1, str, 0);
10619       arg1 = unwrap_value (arg1);
10620       return ada_to_fixed_value (arg1);
10621     }
10622 }
10623
10624 value *
10625 ada_funcall_operation::evaluate (struct type *expect_type,
10626                                  struct expression *exp,
10627                                  enum noside noside)
10628 {
10629   const std::vector<operation_up> &args_up = std::get<1> (m_storage);
10630   int nargs = args_up.size ();
10631   std::vector<value *> argvec (nargs);
10632   operation_up &callee_op = std::get<0> (m_storage);
10633
10634   ada_var_value_operation *avv
10635     = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
10636   if (avv != nullptr
10637       && SYMBOL_DOMAIN (avv->get_symbol ()) == UNDEF_DOMAIN)
10638     error (_("Unexpected unresolved symbol, %s, during evaluation"),
10639            avv->get_symbol ()->print_name ());
10640
10641   value *callee = callee_op->evaluate (nullptr, exp, noside);
10642   for (int i = 0; i < args_up.size (); ++i)
10643     argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
10644
10645   if (ada_is_constrained_packed_array_type
10646       (desc_base_type (value_type (callee))))
10647     callee = ada_coerce_to_simple_array (callee);
10648   else if (value_type (callee)->code () == TYPE_CODE_ARRAY
10649            && TYPE_FIELD_BITSIZE (value_type (callee), 0) != 0)
10650     /* This is a packed array that has already been fixed, and
10651        therefore already coerced to a simple array.  Nothing further
10652        to do.  */
10653     ;
10654   else if (value_type (callee)->code () == TYPE_CODE_REF)
10655     {
10656       /* Make sure we dereference references so that all the code below
10657          feels like it's really handling the referenced value.  Wrapping
10658          types (for alignment) may be there, so make sure we strip them as
10659          well.  */
10660       callee = ada_to_fixed_value (coerce_ref (callee));
10661     }
10662   else if (value_type (callee)->code () == TYPE_CODE_ARRAY
10663            && VALUE_LVAL (callee) == lval_memory)
10664     callee = value_addr (callee);
10665
10666   struct type *type = ada_check_typedef (value_type (callee));
10667
10668   /* Ada allows us to implicitly dereference arrays when subscripting
10669      them.  So, if this is an array typedef (encoding use for array
10670      access types encoded as fat pointers), strip it now.  */
10671   if (type->code () == TYPE_CODE_TYPEDEF)
10672     type = ada_typedef_target_type (type);
10673
10674   if (type->code () == TYPE_CODE_PTR)
10675     {
10676       switch (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ())
10677         {
10678         case TYPE_CODE_FUNC:
10679           type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10680           break;
10681         case TYPE_CODE_ARRAY:
10682           break;
10683         case TYPE_CODE_STRUCT:
10684           if (noside != EVAL_AVOID_SIDE_EFFECTS)
10685             callee = ada_value_ind (callee);
10686           type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10687           break;
10688         default:
10689           error (_("cannot subscript or call something of type `%s'"),
10690                  ada_type_name (value_type (callee)));
10691           break;
10692         }
10693     }
10694
10695   switch (type->code ())
10696     {
10697     case TYPE_CODE_FUNC:
10698       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10699         {
10700           if (TYPE_TARGET_TYPE (type) == NULL)
10701             error_call_unknown_return_type (NULL);
10702           return allocate_value (TYPE_TARGET_TYPE (type));
10703         }
10704       return call_function_by_hand (callee, NULL, argvec);
10705     case TYPE_CODE_INTERNAL_FUNCTION:
10706       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10707         /* We don't know anything about what the internal
10708            function might return, but we have to return
10709            something.  */
10710         return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10711                            not_lval);
10712       else
10713         return call_internal_function (exp->gdbarch, exp->language_defn,
10714                                        callee, nargs,
10715                                        argvec.data ());
10716
10717     case TYPE_CODE_STRUCT:
10718       {
10719         int arity;
10720
10721         arity = ada_array_arity (type);
10722         type = ada_array_element_type (type, nargs);
10723         if (type == NULL)
10724           error (_("cannot subscript or call a record"));
10725         if (arity != nargs)
10726           error (_("wrong number of subscripts; expecting %d"), arity);
10727         if (noside == EVAL_AVOID_SIDE_EFFECTS)
10728           return value_zero (ada_aligned_type (type), lval_memory);
10729         return
10730           unwrap_value (ada_value_subscript
10731                         (callee, nargs, argvec.data ()));
10732       }
10733     case TYPE_CODE_ARRAY:
10734       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10735         {
10736           type = ada_array_element_type (type, nargs);
10737           if (type == NULL)
10738             error (_("element type of array unknown"));
10739           else
10740             return value_zero (ada_aligned_type (type), lval_memory);
10741         }
10742       return
10743         unwrap_value (ada_value_subscript
10744                       (ada_coerce_to_simple_array (callee),
10745                        nargs, argvec.data ()));
10746     case TYPE_CODE_PTR:     /* Pointer to array */
10747       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10748         {
10749           type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
10750           type = ada_array_element_type (type, nargs);
10751           if (type == NULL)
10752             error (_("element type of array unknown"));
10753           else
10754             return value_zero (ada_aligned_type (type), lval_memory);
10755         }
10756       return
10757         unwrap_value (ada_value_ptr_subscript (callee, nargs,
10758                                                argvec.data ()));
10759
10760     default:
10761       error (_("Attempt to index or call something other than an "
10762                "array or function"));
10763     }
10764 }
10765
10766 bool
10767 ada_funcall_operation::resolve (struct expression *exp,
10768                                 bool deprocedure_p,
10769                                 bool parse_completion,
10770                                 innermost_block_tracker *tracker,
10771                                 struct type *context_type)
10772 {
10773   operation_up &callee_op = std::get<0> (m_storage);
10774
10775   ada_var_value_operation *avv
10776     = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
10777   if (avv == nullptr)
10778     return false;
10779
10780   symbol *sym = avv->get_symbol ();
10781   if (SYMBOL_DOMAIN (sym) != UNDEF_DOMAIN)
10782     return false;
10783
10784   const std::vector<operation_up> &args_up = std::get<1> (m_storage);
10785   int nargs = args_up.size ();
10786   std::vector<value *> argvec (nargs);
10787
10788   for (int i = 0; i < args_up.size (); ++i)
10789     argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
10790
10791   const block *block = avv->get_block ();
10792   block_symbol resolved
10793     = ada_resolve_funcall (sym, block,
10794                            context_type, parse_completion,
10795                            nargs, argvec.data (),
10796                            tracker);
10797
10798   std::get<0> (m_storage)
10799     = make_operation<ada_var_value_operation> (resolved);
10800   return false;
10801 }
10802
10803 bool
10804 ada_ternop_slice_operation::resolve (struct expression *exp,
10805                                      bool deprocedure_p,
10806                                      bool parse_completion,
10807                                      innermost_block_tracker *tracker,
10808                                      struct type *context_type)
10809 {
10810   /* Historically this check was done during resolution, so we
10811      continue that here.  */
10812   value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
10813                                                 EVAL_AVOID_SIDE_EFFECTS);
10814   if (ada_is_any_packed_array_type (value_type (v)))
10815     error (_("cannot slice a packed array"));
10816   return false;
10817 }
10818
10819 }
10820
10821 \f
10822
10823 /* Return non-zero iff TYPE represents a System.Address type.  */
10824
10825 int
10826 ada_is_system_address_type (struct type *type)
10827 {
10828   return (type->name () && strcmp (type->name (), "system__address") == 0);
10829 }
10830
10831 \f
10832
10833                                 /* Range types */
10834
10835 /* Scan STR beginning at position K for a discriminant name, and
10836    return the value of that discriminant field of DVAL in *PX.  If
10837    PNEW_K is not null, put the position of the character beyond the
10838    name scanned in *PNEW_K.  Return 1 if successful; return 0 and do
10839    not alter *PX and *PNEW_K if unsuccessful.  */
10840
10841 static int
10842 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
10843                     int *pnew_k)
10844 {
10845   static std::string storage;
10846   const char *pstart, *pend, *bound;
10847   struct value *bound_val;
10848
10849   if (dval == NULL || str == NULL || str[k] == '\0')
10850     return 0;
10851
10852   pstart = str + k;
10853   pend = strstr (pstart, "__");
10854   if (pend == NULL)
10855     {
10856       bound = pstart;
10857       k += strlen (bound);
10858     }
10859   else
10860     {
10861       int len = pend - pstart;
10862
10863       /* Strip __ and beyond.  */
10864       storage = std::string (pstart, len);
10865       bound = storage.c_str ();
10866       k = pend - str;
10867     }
10868
10869   bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
10870   if (bound_val == NULL)
10871     return 0;
10872
10873   *px = value_as_long (bound_val);
10874   if (pnew_k != NULL)
10875     *pnew_k = k;
10876   return 1;
10877 }
10878
10879 /* Value of variable named NAME.  Only exact matches are considered.
10880    If no such variable found, then if ERR_MSG is null, returns 0, and
10881    otherwise causes an error with message ERR_MSG.  */
10882
10883 static struct value *
10884 get_var_value (const char *name, const char *err_msg)
10885 {
10886   std::string quoted_name = add_angle_brackets (name);
10887
10888   lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
10889
10890   std::vector<struct block_symbol> syms
10891     = ada_lookup_symbol_list_worker (lookup_name,
10892                                      get_selected_block (0),
10893                                      VAR_DOMAIN, 1);
10894
10895   if (syms.size () != 1)
10896     {
10897       if (err_msg == NULL)
10898         return 0;
10899       else
10900         error (("%s"), err_msg);
10901     }
10902
10903   return value_of_variable (syms[0].symbol, syms[0].block);
10904 }
10905
10906 /* Value of integer variable named NAME in the current environment.
10907    If no such variable is found, returns false.  Otherwise, sets VALUE
10908    to the variable's value and returns true.  */
10909
10910 bool
10911 get_int_var_value (const char *name, LONGEST &value)
10912 {
10913   struct value *var_val = get_var_value (name, 0);
10914
10915   if (var_val == 0)
10916     return false;
10917
10918   value = value_as_long (var_val);
10919   return true;
10920 }
10921
10922
10923 /* Return a range type whose base type is that of the range type named
10924    NAME in the current environment, and whose bounds are calculated
10925    from NAME according to the GNAT range encoding conventions.
10926    Extract discriminant values, if needed, from DVAL.  ORIG_TYPE is the
10927    corresponding range type from debug information; fall back to using it
10928    if symbol lookup fails.  If a new type must be created, allocate it
10929    like ORIG_TYPE was.  The bounds information, in general, is encoded
10930    in NAME, the base type given in the named range type.  */
10931
10932 static struct type *
10933 to_fixed_range_type (struct type *raw_type, struct value *dval)
10934 {
10935   const char *name;
10936   struct type *base_type;
10937   const char *subtype_info;
10938
10939   gdb_assert (raw_type != NULL);
10940   gdb_assert (raw_type->name () != NULL);
10941
10942   if (raw_type->code () == TYPE_CODE_RANGE)
10943     base_type = TYPE_TARGET_TYPE (raw_type);
10944   else
10945     base_type = raw_type;
10946
10947   name = raw_type->name ();
10948   subtype_info = strstr (name, "___XD");
10949   if (subtype_info == NULL)
10950     {
10951       LONGEST L = ada_discrete_type_low_bound (raw_type);
10952       LONGEST U = ada_discrete_type_high_bound (raw_type);
10953
10954       if (L < INT_MIN || U > INT_MAX)
10955         return raw_type;
10956       else
10957         return create_static_range_type (alloc_type_copy (raw_type), raw_type,
10958                                          L, U);
10959     }
10960   else
10961     {
10962       int prefix_len = subtype_info - name;
10963       LONGEST L, U;
10964       struct type *type;
10965       const char *bounds_str;
10966       int n;
10967
10968       subtype_info += 5;
10969       bounds_str = strchr (subtype_info, '_');
10970       n = 1;
10971
10972       if (*subtype_info == 'L')
10973         {
10974           if (!ada_scan_number (bounds_str, n, &L, &n)
10975               && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
10976             return raw_type;
10977           if (bounds_str[n] == '_')
10978             n += 2;
10979           else if (bounds_str[n] == '.')     /* FIXME? SGI Workshop kludge.  */
10980             n += 1;
10981           subtype_info += 1;
10982         }
10983       else
10984         {
10985           std::string name_buf = std::string (name, prefix_len) + "___L";
10986           if (!get_int_var_value (name_buf.c_str (), L))
10987             {
10988               lim_warning (_("Unknown lower bound, using 1."));
10989               L = 1;
10990             }
10991         }
10992
10993       if (*subtype_info == 'U')
10994         {
10995           if (!ada_scan_number (bounds_str, n, &U, &n)
10996               && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
10997             return raw_type;
10998         }
10999       else
11000         {
11001           std::string name_buf = std::string (name, prefix_len) + "___U";
11002           if (!get_int_var_value (name_buf.c_str (), U))
11003             {
11004               lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11005               U = L;
11006             }
11007         }
11008
11009       type = create_static_range_type (alloc_type_copy (raw_type),
11010                                        base_type, L, U);
11011       /* create_static_range_type alters the resulting type's length
11012          to match the size of the base_type, which is not what we want.
11013          Set it back to the original range type's length.  */
11014       TYPE_LENGTH (type) = TYPE_LENGTH (raw_type);
11015       type->set_name (name);
11016       return type;
11017     }
11018 }
11019
11020 /* True iff NAME is the name of a range type.  */
11021
11022 int
11023 ada_is_range_type_name (const char *name)
11024 {
11025   return (name != NULL && strstr (name, "___XD"));
11026 }
11027 \f
11028
11029                                 /* Modular types */
11030
11031 /* True iff TYPE is an Ada modular type.  */
11032
11033 int
11034 ada_is_modular_type (struct type *type)
11035 {
11036   struct type *subranged_type = get_base_type (type);
11037
11038   return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11039           && subranged_type->code () == TYPE_CODE_INT
11040           && subranged_type->is_unsigned ());
11041 }
11042
11043 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE.  */
11044
11045 ULONGEST
11046 ada_modulus (struct type *type)
11047 {
11048   const dynamic_prop &high = type->bounds ()->high;
11049
11050   if (high.kind () == PROP_CONST)
11051     return (ULONGEST) high.const_val () + 1;
11052
11053   /* If TYPE is unresolved, the high bound might be a location list.  Return
11054      0, for lack of a better value to return.  */
11055   return 0;
11056 }
11057 \f
11058
11059 /* Ada exception catchpoint support:
11060    ---------------------------------
11061
11062    We support 3 kinds of exception catchpoints:
11063      . catchpoints on Ada exceptions
11064      . catchpoints on unhandled Ada exceptions
11065      . catchpoints on failed assertions
11066
11067    Exceptions raised during failed assertions, or unhandled exceptions
11068    could perfectly be caught with the general catchpoint on Ada exceptions.
11069    However, we can easily differentiate these two special cases, and having
11070    the option to distinguish these two cases from the rest can be useful
11071    to zero-in on certain situations.
11072
11073    Exception catchpoints are a specialized form of breakpoint,
11074    since they rely on inserting breakpoints inside known routines
11075    of the GNAT runtime.  The implementation therefore uses a standard
11076    breakpoint structure of the BP_BREAKPOINT type, but with its own set
11077    of breakpoint_ops.
11078
11079    Support in the runtime for exception catchpoints have been changed
11080    a few times already, and these changes affect the implementation
11081    of these catchpoints.  In order to be able to support several
11082    variants of the runtime, we use a sniffer that will determine
11083    the runtime variant used by the program being debugged.  */
11084
11085 /* Ada's standard exceptions.
11086
11087    The Ada 83 standard also defined Numeric_Error.  But there so many
11088    situations where it was unclear from the Ada 83 Reference Manual
11089    (RM) whether Constraint_Error or Numeric_Error should be raised,
11090    that the ARG (Ada Rapporteur Group) eventually issued a Binding
11091    Interpretation saying that anytime the RM says that Numeric_Error
11092    should be raised, the implementation may raise Constraint_Error.
11093    Ada 95 went one step further and pretty much removed Numeric_Error
11094    from the list of standard exceptions (it made it a renaming of
11095    Constraint_Error, to help preserve compatibility when compiling
11096    an Ada83 compiler). As such, we do not include Numeric_Error from
11097    this list of standard exceptions.  */
11098
11099 static const char * const standard_exc[] = {
11100   "constraint_error",
11101   "program_error",
11102   "storage_error",
11103   "tasking_error"
11104 };
11105
11106 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11107
11108 /* A structure that describes how to support exception catchpoints
11109    for a given executable.  */
11110
11111 struct exception_support_info
11112 {
11113    /* The name of the symbol to break on in order to insert
11114       a catchpoint on exceptions.  */
11115    const char *catch_exception_sym;
11116
11117    /* The name of the symbol to break on in order to insert
11118       a catchpoint on unhandled exceptions.  */
11119    const char *catch_exception_unhandled_sym;
11120
11121    /* The name of the symbol to break on in order to insert
11122       a catchpoint on failed assertions.  */
11123    const char *catch_assert_sym;
11124
11125    /* The name of the symbol to break on in order to insert
11126       a catchpoint on exception handling.  */
11127    const char *catch_handlers_sym;
11128
11129    /* Assuming that the inferior just triggered an unhandled exception
11130       catchpoint, this function is responsible for returning the address
11131       in inferior memory where the name of that exception is stored.
11132       Return zero if the address could not be computed.  */
11133    ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11134 };
11135
11136 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11137 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11138
11139 /* The following exception support info structure describes how to
11140    implement exception catchpoints with the latest version of the
11141    Ada runtime (as of 2019-08-??).  */
11142
11143 static const struct exception_support_info default_exception_support_info =
11144 {
11145   "__gnat_debug_raise_exception", /* catch_exception_sym */
11146   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11147   "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11148   "__gnat_begin_handler_v1", /* catch_handlers_sym */
11149   ada_unhandled_exception_name_addr
11150 };
11151
11152 /* The following exception support info structure describes how to
11153    implement exception catchpoints with an earlier version of the
11154    Ada runtime (as of 2007-03-06) using v0 of the EH ABI.  */
11155
11156 static const struct exception_support_info exception_support_info_v0 =
11157 {
11158   "__gnat_debug_raise_exception", /* catch_exception_sym */
11159   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11160   "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11161   "__gnat_begin_handler", /* catch_handlers_sym */
11162   ada_unhandled_exception_name_addr
11163 };
11164
11165 /* The following exception support info structure describes how to
11166    implement exception catchpoints with a slightly older version
11167    of the Ada runtime.  */
11168
11169 static const struct exception_support_info exception_support_info_fallback =
11170 {
11171   "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11172   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11173   "system__assertions__raise_assert_failure",  /* catch_assert_sym */
11174   "__gnat_begin_handler", /* catch_handlers_sym */
11175   ada_unhandled_exception_name_addr_from_raise
11176 };
11177
11178 /* Return nonzero if we can detect the exception support routines
11179    described in EINFO.
11180
11181    This function errors out if an abnormal situation is detected
11182    (for instance, if we find the exception support routines, but
11183    that support is found to be incomplete).  */
11184
11185 static int
11186 ada_has_this_exception_support (const struct exception_support_info *einfo)
11187 {
11188   struct symbol *sym;
11189
11190   /* The symbol we're looking up is provided by a unit in the GNAT runtime
11191      that should be compiled with debugging information.  As a result, we
11192      expect to find that symbol in the symtabs.  */
11193
11194   sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11195   if (sym == NULL)
11196     {
11197       /* Perhaps we did not find our symbol because the Ada runtime was
11198          compiled without debugging info, or simply stripped of it.
11199          It happens on some GNU/Linux distributions for instance, where
11200          users have to install a separate debug package in order to get
11201          the runtime's debugging info.  In that situation, let the user
11202          know why we cannot insert an Ada exception catchpoint.
11203
11204          Note: Just for the purpose of inserting our Ada exception
11205          catchpoint, we could rely purely on the associated minimal symbol.
11206          But we would be operating in degraded mode anyway, since we are
11207          still lacking the debugging info needed later on to extract
11208          the name of the exception being raised (this name is printed in
11209          the catchpoint message, and is also used when trying to catch
11210          a specific exception).  We do not handle this case for now.  */
11211       struct bound_minimal_symbol msym
11212         = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11213
11214       if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
11215         error (_("Your Ada runtime appears to be missing some debugging "
11216                  "information.\nCannot insert Ada exception catchpoint "
11217                  "in this configuration."));
11218
11219       return 0;
11220     }
11221
11222   /* Make sure that the symbol we found corresponds to a function.  */
11223
11224   if (SYMBOL_CLASS (sym) != LOC_BLOCK)
11225     {
11226       error (_("Symbol \"%s\" is not a function (class = %d)"),
11227              sym->linkage_name (), SYMBOL_CLASS (sym));
11228       return 0;
11229     }
11230
11231   sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11232   if (sym == NULL)
11233     {
11234       struct bound_minimal_symbol msym
11235         = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11236
11237       if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
11238         error (_("Your Ada runtime appears to be missing some debugging "
11239                  "information.\nCannot insert Ada exception catchpoint "
11240                  "in this configuration."));
11241
11242       return 0;
11243     }
11244
11245   /* Make sure that the symbol we found corresponds to a function.  */
11246
11247   if (SYMBOL_CLASS (sym) != LOC_BLOCK)
11248     {
11249       error (_("Symbol \"%s\" is not a function (class = %d)"),
11250              sym->linkage_name (), SYMBOL_CLASS (sym));
11251       return 0;
11252     }
11253
11254   return 1;
11255 }
11256
11257 /* Inspect the Ada runtime and determine which exception info structure
11258    should be used to provide support for exception catchpoints.
11259
11260    This function will always set the per-inferior exception_info,
11261    or raise an error.  */
11262
11263 static void
11264 ada_exception_support_info_sniffer (void)
11265 {
11266   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11267
11268   /* If the exception info is already known, then no need to recompute it.  */
11269   if (data->exception_info != NULL)
11270     return;
11271
11272   /* Check the latest (default) exception support info.  */
11273   if (ada_has_this_exception_support (&default_exception_support_info))
11274     {
11275       data->exception_info = &default_exception_support_info;
11276       return;
11277     }
11278
11279   /* Try the v0 exception suport info.  */
11280   if (ada_has_this_exception_support (&exception_support_info_v0))
11281     {
11282       data->exception_info = &exception_support_info_v0;
11283       return;
11284     }
11285
11286   /* Try our fallback exception suport info.  */
11287   if (ada_has_this_exception_support (&exception_support_info_fallback))
11288     {
11289       data->exception_info = &exception_support_info_fallback;
11290       return;
11291     }
11292
11293   /* Sometimes, it is normal for us to not be able to find the routine
11294      we are looking for.  This happens when the program is linked with
11295      the shared version of the GNAT runtime, and the program has not been
11296      started yet.  Inform the user of these two possible causes if
11297      applicable.  */
11298
11299   if (ada_update_initial_language (language_unknown) != language_ada)
11300     error (_("Unable to insert catchpoint.  Is this an Ada main program?"));
11301
11302   /* If the symbol does not exist, then check that the program is
11303      already started, to make sure that shared libraries have been
11304      loaded.  If it is not started, this may mean that the symbol is
11305      in a shared library.  */
11306
11307   if (inferior_ptid.pid () == 0)
11308     error (_("Unable to insert catchpoint. Try to start the program first."));
11309
11310   /* At this point, we know that we are debugging an Ada program and
11311      that the inferior has been started, but we still are not able to
11312      find the run-time symbols.  That can mean that we are in
11313      configurable run time mode, or that a-except as been optimized
11314      out by the linker...  In any case, at this point it is not worth
11315      supporting this feature.  */
11316
11317   error (_("Cannot insert Ada exception catchpoints in this configuration."));
11318 }
11319
11320 /* True iff FRAME is very likely to be that of a function that is
11321    part of the runtime system.  This is all very heuristic, but is
11322    intended to be used as advice as to what frames are uninteresting
11323    to most users.  */
11324
11325 static int
11326 is_known_support_routine (struct frame_info *frame)
11327 {
11328   enum language func_lang;
11329   int i;
11330   const char *fullname;
11331
11332   /* If this code does not have any debugging information (no symtab),
11333      This cannot be any user code.  */
11334
11335   symtab_and_line sal = find_frame_sal (frame);
11336   if (sal.symtab == NULL)
11337     return 1;
11338
11339   /* If there is a symtab, but the associated source file cannot be
11340      located, then assume this is not user code:  Selecting a frame
11341      for which we cannot display the code would not be very helpful
11342      for the user.  This should also take care of case such as VxWorks
11343      where the kernel has some debugging info provided for a few units.  */
11344
11345   fullname = symtab_to_fullname (sal.symtab);
11346   if (access (fullname, R_OK) != 0)
11347     return 1;
11348
11349   /* Check the unit filename against the Ada runtime file naming.
11350      We also check the name of the objfile against the name of some
11351      known system libraries that sometimes come with debugging info
11352      too.  */
11353
11354   for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11355     {
11356       re_comp (known_runtime_file_name_patterns[i]);
11357       if (re_exec (lbasename (sal.symtab->filename)))
11358         return 1;
11359       if (SYMTAB_OBJFILE (sal.symtab) != NULL
11360           && re_exec (objfile_name (SYMTAB_OBJFILE (sal.symtab))))
11361         return 1;
11362     }
11363
11364   /* Check whether the function is a GNAT-generated entity.  */
11365
11366   gdb::unique_xmalloc_ptr<char> func_name
11367     = find_frame_funname (frame, &func_lang, NULL);
11368   if (func_name == NULL)
11369     return 1;
11370
11371   for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11372     {
11373       re_comp (known_auxiliary_function_name_patterns[i]);
11374       if (re_exec (func_name.get ()))
11375         return 1;
11376     }
11377
11378   return 0;
11379 }
11380
11381 /* Find the first frame that contains debugging information and that is not
11382    part of the Ada run-time, starting from FI and moving upward.  */
11383
11384 void
11385 ada_find_printable_frame (struct frame_info *fi)
11386 {
11387   for (; fi != NULL; fi = get_prev_frame (fi))
11388     {
11389       if (!is_known_support_routine (fi))
11390         {
11391           select_frame (fi);
11392           break;
11393         }
11394     }
11395
11396 }
11397
11398 /* Assuming that the inferior just triggered an unhandled exception
11399    catchpoint, return the address in inferior memory where the name
11400    of the exception is stored.
11401    
11402    Return zero if the address could not be computed.  */
11403
11404 static CORE_ADDR
11405 ada_unhandled_exception_name_addr (void)
11406 {
11407   return parse_and_eval_address ("e.full_name");
11408 }
11409
11410 /* Same as ada_unhandled_exception_name_addr, except that this function
11411    should be used when the inferior uses an older version of the runtime,
11412    where the exception name needs to be extracted from a specific frame
11413    several frames up in the callstack.  */
11414
11415 static CORE_ADDR
11416 ada_unhandled_exception_name_addr_from_raise (void)
11417 {
11418   int frame_level;
11419   struct frame_info *fi;
11420   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11421
11422   /* To determine the name of this exception, we need to select
11423      the frame corresponding to RAISE_SYM_NAME.  This frame is
11424      at least 3 levels up, so we simply skip the first 3 frames
11425      without checking the name of their associated function.  */
11426   fi = get_current_frame ();
11427   for (frame_level = 0; frame_level < 3; frame_level += 1)
11428     if (fi != NULL)
11429       fi = get_prev_frame (fi); 
11430
11431   while (fi != NULL)
11432     {
11433       enum language func_lang;
11434
11435       gdb::unique_xmalloc_ptr<char> func_name
11436         = find_frame_funname (fi, &func_lang, NULL);
11437       if (func_name != NULL)
11438         {
11439           if (strcmp (func_name.get (),
11440                       data->exception_info->catch_exception_sym) == 0)
11441             break; /* We found the frame we were looking for...  */
11442         }
11443       fi = get_prev_frame (fi);
11444     }
11445
11446   if (fi == NULL)
11447     return 0;
11448
11449   select_frame (fi);
11450   return parse_and_eval_address ("id.full_name");
11451 }
11452
11453 /* Assuming the inferior just triggered an Ada exception catchpoint
11454    (of any type), return the address in inferior memory where the name
11455    of the exception is stored, if applicable.
11456
11457    Assumes the selected frame is the current frame.
11458
11459    Return zero if the address could not be computed, or if not relevant.  */
11460
11461 static CORE_ADDR
11462 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
11463                            struct breakpoint *b)
11464 {
11465   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11466
11467   switch (ex)
11468     {
11469       case ada_catch_exception:
11470         return (parse_and_eval_address ("e.full_name"));
11471         break;
11472
11473       case ada_catch_exception_unhandled:
11474         return data->exception_info->unhandled_exception_name_addr ();
11475         break;
11476
11477       case ada_catch_handlers:
11478         return 0;  /* The runtimes does not provide access to the exception
11479                       name.  */
11480         break;
11481
11482       case ada_catch_assert:
11483         return 0;  /* Exception name is not relevant in this case.  */
11484         break;
11485
11486       default:
11487         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11488         break;
11489     }
11490
11491   return 0; /* Should never be reached.  */
11492 }
11493
11494 /* Assuming the inferior is stopped at an exception catchpoint,
11495    return the message which was associated to the exception, if
11496    available.  Return NULL if the message could not be retrieved.
11497
11498    Note: The exception message can be associated to an exception
11499    either through the use of the Raise_Exception function, or
11500    more simply (Ada 2005 and later), via:
11501
11502        raise Exception_Name with "exception message";
11503
11504    */
11505
11506 static gdb::unique_xmalloc_ptr<char>
11507 ada_exception_message_1 (void)
11508 {
11509   struct value *e_msg_val;
11510   int e_msg_len;
11511
11512   /* For runtimes that support this feature, the exception message
11513      is passed as an unbounded string argument called "message".  */
11514   e_msg_val = parse_and_eval ("message");
11515   if (e_msg_val == NULL)
11516     return NULL; /* Exception message not supported.  */
11517
11518   e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11519   gdb_assert (e_msg_val != NULL);
11520   e_msg_len = TYPE_LENGTH (value_type (e_msg_val));
11521
11522   /* If the message string is empty, then treat it as if there was
11523      no exception message.  */
11524   if (e_msg_len <= 0)
11525     return NULL;
11526
11527   gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
11528   read_memory (value_address (e_msg_val), (gdb_byte *) e_msg.get (),
11529                e_msg_len);
11530   e_msg.get ()[e_msg_len] = '\0';
11531
11532   return e_msg;
11533 }
11534
11535 /* Same as ada_exception_message_1, except that all exceptions are
11536    contained here (returning NULL instead).  */
11537
11538 static gdb::unique_xmalloc_ptr<char>
11539 ada_exception_message (void)
11540 {
11541   gdb::unique_xmalloc_ptr<char> e_msg;
11542
11543   try
11544     {
11545       e_msg = ada_exception_message_1 ();
11546     }
11547   catch (const gdb_exception_error &e)
11548     {
11549       e_msg.reset (nullptr);
11550     }
11551
11552   return e_msg;
11553 }
11554
11555 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
11556    any error that ada_exception_name_addr_1 might cause to be thrown.
11557    When an error is intercepted, a warning with the error message is printed,
11558    and zero is returned.  */
11559
11560 static CORE_ADDR
11561 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
11562                          struct breakpoint *b)
11563 {
11564   CORE_ADDR result = 0;
11565
11566   try
11567     {
11568       result = ada_exception_name_addr_1 (ex, b);
11569     }
11570
11571   catch (const gdb_exception_error &e)
11572     {
11573       warning (_("failed to get exception name: %s"), e.what ());
11574       return 0;
11575     }
11576
11577   return result;
11578 }
11579
11580 static std::string ada_exception_catchpoint_cond_string
11581   (const char *excep_string,
11582    enum ada_exception_catchpoint_kind ex);
11583
11584 /* Ada catchpoints.
11585
11586    In the case of catchpoints on Ada exceptions, the catchpoint will
11587    stop the target on every exception the program throws.  When a user
11588    specifies the name of a specific exception, we translate this
11589    request into a condition expression (in text form), and then parse
11590    it into an expression stored in each of the catchpoint's locations.
11591    We then use this condition to check whether the exception that was
11592    raised is the one the user is interested in.  If not, then the
11593    target is resumed again.  We store the name of the requested
11594    exception, in order to be able to re-set the condition expression
11595    when symbols change.  */
11596
11597 /* An instance of this type is used to represent an Ada catchpoint
11598    breakpoint location.  */
11599
11600 class ada_catchpoint_location : public bp_location
11601 {
11602 public:
11603   ada_catchpoint_location (breakpoint *owner)
11604     : bp_location (owner, bp_loc_software_breakpoint)
11605   {}
11606
11607   /* The condition that checks whether the exception that was raised
11608      is the specific exception the user specified on catchpoint
11609      creation.  */
11610   expression_up excep_cond_expr;
11611 };
11612
11613 /* An instance of this type is used to represent an Ada catchpoint.  */
11614
11615 struct ada_catchpoint : public breakpoint
11616 {
11617   explicit ada_catchpoint (enum ada_exception_catchpoint_kind kind)
11618     : m_kind (kind)
11619   {
11620   }
11621
11622   /* The name of the specific exception the user specified.  */
11623   std::string excep_string;
11624
11625   /* What kind of catchpoint this is.  */
11626   enum ada_exception_catchpoint_kind m_kind;
11627 };
11628
11629 /* Parse the exception condition string in the context of each of the
11630    catchpoint's locations, and store them for later evaluation.  */
11631
11632 static void
11633 create_excep_cond_exprs (struct ada_catchpoint *c,
11634                          enum ada_exception_catchpoint_kind ex)
11635 {
11636   /* Nothing to do if there's no specific exception to catch.  */
11637   if (c->excep_string.empty ())
11638     return;
11639
11640   /* Same if there are no locations... */
11641   if (c->loc == NULL)
11642     return;
11643
11644   /* Compute the condition expression in text form, from the specific
11645      expection we want to catch.  */
11646   std::string cond_string
11647     = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
11648
11649   /* Iterate over all the catchpoint's locations, and parse an
11650      expression for each.  */
11651   for (bp_location *bl : c->locations ())
11652     {
11653       struct ada_catchpoint_location *ada_loc
11654         = (struct ada_catchpoint_location *) bl;
11655       expression_up exp;
11656
11657       if (!bl->shlib_disabled)
11658         {
11659           const char *s;
11660
11661           s = cond_string.c_str ();
11662           try
11663             {
11664               exp = parse_exp_1 (&s, bl->address,
11665                                  block_for_pc (bl->address),
11666                                  0);
11667             }
11668           catch (const gdb_exception_error &e)
11669             {
11670               warning (_("failed to reevaluate internal exception condition "
11671                          "for catchpoint %d: %s"),
11672                        c->number, e.what ());
11673             }
11674         }
11675
11676       ada_loc->excep_cond_expr = std::move (exp);
11677     }
11678 }
11679
11680 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
11681    structure for all exception catchpoint kinds.  */
11682
11683 static struct bp_location *
11684 allocate_location_exception (struct breakpoint *self)
11685 {
11686   return new ada_catchpoint_location (self);
11687 }
11688
11689 /* Implement the RE_SET method in the breakpoint_ops structure for all
11690    exception catchpoint kinds.  */
11691
11692 static void
11693 re_set_exception (struct breakpoint *b)
11694 {
11695   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11696
11697   /* Call the base class's method.  This updates the catchpoint's
11698      locations.  */
11699   bkpt_breakpoint_ops.re_set (b);
11700
11701   /* Reparse the exception conditional expressions.  One for each
11702      location.  */
11703   create_excep_cond_exprs (c, c->m_kind);
11704 }
11705
11706 /* Returns true if we should stop for this breakpoint hit.  If the
11707    user specified a specific exception, we only want to cause a stop
11708    if the program thrown that exception.  */
11709
11710 static int
11711 should_stop_exception (const struct bp_location *bl)
11712 {
11713   struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
11714   const struct ada_catchpoint_location *ada_loc
11715     = (const struct ada_catchpoint_location *) bl;
11716   int stop;
11717
11718   struct internalvar *var = lookup_internalvar ("_ada_exception");
11719   if (c->m_kind == ada_catch_assert)
11720     clear_internalvar (var);
11721   else
11722     {
11723       try
11724         {
11725           const char *expr;
11726
11727           if (c->m_kind == ada_catch_handlers)
11728             expr = ("GNAT_GCC_exception_Access(gcc_exception)"
11729                     ".all.occurrence.id");
11730           else
11731             expr = "e";
11732
11733           struct value *exc = parse_and_eval (expr);
11734           set_internalvar (var, exc);
11735         }
11736       catch (const gdb_exception_error &ex)
11737         {
11738           clear_internalvar (var);
11739         }
11740     }
11741
11742   /* With no specific exception, should always stop.  */
11743   if (c->excep_string.empty ())
11744     return 1;
11745
11746   if (ada_loc->excep_cond_expr == NULL)
11747     {
11748       /* We will have a NULL expression if back when we were creating
11749          the expressions, this location's had failed to parse.  */
11750       return 1;
11751     }
11752
11753   stop = 1;
11754   try
11755     {
11756       struct value *mark;
11757
11758       mark = value_mark ();
11759       stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
11760       value_free_to_mark (mark);
11761     }
11762   catch (const gdb_exception &ex)
11763     {
11764       exception_fprintf (gdb_stderr, ex,
11765                          _("Error in testing exception condition:\n"));
11766     }
11767
11768   return stop;
11769 }
11770
11771 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
11772    for all exception catchpoint kinds.  */
11773
11774 static void
11775 check_status_exception (bpstat bs)
11776 {
11777   bs->stop = should_stop_exception (bs->bp_location_at.get ());
11778 }
11779
11780 /* Implement the PRINT_IT method in the breakpoint_ops structure
11781    for all exception catchpoint kinds.  */
11782
11783 static enum print_stop_action
11784 print_it_exception (bpstat bs)
11785 {
11786   struct ui_out *uiout = current_uiout;
11787   struct breakpoint *b = bs->breakpoint_at;
11788
11789   annotate_catchpoint (b->number);
11790
11791   if (uiout->is_mi_like_p ())
11792     {
11793       uiout->field_string ("reason",
11794                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11795       uiout->field_string ("disp", bpdisp_text (b->disposition));
11796     }
11797
11798   uiout->text (b->disposition == disp_del
11799                ? "\nTemporary catchpoint " : "\nCatchpoint ");
11800   uiout->field_signed ("bkptno", b->number);
11801   uiout->text (", ");
11802
11803   /* ada_exception_name_addr relies on the selected frame being the
11804      current frame.  Need to do this here because this function may be
11805      called more than once when printing a stop, and below, we'll
11806      select the first frame past the Ada run-time (see
11807      ada_find_printable_frame).  */
11808   select_frame (get_current_frame ());
11809
11810   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11811   switch (c->m_kind)
11812     {
11813       case ada_catch_exception:
11814       case ada_catch_exception_unhandled:
11815       case ada_catch_handlers:
11816         {
11817           const CORE_ADDR addr = ada_exception_name_addr (c->m_kind, b);
11818           char exception_name[256];
11819
11820           if (addr != 0)
11821             {
11822               read_memory (addr, (gdb_byte *) exception_name,
11823                            sizeof (exception_name) - 1);
11824               exception_name [sizeof (exception_name) - 1] = '\0';
11825             }
11826           else
11827             {
11828               /* For some reason, we were unable to read the exception
11829                  name.  This could happen if the Runtime was compiled
11830                  without debugging info, for instance.  In that case,
11831                  just replace the exception name by the generic string
11832                  "exception" - it will read as "an exception" in the
11833                  notification we are about to print.  */
11834               memcpy (exception_name, "exception", sizeof ("exception"));
11835             }
11836           /* In the case of unhandled exception breakpoints, we print
11837              the exception name as "unhandled EXCEPTION_NAME", to make
11838              it clearer to the user which kind of catchpoint just got
11839              hit.  We used ui_out_text to make sure that this extra
11840              info does not pollute the exception name in the MI case.  */
11841           if (c->m_kind == ada_catch_exception_unhandled)
11842             uiout->text ("unhandled ");
11843           uiout->field_string ("exception-name", exception_name);
11844         }
11845         break;
11846       case ada_catch_assert:
11847         /* In this case, the name of the exception is not really
11848            important.  Just print "failed assertion" to make it clearer
11849            that his program just hit an assertion-failure catchpoint.
11850            We used ui_out_text because this info does not belong in
11851            the MI output.  */
11852         uiout->text ("failed assertion");
11853         break;
11854     }
11855
11856   gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
11857   if (exception_message != NULL)
11858     {
11859       uiout->text (" (");
11860       uiout->field_string ("exception-message", exception_message.get ());
11861       uiout->text (")");
11862     }
11863
11864   uiout->text (" at ");
11865   ada_find_printable_frame (get_current_frame ());
11866
11867   return PRINT_SRC_AND_LOC;
11868 }
11869
11870 /* Implement the PRINT_ONE method in the breakpoint_ops structure
11871    for all exception catchpoint kinds.  */
11872
11873 static void
11874 print_one_exception (struct breakpoint *b, struct bp_location **last_loc)
11875
11876   struct ui_out *uiout = current_uiout;
11877   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11878   struct value_print_options opts;
11879
11880   get_user_print_options (&opts);
11881
11882   if (opts.addressprint)
11883     uiout->field_skip ("addr");
11884
11885   annotate_field (5);
11886   switch (c->m_kind)
11887     {
11888       case ada_catch_exception:
11889         if (!c->excep_string.empty ())
11890           {
11891             std::string msg = string_printf (_("`%s' Ada exception"),
11892                                              c->excep_string.c_str ());
11893
11894             uiout->field_string ("what", msg);
11895           }
11896         else
11897           uiout->field_string ("what", "all Ada exceptions");
11898         
11899         break;
11900
11901       case ada_catch_exception_unhandled:
11902         uiout->field_string ("what", "unhandled Ada exceptions");
11903         break;
11904       
11905       case ada_catch_handlers:
11906         if (!c->excep_string.empty ())
11907           {
11908             uiout->field_fmt ("what",
11909                               _("`%s' Ada exception handlers"),
11910                               c->excep_string.c_str ());
11911           }
11912         else
11913           uiout->field_string ("what", "all Ada exceptions handlers");
11914         break;
11915
11916       case ada_catch_assert:
11917         uiout->field_string ("what", "failed Ada assertions");
11918         break;
11919
11920       default:
11921         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11922         break;
11923     }
11924 }
11925
11926 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
11927    for all exception catchpoint kinds.  */
11928
11929 static void
11930 print_mention_exception (struct breakpoint *b)
11931 {
11932   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11933   struct ui_out *uiout = current_uiout;
11934
11935   uiout->text (b->disposition == disp_del ? _("Temporary catchpoint ")
11936                                                  : _("Catchpoint "));
11937   uiout->field_signed ("bkptno", b->number);
11938   uiout->text (": ");
11939
11940   switch (c->m_kind)
11941     {
11942       case ada_catch_exception:
11943         if (!c->excep_string.empty ())
11944           {
11945             std::string info = string_printf (_("`%s' Ada exception"),
11946                                               c->excep_string.c_str ());
11947             uiout->text (info);
11948           }
11949         else
11950           uiout->text (_("all Ada exceptions"));
11951         break;
11952
11953       case ada_catch_exception_unhandled:
11954         uiout->text (_("unhandled Ada exceptions"));
11955         break;
11956
11957       case ada_catch_handlers:
11958         if (!c->excep_string.empty ())
11959           {
11960             std::string info
11961               = string_printf (_("`%s' Ada exception handlers"),
11962                                c->excep_string.c_str ());
11963             uiout->text (info);
11964           }
11965         else
11966           uiout->text (_("all Ada exceptions handlers"));
11967         break;
11968
11969       case ada_catch_assert:
11970         uiout->text (_("failed Ada assertions"));
11971         break;
11972
11973       default:
11974         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11975         break;
11976     }
11977 }
11978
11979 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
11980    for all exception catchpoint kinds.  */
11981
11982 static void
11983 print_recreate_exception (struct breakpoint *b, struct ui_file *fp)
11984 {
11985   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11986
11987   switch (c->m_kind)
11988     {
11989       case ada_catch_exception:
11990         fprintf_filtered (fp, "catch exception");
11991         if (!c->excep_string.empty ())
11992           fprintf_filtered (fp, " %s", c->excep_string.c_str ());
11993         break;
11994
11995       case ada_catch_exception_unhandled:
11996         fprintf_filtered (fp, "catch exception unhandled");
11997         break;
11998
11999       case ada_catch_handlers:
12000         fprintf_filtered (fp, "catch handlers");
12001         break;
12002
12003       case ada_catch_assert:
12004         fprintf_filtered (fp, "catch assert");
12005         break;
12006
12007       default:
12008         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12009     }
12010   print_recreate_thread (b, fp);
12011 }
12012
12013 /* Virtual tables for various breakpoint types.  */
12014 static struct breakpoint_ops catch_exception_breakpoint_ops;
12015 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;
12016 static struct breakpoint_ops catch_assert_breakpoint_ops;
12017 static struct breakpoint_ops catch_handlers_breakpoint_ops;
12018
12019 /* See ada-lang.h.  */
12020
12021 bool
12022 is_ada_exception_catchpoint (breakpoint *bp)
12023 {
12024   return (bp->ops == &catch_exception_breakpoint_ops
12025           || bp->ops == &catch_exception_unhandled_breakpoint_ops
12026           || bp->ops == &catch_assert_breakpoint_ops
12027           || bp->ops == &catch_handlers_breakpoint_ops);
12028 }
12029
12030 /* Split the arguments specified in a "catch exception" command.  
12031    Set EX to the appropriate catchpoint type.
12032    Set EXCEP_STRING to the name of the specific exception if
12033    specified by the user.
12034    IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12035    "catch handlers" command.  False otherwise.
12036    If a condition is found at the end of the arguments, the condition
12037    expression is stored in COND_STRING (memory must be deallocated
12038    after use).  Otherwise COND_STRING is set to NULL.  */
12039
12040 static void
12041 catch_ada_exception_command_split (const char *args,
12042                                    bool is_catch_handlers_cmd,
12043                                    enum ada_exception_catchpoint_kind *ex,
12044                                    std::string *excep_string,
12045                                    std::string *cond_string)
12046 {
12047   std::string exception_name;
12048
12049   exception_name = extract_arg (&args);
12050   if (exception_name == "if")
12051     {
12052       /* This is not an exception name; this is the start of a condition
12053          expression for a catchpoint on all exceptions.  So, "un-get"
12054          this token, and set exception_name to NULL.  */
12055       exception_name.clear ();
12056       args -= 2;
12057     }
12058
12059   /* Check to see if we have a condition.  */
12060
12061   args = skip_spaces (args);
12062   if (startswith (args, "if")
12063       && (isspace (args[2]) || args[2] == '\0'))
12064     {
12065       args += 2;
12066       args = skip_spaces (args);
12067
12068       if (args[0] == '\0')
12069         error (_("Condition missing after `if' keyword"));
12070       *cond_string = args;
12071
12072       args += strlen (args);
12073     }
12074
12075   /* Check that we do not have any more arguments.  Anything else
12076      is unexpected.  */
12077
12078   if (args[0] != '\0')
12079     error (_("Junk at end of expression"));
12080
12081   if (is_catch_handlers_cmd)
12082     {
12083       /* Catch handling of exceptions.  */
12084       *ex = ada_catch_handlers;
12085       *excep_string = exception_name;
12086     }
12087   else if (exception_name.empty ())
12088     {
12089       /* Catch all exceptions.  */
12090       *ex = ada_catch_exception;
12091       excep_string->clear ();
12092     }
12093   else if (exception_name == "unhandled")
12094     {
12095       /* Catch unhandled exceptions.  */
12096       *ex = ada_catch_exception_unhandled;
12097       excep_string->clear ();
12098     }
12099   else
12100     {
12101       /* Catch a specific exception.  */
12102       *ex = ada_catch_exception;
12103       *excep_string = exception_name;
12104     }
12105 }
12106
12107 /* Return the name of the symbol on which we should break in order to
12108    implement a catchpoint of the EX kind.  */
12109
12110 static const char *
12111 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12112 {
12113   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12114
12115   gdb_assert (data->exception_info != NULL);
12116
12117   switch (ex)
12118     {
12119       case ada_catch_exception:
12120         return (data->exception_info->catch_exception_sym);
12121         break;
12122       case ada_catch_exception_unhandled:
12123         return (data->exception_info->catch_exception_unhandled_sym);
12124         break;
12125       case ada_catch_assert:
12126         return (data->exception_info->catch_assert_sym);
12127         break;
12128       case ada_catch_handlers:
12129         return (data->exception_info->catch_handlers_sym);
12130         break;
12131       default:
12132         internal_error (__FILE__, __LINE__,
12133                         _("unexpected catchpoint kind (%d)"), ex);
12134     }
12135 }
12136
12137 /* Return the breakpoint ops "virtual table" used for catchpoints
12138    of the EX kind.  */
12139
12140 static const struct breakpoint_ops *
12141 ada_exception_breakpoint_ops (enum ada_exception_catchpoint_kind ex)
12142 {
12143   switch (ex)
12144     {
12145       case ada_catch_exception:
12146         return (&catch_exception_breakpoint_ops);
12147         break;
12148       case ada_catch_exception_unhandled:
12149         return (&catch_exception_unhandled_breakpoint_ops);
12150         break;
12151       case ada_catch_assert:
12152         return (&catch_assert_breakpoint_ops);
12153         break;
12154       case ada_catch_handlers:
12155         return (&catch_handlers_breakpoint_ops);
12156         break;
12157       default:
12158         internal_error (__FILE__, __LINE__,
12159                         _("unexpected catchpoint kind (%d)"), ex);
12160     }
12161 }
12162
12163 /* Return the condition that will be used to match the current exception
12164    being raised with the exception that the user wants to catch.  This
12165    assumes that this condition is used when the inferior just triggered
12166    an exception catchpoint.
12167    EX: the type of catchpoints used for catching Ada exceptions.  */
12168
12169 static std::string
12170 ada_exception_catchpoint_cond_string (const char *excep_string,
12171                                       enum ada_exception_catchpoint_kind ex)
12172 {
12173   int i;
12174   bool is_standard_exc = false;
12175   std::string result;
12176
12177   if (ex == ada_catch_handlers)
12178     {
12179       /* For exception handlers catchpoints, the condition string does
12180          not use the same parameter as for the other exceptions.  */
12181       result = ("long_integer (GNAT_GCC_exception_Access"
12182                 "(gcc_exception).all.occurrence.id)");
12183     }
12184   else
12185     result = "long_integer (e)";
12186
12187   /* The standard exceptions are a special case.  They are defined in
12188      runtime units that have been compiled without debugging info; if
12189      EXCEP_STRING is the not-fully-qualified name of a standard
12190      exception (e.g. "constraint_error") then, during the evaluation
12191      of the condition expression, the symbol lookup on this name would
12192      *not* return this standard exception.  The catchpoint condition
12193      may then be set only on user-defined exceptions which have the
12194      same not-fully-qualified name (e.g. my_package.constraint_error).
12195
12196      To avoid this unexcepted behavior, these standard exceptions are
12197      systematically prefixed by "standard".  This means that "catch
12198      exception constraint_error" is rewritten into "catch exception
12199      standard.constraint_error".
12200
12201      If an exception named constraint_error is defined in another package of
12202      the inferior program, then the only way to specify this exception as a
12203      breakpoint condition is to use its fully-qualified named:
12204      e.g. my_package.constraint_error.  */
12205
12206   for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
12207     {
12208       if (strcmp (standard_exc [i], excep_string) == 0)
12209         {
12210           is_standard_exc = true;
12211           break;
12212         }
12213     }
12214
12215   result += " = ";
12216
12217   if (is_standard_exc)
12218     string_appendf (result, "long_integer (&standard.%s)", excep_string);
12219   else
12220     string_appendf (result, "long_integer (&%s)", excep_string);
12221
12222   return result;
12223 }
12224
12225 /* Return the symtab_and_line that should be used to insert an exception
12226    catchpoint of the TYPE kind.
12227
12228    ADDR_STRING returns the name of the function where the real
12229    breakpoint that implements the catchpoints is set, depending on the
12230    type of catchpoint we need to create.  */
12231
12232 static struct symtab_and_line
12233 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
12234                    std::string *addr_string, const struct breakpoint_ops **ops)
12235 {
12236   const char *sym_name;
12237   struct symbol *sym;
12238
12239   /* First, find out which exception support info to use.  */
12240   ada_exception_support_info_sniffer ();
12241
12242   /* Then lookup the function on which we will break in order to catch
12243      the Ada exceptions requested by the user.  */
12244   sym_name = ada_exception_sym_name (ex);
12245   sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12246
12247   if (sym == NULL)
12248     error (_("Catchpoint symbol not found: %s"), sym_name);
12249
12250   if (SYMBOL_CLASS (sym) != LOC_BLOCK)
12251     error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12252
12253   /* Set ADDR_STRING.  */
12254   *addr_string = sym_name;
12255
12256   /* Set OPS.  */
12257   *ops = ada_exception_breakpoint_ops (ex);
12258
12259   return find_function_start_sal (sym, 1);
12260 }
12261
12262 /* Create an Ada exception catchpoint.
12263
12264    EX_KIND is the kind of exception catchpoint to be created.
12265
12266    If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12267    for all exceptions.  Otherwise, EXCEPT_STRING indicates the name
12268    of the exception to which this catchpoint applies.
12269
12270    COND_STRING, if not empty, is the catchpoint condition.
12271
12272    TEMPFLAG, if nonzero, means that the underlying breakpoint
12273    should be temporary.
12274
12275    FROM_TTY is the usual argument passed to all commands implementations.  */
12276
12277 void
12278 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12279                                  enum ada_exception_catchpoint_kind ex_kind,
12280                                  const std::string &excep_string,
12281                                  const std::string &cond_string,
12282                                  int tempflag,
12283                                  int disabled,
12284                                  int from_tty)
12285 {
12286   std::string addr_string;
12287   const struct breakpoint_ops *ops = NULL;
12288   struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string, &ops);
12289
12290   std::unique_ptr<ada_catchpoint> c (new ada_catchpoint (ex_kind));
12291   init_ada_exception_breakpoint (c.get (), gdbarch, sal, addr_string.c_str (),
12292                                  ops, tempflag, disabled, from_tty);
12293   c->excep_string = excep_string;
12294   create_excep_cond_exprs (c.get (), ex_kind);
12295   if (!cond_string.empty ())
12296     set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
12297   install_breakpoint (0, std::move (c), 1);
12298 }
12299
12300 /* Implement the "catch exception" command.  */
12301
12302 static void
12303 catch_ada_exception_command (const char *arg_entry, int from_tty,
12304                              struct cmd_list_element *command)
12305 {
12306   const char *arg = arg_entry;
12307   struct gdbarch *gdbarch = get_current_arch ();
12308   int tempflag;
12309   enum ada_exception_catchpoint_kind ex_kind;
12310   std::string excep_string;
12311   std::string cond_string;
12312
12313   tempflag = command->context () == CATCH_TEMPORARY;
12314
12315   if (!arg)
12316     arg = "";
12317   catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12318                                      &cond_string);
12319   create_ada_exception_catchpoint (gdbarch, ex_kind,
12320                                    excep_string, cond_string,
12321                                    tempflag, 1 /* enabled */,
12322                                    from_tty);
12323 }
12324
12325 /* Implement the "catch handlers" command.  */
12326
12327 static void
12328 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12329                             struct cmd_list_element *command)
12330 {
12331   const char *arg = arg_entry;
12332   struct gdbarch *gdbarch = get_current_arch ();
12333   int tempflag;
12334   enum ada_exception_catchpoint_kind ex_kind;
12335   std::string excep_string;
12336   std::string cond_string;
12337
12338   tempflag = command->context () == CATCH_TEMPORARY;
12339
12340   if (!arg)
12341     arg = "";
12342   catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12343                                      &cond_string);
12344   create_ada_exception_catchpoint (gdbarch, ex_kind,
12345                                    excep_string, cond_string,
12346                                    tempflag, 1 /* enabled */,
12347                                    from_tty);
12348 }
12349
12350 /* Completion function for the Ada "catch" commands.  */
12351
12352 static void
12353 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12354                      const char *text, const char *word)
12355 {
12356   std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12357
12358   for (const ada_exc_info &info : exceptions)
12359     {
12360       if (startswith (info.name, word))
12361         tracker.add_completion (make_unique_xstrdup (info.name));
12362     }
12363 }
12364
12365 /* Split the arguments specified in a "catch assert" command.
12366
12367    ARGS contains the command's arguments (or the empty string if
12368    no arguments were passed).
12369
12370    If ARGS contains a condition, set COND_STRING to that condition
12371    (the memory needs to be deallocated after use).  */
12372
12373 static void
12374 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12375 {
12376   args = skip_spaces (args);
12377
12378   /* Check whether a condition was provided.  */
12379   if (startswith (args, "if")
12380       && (isspace (args[2]) || args[2] == '\0'))
12381     {
12382       args += 2;
12383       args = skip_spaces (args);
12384       if (args[0] == '\0')
12385         error (_("condition missing after `if' keyword"));
12386       cond_string.assign (args);
12387     }
12388
12389   /* Otherwise, there should be no other argument at the end of
12390      the command.  */
12391   else if (args[0] != '\0')
12392     error (_("Junk at end of arguments."));
12393 }
12394
12395 /* Implement the "catch assert" command.  */
12396
12397 static void
12398 catch_assert_command (const char *arg_entry, int from_tty,
12399                       struct cmd_list_element *command)
12400 {
12401   const char *arg = arg_entry;
12402   struct gdbarch *gdbarch = get_current_arch ();
12403   int tempflag;
12404   std::string cond_string;
12405
12406   tempflag = command->context () == CATCH_TEMPORARY;
12407
12408   if (!arg)
12409     arg = "";
12410   catch_ada_assert_command_split (arg, cond_string);
12411   create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12412                                    "", cond_string,
12413                                    tempflag, 1 /* enabled */,
12414                                    from_tty);
12415 }
12416
12417 /* Return non-zero if the symbol SYM is an Ada exception object.  */
12418
12419 static int
12420 ada_is_exception_sym (struct symbol *sym)
12421 {
12422   const char *type_name = SYMBOL_TYPE (sym)->name ();
12423
12424   return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
12425           && SYMBOL_CLASS (sym) != LOC_BLOCK
12426           && SYMBOL_CLASS (sym) != LOC_CONST
12427           && SYMBOL_CLASS (sym) != LOC_UNRESOLVED
12428           && type_name != NULL && strcmp (type_name, "exception") == 0);
12429 }
12430
12431 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12432    Ada exception object.  This matches all exceptions except the ones
12433    defined by the Ada language.  */
12434
12435 static int
12436 ada_is_non_standard_exception_sym (struct symbol *sym)
12437 {
12438   int i;
12439
12440   if (!ada_is_exception_sym (sym))
12441     return 0;
12442
12443   for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
12444     if (strcmp (sym->linkage_name (), standard_exc[i]) == 0)
12445       return 0;  /* A standard exception.  */
12446
12447   /* Numeric_Error is also a standard exception, so exclude it.
12448      See the STANDARD_EXC description for more details as to why
12449      this exception is not listed in that array.  */
12450   if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12451     return 0;
12452
12453   return 1;
12454 }
12455
12456 /* A helper function for std::sort, comparing two struct ada_exc_info
12457    objects.
12458
12459    The comparison is determined first by exception name, and then
12460    by exception address.  */
12461
12462 bool
12463 ada_exc_info::operator< (const ada_exc_info &other) const
12464 {
12465   int result;
12466
12467   result = strcmp (name, other.name);
12468   if (result < 0)
12469     return true;
12470   if (result == 0 && addr < other.addr)
12471     return true;
12472   return false;
12473 }
12474
12475 bool
12476 ada_exc_info::operator== (const ada_exc_info &other) const
12477 {
12478   return addr == other.addr && strcmp (name, other.name) == 0;
12479 }
12480
12481 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12482    routine, but keeping the first SKIP elements untouched.
12483
12484    All duplicates are also removed.  */
12485
12486 static void
12487 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
12488                                       int skip)
12489 {
12490   std::sort (exceptions->begin () + skip, exceptions->end ());
12491   exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12492                      exceptions->end ());
12493 }
12494
12495 /* Add all exceptions defined by the Ada standard whose name match
12496    a regular expression.
12497
12498    If PREG is not NULL, then this regexp_t object is used to
12499    perform the symbol name matching.  Otherwise, no name-based
12500    filtering is performed.
12501
12502    EXCEPTIONS is a vector of exceptions to which matching exceptions
12503    gets pushed.  */
12504
12505 static void
12506 ada_add_standard_exceptions (compiled_regex *preg,
12507                              std::vector<ada_exc_info> *exceptions)
12508 {
12509   int i;
12510
12511   for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
12512     {
12513       if (preg == NULL
12514           || preg->exec (standard_exc[i], 0, NULL, 0) == 0)
12515         {
12516           struct bound_minimal_symbol msymbol
12517             = ada_lookup_simple_minsym (standard_exc[i]);
12518
12519           if (msymbol.minsym != NULL)
12520             {
12521               struct ada_exc_info info
12522                 = {standard_exc[i], BMSYMBOL_VALUE_ADDRESS (msymbol)};
12523
12524               exceptions->push_back (info);
12525             }
12526         }
12527     }
12528 }
12529
12530 /* Add all Ada exceptions defined locally and accessible from the given
12531    FRAME.
12532
12533    If PREG is not NULL, then this regexp_t object is used to
12534    perform the symbol name matching.  Otherwise, no name-based
12535    filtering is performed.
12536
12537    EXCEPTIONS is a vector of exceptions to which matching exceptions
12538    gets pushed.  */
12539
12540 static void
12541 ada_add_exceptions_from_frame (compiled_regex *preg,
12542                                struct frame_info *frame,
12543                                std::vector<ada_exc_info> *exceptions)
12544 {
12545   const struct block *block = get_frame_block (frame, 0);
12546
12547   while (block != 0)
12548     {
12549       struct block_iterator iter;
12550       struct symbol *sym;
12551
12552       ALL_BLOCK_SYMBOLS (block, iter, sym)
12553         {
12554           switch (SYMBOL_CLASS (sym))
12555             {
12556             case LOC_TYPEDEF:
12557             case LOC_BLOCK:
12558             case LOC_CONST:
12559               break;
12560             default:
12561               if (ada_is_exception_sym (sym))
12562                 {
12563                   struct ada_exc_info info = {sym->print_name (),
12564                                               SYMBOL_VALUE_ADDRESS (sym)};
12565
12566                   exceptions->push_back (info);
12567                 }
12568             }
12569         }
12570       if (BLOCK_FUNCTION (block) != NULL)
12571         break;
12572       block = BLOCK_SUPERBLOCK (block);
12573     }
12574 }
12575
12576 /* Return true if NAME matches PREG or if PREG is NULL.  */
12577
12578 static bool
12579 name_matches_regex (const char *name, compiled_regex *preg)
12580 {
12581   return (preg == NULL
12582           || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
12583 }
12584
12585 /* Add all exceptions defined globally whose name name match
12586    a regular expression, excluding standard exceptions.
12587
12588    The reason we exclude standard exceptions is that they need
12589    to be handled separately: Standard exceptions are defined inside
12590    a runtime unit which is normally not compiled with debugging info,
12591    and thus usually do not show up in our symbol search.  However,
12592    if the unit was in fact built with debugging info, we need to
12593    exclude them because they would duplicate the entry we found
12594    during the special loop that specifically searches for those
12595    standard exceptions.
12596
12597    If PREG is not NULL, then this regexp_t object is used to
12598    perform the symbol name matching.  Otherwise, no name-based
12599    filtering is performed.
12600
12601    EXCEPTIONS is a vector of exceptions to which matching exceptions
12602    gets pushed.  */
12603
12604 static void
12605 ada_add_global_exceptions (compiled_regex *preg,
12606                            std::vector<ada_exc_info> *exceptions)
12607 {
12608   /* In Ada, the symbol "search name" is a linkage name, whereas the
12609      regular expression used to do the matching refers to the natural
12610      name.  So match against the decoded name.  */
12611   expand_symtabs_matching (NULL,
12612                            lookup_name_info::match_any (),
12613                            [&] (const char *search_name)
12614                            {
12615                              std::string decoded = ada_decode (search_name);
12616                              return name_matches_regex (decoded.c_str (), preg);
12617                            },
12618                            NULL,
12619                            SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
12620                            VARIABLES_DOMAIN);
12621
12622   for (objfile *objfile : current_program_space->objfiles ())
12623     {
12624       for (compunit_symtab *s : objfile->compunits ())
12625         {
12626           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (s);
12627           int i;
12628
12629           for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
12630             {
12631               const struct block *b = BLOCKVECTOR_BLOCK (bv, i);
12632               struct block_iterator iter;
12633               struct symbol *sym;
12634
12635               ALL_BLOCK_SYMBOLS (b, iter, sym)
12636                 if (ada_is_non_standard_exception_sym (sym)
12637                     && name_matches_regex (sym->natural_name (), preg))
12638                   {
12639                     struct ada_exc_info info
12640                       = {sym->print_name (), SYMBOL_VALUE_ADDRESS (sym)};
12641
12642                     exceptions->push_back (info);
12643                   }
12644             }
12645         }
12646     }
12647 }
12648
12649 /* Implements ada_exceptions_list with the regular expression passed
12650    as a regex_t, rather than a string.
12651
12652    If not NULL, PREG is used to filter out exceptions whose names
12653    do not match.  Otherwise, all exceptions are listed.  */
12654
12655 static std::vector<ada_exc_info>
12656 ada_exceptions_list_1 (compiled_regex *preg)
12657 {
12658   std::vector<ada_exc_info> result;
12659   int prev_len;
12660
12661   /* First, list the known standard exceptions.  These exceptions
12662      need to be handled separately, as they are usually defined in
12663      runtime units that have been compiled without debugging info.  */
12664
12665   ada_add_standard_exceptions (preg, &result);
12666
12667   /* Next, find all exceptions whose scope is local and accessible
12668      from the currently selected frame.  */
12669
12670   if (has_stack_frames ())
12671     {
12672       prev_len = result.size ();
12673       ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
12674                                      &result);
12675       if (result.size () > prev_len)
12676         sort_remove_dups_ada_exceptions_list (&result, prev_len);
12677     }
12678
12679   /* Add all exceptions whose scope is global.  */
12680
12681   prev_len = result.size ();
12682   ada_add_global_exceptions (preg, &result);
12683   if (result.size () > prev_len)
12684     sort_remove_dups_ada_exceptions_list (&result, prev_len);
12685
12686   return result;
12687 }
12688
12689 /* Return a vector of ada_exc_info.
12690
12691    If REGEXP is NULL, all exceptions are included in the result.
12692    Otherwise, it should contain a valid regular expression,
12693    and only the exceptions whose names match that regular expression
12694    are included in the result.
12695
12696    The exceptions are sorted in the following order:
12697      - Standard exceptions (defined by the Ada language), in
12698        alphabetical order;
12699      - Exceptions only visible from the current frame, in
12700        alphabetical order;
12701      - Exceptions whose scope is global, in alphabetical order.  */
12702
12703 std::vector<ada_exc_info>
12704 ada_exceptions_list (const char *regexp)
12705 {
12706   if (regexp == NULL)
12707     return ada_exceptions_list_1 (NULL);
12708
12709   compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
12710   return ada_exceptions_list_1 (&reg);
12711 }
12712
12713 /* Implement the "info exceptions" command.  */
12714
12715 static void
12716 info_exceptions_command (const char *regexp, int from_tty)
12717 {
12718   struct gdbarch *gdbarch = get_current_arch ();
12719
12720   std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
12721
12722   if (regexp != NULL)
12723     printf_filtered
12724       (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
12725   else
12726     printf_filtered (_("All defined Ada exceptions:\n"));
12727
12728   for (const ada_exc_info &info : exceptions)
12729     printf_filtered ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
12730 }
12731
12732 \f
12733                                 /* Language vector */
12734
12735 /* symbol_name_matcher_ftype adapter for wild_match.  */
12736
12737 static bool
12738 do_wild_match (const char *symbol_search_name,
12739                const lookup_name_info &lookup_name,
12740                completion_match_result *comp_match_res)
12741 {
12742   return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
12743 }
12744
12745 /* symbol_name_matcher_ftype adapter for full_match.  */
12746
12747 static bool
12748 do_full_match (const char *symbol_search_name,
12749                const lookup_name_info &lookup_name,
12750                completion_match_result *comp_match_res)
12751 {
12752   const char *lname = lookup_name.ada ().lookup_name ().c_str ();
12753
12754   /* If both symbols start with "_ada_", just let the loop below
12755      handle the comparison.  However, if only the symbol name starts
12756      with "_ada_", skip the prefix and let the match proceed as
12757      usual.  */
12758   if (startswith (symbol_search_name, "_ada_")
12759       && !startswith (lname, "_ada"))
12760     symbol_search_name += 5;
12761
12762   int uscore_count = 0;
12763   while (*lname != '\0')
12764     {
12765       if (*symbol_search_name != *lname)
12766         {
12767           if (*symbol_search_name == 'B' && uscore_count == 2
12768               && symbol_search_name[1] == '_')
12769             {
12770               symbol_search_name += 2;
12771               while (isdigit (*symbol_search_name))
12772                 ++symbol_search_name;
12773               if (symbol_search_name[0] == '_'
12774                   && symbol_search_name[1] == '_')
12775                 {
12776                   symbol_search_name += 2;
12777                   continue;
12778                 }
12779             }
12780           return false;
12781         }
12782
12783       if (*symbol_search_name == '_')
12784         ++uscore_count;
12785       else
12786         uscore_count = 0;
12787
12788       ++symbol_search_name;
12789       ++lname;
12790     }
12791
12792   return is_name_suffix (symbol_search_name);
12793 }
12794
12795 /* symbol_name_matcher_ftype for exact (verbatim) matches.  */
12796
12797 static bool
12798 do_exact_match (const char *symbol_search_name,
12799                 const lookup_name_info &lookup_name,
12800                 completion_match_result *comp_match_res)
12801 {
12802   return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
12803 }
12804
12805 /* Build the Ada lookup name for LOOKUP_NAME.  */
12806
12807 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
12808 {
12809   gdb::string_view user_name = lookup_name.name ();
12810
12811   if (!user_name.empty () && user_name[0] == '<')
12812     {
12813       if (user_name.back () == '>')
12814         m_encoded_name
12815           = gdb::to_string (user_name.substr (1, user_name.size () - 2));
12816       else
12817         m_encoded_name
12818           = gdb::to_string (user_name.substr (1, user_name.size () - 1));
12819       m_encoded_p = true;
12820       m_verbatim_p = true;
12821       m_wild_match_p = false;
12822       m_standard_p = false;
12823     }
12824   else
12825     {
12826       m_verbatim_p = false;
12827
12828       m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
12829
12830       if (!m_encoded_p)
12831         {
12832           const char *folded = ada_fold_name (user_name);
12833           m_encoded_name = ada_encode_1 (folded, false);
12834           if (m_encoded_name.empty ())
12835             m_encoded_name = gdb::to_string (user_name);
12836         }
12837       else
12838         m_encoded_name = gdb::to_string (user_name);
12839
12840       /* Handle the 'package Standard' special case.  See description
12841          of m_standard_p.  */
12842       if (startswith (m_encoded_name.c_str (), "standard__"))
12843         {
12844           m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
12845           m_standard_p = true;
12846         }
12847       else
12848         m_standard_p = false;
12849
12850       /* If the name contains a ".", then the user is entering a fully
12851          qualified entity name, and the match must not be done in wild
12852          mode.  Similarly, if the user wants to complete what looks
12853          like an encoded name, the match must not be done in wild
12854          mode.  Also, in the standard__ special case always do
12855          non-wild matching.  */
12856       m_wild_match_p
12857         = (lookup_name.match_type () != symbol_name_match_type::FULL
12858            && !m_encoded_p
12859            && !m_standard_p
12860            && user_name.find ('.') == std::string::npos);
12861     }
12862 }
12863
12864 /* symbol_name_matcher_ftype method for Ada.  This only handles
12865    completion mode.  */
12866
12867 static bool
12868 ada_symbol_name_matches (const char *symbol_search_name,
12869                          const lookup_name_info &lookup_name,
12870                          completion_match_result *comp_match_res)
12871 {
12872   return lookup_name.ada ().matches (symbol_search_name,
12873                                      lookup_name.match_type (),
12874                                      comp_match_res);
12875 }
12876
12877 /* A name matcher that matches the symbol name exactly, with
12878    strcmp.  */
12879
12880 static bool
12881 literal_symbol_name_matcher (const char *symbol_search_name,
12882                              const lookup_name_info &lookup_name,
12883                              completion_match_result *comp_match_res)
12884 {
12885   gdb::string_view name_view = lookup_name.name ();
12886
12887   if (lookup_name.completion_mode ()
12888       ? (strncmp (symbol_search_name, name_view.data (),
12889                   name_view.size ()) == 0)
12890       : symbol_search_name == name_view)
12891     {
12892       if (comp_match_res != NULL)
12893         comp_match_res->set_match (symbol_search_name);
12894       return true;
12895     }
12896   else
12897     return false;
12898 }
12899
12900 /* Implement the "get_symbol_name_matcher" language_defn method for
12901    Ada.  */
12902
12903 static symbol_name_matcher_ftype *
12904 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
12905 {
12906   if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
12907     return literal_symbol_name_matcher;
12908
12909   if (lookup_name.completion_mode ())
12910     return ada_symbol_name_matches;
12911   else
12912     {
12913       if (lookup_name.ada ().wild_match_p ())
12914         return do_wild_match;
12915       else if (lookup_name.ada ().verbatim_p ())
12916         return do_exact_match;
12917       else
12918         return do_full_match;
12919     }
12920 }
12921
12922 /* Class representing the Ada language.  */
12923
12924 class ada_language : public language_defn
12925 {
12926 public:
12927   ada_language ()
12928     : language_defn (language_ada)
12929   { /* Nothing.  */ }
12930
12931   /* See language.h.  */
12932
12933   const char *name () const override
12934   { return "ada"; }
12935
12936   /* See language.h.  */
12937
12938   const char *natural_name () const override
12939   { return "Ada"; }
12940
12941   /* See language.h.  */
12942
12943   const std::vector<const char *> &filename_extensions () const override
12944   {
12945     static const std::vector<const char *> extensions
12946       = { ".adb", ".ads", ".a", ".ada", ".dg" };
12947     return extensions;
12948   }
12949
12950   /* Print an array element index using the Ada syntax.  */
12951
12952   void print_array_index (struct type *index_type,
12953                           LONGEST index,
12954                           struct ui_file *stream,
12955                           const value_print_options *options) const override
12956   {
12957     struct value *index_value = val_atr (index_type, index);
12958
12959     value_print (index_value, stream, options);
12960     fprintf_filtered (stream, " => ");
12961   }
12962
12963   /* Implement the "read_var_value" language_defn method for Ada.  */
12964
12965   struct value *read_var_value (struct symbol *var,
12966                                 const struct block *var_block,
12967                                 struct frame_info *frame) const override
12968   {
12969     /* The only case where default_read_var_value is not sufficient
12970        is when VAR is a renaming...  */
12971     if (frame != nullptr)
12972       {
12973         const struct block *frame_block = get_frame_block (frame, NULL);
12974         if (frame_block != nullptr && ada_is_renaming_symbol (var))
12975           return ada_read_renaming_var_value (var, frame_block);
12976       }
12977
12978     /* This is a typical case where we expect the default_read_var_value
12979        function to work.  */
12980     return language_defn::read_var_value (var, var_block, frame);
12981   }
12982
12983   /* See language.h.  */
12984   void language_arch_info (struct gdbarch *gdbarch,
12985                            struct language_arch_info *lai) const override
12986   {
12987     const struct builtin_type *builtin = builtin_type (gdbarch);
12988
12989     /* Helper function to allow shorter lines below.  */
12990     auto add = [&] (struct type *t)
12991     {
12992       lai->add_primitive_type (t);
12993     };
12994
12995     add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
12996                             0, "integer"));
12997     add (arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
12998                             0, "long_integer"));
12999     add (arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
13000                             0, "short_integer"));
13001     struct type *char_type = arch_character_type (gdbarch, TARGET_CHAR_BIT,
13002                                                   0, "character");
13003     lai->set_string_char_type (char_type);
13004     add (char_type);
13005     add (arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
13006                           "float", gdbarch_float_format (gdbarch)));
13007     add (arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
13008                           "long_float", gdbarch_double_format (gdbarch)));
13009     add (arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
13010                             0, "long_long_integer"));
13011     add (arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
13012                           "long_long_float",
13013                           gdbarch_long_double_format (gdbarch)));
13014     add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13015                             0, "natural"));
13016     add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13017                             0, "positive"));
13018     add (builtin->builtin_void);
13019
13020     struct type *system_addr_ptr
13021       = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
13022                                         "void"));
13023     system_addr_ptr->set_name ("system__address");
13024     add (system_addr_ptr);
13025
13026     /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13027        type.  This is a signed integral type whose size is the same as
13028        the size of addresses.  */
13029     unsigned int addr_length = TYPE_LENGTH (system_addr_ptr);
13030     add (arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
13031                             "storage_offset"));
13032
13033     lai->set_bool_type (builtin->builtin_bool);
13034   }
13035
13036   /* See language.h.  */
13037
13038   bool iterate_over_symbols
13039         (const struct block *block, const lookup_name_info &name,
13040          domain_enum domain,
13041          gdb::function_view<symbol_found_callback_ftype> callback) const override
13042   {
13043     std::vector<struct block_symbol> results
13044       = ada_lookup_symbol_list_worker (name, block, domain, 0);
13045     for (block_symbol &sym : results)
13046       {
13047         if (!callback (&sym))
13048           return false;
13049       }
13050
13051     return true;
13052   }
13053
13054   /* See language.h.  */
13055   bool sniff_from_mangled_name (const char *mangled,
13056                                 char **out) const override
13057   {
13058     std::string demangled = ada_decode (mangled);
13059
13060     *out = NULL;
13061
13062     if (demangled != mangled && demangled[0] != '<')
13063       {
13064         /* Set the gsymbol language to Ada, but still return 0.
13065            Two reasons for that:
13066
13067            1. For Ada, we prefer computing the symbol's decoded name
13068            on the fly rather than pre-compute it, in order to save
13069            memory (Ada projects are typically very large).
13070
13071            2. There are some areas in the definition of the GNAT
13072            encoding where, with a bit of bad luck, we might be able
13073            to decode a non-Ada symbol, generating an incorrect
13074            demangled name (Eg: names ending with "TB" for instance
13075            are identified as task bodies and so stripped from
13076            the decoded name returned).
13077
13078            Returning true, here, but not setting *DEMANGLED, helps us get
13079            a little bit of the best of both worlds.  Because we're last,
13080            we should not affect any of the other languages that were
13081            able to demangle the symbol before us; we get to correctly
13082            tag Ada symbols as such; and even if we incorrectly tagged a
13083            non-Ada symbol, which should be rare, any routing through the
13084            Ada language should be transparent (Ada tries to behave much
13085            like C/C++ with non-Ada symbols).  */
13086         return true;
13087       }
13088
13089     return false;
13090   }
13091
13092   /* See language.h.  */
13093
13094   char *demangle_symbol (const char *mangled, int options) const override
13095   {
13096     return ada_la_decode (mangled, options);
13097   }
13098
13099   /* See language.h.  */
13100
13101   void print_type (struct type *type, const char *varstring,
13102                    struct ui_file *stream, int show, int level,
13103                    const struct type_print_options *flags) const override
13104   {
13105     ada_print_type (type, varstring, stream, show, level, flags);
13106   }
13107
13108   /* See language.h.  */
13109
13110   const char *word_break_characters (void) const override
13111   {
13112     return ada_completer_word_break_characters;
13113   }
13114
13115   /* See language.h.  */
13116
13117   void collect_symbol_completion_matches (completion_tracker &tracker,
13118                                           complete_symbol_mode mode,
13119                                           symbol_name_match_type name_match_type,
13120                                           const char *text, const char *word,
13121                                           enum type_code code) const override
13122   {
13123     struct symbol *sym;
13124     const struct block *b, *surrounding_static_block = 0;
13125     struct block_iterator iter;
13126
13127     gdb_assert (code == TYPE_CODE_UNDEF);
13128
13129     lookup_name_info lookup_name (text, name_match_type, true);
13130
13131     /* First, look at the partial symtab symbols.  */
13132     expand_symtabs_matching (NULL,
13133                              lookup_name,
13134                              NULL,
13135                              NULL,
13136                              SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13137                              ALL_DOMAIN);
13138
13139     /* At this point scan through the misc symbol vectors and add each
13140        symbol you find to the list.  Eventually we want to ignore
13141        anything that isn't a text symbol (everything else will be
13142        handled by the psymtab code above).  */
13143
13144     for (objfile *objfile : current_program_space->objfiles ())
13145       {
13146         for (minimal_symbol *msymbol : objfile->msymbols ())
13147           {
13148             QUIT;
13149
13150             if (completion_skip_symbol (mode, msymbol))
13151               continue;
13152
13153             language symbol_language = msymbol->language ();
13154
13155             /* Ada minimal symbols won't have their language set to Ada.  If
13156                we let completion_list_add_name compare using the
13157                default/C-like matcher, then when completing e.g., symbols in a
13158                package named "pck", we'd match internal Ada symbols like
13159                "pckS", which are invalid in an Ada expression, unless you wrap
13160                them in '<' '>' to request a verbatim match.
13161
13162                Unfortunately, some Ada encoded names successfully demangle as
13163                C++ symbols (using an old mangling scheme), such as "name__2Xn"
13164                -> "Xn::name(void)" and thus some Ada minimal symbols end up
13165                with the wrong language set.  Paper over that issue here.  */
13166             if (symbol_language == language_auto
13167                 || symbol_language == language_cplus)
13168               symbol_language = language_ada;
13169
13170             completion_list_add_name (tracker,
13171                                       symbol_language,
13172                                       msymbol->linkage_name (),
13173                                       lookup_name, text, word);
13174           }
13175       }
13176
13177     /* Search upwards from currently selected frame (so that we can
13178        complete on local vars.  */
13179
13180     for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
13181       {
13182         if (!BLOCK_SUPERBLOCK (b))
13183           surrounding_static_block = b;   /* For elmin of dups */
13184
13185         ALL_BLOCK_SYMBOLS (b, iter, sym)
13186           {
13187             if (completion_skip_symbol (mode, sym))
13188               continue;
13189
13190             completion_list_add_name (tracker,
13191                                       sym->language (),
13192                                       sym->linkage_name (),
13193                                       lookup_name, text, word);
13194           }
13195       }
13196
13197     /* Go through the symtabs and check the externs and statics for
13198        symbols which match.  */
13199
13200     for (objfile *objfile : current_program_space->objfiles ())
13201       {
13202         for (compunit_symtab *s : objfile->compunits ())
13203           {
13204             QUIT;
13205             b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), GLOBAL_BLOCK);
13206             ALL_BLOCK_SYMBOLS (b, iter, sym)
13207               {
13208                 if (completion_skip_symbol (mode, sym))
13209                   continue;
13210
13211                 completion_list_add_name (tracker,
13212                                           sym->language (),
13213                                           sym->linkage_name (),
13214                                           lookup_name, text, word);
13215               }
13216           }
13217       }
13218
13219     for (objfile *objfile : current_program_space->objfiles ())
13220       {
13221         for (compunit_symtab *s : objfile->compunits ())
13222           {
13223             QUIT;
13224             b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), STATIC_BLOCK);
13225             /* Don't do this block twice.  */
13226             if (b == surrounding_static_block)
13227               continue;
13228             ALL_BLOCK_SYMBOLS (b, iter, sym)
13229               {
13230                 if (completion_skip_symbol (mode, sym))
13231                   continue;
13232
13233                 completion_list_add_name (tracker,
13234                                           sym->language (),
13235                                           sym->linkage_name (),
13236                                           lookup_name, text, word);
13237               }
13238           }
13239       }
13240   }
13241
13242   /* See language.h.  */
13243
13244   gdb::unique_xmalloc_ptr<char> watch_location_expression
13245         (struct type *type, CORE_ADDR addr) const override
13246   {
13247     type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
13248     std::string name = type_to_string (type);
13249     return gdb::unique_xmalloc_ptr<char>
13250       (xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr)));
13251   }
13252
13253   /* See language.h.  */
13254
13255   void value_print (struct value *val, struct ui_file *stream,
13256                     const struct value_print_options *options) const override
13257   {
13258     return ada_value_print (val, stream, options);
13259   }
13260
13261   /* See language.h.  */
13262
13263   void value_print_inner
13264         (struct value *val, struct ui_file *stream, int recurse,
13265          const struct value_print_options *options) const override
13266   {
13267     return ada_value_print_inner (val, stream, recurse, options);
13268   }
13269
13270   /* See language.h.  */
13271
13272   struct block_symbol lookup_symbol_nonlocal
13273         (const char *name, const struct block *block,
13274          const domain_enum domain) const override
13275   {
13276     struct block_symbol sym;
13277
13278     sym = ada_lookup_symbol (name, block_static_block (block), domain);
13279     if (sym.symbol != NULL)
13280       return sym;
13281
13282     /* If we haven't found a match at this point, try the primitive
13283        types.  In other languages, this search is performed before
13284        searching for global symbols in order to short-circuit that
13285        global-symbol search if it happens that the name corresponds
13286        to a primitive type.  But we cannot do the same in Ada, because
13287        it is perfectly legitimate for a program to declare a type which
13288        has the same name as a standard type.  If looking up a type in
13289        that situation, we have traditionally ignored the primitive type
13290        in favor of user-defined types.  This is why, unlike most other
13291        languages, we search the primitive types this late and only after
13292        having searched the global symbols without success.  */
13293
13294     if (domain == VAR_DOMAIN)
13295       {
13296         struct gdbarch *gdbarch;
13297
13298         if (block == NULL)
13299           gdbarch = target_gdbarch ();
13300         else
13301           gdbarch = block_gdbarch (block);
13302         sym.symbol
13303           = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13304         if (sym.symbol != NULL)
13305           return sym;
13306       }
13307
13308     return {};
13309   }
13310
13311   /* See language.h.  */
13312
13313   int parser (struct parser_state *ps) const override
13314   {
13315     warnings_issued = 0;
13316     return ada_parse (ps);
13317   }
13318
13319   /* See language.h.  */
13320
13321   void emitchar (int ch, struct type *chtype,
13322                  struct ui_file *stream, int quoter) const override
13323   {
13324     ada_emit_char (ch, chtype, stream, quoter, 1);
13325   }
13326
13327   /* See language.h.  */
13328
13329   void printchar (int ch, struct type *chtype,
13330                   struct ui_file *stream) const override
13331   {
13332     ada_printchar (ch, chtype, stream);
13333   }
13334
13335   /* See language.h.  */
13336
13337   void printstr (struct ui_file *stream, struct type *elttype,
13338                  const gdb_byte *string, unsigned int length,
13339                  const char *encoding, int force_ellipses,
13340                  const struct value_print_options *options) const override
13341   {
13342     ada_printstr (stream, elttype, string, length, encoding,
13343                   force_ellipses, options);
13344   }
13345
13346   /* See language.h.  */
13347
13348   void print_typedef (struct type *type, struct symbol *new_symbol,
13349                       struct ui_file *stream) const override
13350   {
13351     ada_print_typedef (type, new_symbol, stream);
13352   }
13353
13354   /* See language.h.  */
13355
13356   bool is_string_type_p (struct type *type) const override
13357   {
13358     return ada_is_string_type (type);
13359   }
13360
13361   /* See language.h.  */
13362
13363   const char *struct_too_deep_ellipsis () const override
13364   { return "(...)"; }
13365
13366   /* See language.h.  */
13367
13368   bool c_style_arrays_p () const override
13369   { return false; }
13370
13371   /* See language.h.  */
13372
13373   bool store_sym_names_in_linkage_form_p () const override
13374   { return true; }
13375
13376   /* See language.h.  */
13377
13378   const struct lang_varobj_ops *varobj_ops () const override
13379   { return &ada_varobj_ops; }
13380
13381 protected:
13382   /* See language.h.  */
13383
13384   symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13385         (const lookup_name_info &lookup_name) const override
13386   {
13387     return ada_get_symbol_name_matcher (lookup_name);
13388   }
13389 };
13390
13391 /* Single instance of the Ada language class.  */
13392
13393 static ada_language ada_language_defn;
13394
13395 /* Command-list for the "set/show ada" prefix command.  */
13396 static struct cmd_list_element *set_ada_list;
13397 static struct cmd_list_element *show_ada_list;
13398
13399 static void
13400 initialize_ada_catchpoint_ops (void)
13401 {
13402   struct breakpoint_ops *ops;
13403
13404   initialize_breakpoint_ops ();
13405
13406   ops = &catch_exception_breakpoint_ops;
13407   *ops = bkpt_breakpoint_ops;
13408   ops->allocate_location = allocate_location_exception;
13409   ops->re_set = re_set_exception;
13410   ops->check_status = check_status_exception;
13411   ops->print_it = print_it_exception;
13412   ops->print_one = print_one_exception;
13413   ops->print_mention = print_mention_exception;
13414   ops->print_recreate = print_recreate_exception;
13415
13416   ops = &catch_exception_unhandled_breakpoint_ops;
13417   *ops = bkpt_breakpoint_ops;
13418   ops->allocate_location = allocate_location_exception;
13419   ops->re_set = re_set_exception;
13420   ops->check_status = check_status_exception;
13421   ops->print_it = print_it_exception;
13422   ops->print_one = print_one_exception;
13423   ops->print_mention = print_mention_exception;
13424   ops->print_recreate = print_recreate_exception;
13425
13426   ops = &catch_assert_breakpoint_ops;
13427   *ops = bkpt_breakpoint_ops;
13428   ops->allocate_location = allocate_location_exception;
13429   ops->re_set = re_set_exception;
13430   ops->check_status = check_status_exception;
13431   ops->print_it = print_it_exception;
13432   ops->print_one = print_one_exception;
13433   ops->print_mention = print_mention_exception;
13434   ops->print_recreate = print_recreate_exception;
13435
13436   ops = &catch_handlers_breakpoint_ops;
13437   *ops = bkpt_breakpoint_ops;
13438   ops->allocate_location = allocate_location_exception;
13439   ops->re_set = re_set_exception;
13440   ops->check_status = check_status_exception;
13441   ops->print_it = print_it_exception;
13442   ops->print_one = print_one_exception;
13443   ops->print_mention = print_mention_exception;
13444   ops->print_recreate = print_recreate_exception;
13445 }
13446
13447 /* This module's 'new_objfile' observer.  */
13448
13449 static void
13450 ada_new_objfile_observer (struct objfile *objfile)
13451 {
13452   ada_clear_symbol_cache ();
13453 }
13454
13455 /* This module's 'free_objfile' observer.  */
13456
13457 static void
13458 ada_free_objfile_observer (struct objfile *objfile)
13459 {
13460   ada_clear_symbol_cache ();
13461 }
13462
13463 void _initialize_ada_language ();
13464 void
13465 _initialize_ada_language ()
13466 {
13467   initialize_ada_catchpoint_ops ();
13468
13469   add_basic_prefix_cmd ("ada", no_class,
13470                         _("Prefix command for changing Ada-specific settings."),
13471                         &set_ada_list, 0, &setlist);
13472
13473   add_show_prefix_cmd ("ada", no_class,
13474                        _("Generic command for showing Ada-specific settings."),
13475                        &show_ada_list, 0, &showlist);
13476
13477   add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13478                            &trust_pad_over_xvs, _("\
13479 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13480 Show whether an optimization trusting PAD types over XVS types is activated."),
13481                            _("\
13482 This is related to the encoding used by the GNAT compiler.  The debugger\n\
13483 should normally trust the contents of PAD types, but certain older versions\n\
13484 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13485 to be incorrect.  Turning this setting \"off\" allows the debugger to\n\
13486 work around this bug.  It is always safe to turn this option \"off\", but\n\
13487 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13488 this option to \"off\" unless necessary."),
13489                             NULL, NULL, &set_ada_list, &show_ada_list);
13490
13491   add_setshow_boolean_cmd ("print-signatures", class_vars,
13492                            &print_signatures, _("\
13493 Enable or disable the output of formal and return types for functions in the \
13494 overloads selection menu."), _("\
13495 Show whether the output of formal and return types for functions in the \
13496 overloads selection menu is activated."),
13497                            NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13498
13499   add_catch_command ("exception", _("\
13500 Catch Ada exceptions, when raised.\n\
13501 Usage: catch exception [ARG] [if CONDITION]\n\
13502 Without any argument, stop when any Ada exception is raised.\n\
13503 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13504 being raised does not have a handler (and will therefore lead to the task's\n\
13505 termination).\n\
13506 Otherwise, the catchpoint only stops when the name of the exception being\n\
13507 raised is the same as ARG.\n\
13508 CONDITION is a boolean expression that is evaluated to see whether the\n\
13509 exception should cause a stop."),
13510                      catch_ada_exception_command,
13511                      catch_ada_completer,
13512                      CATCH_PERMANENT,
13513                      CATCH_TEMPORARY);
13514
13515   add_catch_command ("handlers", _("\
13516 Catch Ada exceptions, when handled.\n\
13517 Usage: catch handlers [ARG] [if CONDITION]\n\
13518 Without any argument, stop when any Ada exception is handled.\n\
13519 With an argument, catch only exceptions with the given name.\n\
13520 CONDITION is a boolean expression that is evaluated to see whether the\n\
13521 exception should cause a stop."),
13522                      catch_ada_handlers_command,
13523                      catch_ada_completer,
13524                      CATCH_PERMANENT,
13525                      CATCH_TEMPORARY);
13526   add_catch_command ("assert", _("\
13527 Catch failed Ada assertions, when raised.\n\
13528 Usage: catch assert [if CONDITION]\n\
13529 CONDITION is a boolean expression that is evaluated to see whether the\n\
13530 exception should cause a stop."),
13531                      catch_assert_command,
13532                      NULL,
13533                      CATCH_PERMANENT,
13534                      CATCH_TEMPORARY);
13535
13536   varsize_limit = 65536;
13537   add_setshow_uinteger_cmd ("varsize-limit", class_support,
13538                             &varsize_limit, _("\
13539 Set the maximum number of bytes allowed in a variable-size object."), _("\
13540 Show the maximum number of bytes allowed in a variable-size object."), _("\
13541 Attempts to access an object whose size is not a compile-time constant\n\
13542 and exceeds this limit will cause an error."),
13543                             NULL, NULL, &setlist, &showlist);
13544
13545   add_info ("exceptions", info_exceptions_command,
13546             _("\
13547 List all Ada exception names.\n\
13548 Usage: info exceptions [REGEXP]\n\
13549 If a regular expression is passed as an argument, only those matching\n\
13550 the regular expression are listed."));
13551
13552   add_basic_prefix_cmd ("ada", class_maintenance,
13553                         _("Set Ada maintenance-related variables."),
13554                         &maint_set_ada_cmdlist,
13555                         0/*allow-unknown*/, &maintenance_set_cmdlist);
13556
13557   add_show_prefix_cmd ("ada", class_maintenance,
13558                        _("Show Ada maintenance-related variables."),
13559                        &maint_show_ada_cmdlist,
13560                        0/*allow-unknown*/, &maintenance_show_cmdlist);
13561
13562   add_setshow_boolean_cmd
13563     ("ignore-descriptive-types", class_maintenance,
13564      &ada_ignore_descriptive_types_p,
13565      _("Set whether descriptive types generated by GNAT should be ignored."),
13566      _("Show whether descriptive types generated by GNAT should be ignored."),
13567      _("\
13568 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
13569 DWARF attribute."),
13570      NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
13571
13572   decoded_names_store = htab_create_alloc (256, htab_hash_string,
13573                                            htab_eq_string,
13574                                            NULL, xcalloc, xfree);
13575
13576   /* The ada-lang observers.  */
13577   gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
13578   gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
13579   gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
13580 }
This page took 0.786203 seconds and 4 git commands to generate.