]> Git Repo - binutils.git/blob - gdb/ada-lang.c
Don't pre-size result string in ada_decode
[binutils.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3    Copyright (C) 1992-2022 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 "gdbsupport/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 "gdbsupport/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 static const char ada_completer_word_break_characters[] =
251 #ifdef VMS
252   " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
253 #else
254   " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
255 #endif
256
257 /* The name of the symbol to use to get the name of the main subprogram.  */
258 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
259   = "__gnat_ada_main_program_name";
260
261 /* Limit on the number of warnings to raise per expression evaluation.  */
262 static int warning_limit = 2;
263
264 /* Number of warning messages issued; reset to 0 by cleanups after
265    expression evaluation.  */
266 static int warnings_issued = 0;
267
268 static const char * const known_runtime_file_name_patterns[] = {
269   ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
270 };
271
272 static const char * const known_auxiliary_function_name_patterns[] = {
273   ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
274 };
275
276 /* Maintenance-related settings for this module.  */
277
278 static struct cmd_list_element *maint_set_ada_cmdlist;
279 static struct cmd_list_element *maint_show_ada_cmdlist;
280
281 /* The "maintenance ada set/show ignore-descriptive-type" value.  */
282
283 static bool ada_ignore_descriptive_types_p = false;
284
285                         /* Inferior-specific data.  */
286
287 /* Per-inferior data for this module.  */
288
289 struct ada_inferior_data
290 {
291   /* The ada__tags__type_specific_data type, which is used when decoding
292      tagged types.  With older versions of GNAT, this type was directly
293      accessible through a component ("tsd") in the object tag.  But this
294      is no longer the case, so we cache it for each inferior.  */
295   struct type *tsd_type = nullptr;
296
297   /* The exception_support_info data.  This data is used to determine
298      how to implement support for Ada exception catchpoints in a given
299      inferior.  */
300   const struct exception_support_info *exception_info = nullptr;
301 };
302
303 /* Our key to this module's inferior data.  */
304 static const struct inferior_key<ada_inferior_data> ada_inferior_data;
305
306 /* Return our inferior data for the given inferior (INF).
307
308    This function always returns a valid pointer to an allocated
309    ada_inferior_data structure.  If INF's inferior data has not
310    been previously set, this functions creates a new one with all
311    fields set to zero, sets INF's inferior to it, and then returns
312    a pointer to that newly allocated ada_inferior_data.  */
313
314 static struct ada_inferior_data *
315 get_ada_inferior_data (struct inferior *inf)
316 {
317   struct ada_inferior_data *data;
318
319   data = ada_inferior_data.get (inf);
320   if (data == NULL)
321     data = ada_inferior_data.emplace (inf);
322
323   return data;
324 }
325
326 /* Perform all necessary cleanups regarding our module's inferior data
327    that is required after the inferior INF just exited.  */
328
329 static void
330 ada_inferior_exit (struct inferior *inf)
331 {
332   ada_inferior_data.clear (inf);
333 }
334
335
336                         /* program-space-specific data.  */
337
338 /* This module's per-program-space data.  */
339 struct ada_pspace_data
340 {
341   /* The Ada symbol cache.  */
342   std::unique_ptr<ada_symbol_cache> sym_cache;
343 };
344
345 /* Key to our per-program-space data.  */
346 static const struct program_space_key<ada_pspace_data> ada_pspace_data_handle;
347
348 /* Return this module's data for the given program space (PSPACE).
349    If not is found, add a zero'ed one now.
350
351    This function always returns a valid object.  */
352
353 static struct ada_pspace_data *
354 get_ada_pspace_data (struct program_space *pspace)
355 {
356   struct ada_pspace_data *data;
357
358   data = ada_pspace_data_handle.get (pspace);
359   if (data == NULL)
360     data = ada_pspace_data_handle.emplace (pspace);
361
362   return data;
363 }
364
365                         /* Utilities */
366
367 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
368    all typedef layers have been peeled.  Otherwise, return TYPE.
369
370    Normally, we really expect a typedef type to only have 1 typedef layer.
371    In other words, we really expect the target type of a typedef type to be
372    a non-typedef type.  This is particularly true for Ada units, because
373    the language does not have a typedef vs not-typedef distinction.
374    In that respect, the Ada compiler has been trying to eliminate as many
375    typedef definitions in the debugging information, since they generally
376    do not bring any extra information (we still use typedef under certain
377    circumstances related mostly to the GNAT encoding).
378
379    Unfortunately, we have seen situations where the debugging information
380    generated by the compiler leads to such multiple typedef layers.  For
381    instance, consider the following example with stabs:
382
383      .stabs  "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
384      .stabs  "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
385
386    This is an error in the debugging information which causes type
387    pck__float_array___XUP to be defined twice, and the second time,
388    it is defined as a typedef of a typedef.
389
390    This is on the fringe of legality as far as debugging information is
391    concerned, and certainly unexpected.  But it is easy to handle these
392    situations correctly, so we can afford to be lenient in this case.  */
393
394 static struct type *
395 ada_typedef_target_type (struct type *type)
396 {
397   while (type->code () == TYPE_CODE_TYPEDEF)
398     type = TYPE_TARGET_TYPE (type);
399   return type;
400 }
401
402 /* Given DECODED_NAME a string holding a symbol name in its
403    decoded form (ie using the Ada dotted notation), returns
404    its unqualified name.  */
405
406 static const char *
407 ada_unqualified_name (const char *decoded_name)
408 {
409   const char *result;
410   
411   /* If the decoded name starts with '<', it means that the encoded
412      name does not follow standard naming conventions, and thus that
413      it is not your typical Ada symbol name.  Trying to unqualify it
414      is therefore pointless and possibly erroneous.  */
415   if (decoded_name[0] == '<')
416     return decoded_name;
417
418   result = strrchr (decoded_name, '.');
419   if (result != NULL)
420     result++;                   /* Skip the dot...  */
421   else
422     result = decoded_name;
423
424   return result;
425 }
426
427 /* Return a string starting with '<', followed by STR, and '>'.  */
428
429 static std::string
430 add_angle_brackets (const char *str)
431 {
432   return string_printf ("<%s>", str);
433 }
434
435 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
436    suffix of FIELD_NAME beginning "___".  */
437
438 static int
439 field_name_match (const char *field_name, const char *target)
440 {
441   int len = strlen (target);
442
443   return
444     (strncmp (field_name, target, len) == 0
445      && (field_name[len] == '\0'
446          || (startswith (field_name + len, "___")
447              && strcmp (field_name + strlen (field_name) - 6,
448                         "___XVN") != 0)));
449 }
450
451
452 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
453    a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
454    and return its index.  This function also handles fields whose name
455    have ___ suffixes because the compiler sometimes alters their name
456    by adding such a suffix to represent fields with certain constraints.
457    If the field could not be found, return a negative number if
458    MAYBE_MISSING is set.  Otherwise raise an error.  */
459
460 int
461 ada_get_field_index (const struct type *type, const char *field_name,
462                      int maybe_missing)
463 {
464   int fieldno;
465   struct type *struct_type = check_typedef ((struct type *) type);
466
467   for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
468     if (field_name_match (struct_type->field (fieldno).name (), field_name))
469       return fieldno;
470
471   if (!maybe_missing)
472     error (_("Unable to find field %s in struct %s.  Aborting"),
473            field_name, struct_type->name ());
474
475   return -1;
476 }
477
478 /* The length of the prefix of NAME prior to any "___" suffix.  */
479
480 int
481 ada_name_prefix_len (const char *name)
482 {
483   if (name == NULL)
484     return 0;
485   else
486     {
487       const char *p = strstr (name, "___");
488
489       if (p == NULL)
490         return strlen (name);
491       else
492         return p - name;
493     }
494 }
495
496 /* Return non-zero if SUFFIX is a suffix of STR.
497    Return zero if STR is null.  */
498
499 static int
500 is_suffix (const char *str, const char *suffix)
501 {
502   int len1, len2;
503
504   if (str == NULL)
505     return 0;
506   len1 = strlen (str);
507   len2 = strlen (suffix);
508   return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
509 }
510
511 /* The contents of value VAL, treated as a value of type TYPE.  The
512    result is an lval in memory if VAL is.  */
513
514 static struct value *
515 coerce_unspec_val_to_type (struct value *val, struct type *type)
516 {
517   type = ada_check_typedef (type);
518   if (value_type (val) == type)
519     return val;
520   else
521     {
522       struct value *result;
523
524       if (value_optimized_out (val))
525         result = allocate_optimized_out_value (type);
526       else if (value_lazy (val)
527                /* Be careful not to make a lazy not_lval value.  */
528                || (VALUE_LVAL (val) != not_lval
529                    && TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val))))
530         result = allocate_value_lazy (type);
531       else
532         {
533           result = allocate_value (type);
534           value_contents_copy (result, 0, val, 0, TYPE_LENGTH (type));
535         }
536       set_value_component_location (result, val);
537       set_value_bitsize (result, value_bitsize (val));
538       set_value_bitpos (result, value_bitpos (val));
539       if (VALUE_LVAL (result) == lval_memory)
540         set_value_address (result, value_address (val));
541       return result;
542     }
543 }
544
545 static const gdb_byte *
546 cond_offset_host (const gdb_byte *valaddr, long offset)
547 {
548   if (valaddr == NULL)
549     return NULL;
550   else
551     return valaddr + offset;
552 }
553
554 static CORE_ADDR
555 cond_offset_target (CORE_ADDR address, long offset)
556 {
557   if (address == 0)
558     return 0;
559   else
560     return address + offset;
561 }
562
563 /* Issue a warning (as for the definition of warning in utils.c, but
564    with exactly one argument rather than ...), unless the limit on the
565    number of warnings has passed during the evaluation of the current
566    expression.  */
567
568 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
569    provided by "complaint".  */
570 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
571
572 static void
573 lim_warning (const char *format, ...)
574 {
575   va_list args;
576
577   va_start (args, format);
578   warnings_issued += 1;
579   if (warnings_issued <= warning_limit)
580     vwarning (format, args);
581
582   va_end (args);
583 }
584
585 /* Maximum value of a SIZE-byte signed integer type.  */
586 static LONGEST
587 max_of_size (int size)
588 {
589   LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
590
591   return top_bit | (top_bit - 1);
592 }
593
594 /* Minimum value of a SIZE-byte signed integer type.  */
595 static LONGEST
596 min_of_size (int size)
597 {
598   return -max_of_size (size) - 1;
599 }
600
601 /* Maximum value of a SIZE-byte unsigned integer type.  */
602 static ULONGEST
603 umax_of_size (int size)
604 {
605   ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
606
607   return top_bit | (top_bit - 1);
608 }
609
610 /* Maximum value of integral type T, as a signed quantity.  */
611 static LONGEST
612 max_of_type (struct type *t)
613 {
614   if (t->is_unsigned ())
615     return (LONGEST) umax_of_size (TYPE_LENGTH (t));
616   else
617     return max_of_size (TYPE_LENGTH (t));
618 }
619
620 /* Minimum value of integral type T, as a signed quantity.  */
621 static LONGEST
622 min_of_type (struct type *t)
623 {
624   if (t->is_unsigned ())
625     return 0;
626   else
627     return min_of_size (TYPE_LENGTH (t));
628 }
629
630 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
631 LONGEST
632 ada_discrete_type_high_bound (struct type *type)
633 {
634   type = resolve_dynamic_type (type, {}, 0);
635   switch (type->code ())
636     {
637     case TYPE_CODE_RANGE:
638       {
639         const dynamic_prop &high = type->bounds ()->high;
640
641         if (high.kind () == PROP_CONST)
642           return high.const_val ();
643         else
644           {
645             gdb_assert (high.kind () == PROP_UNDEFINED);
646
647             /* This happens when trying to evaluate a type's dynamic bound
648                without a live target.  There is nothing relevant for us to
649                return here, so return 0.  */
650             return 0;
651           }
652       }
653     case TYPE_CODE_ENUM:
654       return type->field (type->num_fields () - 1).loc_enumval ();
655     case TYPE_CODE_BOOL:
656       return 1;
657     case TYPE_CODE_CHAR:
658     case TYPE_CODE_INT:
659       return max_of_type (type);
660     default:
661       error (_("Unexpected type in ada_discrete_type_high_bound."));
662     }
663 }
664
665 /* The smallest value in the domain of TYPE, a discrete type, as an integer.  */
666 LONGEST
667 ada_discrete_type_low_bound (struct type *type)
668 {
669   type = resolve_dynamic_type (type, {}, 0);
670   switch (type->code ())
671     {
672     case TYPE_CODE_RANGE:
673       {
674         const dynamic_prop &low = type->bounds ()->low;
675
676         if (low.kind () == PROP_CONST)
677           return low.const_val ();
678         else
679           {
680             gdb_assert (low.kind () == PROP_UNDEFINED);
681
682             /* This happens when trying to evaluate a type's dynamic bound
683                without a live target.  There is nothing relevant for us to
684                return here, so return 0.  */
685             return 0;
686           }
687       }
688     case TYPE_CODE_ENUM:
689       return type->field (0).loc_enumval ();
690     case TYPE_CODE_BOOL:
691       return 0;
692     case TYPE_CODE_CHAR:
693     case TYPE_CODE_INT:
694       return min_of_type (type);
695     default:
696       error (_("Unexpected type in ada_discrete_type_low_bound."));
697     }
698 }
699
700 /* The identity on non-range types.  For range types, the underlying
701    non-range scalar type.  */
702
703 static struct type *
704 get_base_type (struct type *type)
705 {
706   while (type != NULL && type->code () == TYPE_CODE_RANGE)
707     {
708       if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
709         return type;
710       type = TYPE_TARGET_TYPE (type);
711     }
712   return type;
713 }
714
715 /* Return a decoded version of the given VALUE.  This means returning
716    a value whose type is obtained by applying all the GNAT-specific
717    encodings, making the resulting type a static but standard description
718    of the initial type.  */
719
720 struct value *
721 ada_get_decoded_value (struct value *value)
722 {
723   struct type *type = ada_check_typedef (value_type (value));
724
725   if (ada_is_array_descriptor_type (type)
726       || (ada_is_constrained_packed_array_type (type)
727           && type->code () != TYPE_CODE_PTR))
728     {
729       if (type->code () == TYPE_CODE_TYPEDEF)  /* array access type.  */
730         value = ada_coerce_to_simple_array_ptr (value);
731       else
732         value = ada_coerce_to_simple_array (value);
733     }
734   else
735     value = ada_to_fixed_value (value);
736
737   return value;
738 }
739
740 /* Same as ada_get_decoded_value, but with the given TYPE.
741    Because there is no associated actual value for this type,
742    the resulting type might be a best-effort approximation in
743    the case of dynamic types.  */
744
745 struct type *
746 ada_get_decoded_type (struct type *type)
747 {
748   type = to_static_fixed_type (type);
749   if (ada_is_constrained_packed_array_type (type))
750     type = ada_coerce_to_simple_array_type (type);
751   return type;
752 }
753
754 \f
755
756                                 /* Language Selection */
757
758 /* If the main program is in Ada, return language_ada, otherwise return LANG
759    (the main program is in Ada iif the adainit symbol is found).  */
760
761 static enum language
762 ada_update_initial_language (enum language lang)
763 {
764   if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
765     return language_ada;
766
767   return lang;
768 }
769
770 /* If the main procedure is written in Ada, then return its name.
771    The result is good until the next call.  Return NULL if the main
772    procedure doesn't appear to be in Ada.  */
773
774 char *
775 ada_main_name (void)
776 {
777   struct bound_minimal_symbol msym;
778   static gdb::unique_xmalloc_ptr<char> main_program_name;
779
780   /* For Ada, the name of the main procedure is stored in a specific
781      string constant, generated by the binder.  Look for that symbol,
782      extract its address, and then read that string.  If we didn't find
783      that string, then most probably the main procedure is not written
784      in Ada.  */
785   msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
786
787   if (msym.minsym != NULL)
788     {
789       CORE_ADDR main_program_name_addr = BMSYMBOL_VALUE_ADDRESS (msym);
790       if (main_program_name_addr == 0)
791         error (_("Invalid address for Ada main program name."));
792
793       main_program_name = target_read_string (main_program_name_addr, 1024);
794       return main_program_name.get ();
795     }
796
797   /* The main procedure doesn't seem to be in Ada.  */
798   return NULL;
799 }
800 \f
801                                 /* Symbols */
802
803 /* Table of Ada operators and their GNAT-encoded names.  Last entry is pair
804    of NULLs.  */
805
806 const struct ada_opname_map ada_opname_table[] = {
807   {"Oadd", "\"+\"", BINOP_ADD},
808   {"Osubtract", "\"-\"", BINOP_SUB},
809   {"Omultiply", "\"*\"", BINOP_MUL},
810   {"Odivide", "\"/\"", BINOP_DIV},
811   {"Omod", "\"mod\"", BINOP_MOD},
812   {"Orem", "\"rem\"", BINOP_REM},
813   {"Oexpon", "\"**\"", BINOP_EXP},
814   {"Olt", "\"<\"", BINOP_LESS},
815   {"Ole", "\"<=\"", BINOP_LEQ},
816   {"Ogt", "\">\"", BINOP_GTR},
817   {"Oge", "\">=\"", BINOP_GEQ},
818   {"Oeq", "\"=\"", BINOP_EQUAL},
819   {"One", "\"/=\"", BINOP_NOTEQUAL},
820   {"Oand", "\"and\"", BINOP_BITWISE_AND},
821   {"Oor", "\"or\"", BINOP_BITWISE_IOR},
822   {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
823   {"Oconcat", "\"&\"", BINOP_CONCAT},
824   {"Oabs", "\"abs\"", UNOP_ABS},
825   {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
826   {"Oadd", "\"+\"", UNOP_PLUS},
827   {"Osubtract", "\"-\"", UNOP_NEG},
828   {NULL, NULL}
829 };
830
831 /* If STR is a decoded version of a compiler-provided suffix (like the
832    "[cold]" in "symbol[cold]"), return true.  Otherwise, return
833    false.  */
834
835 static bool
836 is_compiler_suffix (const char *str)
837 {
838   gdb_assert (*str == '[');
839   ++str;
840   while (*str != '\0' && isalpha (*str))
841     ++str;
842   /* We accept a missing "]" in order to support completion.  */
843   return *str == '\0' || (str[0] == ']' && str[1] == '\0');
844 }
845
846 /* The "encoded" form of DECODED, according to GNAT conventions.  If
847    THROW_ERRORS, throw an error if invalid operator name is found.
848    Otherwise, return the empty string in that case.  */
849
850 static std::string
851 ada_encode_1 (const char *decoded, bool throw_errors)
852 {
853   if (decoded == NULL)
854     return {};
855
856   std::string encoding_buffer;
857   for (const char *p = decoded; *p != '\0'; p += 1)
858     {
859       if (*p == '.')
860         encoding_buffer.append ("__");
861       else if (*p == '[' && is_compiler_suffix (p))
862         {
863           encoding_buffer = encoding_buffer + "." + (p + 1);
864           if (encoding_buffer.back () == ']')
865             encoding_buffer.pop_back ();
866           break;
867         }
868       else if (*p == '"')
869         {
870           const struct ada_opname_map *mapping;
871
872           for (mapping = ada_opname_table;
873                mapping->encoded != NULL
874                && !startswith (p, mapping->decoded); mapping += 1)
875             ;
876           if (mapping->encoded == NULL)
877             {
878               if (throw_errors)
879                 error (_("invalid Ada operator name: %s"), p);
880               else
881                 return {};
882             }
883           encoding_buffer.append (mapping->encoded);
884           break;
885         }
886       else
887         encoding_buffer.push_back (*p);
888     }
889
890   return encoding_buffer;
891 }
892
893 /* The "encoded" form of DECODED, according to GNAT conventions.  */
894
895 std::string
896 ada_encode (const char *decoded)
897 {
898   return ada_encode_1 (decoded, true);
899 }
900
901 /* Return NAME folded to lower case, or, if surrounded by single
902    quotes, unfolded, but with the quotes stripped away.  Result good
903    to next call.  */
904
905 static const char *
906 ada_fold_name (gdb::string_view name)
907 {
908   static std::string fold_storage;
909
910   if (!name.empty () && name[0] == '\'')
911     fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
912   else
913     {
914       fold_storage = gdb::to_string (name);
915       for (int i = 0; i < name.size (); i += 1)
916         fold_storage[i] = tolower (fold_storage[i]);
917     }
918
919   return fold_storage.c_str ();
920 }
921
922 /* Return nonzero if C is either a digit or a lowercase alphabet character.  */
923
924 static int
925 is_lower_alphanum (const char c)
926 {
927   return (isdigit (c) || (isalpha (c) && islower (c)));
928 }
929
930 /* ENCODED is the linkage name of a symbol and LEN contains its length.
931    This function saves in LEN the length of that same symbol name but
932    without either of these suffixes:
933      . .{DIGIT}+
934      . ${DIGIT}+
935      . ___{DIGIT}+
936      . __{DIGIT}+.
937
938    These are suffixes introduced by the compiler for entities such as
939    nested subprogram for instance, in order to avoid name clashes.
940    They do not serve any purpose for the debugger.  */
941
942 static void
943 ada_remove_trailing_digits (const char *encoded, int *len)
944 {
945   if (*len > 1 && isdigit (encoded[*len - 1]))
946     {
947       int i = *len - 2;
948
949       while (i > 0 && isdigit (encoded[i]))
950         i--;
951       if (i >= 0 && encoded[i] == '.')
952         *len = i;
953       else if (i >= 0 && encoded[i] == '$')
954         *len = i;
955       else if (i >= 2 && startswith (encoded + i - 2, "___"))
956         *len = i - 2;
957       else if (i >= 1 && startswith (encoded + i - 1, "__"))
958         *len = i - 1;
959     }
960 }
961
962 /* Remove the suffix introduced by the compiler for protected object
963    subprograms.  */
964
965 static void
966 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
967 {
968   /* Remove trailing N.  */
969
970   /* Protected entry subprograms are broken into two
971      separate subprograms: The first one is unprotected, and has
972      a 'N' suffix; the second is the protected version, and has
973      the 'P' suffix.  The second calls the first one after handling
974      the protection.  Since the P subprograms are internally generated,
975      we leave these names undecoded, giving the user a clue that this
976      entity is internal.  */
977
978   if (*len > 1
979       && encoded[*len - 1] == 'N'
980       && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
981     *len = *len - 1;
982 }
983
984 /* If ENCODED ends with a compiler-provided suffix (like ".cold"),
985    then update *LEN to remove the suffix and return the offset of the
986    character just past the ".".  Otherwise, return -1.  */
987
988 static int
989 remove_compiler_suffix (const char *encoded, int *len)
990 {
991   int offset = *len - 1;
992   while (offset > 0 && isalpha (encoded[offset]))
993     --offset;
994   if (offset > 0 && encoded[offset] == '.')
995     {
996       *len = offset;
997       return offset + 1;
998     }
999   return -1;
1000 }
1001
1002 /* See ada-lang.h.  */
1003
1004 std::string
1005 ada_decode (const char *encoded, bool wrap)
1006 {
1007   int i;
1008   int len0;
1009   const char *p;
1010   int at_start_name;
1011   std::string decoded;
1012   int suffix = -1;
1013
1014   /* With function descriptors on PPC64, the value of a symbol named
1015      ".FN", if it exists, is the entry point of the function "FN".  */
1016   if (encoded[0] == '.')
1017     encoded += 1;
1018
1019   /* The name of the Ada main procedure starts with "_ada_".
1020      This prefix is not part of the decoded name, so skip this part
1021      if we see this prefix.  */
1022   if (startswith (encoded, "_ada_"))
1023     encoded += 5;
1024
1025   /* If the name starts with '_', then it is not a properly encoded
1026      name, so do not attempt to decode it.  Similarly, if the name
1027      starts with '<', the name should not be decoded.  */
1028   if (encoded[0] == '_' || encoded[0] == '<')
1029     goto Suppress;
1030
1031   len0 = strlen (encoded);
1032
1033   suffix = remove_compiler_suffix (encoded, &len0);
1034
1035   ada_remove_trailing_digits (encoded, &len0);
1036   ada_remove_po_subprogram_suffix (encoded, &len0);
1037
1038   /* Remove the ___X.* suffix if present.  Do not forget to verify that
1039      the suffix is located before the current "end" of ENCODED.  We want
1040      to avoid re-matching parts of ENCODED that have previously been
1041      marked as discarded (by decrementing LEN0).  */
1042   p = strstr (encoded, "___");
1043   if (p != NULL && p - encoded < len0 - 3)
1044     {
1045       if (p[3] == 'X')
1046         len0 = p - encoded;
1047       else
1048         goto Suppress;
1049     }
1050
1051   /* Remove any trailing TKB suffix.  It tells us that this symbol
1052      is for the body of a task, but that information does not actually
1053      appear in the decoded name.  */
1054
1055   if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1056     len0 -= 3;
1057
1058   /* Remove any trailing TB suffix.  The TB suffix is slightly different
1059      from the TKB suffix because it is used for non-anonymous task
1060      bodies.  */
1061
1062   if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1063     len0 -= 2;
1064
1065   /* Remove trailing "B" suffixes.  */
1066   /* FIXME: brobecker/2006-04-19: Not sure what this are used for...  */
1067
1068   if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1069     len0 -= 1;
1070
1071   /* Remove trailing __{digit}+ or trailing ${digit}+.  */
1072
1073   if (len0 > 1 && isdigit (encoded[len0 - 1]))
1074     {
1075       i = len0 - 2;
1076       while ((i >= 0 && isdigit (encoded[i]))
1077              || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1078         i -= 1;
1079       if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1080         len0 = i - 1;
1081       else if (encoded[i] == '$')
1082         len0 = i;
1083     }
1084
1085   /* The first few characters that are not alphabetic are not part
1086      of any encoding we use, so we can copy them over verbatim.  */
1087
1088   for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1089     decoded.push_back (encoded[i]);
1090
1091   at_start_name = 1;
1092   while (i < len0)
1093     {
1094       /* Is this a symbol function?  */
1095       if (at_start_name && encoded[i] == 'O')
1096         {
1097           int k;
1098
1099           for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1100             {
1101               int op_len = strlen (ada_opname_table[k].encoded);
1102               if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1103                             op_len - 1) == 0)
1104                   && !isalnum (encoded[i + op_len]))
1105                 {
1106                   decoded.append (ada_opname_table[k].decoded);
1107                   at_start_name = 0;
1108                   i += op_len;
1109                   break;
1110                 }
1111             }
1112           if (ada_opname_table[k].encoded != NULL)
1113             continue;
1114         }
1115       at_start_name = 0;
1116
1117       /* Replace "TK__" with "__", which will eventually be translated
1118          into "." (just below).  */
1119
1120       if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1121         i += 2;
1122
1123       /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1124          be translated into "." (just below).  These are internal names
1125          generated for anonymous blocks inside which our symbol is nested.  */
1126
1127       if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1128           && encoded [i+2] == 'B' && encoded [i+3] == '_'
1129           && isdigit (encoded [i+4]))
1130         {
1131           int k = i + 5;
1132           
1133           while (k < len0 && isdigit (encoded[k]))
1134             k++;  /* Skip any extra digit.  */
1135
1136           /* Double-check that the "__B_{DIGITS}+" sequence we found
1137              is indeed followed by "__".  */
1138           if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1139             i = k;
1140         }
1141
1142       /* Remove _E{DIGITS}+[sb] */
1143
1144       /* Just as for protected object subprograms, there are 2 categories
1145          of subprograms created by the compiler for each entry.  The first
1146          one implements the actual entry code, and has a suffix following
1147          the convention above; the second one implements the barrier and
1148          uses the same convention as above, except that the 'E' is replaced
1149          by a 'B'.
1150
1151          Just as above, we do not decode the name of barrier functions
1152          to give the user a clue that the code he is debugging has been
1153          internally generated.  */
1154
1155       if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1156           && isdigit (encoded[i+2]))
1157         {
1158           int k = i + 3;
1159
1160           while (k < len0 && isdigit (encoded[k]))
1161             k++;
1162
1163           if (k < len0
1164               && (encoded[k] == 'b' || encoded[k] == 's'))
1165             {
1166               k++;
1167               /* Just as an extra precaution, make sure that if this
1168                  suffix is followed by anything else, it is a '_'.
1169                  Otherwise, we matched this sequence by accident.  */
1170               if (k == len0
1171                   || (k < len0 && encoded[k] == '_'))
1172                 i = k;
1173             }
1174         }
1175
1176       /* Remove trailing "N" in [a-z0-9]+N__.  The N is added by
1177          the GNAT front-end in protected object subprograms.  */
1178
1179       if (i < len0 + 3
1180           && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1181         {
1182           /* Backtrack a bit up until we reach either the begining of
1183              the encoded name, or "__".  Make sure that we only find
1184              digits or lowercase characters.  */
1185           const char *ptr = encoded + i - 1;
1186
1187           while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1188             ptr--;
1189           if (ptr < encoded
1190               || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1191             i++;
1192         }
1193
1194       if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1195         {
1196           /* This is a X[bn]* sequence not separated from the previous
1197              part of the name with a non-alpha-numeric character (in other
1198              words, immediately following an alpha-numeric character), then
1199              verify that it is placed at the end of the encoded name.  If
1200              not, then the encoding is not valid and we should abort the
1201              decoding.  Otherwise, just skip it, it is used in body-nested
1202              package names.  */
1203           do
1204             i += 1;
1205           while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1206           if (i < len0)
1207             goto Suppress;
1208         }
1209       else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1210         {
1211          /* Replace '__' by '.'.  */
1212           decoded.push_back ('.');
1213           at_start_name = 1;
1214           i += 2;
1215         }
1216       else
1217         {
1218           /* It's a character part of the decoded name, so just copy it
1219              over.  */
1220           decoded.push_back (encoded[i]);
1221           i += 1;
1222         }
1223     }
1224
1225   /* Decoded names should never contain any uppercase character.
1226      Double-check this, and abort the decoding if we find one.  */
1227
1228   for (i = 0; i < decoded.length(); ++i)
1229     if (isupper (decoded[i]) || decoded[i] == ' ')
1230       goto Suppress;
1231
1232   /* If the compiler added a suffix, append it now.  */
1233   if (suffix >= 0)
1234     decoded = decoded + "[" + &encoded[suffix] + "]";
1235
1236   return decoded;
1237
1238 Suppress:
1239   if (!wrap)
1240     return {};
1241
1242   if (encoded[0] == '<')
1243     decoded = encoded;
1244   else
1245     decoded = '<' + std::string(encoded) + '>';
1246   return decoded;
1247 }
1248
1249 /* Table for keeping permanent unique copies of decoded names.  Once
1250    allocated, names in this table are never released.  While this is a
1251    storage leak, it should not be significant unless there are massive
1252    changes in the set of decoded names in successive versions of a 
1253    symbol table loaded during a single session.  */
1254 static struct htab *decoded_names_store;
1255
1256 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1257    in the language-specific part of GSYMBOL, if it has not been
1258    previously computed.  Tries to save the decoded name in the same
1259    obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1260    in any case, the decoded symbol has a lifetime at least that of
1261    GSYMBOL).
1262    The GSYMBOL parameter is "mutable" in the C++ sense: logically
1263    const, but nevertheless modified to a semantically equivalent form
1264    when a decoded name is cached in it.  */
1265
1266 const char *
1267 ada_decode_symbol (const struct general_symbol_info *arg)
1268 {
1269   struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1270   const char **resultp =
1271     &gsymbol->language_specific.demangled_name;
1272
1273   if (!gsymbol->ada_mangled)
1274     {
1275       std::string decoded = ada_decode (gsymbol->linkage_name ());
1276       struct obstack *obstack = gsymbol->language_specific.obstack;
1277
1278       gsymbol->ada_mangled = 1;
1279
1280       if (obstack != NULL)
1281         *resultp = obstack_strdup (obstack, decoded.c_str ());
1282       else
1283         {
1284           /* Sometimes, we can't find a corresponding objfile, in
1285              which case, we put the result on the heap.  Since we only
1286              decode when needed, we hope this usually does not cause a
1287              significant memory leak (FIXME).  */
1288
1289           char **slot = (char **) htab_find_slot (decoded_names_store,
1290                                                   decoded.c_str (), INSERT);
1291
1292           if (*slot == NULL)
1293             *slot = xstrdup (decoded.c_str ());
1294           *resultp = *slot;
1295         }
1296     }
1297
1298   return *resultp;
1299 }
1300
1301 \f
1302
1303                                 /* Arrays */
1304
1305 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1306    generated by the GNAT compiler to describe the index type used
1307    for each dimension of an array, check whether it follows the latest
1308    known encoding.  If not, fix it up to conform to the latest encoding.
1309    Otherwise, do nothing.  This function also does nothing if
1310    INDEX_DESC_TYPE is NULL.
1311
1312    The GNAT encoding used to describe the array index type evolved a bit.
1313    Initially, the information would be provided through the name of each
1314    field of the structure type only, while the type of these fields was
1315    described as unspecified and irrelevant.  The debugger was then expected
1316    to perform a global type lookup using the name of that field in order
1317    to get access to the full index type description.  Because these global
1318    lookups can be very expensive, the encoding was later enhanced to make
1319    the global lookup unnecessary by defining the field type as being
1320    the full index type description.
1321
1322    The purpose of this routine is to allow us to support older versions
1323    of the compiler by detecting the use of the older encoding, and by
1324    fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1325    we essentially replace each field's meaningless type by the associated
1326    index subtype).  */
1327
1328 void
1329 ada_fixup_array_indexes_type (struct type *index_desc_type)
1330 {
1331   int i;
1332
1333   if (index_desc_type == NULL)
1334     return;
1335   gdb_assert (index_desc_type->num_fields () > 0);
1336
1337   /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1338      to check one field only, no need to check them all).  If not, return
1339      now.
1340
1341      If our INDEX_DESC_TYPE was generated using the older encoding,
1342      the field type should be a meaningless integer type whose name
1343      is not equal to the field name.  */
1344   if (index_desc_type->field (0).type ()->name () != NULL
1345       && strcmp (index_desc_type->field (0).type ()->name (),
1346                  index_desc_type->field (0).name ()) == 0)
1347     return;
1348
1349   /* Fixup each field of INDEX_DESC_TYPE.  */
1350   for (i = 0; i < index_desc_type->num_fields (); i++)
1351    {
1352      const char *name = index_desc_type->field (i).name ();
1353      struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1354
1355      if (raw_type)
1356        index_desc_type->field (i).set_type (raw_type);
1357    }
1358 }
1359
1360 /* The desc_* routines return primitive portions of array descriptors
1361    (fat pointers).  */
1362
1363 /* The descriptor or array type, if any, indicated by TYPE; removes
1364    level of indirection, if needed.  */
1365
1366 static struct type *
1367 desc_base_type (struct type *type)
1368 {
1369   if (type == NULL)
1370     return NULL;
1371   type = ada_check_typedef (type);
1372   if (type->code () == TYPE_CODE_TYPEDEF)
1373     type = ada_typedef_target_type (type);
1374
1375   if (type != NULL
1376       && (type->code () == TYPE_CODE_PTR
1377           || type->code () == TYPE_CODE_REF))
1378     return ada_check_typedef (TYPE_TARGET_TYPE (type));
1379   else
1380     return type;
1381 }
1382
1383 /* True iff TYPE indicates a "thin" array pointer type.  */
1384
1385 static int
1386 is_thin_pntr (struct type *type)
1387 {
1388   return
1389     is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1390     || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1391 }
1392
1393 /* The descriptor type for thin pointer type TYPE.  */
1394
1395 static struct type *
1396 thin_descriptor_type (struct type *type)
1397 {
1398   struct type *base_type = desc_base_type (type);
1399
1400   if (base_type == NULL)
1401     return NULL;
1402   if (is_suffix (ada_type_name (base_type), "___XVE"))
1403     return base_type;
1404   else
1405     {
1406       struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1407
1408       if (alt_type == NULL)
1409         return base_type;
1410       else
1411         return alt_type;
1412     }
1413 }
1414
1415 /* A pointer to the array data for thin-pointer value VAL.  */
1416
1417 static struct value *
1418 thin_data_pntr (struct value *val)
1419 {
1420   struct type *type = ada_check_typedef (value_type (val));
1421   struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1422
1423   data_type = lookup_pointer_type (data_type);
1424
1425   if (type->code () == TYPE_CODE_PTR)
1426     return value_cast (data_type, value_copy (val));
1427   else
1428     return value_from_longest (data_type, value_address (val));
1429 }
1430
1431 /* True iff TYPE indicates a "thick" array pointer type.  */
1432
1433 static int
1434 is_thick_pntr (struct type *type)
1435 {
1436   type = desc_base_type (type);
1437   return (type != NULL && type->code () == TYPE_CODE_STRUCT
1438           && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1439 }
1440
1441 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1442    pointer to one, the type of its bounds data; otherwise, NULL.  */
1443
1444 static struct type *
1445 desc_bounds_type (struct type *type)
1446 {
1447   struct type *r;
1448
1449   type = desc_base_type (type);
1450
1451   if (type == NULL)
1452     return NULL;
1453   else if (is_thin_pntr (type))
1454     {
1455       type = thin_descriptor_type (type);
1456       if (type == NULL)
1457         return NULL;
1458       r = lookup_struct_elt_type (type, "BOUNDS", 1);
1459       if (r != NULL)
1460         return ada_check_typedef (r);
1461     }
1462   else if (type->code () == TYPE_CODE_STRUCT)
1463     {
1464       r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1465       if (r != NULL)
1466         return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1467     }
1468   return NULL;
1469 }
1470
1471 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1472    one, a pointer to its bounds data.   Otherwise NULL.  */
1473
1474 static struct value *
1475 desc_bounds (struct value *arr)
1476 {
1477   struct type *type = ada_check_typedef (value_type (arr));
1478
1479   if (is_thin_pntr (type))
1480     {
1481       struct type *bounds_type =
1482         desc_bounds_type (thin_descriptor_type (type));
1483       LONGEST addr;
1484
1485       if (bounds_type == NULL)
1486         error (_("Bad GNAT array descriptor"));
1487
1488       /* NOTE: The following calculation is not really kosher, but
1489          since desc_type is an XVE-encoded type (and shouldn't be),
1490          the correct calculation is a real pain.  FIXME (and fix GCC).  */
1491       if (type->code () == TYPE_CODE_PTR)
1492         addr = value_as_long (arr);
1493       else
1494         addr = value_address (arr);
1495
1496       return
1497         value_from_longest (lookup_pointer_type (bounds_type),
1498                             addr - TYPE_LENGTH (bounds_type));
1499     }
1500
1501   else if (is_thick_pntr (type))
1502     {
1503       struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
1504                                                _("Bad GNAT array descriptor"));
1505       struct type *p_bounds_type = value_type (p_bounds);
1506
1507       if (p_bounds_type
1508           && p_bounds_type->code () == TYPE_CODE_PTR)
1509         {
1510           struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
1511
1512           if (target_type->is_stub ())
1513             p_bounds = value_cast (lookup_pointer_type
1514                                    (ada_check_typedef (target_type)),
1515                                    p_bounds);
1516         }
1517       else
1518         error (_("Bad GNAT array descriptor"));
1519
1520       return p_bounds;
1521     }
1522   else
1523     return NULL;
1524 }
1525
1526 /* If TYPE is the type of an array-descriptor (fat pointer),  the bit
1527    position of the field containing the address of the bounds data.  */
1528
1529 static int
1530 fat_pntr_bounds_bitpos (struct type *type)
1531 {
1532   return desc_base_type (type)->field (1).loc_bitpos ();
1533 }
1534
1535 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1536    size of the field containing the address of the bounds data.  */
1537
1538 static int
1539 fat_pntr_bounds_bitsize (struct type *type)
1540 {
1541   type = desc_base_type (type);
1542
1543   if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1544     return TYPE_FIELD_BITSIZE (type, 1);
1545   else
1546     return 8 * TYPE_LENGTH (ada_check_typedef (type->field (1).type ()));
1547 }
1548
1549 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1550    pointer to one, the type of its array data (a array-with-no-bounds type);
1551    otherwise, NULL.  Use ada_type_of_array to get an array type with bounds
1552    data.  */
1553
1554 static struct type *
1555 desc_data_target_type (struct type *type)
1556 {
1557   type = desc_base_type (type);
1558
1559   /* NOTE: The following is bogus; see comment in desc_bounds.  */
1560   if (is_thin_pntr (type))
1561     return desc_base_type (thin_descriptor_type (type)->field (1).type ());
1562   else if (is_thick_pntr (type))
1563     {
1564       struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1565
1566       if (data_type
1567           && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
1568         return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
1569     }
1570
1571   return NULL;
1572 }
1573
1574 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1575    its array data.  */
1576
1577 static struct value *
1578 desc_data (struct value *arr)
1579 {
1580   struct type *type = value_type (arr);
1581
1582   if (is_thin_pntr (type))
1583     return thin_data_pntr (arr);
1584   else if (is_thick_pntr (type))
1585     return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
1586                              _("Bad GNAT array descriptor"));
1587   else
1588     return NULL;
1589 }
1590
1591
1592 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1593    position of the field containing the address of the data.  */
1594
1595 static int
1596 fat_pntr_data_bitpos (struct type *type)
1597 {
1598   return desc_base_type (type)->field (0).loc_bitpos ();
1599 }
1600
1601 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1602    size of the field containing the address of the data.  */
1603
1604 static int
1605 fat_pntr_data_bitsize (struct type *type)
1606 {
1607   type = desc_base_type (type);
1608
1609   if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1610     return TYPE_FIELD_BITSIZE (type, 0);
1611   else
1612     return TARGET_CHAR_BIT * TYPE_LENGTH (type->field (0).type ());
1613 }
1614
1615 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1616    the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1617    bound, if WHICH is 1.  The first bound is I=1.  */
1618
1619 static struct value *
1620 desc_one_bound (struct value *bounds, int i, int which)
1621 {
1622   char bound_name[20];
1623   xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1624              which ? 'U' : 'L', i - 1);
1625   return value_struct_elt (&bounds, {}, bound_name, NULL,
1626                            _("Bad GNAT array descriptor bounds"));
1627 }
1628
1629 /* If BOUNDS is an array-bounds structure type, return the bit position
1630    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1631    bound, if WHICH is 1.  The first bound is I=1.  */
1632
1633 static int
1634 desc_bound_bitpos (struct type *type, int i, int which)
1635 {
1636   return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
1637 }
1638
1639 /* If BOUNDS is an array-bounds structure type, return the bit field size
1640    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1641    bound, if WHICH is 1.  The first bound is I=1.  */
1642
1643 static int
1644 desc_bound_bitsize (struct type *type, int i, int which)
1645 {
1646   type = desc_base_type (type);
1647
1648   if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1649     return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1650   else
1651     return 8 * TYPE_LENGTH (type->field (2 * i + which - 2).type ());
1652 }
1653
1654 /* If TYPE is the type of an array-bounds structure, the type of its
1655    Ith bound (numbering from 1).  Otherwise, NULL.  */
1656
1657 static struct type *
1658 desc_index_type (struct type *type, int i)
1659 {
1660   type = desc_base_type (type);
1661
1662   if (type->code () == TYPE_CODE_STRUCT)
1663     {
1664       char bound_name[20];
1665       xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
1666       return lookup_struct_elt_type (type, bound_name, 1);
1667     }
1668   else
1669     return NULL;
1670 }
1671
1672 /* The number of index positions in the array-bounds type TYPE.
1673    Return 0 if TYPE is NULL.  */
1674
1675 static int
1676 desc_arity (struct type *type)
1677 {
1678   type = desc_base_type (type);
1679
1680   if (type != NULL)
1681     return type->num_fields () / 2;
1682   return 0;
1683 }
1684
1685 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or 
1686    an array descriptor type (representing an unconstrained array
1687    type).  */
1688
1689 static int
1690 ada_is_direct_array_type (struct type *type)
1691 {
1692   if (type == NULL)
1693     return 0;
1694   type = ada_check_typedef (type);
1695   return (type->code () == TYPE_CODE_ARRAY
1696           || ada_is_array_descriptor_type (type));
1697 }
1698
1699 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
1700  * to one.  */
1701
1702 static int
1703 ada_is_array_type (struct type *type)
1704 {
1705   while (type != NULL
1706          && (type->code () == TYPE_CODE_PTR
1707              || type->code () == TYPE_CODE_REF))
1708     type = TYPE_TARGET_TYPE (type);
1709   return ada_is_direct_array_type (type);
1710 }
1711
1712 /* Non-zero iff TYPE is a simple array type or pointer to one.  */
1713
1714 int
1715 ada_is_simple_array_type (struct type *type)
1716 {
1717   if (type == NULL)
1718     return 0;
1719   type = ada_check_typedef (type);
1720   return (type->code () == TYPE_CODE_ARRAY
1721           || (type->code () == TYPE_CODE_PTR
1722               && (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ()
1723                   == TYPE_CODE_ARRAY)));
1724 }
1725
1726 /* Non-zero iff TYPE belongs to a GNAT array descriptor.  */
1727
1728 int
1729 ada_is_array_descriptor_type (struct type *type)
1730 {
1731   struct type *data_type = desc_data_target_type (type);
1732
1733   if (type == NULL)
1734     return 0;
1735   type = ada_check_typedef (type);
1736   return (data_type != NULL
1737           && data_type->code () == TYPE_CODE_ARRAY
1738           && desc_arity (desc_bounds_type (type)) > 0);
1739 }
1740
1741 /* Non-zero iff type is a partially mal-formed GNAT array
1742    descriptor.  FIXME: This is to compensate for some problems with
1743    debugging output from GNAT.  Re-examine periodically to see if it
1744    is still needed.  */
1745
1746 int
1747 ada_is_bogus_array_descriptor (struct type *type)
1748 {
1749   return
1750     type != NULL
1751     && type->code () == TYPE_CODE_STRUCT
1752     && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1753         || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1754     && !ada_is_array_descriptor_type (type);
1755 }
1756
1757
1758 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1759    (fat pointer) returns the type of the array data described---specifically,
1760    a pointer-to-array type.  If BOUNDS is non-zero, the bounds data are filled
1761    in from the descriptor; otherwise, they are left unspecified.  If
1762    the ARR denotes a null array descriptor and BOUNDS is non-zero,
1763    returns NULL.  The result is simply the type of ARR if ARR is not
1764    a descriptor.  */
1765
1766 static struct type *
1767 ada_type_of_array (struct value *arr, int bounds)
1768 {
1769   if (ada_is_constrained_packed_array_type (value_type (arr)))
1770     return decode_constrained_packed_array_type (value_type (arr));
1771
1772   if (!ada_is_array_descriptor_type (value_type (arr)))
1773     return value_type (arr);
1774
1775   if (!bounds)
1776     {
1777       struct type *array_type =
1778         ada_check_typedef (desc_data_target_type (value_type (arr)));
1779
1780       if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1781         TYPE_FIELD_BITSIZE (array_type, 0) =
1782           decode_packed_array_bitsize (value_type (arr));
1783       
1784       return array_type;
1785     }
1786   else
1787     {
1788       struct type *elt_type;
1789       int arity;
1790       struct value *descriptor;
1791
1792       elt_type = ada_array_element_type (value_type (arr), -1);
1793       arity = ada_array_arity (value_type (arr));
1794
1795       if (elt_type == NULL || arity == 0)
1796         return ada_check_typedef (value_type (arr));
1797
1798       descriptor = desc_bounds (arr);
1799       if (value_as_long (descriptor) == 0)
1800         return NULL;
1801       while (arity > 0)
1802         {
1803           struct type *range_type = alloc_type_copy (value_type (arr));
1804           struct type *array_type = alloc_type_copy (value_type (arr));
1805           struct value *low = desc_one_bound (descriptor, arity, 0);
1806           struct value *high = desc_one_bound (descriptor, arity, 1);
1807
1808           arity -= 1;
1809           create_static_range_type (range_type, value_type (low),
1810                                     longest_to_int (value_as_long (low)),
1811                                     longest_to_int (value_as_long (high)));
1812           elt_type = create_array_type (array_type, elt_type, range_type);
1813
1814           if (ada_is_unconstrained_packed_array_type (value_type (arr)))
1815             {
1816               /* We need to store the element packed bitsize, as well as
1817                  recompute the array size, because it was previously
1818                  computed based on the unpacked element size.  */
1819               LONGEST lo = value_as_long (low);
1820               LONGEST hi = value_as_long (high);
1821
1822               TYPE_FIELD_BITSIZE (elt_type, 0) =
1823                 decode_packed_array_bitsize (value_type (arr));
1824               /* If the array has no element, then the size is already
1825                  zero, and does not need to be recomputed.  */
1826               if (lo < hi)
1827                 {
1828                   int array_bitsize =
1829                         (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
1830
1831                   TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
1832                 }
1833             }
1834         }
1835
1836       return lookup_pointer_type (elt_type);
1837     }
1838 }
1839
1840 /* If ARR does not represent an array, returns ARR unchanged.
1841    Otherwise, returns either a standard GDB array with bounds set
1842    appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
1843    GDB array.  Returns NULL if ARR is a null fat pointer.  */
1844
1845 struct value *
1846 ada_coerce_to_simple_array_ptr (struct value *arr)
1847 {
1848   if (ada_is_array_descriptor_type (value_type (arr)))
1849     {
1850       struct type *arrType = ada_type_of_array (arr, 1);
1851
1852       if (arrType == NULL)
1853         return NULL;
1854       return value_cast (arrType, value_copy (desc_data (arr)));
1855     }
1856   else if (ada_is_constrained_packed_array_type (value_type (arr)))
1857     return decode_constrained_packed_array (arr);
1858   else
1859     return arr;
1860 }
1861
1862 /* If ARR does not represent an array, returns ARR unchanged.
1863    Otherwise, returns a standard GDB array describing ARR (which may
1864    be ARR itself if it already is in the proper form).  */
1865
1866 struct value *
1867 ada_coerce_to_simple_array (struct value *arr)
1868 {
1869   if (ada_is_array_descriptor_type (value_type (arr)))
1870     {
1871       struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
1872
1873       if (arrVal == NULL)
1874         error (_("Bounds unavailable for null array pointer."));
1875       return value_ind (arrVal);
1876     }
1877   else if (ada_is_constrained_packed_array_type (value_type (arr)))
1878     return decode_constrained_packed_array (arr);
1879   else
1880     return arr;
1881 }
1882
1883 /* If TYPE represents a GNAT array type, return it translated to an
1884    ordinary GDB array type (possibly with BITSIZE fields indicating
1885    packing).  For other types, is the identity.  */
1886
1887 struct type *
1888 ada_coerce_to_simple_array_type (struct type *type)
1889 {
1890   if (ada_is_constrained_packed_array_type (type))
1891     return decode_constrained_packed_array_type (type);
1892
1893   if (ada_is_array_descriptor_type (type))
1894     return ada_check_typedef (desc_data_target_type (type));
1895
1896   return type;
1897 }
1898
1899 /* Non-zero iff TYPE represents a standard GNAT packed-array type.  */
1900
1901 static int
1902 ada_is_gnat_encoded_packed_array_type  (struct type *type)
1903 {
1904   if (type == NULL)
1905     return 0;
1906   type = desc_base_type (type);
1907   type = ada_check_typedef (type);
1908   return
1909     ada_type_name (type) != NULL
1910     && strstr (ada_type_name (type), "___XP") != NULL;
1911 }
1912
1913 /* Non-zero iff TYPE represents a standard GNAT constrained
1914    packed-array type.  */
1915
1916 int
1917 ada_is_constrained_packed_array_type (struct type *type)
1918 {
1919   return ada_is_gnat_encoded_packed_array_type (type)
1920     && !ada_is_array_descriptor_type (type);
1921 }
1922
1923 /* Non-zero iff TYPE represents an array descriptor for a
1924    unconstrained packed-array type.  */
1925
1926 static int
1927 ada_is_unconstrained_packed_array_type (struct type *type)
1928 {
1929   if (!ada_is_array_descriptor_type (type))
1930     return 0;
1931
1932   if (ada_is_gnat_encoded_packed_array_type (type))
1933     return 1;
1934
1935   /* If we saw GNAT encodings, then the above code is sufficient.
1936      However, with minimal encodings, we will just have a thick
1937      pointer instead.  */
1938   if (is_thick_pntr (type))
1939     {
1940       type = desc_base_type (type);
1941       /* The structure's first field is a pointer to an array, so this
1942          fetches the array type.  */
1943       type = TYPE_TARGET_TYPE (type->field (0).type ());
1944       if (type->code () == TYPE_CODE_TYPEDEF)
1945         type = ada_typedef_target_type (type);
1946       /* Now we can see if the array elements are packed.  */
1947       return TYPE_FIELD_BITSIZE (type, 0) > 0;
1948     }
1949
1950   return 0;
1951 }
1952
1953 /* Return true if TYPE is a (Gnat-encoded) constrained packed array
1954    type, or if it is an ordinary (non-Gnat-encoded) packed array.  */
1955
1956 static bool
1957 ada_is_any_packed_array_type (struct type *type)
1958 {
1959   return (ada_is_constrained_packed_array_type (type)
1960           || (type->code () == TYPE_CODE_ARRAY
1961               && TYPE_FIELD_BITSIZE (type, 0) % 8 != 0));
1962 }
1963
1964 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
1965    return the size of its elements in bits.  */
1966
1967 static long
1968 decode_packed_array_bitsize (struct type *type)
1969 {
1970   const char *raw_name;
1971   const char *tail;
1972   long bits;
1973
1974   /* Access to arrays implemented as fat pointers are encoded as a typedef
1975      of the fat pointer type.  We need the name of the fat pointer type
1976      to do the decoding, so strip the typedef layer.  */
1977   if (type->code () == TYPE_CODE_TYPEDEF)
1978     type = ada_typedef_target_type (type);
1979
1980   raw_name = ada_type_name (ada_check_typedef (type));
1981   if (!raw_name)
1982     raw_name = ada_type_name (desc_base_type (type));
1983
1984   if (!raw_name)
1985     return 0;
1986
1987   tail = strstr (raw_name, "___XP");
1988   if (tail == nullptr)
1989     {
1990       gdb_assert (is_thick_pntr (type));
1991       /* The structure's first field is a pointer to an array, so this
1992          fetches the array type.  */
1993       type = TYPE_TARGET_TYPE (type->field (0).type ());
1994       /* Now we can see if the array elements are packed.  */
1995       return TYPE_FIELD_BITSIZE (type, 0);
1996     }
1997
1998   if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
1999     {
2000       lim_warning
2001         (_("could not understand bit size information on packed array"));
2002       return 0;
2003     }
2004
2005   return bits;
2006 }
2007
2008 /* Given that TYPE is a standard GDB array type with all bounds filled
2009    in, and that the element size of its ultimate scalar constituents
2010    (that is, either its elements, or, if it is an array of arrays, its
2011    elements' elements, etc.) is *ELT_BITS, return an identical type,
2012    but with the bit sizes of its elements (and those of any
2013    constituent arrays) recorded in the BITSIZE components of its
2014    TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2015    in bits.
2016
2017    Note that, for arrays whose index type has an XA encoding where
2018    a bound references a record discriminant, getting that discriminant,
2019    and therefore the actual value of that bound, is not possible
2020    because none of the given parameters gives us access to the record.
2021    This function assumes that it is OK in the context where it is being
2022    used to return an array whose bounds are still dynamic and where
2023    the length is arbitrary.  */
2024
2025 static struct type *
2026 constrained_packed_array_type (struct type *type, long *elt_bits)
2027 {
2028   struct type *new_elt_type;
2029   struct type *new_type;
2030   struct type *index_type_desc;
2031   struct type *index_type;
2032   LONGEST low_bound, high_bound;
2033
2034   type = ada_check_typedef (type);
2035   if (type->code () != TYPE_CODE_ARRAY)
2036     return type;
2037
2038   index_type_desc = ada_find_parallel_type (type, "___XA");
2039   if (index_type_desc)
2040     index_type = to_fixed_range_type (index_type_desc->field (0).type (),
2041                                       NULL);
2042   else
2043     index_type = type->index_type ();
2044
2045   new_type = alloc_type_copy (type);
2046   new_elt_type =
2047     constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
2048                                    elt_bits);
2049   create_array_type (new_type, new_elt_type, index_type);
2050   TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2051   new_type->set_name (ada_type_name (type));
2052
2053   if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
2054        && is_dynamic_type (check_typedef (index_type)))
2055       || !get_discrete_bounds (index_type, &low_bound, &high_bound))
2056     low_bound = high_bound = 0;
2057   if (high_bound < low_bound)
2058     *elt_bits = TYPE_LENGTH (new_type) = 0;
2059   else
2060     {
2061       *elt_bits *= (high_bound - low_bound + 1);
2062       TYPE_LENGTH (new_type) =
2063         (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2064     }
2065
2066   new_type->set_is_fixed_instance (true);
2067   return new_type;
2068 }
2069
2070 /* The array type encoded by TYPE, where
2071    ada_is_constrained_packed_array_type (TYPE).  */
2072
2073 static struct type *
2074 decode_constrained_packed_array_type (struct type *type)
2075 {
2076   const char *raw_name = ada_type_name (ada_check_typedef (type));
2077   char *name;
2078   const char *tail;
2079   struct type *shadow_type;
2080   long bits;
2081
2082   if (!raw_name)
2083     raw_name = ada_type_name (desc_base_type (type));
2084
2085   if (!raw_name)
2086     return NULL;
2087
2088   name = (char *) alloca (strlen (raw_name) + 1);
2089   tail = strstr (raw_name, "___XP");
2090   type = desc_base_type (type);
2091
2092   memcpy (name, raw_name, tail - raw_name);
2093   name[tail - raw_name] = '\000';
2094
2095   shadow_type = ada_find_parallel_type_with_name (type, name);
2096
2097   if (shadow_type == NULL)
2098     {
2099       lim_warning (_("could not find bounds information on packed array"));
2100       return NULL;
2101     }
2102   shadow_type = check_typedef (shadow_type);
2103
2104   if (shadow_type->code () != TYPE_CODE_ARRAY)
2105     {
2106       lim_warning (_("could not understand bounds "
2107                      "information on packed array"));
2108       return NULL;
2109     }
2110
2111   bits = decode_packed_array_bitsize (type);
2112   return constrained_packed_array_type (shadow_type, &bits);
2113 }
2114
2115 /* Helper function for decode_constrained_packed_array.  Set the field
2116    bitsize on a series of packed arrays.  Returns the number of
2117    elements in TYPE.  */
2118
2119 static LONGEST
2120 recursively_update_array_bitsize (struct type *type)
2121 {
2122   gdb_assert (type->code () == TYPE_CODE_ARRAY);
2123
2124   LONGEST low, high;
2125   if (!get_discrete_bounds (type->index_type (), &low, &high)
2126       || low > high)
2127     return 0;
2128   LONGEST our_len = high - low + 1;
2129
2130   struct type *elt_type = TYPE_TARGET_TYPE (type);
2131   if (elt_type->code () == TYPE_CODE_ARRAY)
2132     {
2133       LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2134       LONGEST elt_bitsize = elt_len * TYPE_FIELD_BITSIZE (elt_type, 0);
2135       TYPE_FIELD_BITSIZE (type, 0) = elt_bitsize;
2136
2137       TYPE_LENGTH (type) = ((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2138                             / HOST_CHAR_BIT);
2139     }
2140
2141   return our_len;
2142 }
2143
2144 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2145    array, returns a simple array that denotes that array.  Its type is a
2146    standard GDB array type except that the BITSIZEs of the array
2147    target types are set to the number of bits in each element, and the
2148    type length is set appropriately.  */
2149
2150 static struct value *
2151 decode_constrained_packed_array (struct value *arr)
2152 {
2153   struct type *type;
2154
2155   /* If our value is a pointer, then dereference it. Likewise if
2156      the value is a reference.  Make sure that this operation does not
2157      cause the target type to be fixed, as this would indirectly cause
2158      this array to be decoded.  The rest of the routine assumes that
2159      the array hasn't been decoded yet, so we use the basic "coerce_ref"
2160      and "value_ind" routines to perform the dereferencing, as opposed
2161      to using "ada_coerce_ref" or "ada_value_ind".  */
2162   arr = coerce_ref (arr);
2163   if (ada_check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2164     arr = value_ind (arr);
2165
2166   type = decode_constrained_packed_array_type (value_type (arr));
2167   if (type == NULL)
2168     {
2169       error (_("can't unpack array"));
2170       return NULL;
2171     }
2172
2173   /* Decoding the packed array type could not correctly set the field
2174      bitsizes for any dimension except the innermost, because the
2175      bounds may be variable and were not passed to that function.  So,
2176      we further resolve the array bounds here and then update the
2177      sizes.  */
2178   const gdb_byte *valaddr = value_contents_for_printing (arr).data ();
2179   CORE_ADDR address = value_address (arr);
2180   gdb::array_view<const gdb_byte> view
2181     = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
2182   type = resolve_dynamic_type (type, view, address);
2183   recursively_update_array_bitsize (type);
2184
2185   if (type_byte_order (value_type (arr)) == BFD_ENDIAN_BIG
2186       && ada_is_modular_type (value_type (arr)))
2187     {
2188        /* This is a (right-justified) modular type representing a packed
2189           array with no wrapper.  In order to interpret the value through
2190           the (left-justified) packed array type we just built, we must
2191           first left-justify it.  */
2192       int bit_size, bit_pos;
2193       ULONGEST mod;
2194
2195       mod = ada_modulus (value_type (arr)) - 1;
2196       bit_size = 0;
2197       while (mod > 0)
2198         {
2199           bit_size += 1;
2200           mod >>= 1;
2201         }
2202       bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
2203       arr = ada_value_primitive_packed_val (arr, NULL,
2204                                             bit_pos / HOST_CHAR_BIT,
2205                                             bit_pos % HOST_CHAR_BIT,
2206                                             bit_size,
2207                                             type);
2208     }
2209
2210   return coerce_unspec_val_to_type (arr, type);
2211 }
2212
2213
2214 /* The value of the element of packed array ARR at the ARITY indices
2215    given in IND.   ARR must be a simple array.  */
2216
2217 static struct value *
2218 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2219 {
2220   int i;
2221   int bits, elt_off, bit_off;
2222   long elt_total_bit_offset;
2223   struct type *elt_type;
2224   struct value *v;
2225
2226   bits = 0;
2227   elt_total_bit_offset = 0;
2228   elt_type = ada_check_typedef (value_type (arr));
2229   for (i = 0; i < arity; i += 1)
2230     {
2231       if (elt_type->code () != TYPE_CODE_ARRAY
2232           || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2233         error
2234           (_("attempt to do packed indexing of "
2235              "something other than a packed array"));
2236       else
2237         {
2238           struct type *range_type = elt_type->index_type ();
2239           LONGEST lowerbound, upperbound;
2240           LONGEST idx;
2241
2242           if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
2243             {
2244               lim_warning (_("don't know bounds of array"));
2245               lowerbound = upperbound = 0;
2246             }
2247
2248           idx = pos_atr (ind[i]);
2249           if (idx < lowerbound || idx > upperbound)
2250             lim_warning (_("packed array index %ld out of bounds"),
2251                          (long) idx);
2252           bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2253           elt_total_bit_offset += (idx - lowerbound) * bits;
2254           elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
2255         }
2256     }
2257   elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2258   bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2259
2260   v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2261                                       bits, elt_type);
2262   return v;
2263 }
2264
2265 /* Non-zero iff TYPE includes negative integer values.  */
2266
2267 static int
2268 has_negatives (struct type *type)
2269 {
2270   switch (type->code ())
2271     {
2272     default:
2273       return 0;
2274     case TYPE_CODE_INT:
2275       return !type->is_unsigned ();
2276     case TYPE_CODE_RANGE:
2277       return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
2278     }
2279 }
2280
2281 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2282    unpack that data into UNPACKED.  UNPACKED_LEN is the size in bytes of
2283    the unpacked buffer.
2284
2285    The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2286    enough to contain at least BIT_OFFSET bits.  If not, an error is raised.
2287
2288    IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2289    zero otherwise.
2290
2291    IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2292
2293    IS_SCALAR is nonzero if the data corresponds to a signed type.  */
2294
2295 static void
2296 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2297                           gdb_byte *unpacked, int unpacked_len,
2298                           int is_big_endian, int is_signed_type,
2299                           int is_scalar)
2300 {
2301   int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2302   int src_idx;                  /* Index into the source area */
2303   int src_bytes_left;           /* Number of source bytes left to process.  */
2304   int srcBitsLeft;              /* Number of source bits left to move */
2305   int unusedLS;                 /* Number of bits in next significant
2306                                    byte of source that are unused */
2307
2308   int unpacked_idx;             /* Index into the unpacked buffer */
2309   int unpacked_bytes_left;      /* Number of bytes left to set in unpacked.  */
2310
2311   unsigned long accum;          /* Staging area for bits being transferred */
2312   int accumSize;                /* Number of meaningful bits in accum */
2313   unsigned char sign;
2314
2315   /* Transmit bytes from least to most significant; delta is the direction
2316      the indices move.  */
2317   int delta = is_big_endian ? -1 : 1;
2318
2319   /* Make sure that unpacked is large enough to receive the BIT_SIZE
2320      bits from SRC.  .*/
2321   if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2322     error (_("Cannot unpack %d bits into buffer of %d bytes"),
2323            bit_size, unpacked_len);
2324
2325   srcBitsLeft = bit_size;
2326   src_bytes_left = src_len;
2327   unpacked_bytes_left = unpacked_len;
2328   sign = 0;
2329
2330   if (is_big_endian)
2331     {
2332       src_idx = src_len - 1;
2333       if (is_signed_type
2334           && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2335         sign = ~0;
2336
2337       unusedLS =
2338         (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2339         % HOST_CHAR_BIT;
2340
2341       if (is_scalar)
2342         {
2343           accumSize = 0;
2344           unpacked_idx = unpacked_len - 1;
2345         }
2346       else
2347         {
2348           /* Non-scalar values must be aligned at a byte boundary...  */
2349           accumSize =
2350             (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2351           /* ... And are placed at the beginning (most-significant) bytes
2352              of the target.  */
2353           unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2354           unpacked_bytes_left = unpacked_idx + 1;
2355         }
2356     }
2357   else
2358     {
2359       int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2360
2361       src_idx = unpacked_idx = 0;
2362       unusedLS = bit_offset;
2363       accumSize = 0;
2364
2365       if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2366         sign = ~0;
2367     }
2368
2369   accum = 0;
2370   while (src_bytes_left > 0)
2371     {
2372       /* Mask for removing bits of the next source byte that are not
2373          part of the value.  */
2374       unsigned int unusedMSMask =
2375         (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2376         1;
2377       /* Sign-extend bits for this byte.  */
2378       unsigned int signMask = sign & ~unusedMSMask;
2379
2380       accum |=
2381         (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2382       accumSize += HOST_CHAR_BIT - unusedLS;
2383       if (accumSize >= HOST_CHAR_BIT)
2384         {
2385           unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2386           accumSize -= HOST_CHAR_BIT;
2387           accum >>= HOST_CHAR_BIT;
2388           unpacked_bytes_left -= 1;
2389           unpacked_idx += delta;
2390         }
2391       srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2392       unusedLS = 0;
2393       src_bytes_left -= 1;
2394       src_idx += delta;
2395     }
2396   while (unpacked_bytes_left > 0)
2397     {
2398       accum |= sign << accumSize;
2399       unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2400       accumSize -= HOST_CHAR_BIT;
2401       if (accumSize < 0)
2402         accumSize = 0;
2403       accum >>= HOST_CHAR_BIT;
2404       unpacked_bytes_left -= 1;
2405       unpacked_idx += delta;
2406     }
2407 }
2408
2409 /* Create a new value of type TYPE from the contents of OBJ starting
2410    at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2411    proceeding for BIT_SIZE bits.  If OBJ is an lval in memory, then
2412    assigning through the result will set the field fetched from.
2413    VALADDR is ignored unless OBJ is NULL, in which case,
2414    VALADDR+OFFSET must address the start of storage containing the 
2415    packed value.  The value returned  in this case is never an lval.
2416    Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT.  */
2417
2418 struct value *
2419 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2420                                 long offset, int bit_offset, int bit_size,
2421                                 struct type *type)
2422 {
2423   struct value *v;
2424   const gdb_byte *src;                /* First byte containing data to unpack */
2425   gdb_byte *unpacked;
2426   const int is_scalar = is_scalar_type (type);
2427   const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2428   gdb::byte_vector staging;
2429
2430   type = ada_check_typedef (type);
2431
2432   if (obj == NULL)
2433     src = valaddr + offset;
2434   else
2435     src = value_contents (obj).data () + offset;
2436
2437   if (is_dynamic_type (type))
2438     {
2439       /* The length of TYPE might by dynamic, so we need to resolve
2440          TYPE in order to know its actual size, which we then use
2441          to create the contents buffer of the value we return.
2442          The difficulty is that the data containing our object is
2443          packed, and therefore maybe not at a byte boundary.  So, what
2444          we do, is unpack the data into a byte-aligned buffer, and then
2445          use that buffer as our object's value for resolving the type.  */
2446       int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2447       staging.resize (staging_len);
2448
2449       ada_unpack_from_contents (src, bit_offset, bit_size,
2450                                 staging.data (), staging.size (),
2451                                 is_big_endian, has_negatives (type),
2452                                 is_scalar);
2453       type = resolve_dynamic_type (type, staging, 0);
2454       if (TYPE_LENGTH (type) < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2455         {
2456           /* This happens when the length of the object is dynamic,
2457              and is actually smaller than the space reserved for it.
2458              For instance, in an array of variant records, the bit_size
2459              we're given is the array stride, which is constant and
2460              normally equal to the maximum size of its element.
2461              But, in reality, each element only actually spans a portion
2462              of that stride.  */
2463           bit_size = TYPE_LENGTH (type) * HOST_CHAR_BIT;
2464         }
2465     }
2466
2467   if (obj == NULL)
2468     {
2469       v = allocate_value (type);
2470       src = valaddr + offset;
2471     }
2472   else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2473     {
2474       int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2475       gdb_byte *buf;
2476
2477       v = value_at (type, value_address (obj) + offset);
2478       buf = (gdb_byte *) alloca (src_len);
2479       read_memory (value_address (v), buf, src_len);
2480       src = buf;
2481     }
2482   else
2483     {
2484       v = allocate_value (type);
2485       src = value_contents (obj).data () + offset;
2486     }
2487
2488   if (obj != NULL)
2489     {
2490       long new_offset = offset;
2491
2492       set_value_component_location (v, obj);
2493       set_value_bitpos (v, bit_offset + value_bitpos (obj));
2494       set_value_bitsize (v, bit_size);
2495       if (value_bitpos (v) >= HOST_CHAR_BIT)
2496         {
2497           ++new_offset;
2498           set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2499         }
2500       set_value_offset (v, new_offset);
2501
2502       /* Also set the parent value.  This is needed when trying to
2503          assign a new value (in inferior memory).  */
2504       set_value_parent (v, obj);
2505     }
2506   else
2507     set_value_bitsize (v, bit_size);
2508   unpacked = value_contents_writeable (v).data ();
2509
2510   if (bit_size == 0)
2511     {
2512       memset (unpacked, 0, TYPE_LENGTH (type));
2513       return v;
2514     }
2515
2516   if (staging.size () == TYPE_LENGTH (type))
2517     {
2518       /* Small short-cut: If we've unpacked the data into a buffer
2519          of the same size as TYPE's length, then we can reuse that,
2520          instead of doing the unpacking again.  */
2521       memcpy (unpacked, staging.data (), staging.size ());
2522     }
2523   else
2524     ada_unpack_from_contents (src, bit_offset, bit_size,
2525                               unpacked, TYPE_LENGTH (type),
2526                               is_big_endian, has_negatives (type), is_scalar);
2527
2528   return v;
2529 }
2530
2531 /* Store the contents of FROMVAL into the location of TOVAL.
2532    Return a new value with the location of TOVAL and contents of
2533    FROMVAL.   Handles assignment into packed fields that have
2534    floating-point or non-scalar types.  */
2535
2536 static struct value *
2537 ada_value_assign (struct value *toval, struct value *fromval)
2538 {
2539   struct type *type = value_type (toval);
2540   int bits = value_bitsize (toval);
2541
2542   toval = ada_coerce_ref (toval);
2543   fromval = ada_coerce_ref (fromval);
2544
2545   if (ada_is_direct_array_type (value_type (toval)))
2546     toval = ada_coerce_to_simple_array (toval);
2547   if (ada_is_direct_array_type (value_type (fromval)))
2548     fromval = ada_coerce_to_simple_array (fromval);
2549
2550   if (!deprecated_value_modifiable (toval))
2551     error (_("Left operand of assignment is not a modifiable lvalue."));
2552
2553   if (VALUE_LVAL (toval) == lval_memory
2554       && bits > 0
2555       && (type->code () == TYPE_CODE_FLT
2556           || type->code () == TYPE_CODE_STRUCT))
2557     {
2558       int len = (value_bitpos (toval)
2559                  + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2560       int from_size;
2561       gdb_byte *buffer = (gdb_byte *) alloca (len);
2562       struct value *val;
2563       CORE_ADDR to_addr = value_address (toval);
2564
2565       if (type->code () == TYPE_CODE_FLT)
2566         fromval = value_cast (type, fromval);
2567
2568       read_memory (to_addr, buffer, len);
2569       from_size = value_bitsize (fromval);
2570       if (from_size == 0)
2571         from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2572
2573       const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
2574       ULONGEST from_offset = 0;
2575       if (is_big_endian && is_scalar_type (value_type (fromval)))
2576         from_offset = from_size - bits;
2577       copy_bitwise (buffer, value_bitpos (toval),
2578                     value_contents (fromval).data (), from_offset,
2579                     bits, is_big_endian);
2580       write_memory_with_notification (to_addr, buffer, len);
2581
2582       val = value_copy (toval);
2583       memcpy (value_contents_raw (val).data (),
2584               value_contents (fromval).data (),
2585               TYPE_LENGTH (type));
2586       deprecated_set_value_type (val, type);
2587
2588       return val;
2589     }
2590
2591   return value_assign (toval, fromval);
2592 }
2593
2594
2595 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2596    CONTAINER, assign the contents of VAL to COMPONENTS's place in
2597    CONTAINER.  Modifies the VALUE_CONTENTS of CONTAINER only, not
2598    COMPONENT, and not the inferior's memory.  The current contents
2599    of COMPONENT are ignored.
2600
2601    Although not part of the initial design, this function also works
2602    when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2603    had a null address, and COMPONENT had an address which is equal to
2604    its offset inside CONTAINER.  */
2605
2606 static void
2607 value_assign_to_component (struct value *container, struct value *component,
2608                            struct value *val)
2609 {
2610   LONGEST offset_in_container =
2611     (LONGEST)  (value_address (component) - value_address (container));
2612   int bit_offset_in_container =
2613     value_bitpos (component) - value_bitpos (container);
2614   int bits;
2615
2616   val = value_cast (value_type (component), val);
2617
2618   if (value_bitsize (component) == 0)
2619     bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2620   else
2621     bits = value_bitsize (component);
2622
2623   if (type_byte_order (value_type (container)) == BFD_ENDIAN_BIG)
2624     {
2625       int src_offset;
2626
2627       if (is_scalar_type (check_typedef (value_type (component))))
2628         src_offset
2629           = TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits;
2630       else
2631         src_offset = 0;
2632       copy_bitwise ((value_contents_writeable (container).data ()
2633                      + offset_in_container),
2634                     value_bitpos (container) + bit_offset_in_container,
2635                     value_contents (val).data (), src_offset, bits, 1);
2636     }
2637   else
2638     copy_bitwise ((value_contents_writeable (container).data ()
2639                    + offset_in_container),
2640                   value_bitpos (container) + bit_offset_in_container,
2641                   value_contents (val).data (), 0, bits, 0);
2642 }
2643
2644 /* Determine if TYPE is an access to an unconstrained array.  */
2645
2646 bool
2647 ada_is_access_to_unconstrained_array (struct type *type)
2648 {
2649   return (type->code () == TYPE_CODE_TYPEDEF
2650           && is_thick_pntr (ada_typedef_target_type (type)));
2651 }
2652
2653 /* The value of the element of array ARR at the ARITY indices given in IND.
2654    ARR may be either a simple array, GNAT array descriptor, or pointer
2655    thereto.  */
2656
2657 struct value *
2658 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2659 {
2660   int k;
2661   struct value *elt;
2662   struct type *elt_type;
2663
2664   elt = ada_coerce_to_simple_array (arr);
2665
2666   elt_type = ada_check_typedef (value_type (elt));
2667   if (elt_type->code () == TYPE_CODE_ARRAY
2668       && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2669     return value_subscript_packed (elt, arity, ind);
2670
2671   for (k = 0; k < arity; k += 1)
2672     {
2673       struct type *saved_elt_type = TYPE_TARGET_TYPE (elt_type);
2674
2675       if (elt_type->code () != TYPE_CODE_ARRAY)
2676         error (_("too many subscripts (%d expected)"), k);
2677
2678       elt = value_subscript (elt, pos_atr (ind[k]));
2679
2680       if (ada_is_access_to_unconstrained_array (saved_elt_type)
2681           && value_type (elt)->code () != TYPE_CODE_TYPEDEF)
2682         {
2683           /* The element is a typedef to an unconstrained array,
2684              except that the value_subscript call stripped the
2685              typedef layer.  The typedef layer is GNAT's way to
2686              specify that the element is, at the source level, an
2687              access to the unconstrained array, rather than the
2688              unconstrained array.  So, we need to restore that
2689              typedef layer, which we can do by forcing the element's
2690              type back to its original type. Otherwise, the returned
2691              value is going to be printed as the array, rather
2692              than as an access.  Another symptom of the same issue
2693              would be that an expression trying to dereference the
2694              element would also be improperly rejected.  */
2695           deprecated_set_value_type (elt, saved_elt_type);
2696         }
2697
2698       elt_type = ada_check_typedef (value_type (elt));
2699     }
2700
2701   return elt;
2702 }
2703
2704 /* Assuming ARR is a pointer to a GDB array, the value of the element
2705    of *ARR at the ARITY indices given in IND.
2706    Does not read the entire array into memory.
2707
2708    Note: Unlike what one would expect, this function is used instead of
2709    ada_value_subscript for basically all non-packed array types.  The reason
2710    for this is that a side effect of doing our own pointer arithmetics instead
2711    of relying on value_subscript is that there is no implicit typedef peeling.
2712    This is important for arrays of array accesses, where it allows us to
2713    preserve the fact that the array's element is an array access, where the
2714    access part os encoded in a typedef layer.  */
2715
2716 static struct value *
2717 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
2718 {
2719   int k;
2720   struct value *array_ind = ada_value_ind (arr);
2721   struct type *type
2722     = check_typedef (value_enclosing_type (array_ind));
2723
2724   if (type->code () == TYPE_CODE_ARRAY
2725       && TYPE_FIELD_BITSIZE (type, 0) > 0)
2726     return value_subscript_packed (array_ind, arity, ind);
2727
2728   for (k = 0; k < arity; k += 1)
2729     {
2730       LONGEST lwb, upb;
2731
2732       if (type->code () != TYPE_CODE_ARRAY)
2733         error (_("too many subscripts (%d expected)"), k);
2734       arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2735                         value_copy (arr));
2736       get_discrete_bounds (type->index_type (), &lwb, &upb);
2737       arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
2738       type = TYPE_TARGET_TYPE (type);
2739     }
2740
2741   return value_ind (arr);
2742 }
2743
2744 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2745    actual type of ARRAY_PTR is ignored), returns the Ada slice of
2746    HIGH'Pos-LOW'Pos+1 elements starting at index LOW.  The lower bound of
2747    this array is LOW, as per Ada rules.  */
2748 static struct value *
2749 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
2750                           int low, int high)
2751 {
2752   struct type *type0 = ada_check_typedef (type);
2753   struct type *base_index_type = TYPE_TARGET_TYPE (type0->index_type ());
2754   struct type *index_type
2755     = create_static_range_type (NULL, base_index_type, low, high);
2756   struct type *slice_type = create_array_type_with_stride
2757                               (NULL, TYPE_TARGET_TYPE (type0), index_type,
2758                                type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
2759                                TYPE_FIELD_BITSIZE (type0, 0));
2760   int base_low =  ada_discrete_type_low_bound (type0->index_type ());
2761   gdb::optional<LONGEST> base_low_pos, low_pos;
2762   CORE_ADDR base;
2763
2764   low_pos = discrete_position (base_index_type, low);
2765   base_low_pos = discrete_position (base_index_type, base_low);
2766
2767   if (!low_pos.has_value () || !base_low_pos.has_value ())
2768     {
2769       warning (_("unable to get positions in slice, use bounds instead"));
2770       low_pos = low;
2771       base_low_pos = base_low;
2772     }
2773
2774   ULONGEST stride = TYPE_FIELD_BITSIZE (slice_type, 0) / 8;
2775   if (stride == 0)
2776     stride = TYPE_LENGTH (TYPE_TARGET_TYPE (type0));
2777
2778   base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
2779   return value_at_lazy (slice_type, base);
2780 }
2781
2782
2783 static struct value *
2784 ada_value_slice (struct value *array, int low, int high)
2785 {
2786   struct type *type = ada_check_typedef (value_type (array));
2787   struct type *base_index_type = TYPE_TARGET_TYPE (type->index_type ());
2788   struct type *index_type
2789     = create_static_range_type (NULL, type->index_type (), low, high);
2790   struct type *slice_type = create_array_type_with_stride
2791                               (NULL, TYPE_TARGET_TYPE (type), index_type,
2792                                type->dyn_prop (DYN_PROP_BYTE_STRIDE),
2793                                TYPE_FIELD_BITSIZE (type, 0));
2794   gdb::optional<LONGEST> low_pos, high_pos;
2795
2796
2797   low_pos = discrete_position (base_index_type, low);
2798   high_pos = discrete_position (base_index_type, high);
2799
2800   if (!low_pos.has_value () || !high_pos.has_value ())
2801     {
2802       warning (_("unable to get positions in slice, use bounds instead"));
2803       low_pos = low;
2804       high_pos = high;
2805     }
2806
2807   return value_cast (slice_type,
2808                      value_slice (array, low, *high_pos - *low_pos + 1));
2809 }
2810
2811 /* If type is a record type in the form of a standard GNAT array
2812    descriptor, returns the number of dimensions for type.  If arr is a
2813    simple array, returns the number of "array of"s that prefix its
2814    type designation.  Otherwise, returns 0.  */
2815
2816 int
2817 ada_array_arity (struct type *type)
2818 {
2819   int arity;
2820
2821   if (type == NULL)
2822     return 0;
2823
2824   type = desc_base_type (type);
2825
2826   arity = 0;
2827   if (type->code () == TYPE_CODE_STRUCT)
2828     return desc_arity (desc_bounds_type (type));
2829   else
2830     while (type->code () == TYPE_CODE_ARRAY)
2831       {
2832         arity += 1;
2833         type = ada_check_typedef (TYPE_TARGET_TYPE (type));
2834       }
2835
2836   return arity;
2837 }
2838
2839 /* If TYPE is a record type in the form of a standard GNAT array
2840    descriptor or a simple array type, returns the element type for
2841    TYPE after indexing by NINDICES indices, or by all indices if
2842    NINDICES is -1.  Otherwise, returns NULL.  */
2843
2844 struct type *
2845 ada_array_element_type (struct type *type, int nindices)
2846 {
2847   type = desc_base_type (type);
2848
2849   if (type->code () == TYPE_CODE_STRUCT)
2850     {
2851       int k;
2852       struct type *p_array_type;
2853
2854       p_array_type = desc_data_target_type (type);
2855
2856       k = ada_array_arity (type);
2857       if (k == 0)
2858         return NULL;
2859
2860       /* Initially p_array_type = elt_type(*)[]...(k times)...[].  */
2861       if (nindices >= 0 && k > nindices)
2862         k = nindices;
2863       while (k > 0 && p_array_type != NULL)
2864         {
2865           p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
2866           k -= 1;
2867         }
2868       return p_array_type;
2869     }
2870   else if (type->code () == TYPE_CODE_ARRAY)
2871     {
2872       while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
2873         {
2874           type = TYPE_TARGET_TYPE (type);
2875           nindices -= 1;
2876         }
2877       return type;
2878     }
2879
2880   return NULL;
2881 }
2882
2883 /* See ada-lang.h.  */
2884
2885 struct type *
2886 ada_index_type (struct type *type, int n, const char *name)
2887 {
2888   struct type *result_type;
2889
2890   type = desc_base_type (type);
2891
2892   if (n < 0 || n > ada_array_arity (type))
2893     error (_("invalid dimension number to '%s"), name);
2894
2895   if (ada_is_simple_array_type (type))
2896     {
2897       int i;
2898
2899       for (i = 1; i < n; i += 1)
2900         {
2901           type = ada_check_typedef (type);
2902           type = TYPE_TARGET_TYPE (type);
2903         }
2904       result_type = TYPE_TARGET_TYPE (ada_check_typedef (type)->index_type ());
2905       /* FIXME: The stabs type r(0,0);bound;bound in an array type
2906          has a target type of TYPE_CODE_UNDEF.  We compensate here, but
2907          perhaps stabsread.c would make more sense.  */
2908       if (result_type && result_type->code () == TYPE_CODE_UNDEF)
2909         result_type = NULL;
2910     }
2911   else
2912     {
2913       result_type = desc_index_type (desc_bounds_type (type), n);
2914       if (result_type == NULL)
2915         error (_("attempt to take bound of something that is not an array"));
2916     }
2917
2918   return result_type;
2919 }
2920
2921 /* Given that arr is an array type, returns the lower bound of the
2922    Nth index (numbering from 1) if WHICH is 0, and the upper bound if
2923    WHICH is 1.  This returns bounds 0 .. -1 if ARR_TYPE is an
2924    array-descriptor type.  It works for other arrays with bounds supplied
2925    by run-time quantities other than discriminants.  */
2926
2927 static LONGEST
2928 ada_array_bound_from_type (struct type *arr_type, int n, int which)
2929 {
2930   struct type *type, *index_type_desc, *index_type;
2931   int i;
2932
2933   gdb_assert (which == 0 || which == 1);
2934
2935   if (ada_is_constrained_packed_array_type (arr_type))
2936     arr_type = decode_constrained_packed_array_type (arr_type);
2937
2938   if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
2939     return (LONGEST) - which;
2940
2941   if (arr_type->code () == TYPE_CODE_PTR)
2942     type = TYPE_TARGET_TYPE (arr_type);
2943   else
2944     type = arr_type;
2945
2946   if (type->is_fixed_instance ())
2947     {
2948       /* The array has already been fixed, so we do not need to
2949          check the parallel ___XA type again.  That encoding has
2950          already been applied, so ignore it now.  */
2951       index_type_desc = NULL;
2952     }
2953   else
2954     {
2955       index_type_desc = ada_find_parallel_type (type, "___XA");
2956       ada_fixup_array_indexes_type (index_type_desc);
2957     }
2958
2959   if (index_type_desc != NULL)
2960     index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
2961                                       NULL);
2962   else
2963     {
2964       struct type *elt_type = check_typedef (type);
2965
2966       for (i = 1; i < n; i++)
2967         elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
2968
2969       index_type = elt_type->index_type ();
2970     }
2971
2972   return
2973     (LONGEST) (which == 0
2974                ? ada_discrete_type_low_bound (index_type)
2975                : ada_discrete_type_high_bound (index_type));
2976 }
2977
2978 /* Given that arr is an array value, returns the lower bound of the
2979    nth index (numbering from 1) if WHICH is 0, and the upper bound if
2980    WHICH is 1.  This routine will also work for arrays with bounds
2981    supplied by run-time quantities other than discriminants.  */
2982
2983 static LONGEST
2984 ada_array_bound (struct value *arr, int n, int which)
2985 {
2986   struct type *arr_type;
2987
2988   if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
2989     arr = value_ind (arr);
2990   arr_type = value_enclosing_type (arr);
2991
2992   if (ada_is_constrained_packed_array_type (arr_type))
2993     return ada_array_bound (decode_constrained_packed_array (arr), n, which);
2994   else if (ada_is_simple_array_type (arr_type))
2995     return ada_array_bound_from_type (arr_type, n, which);
2996   else
2997     return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
2998 }
2999
3000 /* Given that arr is an array value, returns the length of the
3001    nth index.  This routine will also work for arrays with bounds
3002    supplied by run-time quantities other than discriminants.
3003    Does not work for arrays indexed by enumeration types with representation
3004    clauses at the moment.  */
3005
3006 static LONGEST
3007 ada_array_length (struct value *arr, int n)
3008 {
3009   struct type *arr_type, *index_type;
3010   int low, high;
3011
3012   if (check_typedef (value_type (arr))->code () == TYPE_CODE_PTR)
3013     arr = value_ind (arr);
3014   arr_type = value_enclosing_type (arr);
3015
3016   if (ada_is_constrained_packed_array_type (arr_type))
3017     return ada_array_length (decode_constrained_packed_array (arr), n);
3018
3019   if (ada_is_simple_array_type (arr_type))
3020     {
3021       low = ada_array_bound_from_type (arr_type, n, 0);
3022       high = ada_array_bound_from_type (arr_type, n, 1);
3023     }
3024   else
3025     {
3026       low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3027       high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3028     }
3029
3030   arr_type = check_typedef (arr_type);
3031   index_type = ada_index_type (arr_type, n, "length");
3032   if (index_type != NULL)
3033     {
3034       struct type *base_type;
3035       if (index_type->code () == TYPE_CODE_RANGE)
3036         base_type = TYPE_TARGET_TYPE (index_type);
3037       else
3038         base_type = index_type;
3039
3040       low = pos_atr (value_from_longest (base_type, low));
3041       high = pos_atr (value_from_longest (base_type, high));
3042     }
3043   return high - low + 1;
3044 }
3045
3046 /* An array whose type is that of ARR_TYPE (an array type), with
3047    bounds LOW to HIGH, but whose contents are unimportant.  If HIGH is
3048    less than LOW, then LOW-1 is used.  */
3049
3050 static struct value *
3051 empty_array (struct type *arr_type, int low, int high)
3052 {
3053   struct type *arr_type0 = ada_check_typedef (arr_type);
3054   struct type *index_type
3055     = create_static_range_type
3056         (NULL, TYPE_TARGET_TYPE (arr_type0->index_type ()), low,
3057          high < low ? low - 1 : high);
3058   struct type *elt_type = ada_array_element_type (arr_type0, 1);
3059
3060   return allocate_value (create_array_type (NULL, elt_type, index_type));
3061 }
3062 \f
3063
3064                                 /* Name resolution */
3065
3066 /* The "decoded" name for the user-definable Ada operator corresponding
3067    to OP.  */
3068
3069 static const char *
3070 ada_decoded_op_name (enum exp_opcode op)
3071 {
3072   int i;
3073
3074   for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3075     {
3076       if (ada_opname_table[i].op == op)
3077         return ada_opname_table[i].decoded;
3078     }
3079   error (_("Could not find operator name for opcode"));
3080 }
3081
3082 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3083    in a listing of choices during disambiguation (see sort_choices, below).
3084    The idea is that overloadings of a subprogram name from the
3085    same package should sort in their source order.  We settle for ordering
3086    such symbols by their trailing number (__N  or $N).  */
3087
3088 static int
3089 encoded_ordered_before (const char *N0, const char *N1)
3090 {
3091   if (N1 == NULL)
3092     return 0;
3093   else if (N0 == NULL)
3094     return 1;
3095   else
3096     {
3097       int k0, k1;
3098
3099       for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3100         ;
3101       for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3102         ;
3103       if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3104           && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3105         {
3106           int n0, n1;
3107
3108           n0 = k0;
3109           while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3110             n0 -= 1;
3111           n1 = k1;
3112           while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3113             n1 -= 1;
3114           if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3115             return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3116         }
3117       return (strcmp (N0, N1) < 0);
3118     }
3119 }
3120
3121 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3122    encoded names.  */
3123
3124 static void
3125 sort_choices (struct block_symbol syms[], int nsyms)
3126 {
3127   int i;
3128
3129   for (i = 1; i < nsyms; i += 1)
3130     {
3131       struct block_symbol sym = syms[i];
3132       int j;
3133
3134       for (j = i - 1; j >= 0; j -= 1)
3135         {
3136           if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3137                                       sym.symbol->linkage_name ()))
3138             break;
3139           syms[j + 1] = syms[j];
3140         }
3141       syms[j + 1] = sym;
3142     }
3143 }
3144
3145 /* Whether GDB should display formals and return types for functions in the
3146    overloads selection menu.  */
3147 static bool print_signatures = true;
3148
3149 /* Print the signature for SYM on STREAM according to the FLAGS options.  For
3150    all but functions, the signature is just the name of the symbol.  For
3151    functions, this is the name of the function, the list of types for formals
3152    and the return type (if any).  */
3153
3154 static void
3155 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3156                             const struct type_print_options *flags)
3157 {
3158   struct type *type = sym->type ();
3159
3160   fprintf_filtered (stream, "%s", sym->print_name ());
3161   if (!print_signatures
3162       || type == NULL
3163       || type->code () != TYPE_CODE_FUNC)
3164     return;
3165
3166   if (type->num_fields () > 0)
3167     {
3168       int i;
3169
3170       fprintf_filtered (stream, " (");
3171       for (i = 0; i < type->num_fields (); ++i)
3172         {
3173           if (i > 0)
3174             fprintf_filtered (stream, "; ");
3175           ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
3176                           flags);
3177         }
3178       fprintf_filtered (stream, ")");
3179     }
3180   if (TYPE_TARGET_TYPE (type) != NULL
3181       && TYPE_TARGET_TYPE (type)->code () != TYPE_CODE_VOID)
3182     {
3183       fprintf_filtered (stream, " return ");
3184       ada_print_type (TYPE_TARGET_TYPE (type), NULL, stream, -1, 0, flags);
3185     }
3186 }
3187
3188 /* Read and validate a set of numeric choices from the user in the
3189    range 0 .. N_CHOICES-1.  Place the results in increasing
3190    order in CHOICES[0 .. N-1], and return N.
3191
3192    The user types choices as a sequence of numbers on one line
3193    separated by blanks, encoding them as follows:
3194
3195      + A choice of 0 means to cancel the selection, throwing an error.
3196      + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3197      + The user chooses k by typing k+IS_ALL_CHOICE+1.
3198
3199    The user is not allowed to choose more than MAX_RESULTS values.
3200
3201    ANNOTATION_SUFFIX, if present, is used to annotate the input
3202    prompts (for use with the -f switch).  */
3203
3204 static int
3205 get_selections (int *choices, int n_choices, int max_results,
3206                 int is_all_choice, const char *annotation_suffix)
3207 {
3208   const char *args;
3209   const char *prompt;
3210   int n_chosen;
3211   int first_choice = is_all_choice ? 2 : 1;
3212
3213   prompt = getenv ("PS2");
3214   if (prompt == NULL)
3215     prompt = "> ";
3216
3217   args = command_line_input (prompt, annotation_suffix);
3218
3219   if (args == NULL)
3220     error_no_arg (_("one or more choice numbers"));
3221
3222   n_chosen = 0;
3223
3224   /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3225      order, as given in args.  Choices are validated.  */
3226   while (1)
3227     {
3228       char *args2;
3229       int choice, j;
3230
3231       args = skip_spaces (args);
3232       if (*args == '\0' && n_chosen == 0)
3233         error_no_arg (_("one or more choice numbers"));
3234       else if (*args == '\0')
3235         break;
3236
3237       choice = strtol (args, &args2, 10);
3238       if (args == args2 || choice < 0
3239           || choice > n_choices + first_choice - 1)
3240         error (_("Argument must be choice number"));
3241       args = args2;
3242
3243       if (choice == 0)
3244         error (_("cancelled"));
3245
3246       if (choice < first_choice)
3247         {
3248           n_chosen = n_choices;
3249           for (j = 0; j < n_choices; j += 1)
3250             choices[j] = j;
3251           break;
3252         }
3253       choice -= first_choice;
3254
3255       for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3256         {
3257         }
3258
3259       if (j < 0 || choice != choices[j])
3260         {
3261           int k;
3262
3263           for (k = n_chosen - 1; k > j; k -= 1)
3264             choices[k + 1] = choices[k];
3265           choices[j + 1] = choice;
3266           n_chosen += 1;
3267         }
3268     }
3269
3270   if (n_chosen > max_results)
3271     error (_("Select no more than %d of the above"), max_results);
3272
3273   return n_chosen;
3274 }
3275
3276 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3277    by asking the user (if necessary), returning the number selected,
3278    and setting the first elements of SYMS items.  Error if no symbols
3279    selected.  */
3280
3281 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3282    to be re-integrated one of these days.  */
3283
3284 static int
3285 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3286 {
3287   int i;
3288   int *chosen = XALLOCAVEC (int , nsyms);
3289   int n_chosen;
3290   int first_choice = (max_results == 1) ? 1 : 2;
3291   const char *select_mode = multiple_symbols_select_mode ();
3292
3293   if (max_results < 1)
3294     error (_("Request to select 0 symbols!"));
3295   if (nsyms <= 1)
3296     return nsyms;
3297
3298   if (select_mode == multiple_symbols_cancel)
3299     error (_("\
3300 canceled because the command is ambiguous\n\
3301 See set/show multiple-symbol."));
3302
3303   /* If select_mode is "all", then return all possible symbols.
3304      Only do that if more than one symbol can be selected, of course.
3305      Otherwise, display the menu as usual.  */
3306   if (select_mode == multiple_symbols_all && max_results > 1)
3307     return nsyms;
3308
3309   printf_filtered (_("[0] cancel\n"));
3310   if (max_results > 1)
3311     printf_filtered (_("[1] all\n"));
3312
3313   sort_choices (syms, nsyms);
3314
3315   for (i = 0; i < nsyms; i += 1)
3316     {
3317       if (syms[i].symbol == NULL)
3318         continue;
3319
3320       if (syms[i].symbol->aclass () == LOC_BLOCK)
3321         {
3322           struct symtab_and_line sal =
3323             find_function_start_sal (syms[i].symbol, 1);
3324
3325           printf_filtered ("[%d] ", i + first_choice);
3326           ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3327                                       &type_print_raw_options);
3328           if (sal.symtab == NULL)
3329             printf_filtered (_(" at %p[<no source file available>%p]:%d\n"),
3330                              metadata_style.style ().ptr (), nullptr, sal.line);
3331           else
3332             printf_filtered
3333               (_(" at %ps:%d\n"),
3334                styled_string (file_name_style.style (),
3335                               symtab_to_filename_for_display (sal.symtab)),
3336                sal.line);
3337           continue;
3338         }
3339       else
3340         {
3341           int is_enumeral =
3342             (syms[i].symbol->aclass () == LOC_CONST
3343              && syms[i].symbol->type () != NULL
3344              && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
3345           struct symtab *symtab = NULL;
3346
3347           if (syms[i].symbol->is_objfile_owned ())
3348             symtab = symbol_symtab (syms[i].symbol);
3349
3350           if (syms[i].symbol->line () != 0 && symtab != NULL)
3351             {
3352               printf_filtered ("[%d] ", i + first_choice);
3353               ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3354                                           &type_print_raw_options);
3355               printf_filtered (_(" at %s:%d\n"),
3356                                symtab_to_filename_for_display (symtab),
3357                                syms[i].symbol->line ());
3358             }
3359           else if (is_enumeral
3360                    && syms[i].symbol->type ()->name () != NULL)
3361             {
3362               printf_filtered (("[%d] "), i + first_choice);
3363               ada_print_type (syms[i].symbol->type (), NULL,
3364                               gdb_stdout, -1, 0, &type_print_raw_options);
3365               printf_filtered (_("'(%s) (enumeral)\n"),
3366                                syms[i].symbol->print_name ());
3367             }
3368           else
3369             {
3370               printf_filtered ("[%d] ", i + first_choice);
3371               ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3372                                           &type_print_raw_options);
3373
3374               if (symtab != NULL)
3375                 printf_filtered (is_enumeral
3376                                  ? _(" in %s (enumeral)\n")
3377                                  : _(" at %s:?\n"),
3378                                  symtab_to_filename_for_display (symtab));
3379               else
3380                 printf_filtered (is_enumeral
3381                                  ? _(" (enumeral)\n")
3382                                  : _(" at ?\n"));
3383             }
3384         }
3385     }
3386
3387   n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3388                              "overload-choice");
3389
3390   for (i = 0; i < n_chosen; i += 1)
3391     syms[i] = syms[chosen[i]];
3392
3393   return n_chosen;
3394 }
3395
3396 /* See ada-lang.h.  */
3397
3398 block_symbol
3399 ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
3400                           int nargs, value *argvec[])
3401 {
3402   if (possible_user_operator_p (op, argvec))
3403     {
3404       std::vector<struct block_symbol> candidates
3405         = ada_lookup_symbol_list (ada_decoded_op_name (op),
3406                                   NULL, VAR_DOMAIN);
3407
3408       int i = ada_resolve_function (candidates, argvec,
3409                                     nargs, ada_decoded_op_name (op), NULL,
3410                                     parse_completion);
3411       if (i >= 0)
3412         return candidates[i];
3413     }
3414   return {};
3415 }
3416
3417 /* See ada-lang.h.  */
3418
3419 block_symbol
3420 ada_resolve_funcall (struct symbol *sym, const struct block *block,
3421                      struct type *context_type,
3422                      bool parse_completion,
3423                      int nargs, value *argvec[],
3424                      innermost_block_tracker *tracker)
3425 {
3426   std::vector<struct block_symbol> candidates
3427     = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3428
3429   int i;
3430   if (candidates.size () == 1)
3431     i = 0;
3432   else
3433     {
3434       i = ada_resolve_function
3435         (candidates,
3436          argvec, nargs,
3437          sym->linkage_name (),
3438          context_type, parse_completion);
3439       if (i < 0)
3440         error (_("Could not find a match for %s"), sym->print_name ());
3441     }
3442
3443   tracker->update (candidates[i]);
3444   return candidates[i];
3445 }
3446
3447 /* Resolve a mention of a name where the context type is an
3448    enumeration type.  */
3449
3450 static int
3451 ada_resolve_enum (std::vector<struct block_symbol> &syms,
3452                   const char *name, struct type *context_type,
3453                   bool parse_completion)
3454 {
3455   gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3456   context_type = ada_check_typedef (context_type);
3457
3458   for (int i = 0; i < syms.size (); ++i)
3459     {
3460       /* We already know the name matches, so we're just looking for
3461          an element of the correct enum type.  */
3462       if (ada_check_typedef (syms[i].symbol->type ()) == context_type)
3463         return i;
3464     }
3465
3466   error (_("No name '%s' in enumeration type '%s'"), name,
3467          ada_type_name (context_type));
3468 }
3469
3470 /* See ada-lang.h.  */
3471
3472 block_symbol
3473 ada_resolve_variable (struct symbol *sym, const struct block *block,
3474                       struct type *context_type,
3475                       bool parse_completion,
3476                       int deprocedure_p,
3477                       innermost_block_tracker *tracker)
3478 {
3479   std::vector<struct block_symbol> candidates
3480     = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3481
3482   if (std::any_of (candidates.begin (),
3483                    candidates.end (),
3484                    [] (block_symbol &bsym)
3485                    {
3486                      switch (bsym.symbol->aclass ())
3487                        {
3488                        case LOC_REGISTER:
3489                        case LOC_ARG:
3490                        case LOC_REF_ARG:
3491                        case LOC_REGPARM_ADDR:
3492                        case LOC_LOCAL:
3493                        case LOC_COMPUTED:
3494                          return true;
3495                        default:
3496                          return false;
3497                        }
3498                    }))
3499     {
3500       /* Types tend to get re-introduced locally, so if there
3501          are any local symbols that are not types, first filter
3502          out all types.  */
3503       candidates.erase
3504         (std::remove_if
3505          (candidates.begin (),
3506           candidates.end (),
3507           [] (block_symbol &bsym)
3508           {
3509             return bsym.symbol->aclass () == LOC_TYPEDEF;
3510           }),
3511          candidates.end ());
3512     }
3513
3514   /* Filter out artificial symbols.  */
3515   candidates.erase
3516     (std::remove_if
3517      (candidates.begin (),
3518       candidates.end (),
3519       [] (block_symbol &bsym)
3520       {
3521        return bsym.symbol->artificial;
3522       }),
3523      candidates.end ());
3524
3525   int i;
3526   if (candidates.empty ())
3527     error (_("No definition found for %s"), sym->print_name ());
3528   else if (candidates.size () == 1)
3529     i = 0;
3530   else if (context_type != nullptr
3531            && context_type->code () == TYPE_CODE_ENUM)
3532     i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3533                           parse_completion);
3534   else if (deprocedure_p && !is_nonfunction (candidates))
3535     {
3536       i = ada_resolve_function
3537         (candidates, NULL, 0,
3538          sym->linkage_name (),
3539          context_type, parse_completion);
3540       if (i < 0)
3541         error (_("Could not find a match for %s"), sym->print_name ());
3542     }
3543   else
3544     {
3545       printf_filtered (_("Multiple matches for %s\n"), sym->print_name ());
3546       user_select_syms (candidates.data (), candidates.size (), 1);
3547       i = 0;
3548     }
3549
3550   tracker->update (candidates[i]);
3551   return candidates[i];
3552 }
3553
3554 /* Return non-zero if formal type FTYPE matches actual type ATYPE.  */
3555 /* The term "match" here is rather loose.  The match is heuristic and
3556    liberal.  */
3557
3558 static int
3559 ada_type_match (struct type *ftype, struct type *atype)
3560 {
3561   ftype = ada_check_typedef (ftype);
3562   atype = ada_check_typedef (atype);
3563
3564   if (ftype->code () == TYPE_CODE_REF)
3565     ftype = TYPE_TARGET_TYPE (ftype);
3566   if (atype->code () == TYPE_CODE_REF)
3567     atype = TYPE_TARGET_TYPE (atype);
3568
3569   switch (ftype->code ())
3570     {
3571     default:
3572       return ftype->code () == atype->code ();
3573     case TYPE_CODE_PTR:
3574       if (atype->code () != TYPE_CODE_PTR)
3575         return 0;
3576       atype = TYPE_TARGET_TYPE (atype);
3577       /* This can only happen if the actual argument is 'null'.  */
3578       if (atype->code () == TYPE_CODE_INT && TYPE_LENGTH (atype) == 0)
3579         return 1;
3580       return ada_type_match (TYPE_TARGET_TYPE (ftype), atype);
3581     case TYPE_CODE_INT:
3582     case TYPE_CODE_ENUM:
3583     case TYPE_CODE_RANGE:
3584       switch (atype->code ())
3585         {
3586         case TYPE_CODE_INT:
3587         case TYPE_CODE_ENUM:
3588         case TYPE_CODE_RANGE:
3589           return 1;
3590         default:
3591           return 0;
3592         }
3593
3594     case TYPE_CODE_ARRAY:
3595       return (atype->code () == TYPE_CODE_ARRAY
3596               || ada_is_array_descriptor_type (atype));
3597
3598     case TYPE_CODE_STRUCT:
3599       if (ada_is_array_descriptor_type (ftype))
3600         return (atype->code () == TYPE_CODE_ARRAY
3601                 || ada_is_array_descriptor_type (atype));
3602       else
3603         return (atype->code () == TYPE_CODE_STRUCT
3604                 && !ada_is_array_descriptor_type (atype));
3605
3606     case TYPE_CODE_UNION:
3607     case TYPE_CODE_FLT:
3608       return (atype->code () == ftype->code ());
3609     }
3610 }
3611
3612 /* Return non-zero if the formals of FUNC "sufficiently match" the
3613    vector of actual argument types ACTUALS of size N_ACTUALS.  FUNC
3614    may also be an enumeral, in which case it is treated as a 0-
3615    argument function.  */
3616
3617 static int
3618 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3619 {
3620   int i;
3621   struct type *func_type = func->type ();
3622
3623   if (func->aclass () == LOC_CONST
3624       && func_type->code () == TYPE_CODE_ENUM)
3625     return (n_actuals == 0);
3626   else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
3627     return 0;
3628
3629   if (func_type->num_fields () != n_actuals)
3630     return 0;
3631
3632   for (i = 0; i < n_actuals; i += 1)
3633     {
3634       if (actuals[i] == NULL)
3635         return 0;
3636       else
3637         {
3638           struct type *ftype = ada_check_typedef (func_type->field (i).type ());
3639           struct type *atype = ada_check_typedef (value_type (actuals[i]));
3640
3641           if (!ada_type_match (ftype, atype))
3642             return 0;
3643         }
3644     }
3645   return 1;
3646 }
3647
3648 /* False iff function type FUNC_TYPE definitely does not produce a value
3649    compatible with type CONTEXT_TYPE.  Conservatively returns 1 if
3650    FUNC_TYPE is not a valid function type with a non-null return type
3651    or an enumerated type.  A null CONTEXT_TYPE indicates any non-void type.  */
3652
3653 static int
3654 return_match (struct type *func_type, struct type *context_type)
3655 {
3656   struct type *return_type;
3657
3658   if (func_type == NULL)
3659     return 1;
3660
3661   if (func_type->code () == TYPE_CODE_FUNC)
3662     return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
3663   else
3664     return_type = get_base_type (func_type);
3665   if (return_type == NULL)
3666     return 1;
3667
3668   context_type = get_base_type (context_type);
3669
3670   if (return_type->code () == TYPE_CODE_ENUM)
3671     return context_type == NULL || return_type == context_type;
3672   else if (context_type == NULL)
3673     return return_type->code () != TYPE_CODE_VOID;
3674   else
3675     return return_type->code () == context_type->code ();
3676 }
3677
3678
3679 /* Returns the index in SYMS that contains the symbol for the
3680    function (if any) that matches the types of the NARGS arguments in
3681    ARGS.  If CONTEXT_TYPE is non-null and there is at least one match
3682    that returns that type, then eliminate matches that don't.  If
3683    CONTEXT_TYPE is void and there is at least one match that does not
3684    return void, eliminate all matches that do.
3685
3686    Asks the user if there is more than one match remaining.  Returns -1
3687    if there is no such symbol or none is selected.  NAME is used
3688    solely for messages.  May re-arrange and modify SYMS in
3689    the process; the index returned is for the modified vector.  */
3690
3691 static int
3692 ada_resolve_function (std::vector<struct block_symbol> &syms,
3693                       struct value **args, int nargs,
3694                       const char *name, struct type *context_type,
3695                       bool parse_completion)
3696 {
3697   int fallback;
3698   int k;
3699   int m;                        /* Number of hits */
3700
3701   m = 0;
3702   /* In the first pass of the loop, we only accept functions matching
3703      context_type.  If none are found, we add a second pass of the loop
3704      where every function is accepted.  */
3705   for (fallback = 0; m == 0 && fallback < 2; fallback++)
3706     {
3707       for (k = 0; k < syms.size (); k += 1)
3708         {
3709           struct type *type = ada_check_typedef (syms[k].symbol->type ());
3710
3711           if (ada_args_match (syms[k].symbol, args, nargs)
3712               && (fallback || return_match (type, context_type)))
3713             {
3714               syms[m] = syms[k];
3715               m += 1;
3716             }
3717         }
3718     }
3719
3720   /* If we got multiple matches, ask the user which one to use.  Don't do this
3721      interactive thing during completion, though, as the purpose of the
3722      completion is providing a list of all possible matches.  Prompting the
3723      user to filter it down would be completely unexpected in this case.  */
3724   if (m == 0)
3725     return -1;
3726   else if (m > 1 && !parse_completion)
3727     {
3728       printf_filtered (_("Multiple matches for %s\n"), name);
3729       user_select_syms (syms.data (), m, 1);
3730       return 0;
3731     }
3732   return 0;
3733 }
3734
3735 /* Type-class predicates */
3736
3737 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
3738    or FLOAT).  */
3739
3740 static int
3741 numeric_type_p (struct type *type)
3742 {
3743   if (type == NULL)
3744     return 0;
3745   else
3746     {
3747       switch (type->code ())
3748         {
3749         case TYPE_CODE_INT:
3750         case TYPE_CODE_FLT:
3751         case TYPE_CODE_FIXED_POINT:
3752           return 1;
3753         case TYPE_CODE_RANGE:
3754           return (type == TYPE_TARGET_TYPE (type)
3755                   || numeric_type_p (TYPE_TARGET_TYPE (type)));
3756         default:
3757           return 0;
3758         }
3759     }
3760 }
3761
3762 /* True iff TYPE is integral (an INT or RANGE of INTs).  */
3763
3764 static int
3765 integer_type_p (struct type *type)
3766 {
3767   if (type == NULL)
3768     return 0;
3769   else
3770     {
3771       switch (type->code ())
3772         {
3773         case TYPE_CODE_INT:
3774           return 1;
3775         case TYPE_CODE_RANGE:
3776           return (type == TYPE_TARGET_TYPE (type)
3777                   || integer_type_p (TYPE_TARGET_TYPE (type)));
3778         default:
3779           return 0;
3780         }
3781     }
3782 }
3783
3784 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM).  */
3785
3786 static int
3787 scalar_type_p (struct type *type)
3788 {
3789   if (type == NULL)
3790     return 0;
3791   else
3792     {
3793       switch (type->code ())
3794         {
3795         case TYPE_CODE_INT:
3796         case TYPE_CODE_RANGE:
3797         case TYPE_CODE_ENUM:
3798         case TYPE_CODE_FLT:
3799         case TYPE_CODE_FIXED_POINT:
3800           return 1;
3801         default:
3802           return 0;
3803         }
3804     }
3805 }
3806
3807 /* True iff TYPE is discrete (INT, RANGE, ENUM).  */
3808
3809 static int
3810 discrete_type_p (struct type *type)
3811 {
3812   if (type == NULL)
3813     return 0;
3814   else
3815     {
3816       switch (type->code ())
3817         {
3818         case TYPE_CODE_INT:
3819         case TYPE_CODE_RANGE:
3820         case TYPE_CODE_ENUM:
3821         case TYPE_CODE_BOOL:
3822           return 1;
3823         default:
3824           return 0;
3825         }
3826     }
3827 }
3828
3829 /* Returns non-zero if OP with operands in the vector ARGS could be
3830    a user-defined function.  Errs on the side of pre-defined operators
3831    (i.e., result 0).  */
3832
3833 static int
3834 possible_user_operator_p (enum exp_opcode op, struct value *args[])
3835 {
3836   struct type *type0 =
3837     (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
3838   struct type *type1 =
3839     (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
3840
3841   if (type0 == NULL)
3842     return 0;
3843
3844   switch (op)
3845     {
3846     default:
3847       return 0;
3848
3849     case BINOP_ADD:
3850     case BINOP_SUB:
3851     case BINOP_MUL:
3852     case BINOP_DIV:
3853       return (!(numeric_type_p (type0) && numeric_type_p (type1)));
3854
3855     case BINOP_REM:
3856     case BINOP_MOD:
3857     case BINOP_BITWISE_AND:
3858     case BINOP_BITWISE_IOR:
3859     case BINOP_BITWISE_XOR:
3860       return (!(integer_type_p (type0) && integer_type_p (type1)));
3861
3862     case BINOP_EQUAL:
3863     case BINOP_NOTEQUAL:
3864     case BINOP_LESS:
3865     case BINOP_GTR:
3866     case BINOP_LEQ:
3867     case BINOP_GEQ:
3868       return (!(scalar_type_p (type0) && scalar_type_p (type1)));
3869
3870     case BINOP_CONCAT:
3871       return !ada_is_array_type (type0) || !ada_is_array_type (type1);
3872
3873     case BINOP_EXP:
3874       return (!(numeric_type_p (type0) && integer_type_p (type1)));
3875
3876     case UNOP_NEG:
3877     case UNOP_PLUS:
3878     case UNOP_LOGICAL_NOT:
3879     case UNOP_ABS:
3880       return (!numeric_type_p (type0));
3881
3882     }
3883 }
3884 \f
3885                                 /* Renaming */
3886
3887 /* NOTES: 
3888
3889    1. In the following, we assume that a renaming type's name may
3890       have an ___XD suffix.  It would be nice if this went away at some
3891       point.
3892    2. We handle both the (old) purely type-based representation of 
3893       renamings and the (new) variable-based encoding.  At some point,
3894       it is devoutly to be hoped that the former goes away 
3895       (FIXME: hilfinger-2007-07-09).
3896    3. Subprogram renamings are not implemented, although the XRS
3897       suffix is recognized (FIXME: hilfinger-2007-07-09).  */
3898
3899 /* If SYM encodes a renaming, 
3900
3901        <renaming> renames <renamed entity>,
3902
3903    sets *LEN to the length of the renamed entity's name,
3904    *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
3905    the string describing the subcomponent selected from the renamed
3906    entity.  Returns ADA_NOT_RENAMING if SYM does not encode a renaming
3907    (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
3908    are undefined).  Otherwise, returns a value indicating the category
3909    of entity renamed: an object (ADA_OBJECT_RENAMING), exception
3910    (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
3911    subprogram (ADA_SUBPROGRAM_RENAMING).  Does no allocation; the
3912    strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
3913    deallocated.  The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
3914    may be NULL, in which case they are not assigned.
3915
3916    [Currently, however, GCC does not generate subprogram renamings.]  */
3917
3918 enum ada_renaming_category
3919 ada_parse_renaming (struct symbol *sym,
3920                     const char **renamed_entity, int *len, 
3921                     const char **renaming_expr)
3922 {
3923   enum ada_renaming_category kind;
3924   const char *info;
3925   const char *suffix;
3926
3927   if (sym == NULL)
3928     return ADA_NOT_RENAMING;
3929   switch (sym->aclass ()) 
3930     {
3931     default:
3932       return ADA_NOT_RENAMING;
3933     case LOC_LOCAL:
3934     case LOC_STATIC:
3935     case LOC_COMPUTED:
3936     case LOC_OPTIMIZED_OUT:
3937       info = strstr (sym->linkage_name (), "___XR");
3938       if (info == NULL)
3939         return ADA_NOT_RENAMING;
3940       switch (info[5])
3941         {
3942         case '_':
3943           kind = ADA_OBJECT_RENAMING;
3944           info += 6;
3945           break;
3946         case 'E':
3947           kind = ADA_EXCEPTION_RENAMING;
3948           info += 7;
3949           break;
3950         case 'P':
3951           kind = ADA_PACKAGE_RENAMING;
3952           info += 7;
3953           break;
3954         case 'S':
3955           kind = ADA_SUBPROGRAM_RENAMING;
3956           info += 7;
3957           break;
3958         default:
3959           return ADA_NOT_RENAMING;
3960         }
3961     }
3962
3963   if (renamed_entity != NULL)
3964     *renamed_entity = info;
3965   suffix = strstr (info, "___XE");
3966   if (suffix == NULL || suffix == info)
3967     return ADA_NOT_RENAMING;
3968   if (len != NULL)
3969     *len = strlen (info) - strlen (suffix);
3970   suffix += 5;
3971   if (renaming_expr != NULL)
3972     *renaming_expr = suffix;
3973   return kind;
3974 }
3975
3976 /* Compute the value of the given RENAMING_SYM, which is expected to
3977    be a symbol encoding a renaming expression.  BLOCK is the block
3978    used to evaluate the renaming.  */
3979
3980 static struct value *
3981 ada_read_renaming_var_value (struct symbol *renaming_sym,
3982                              const struct block *block)
3983 {
3984   const char *sym_name;
3985
3986   sym_name = renaming_sym->linkage_name ();
3987   expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
3988   return evaluate_expression (expr.get ());
3989 }
3990 \f
3991
3992                                 /* Evaluation: Function Calls */
3993
3994 /* Return an lvalue containing the value VAL.  This is the identity on
3995    lvalues, and otherwise has the side-effect of allocating memory
3996    in the inferior where a copy of the value contents is copied.  */
3997
3998 static struct value *
3999 ensure_lval (struct value *val)
4000 {
4001   if (VALUE_LVAL (val) == not_lval
4002       || VALUE_LVAL (val) == lval_internalvar)
4003     {
4004       int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
4005       const CORE_ADDR addr =
4006         value_as_long (value_allocate_space_in_inferior (len));
4007
4008       VALUE_LVAL (val) = lval_memory;
4009       set_value_address (val, addr);
4010       write_memory (addr, value_contents (val).data (), len);
4011     }
4012
4013   return val;
4014 }
4015
4016 /* Given ARG, a value of type (pointer or reference to a)*
4017    structure/union, extract the component named NAME from the ultimate
4018    target structure/union and return it as a value with its
4019    appropriate type.
4020
4021    The routine searches for NAME among all members of the structure itself
4022    and (recursively) among all members of any wrapper members
4023    (e.g., '_parent').
4024
4025    If NO_ERR, then simply return NULL in case of error, rather than
4026    calling error.  */
4027
4028 static struct value *
4029 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4030 {
4031   struct type *t, *t1;
4032   struct value *v;
4033   int check_tag;
4034
4035   v = NULL;
4036   t1 = t = ada_check_typedef (value_type (arg));
4037   if (t->code () == TYPE_CODE_REF)
4038     {
4039       t1 = TYPE_TARGET_TYPE (t);
4040       if (t1 == NULL)
4041         goto BadValue;
4042       t1 = ada_check_typedef (t1);
4043       if (t1->code () == TYPE_CODE_PTR)
4044         {
4045           arg = coerce_ref (arg);
4046           t = t1;
4047         }
4048     }
4049
4050   while (t->code () == TYPE_CODE_PTR)
4051     {
4052       t1 = TYPE_TARGET_TYPE (t);
4053       if (t1 == NULL)
4054         goto BadValue;
4055       t1 = ada_check_typedef (t1);
4056       if (t1->code () == TYPE_CODE_PTR)
4057         {
4058           arg = value_ind (arg);
4059           t = t1;
4060         }
4061       else
4062         break;
4063     }
4064
4065   if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
4066     goto BadValue;
4067
4068   if (t1 == t)
4069     v = ada_search_struct_field (name, arg, 0, t);
4070   else
4071     {
4072       int bit_offset, bit_size, byte_offset;
4073       struct type *field_type;
4074       CORE_ADDR address;
4075
4076       if (t->code () == TYPE_CODE_PTR)
4077         address = value_address (ada_value_ind (arg));
4078       else
4079         address = value_address (ada_coerce_ref (arg));
4080
4081       /* Check to see if this is a tagged type.  We also need to handle
4082          the case where the type is a reference to a tagged type, but
4083          we have to be careful to exclude pointers to tagged types.
4084          The latter should be shown as usual (as a pointer), whereas
4085          a reference should mostly be transparent to the user.  */
4086
4087       if (ada_is_tagged_type (t1, 0)
4088           || (t1->code () == TYPE_CODE_REF
4089               && ada_is_tagged_type (TYPE_TARGET_TYPE (t1), 0)))
4090         {
4091           /* We first try to find the searched field in the current type.
4092              If not found then let's look in the fixed type.  */
4093
4094           if (!find_struct_field (name, t1, 0,
4095                                   nullptr, nullptr, nullptr,
4096                                   nullptr, nullptr))
4097             check_tag = 1;
4098           else
4099             check_tag = 0;
4100         }
4101       else
4102         check_tag = 0;
4103
4104       /* Convert to fixed type in all cases, so that we have proper
4105          offsets to each field in unconstrained record types.  */
4106       t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4107                               address, NULL, check_tag);
4108
4109       /* Resolve the dynamic type as well.  */
4110       arg = value_from_contents_and_address (t1, nullptr, address);
4111       t1 = value_type (arg);
4112
4113       if (find_struct_field (name, t1, 0,
4114                              &field_type, &byte_offset, &bit_offset,
4115                              &bit_size, NULL))
4116         {
4117           if (bit_size != 0)
4118             {
4119               if (t->code () == TYPE_CODE_REF)
4120                 arg = ada_coerce_ref (arg);
4121               else
4122                 arg = ada_value_ind (arg);
4123               v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4124                                                   bit_offset, bit_size,
4125                                                   field_type);
4126             }
4127           else
4128             v = value_at_lazy (field_type, address + byte_offset);
4129         }
4130     }
4131
4132   if (v != NULL || no_err)
4133     return v;
4134   else
4135     error (_("There is no member named %s."), name);
4136
4137  BadValue:
4138   if (no_err)
4139     return NULL;
4140   else
4141     error (_("Attempt to extract a component of "
4142              "a value that is not a record."));
4143 }
4144
4145 /* Return the value ACTUAL, converted to be an appropriate value for a
4146    formal of type FORMAL_TYPE.  Use *SP as a stack pointer for
4147    allocating any necessary descriptors (fat pointers), or copies of
4148    values not residing in memory, updating it as needed.  */
4149
4150 struct value *
4151 ada_convert_actual (struct value *actual, struct type *formal_type0)
4152 {
4153   struct type *actual_type = ada_check_typedef (value_type (actual));
4154   struct type *formal_type = ada_check_typedef (formal_type0);
4155   struct type *formal_target =
4156     formal_type->code () == TYPE_CODE_PTR
4157     ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
4158   struct type *actual_target =
4159     actual_type->code () == TYPE_CODE_PTR
4160     ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
4161
4162   if (ada_is_array_descriptor_type (formal_target)
4163       && actual_target->code () == TYPE_CODE_ARRAY)
4164     return make_array_descriptor (formal_type, actual);
4165   else if (formal_type->code () == TYPE_CODE_PTR
4166            || formal_type->code () == TYPE_CODE_REF)
4167     {
4168       struct value *result;
4169
4170       if (formal_target->code () == TYPE_CODE_ARRAY
4171           && ada_is_array_descriptor_type (actual_target))
4172         result = desc_data (actual);
4173       else if (formal_type->code () != TYPE_CODE_PTR)
4174         {
4175           if (VALUE_LVAL (actual) != lval_memory)
4176             {
4177               struct value *val;
4178
4179               actual_type = ada_check_typedef (value_type (actual));
4180               val = allocate_value (actual_type);
4181               copy (value_contents (actual), value_contents_raw (val));
4182               actual = ensure_lval (val);
4183             }
4184           result = value_addr (actual);
4185         }
4186       else
4187         return actual;
4188       return value_cast_pointers (formal_type, result, 0);
4189     }
4190   else if (actual_type->code () == TYPE_CODE_PTR)
4191     return ada_value_ind (actual);
4192   else if (ada_is_aligner_type (formal_type))
4193     {
4194       /* We need to turn this parameter into an aligner type
4195          as well.  */
4196       struct value *aligner = allocate_value (formal_type);
4197       struct value *component = ada_value_struct_elt (aligner, "F", 0);
4198
4199       value_assign_to_component (aligner, component, actual);
4200       return aligner;
4201     }
4202
4203   return actual;
4204 }
4205
4206 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4207    type TYPE.  This is usually an inefficient no-op except on some targets
4208    (such as AVR) where the representation of a pointer and an address
4209    differs.  */
4210
4211 static CORE_ADDR
4212 value_pointer (struct value *value, struct type *type)
4213 {
4214   unsigned len = TYPE_LENGTH (type);
4215   gdb_byte *buf = (gdb_byte *) alloca (len);
4216   CORE_ADDR addr;
4217
4218   addr = value_address (value);
4219   gdbarch_address_to_pointer (type->arch (), type, buf, addr);
4220   addr = extract_unsigned_integer (buf, len, type_byte_order (type));
4221   return addr;
4222 }
4223
4224
4225 /* Push a descriptor of type TYPE for array value ARR on the stack at
4226    *SP, updating *SP to reflect the new descriptor.  Return either
4227    an lvalue representing the new descriptor, or (if TYPE is a pointer-
4228    to-descriptor type rather than a descriptor type), a struct value *
4229    representing a pointer to this descriptor.  */
4230
4231 static struct value *
4232 make_array_descriptor (struct type *type, struct value *arr)
4233 {
4234   struct type *bounds_type = desc_bounds_type (type);
4235   struct type *desc_type = desc_base_type (type);
4236   struct value *descriptor = allocate_value (desc_type);
4237   struct value *bounds = allocate_value (bounds_type);
4238   int i;
4239
4240   for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4241        i > 0; i -= 1)
4242     {
4243       modify_field (value_type (bounds),
4244                     value_contents_writeable (bounds).data (),
4245                     ada_array_bound (arr, i, 0),
4246                     desc_bound_bitpos (bounds_type, i, 0),
4247                     desc_bound_bitsize (bounds_type, i, 0));
4248       modify_field (value_type (bounds),
4249                     value_contents_writeable (bounds).data (),
4250                     ada_array_bound (arr, i, 1),
4251                     desc_bound_bitpos (bounds_type, i, 1),
4252                     desc_bound_bitsize (bounds_type, i, 1));
4253     }
4254
4255   bounds = ensure_lval (bounds);
4256
4257   modify_field (value_type (descriptor),
4258                 value_contents_writeable (descriptor).data (),
4259                 value_pointer (ensure_lval (arr),
4260                                desc_type->field (0).type ()),
4261                 fat_pntr_data_bitpos (desc_type),
4262                 fat_pntr_data_bitsize (desc_type));
4263
4264   modify_field (value_type (descriptor),
4265                 value_contents_writeable (descriptor).data (),
4266                 value_pointer (bounds,
4267                                desc_type->field (1).type ()),
4268                 fat_pntr_bounds_bitpos (desc_type),
4269                 fat_pntr_bounds_bitsize (desc_type));
4270
4271   descriptor = ensure_lval (descriptor);
4272
4273   if (type->code () == TYPE_CODE_PTR)
4274     return value_addr (descriptor);
4275   else
4276     return descriptor;
4277 }
4278 \f
4279                                 /* Symbol Cache Module */
4280
4281 /* Performance measurements made as of 2010-01-15 indicate that
4282    this cache does bring some noticeable improvements.  Depending
4283    on the type of entity being printed, the cache can make it as much
4284    as an order of magnitude faster than without it.
4285
4286    The descriptive type DWARF extension has significantly reduced
4287    the need for this cache, at least when DWARF is being used.  However,
4288    even in this case, some expensive name-based symbol searches are still
4289    sometimes necessary - to find an XVZ variable, mostly.  */
4290
4291 /* Return the symbol cache associated to the given program space PSPACE.
4292    If not allocated for this PSPACE yet, allocate and initialize one.  */
4293
4294 static struct ada_symbol_cache *
4295 ada_get_symbol_cache (struct program_space *pspace)
4296 {
4297   struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4298
4299   if (pspace_data->sym_cache == nullptr)
4300     pspace_data->sym_cache.reset (new ada_symbol_cache);
4301
4302   return pspace_data->sym_cache.get ();
4303 }
4304
4305 /* Clear all entries from the symbol cache.  */
4306
4307 static void
4308 ada_clear_symbol_cache ()
4309 {
4310   struct ada_pspace_data *pspace_data
4311     = get_ada_pspace_data (current_program_space);
4312
4313   if (pspace_data->sym_cache != nullptr)
4314     pspace_data->sym_cache.reset ();
4315 }
4316
4317 /* Search our cache for an entry matching NAME and DOMAIN.
4318    Return it if found, or NULL otherwise.  */
4319
4320 static struct cache_entry **
4321 find_entry (const char *name, domain_enum domain)
4322 {
4323   struct ada_symbol_cache *sym_cache
4324     = ada_get_symbol_cache (current_program_space);
4325   int h = msymbol_hash (name) % HASH_SIZE;
4326   struct cache_entry **e;
4327
4328   for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4329     {
4330       if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4331         return e;
4332     }
4333   return NULL;
4334 }
4335
4336 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4337    Return 1 if found, 0 otherwise.
4338
4339    If an entry was found and SYM is not NULL, set *SYM to the entry's
4340    SYM.  Same principle for BLOCK if not NULL.  */
4341
4342 static int
4343 lookup_cached_symbol (const char *name, domain_enum domain,
4344                       struct symbol **sym, const struct block **block)
4345 {
4346   struct cache_entry **e = find_entry (name, domain);
4347
4348   if (e == NULL)
4349     return 0;
4350   if (sym != NULL)
4351     *sym = (*e)->sym;
4352   if (block != NULL)
4353     *block = (*e)->block;
4354   return 1;
4355 }
4356
4357 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4358    in domain DOMAIN, save this result in our symbol cache.  */
4359
4360 static void
4361 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4362               const struct block *block)
4363 {
4364   struct ada_symbol_cache *sym_cache
4365     = ada_get_symbol_cache (current_program_space);
4366   int h;
4367   struct cache_entry *e;
4368
4369   /* Symbols for builtin types don't have a block.
4370      For now don't cache such symbols.  */
4371   if (sym != NULL && !sym->is_objfile_owned ())
4372     return;
4373
4374   /* If the symbol is a local symbol, then do not cache it, as a search
4375      for that symbol depends on the context.  To determine whether
4376      the symbol is local or not, we check the block where we found it
4377      against the global and static blocks of its associated symtab.  */
4378   if (sym
4379       && BLOCKVECTOR_BLOCK (symbol_symtab (sym)->blockvector (),
4380                             GLOBAL_BLOCK) != block
4381       && BLOCKVECTOR_BLOCK (symbol_symtab (sym)->blockvector (),
4382                             STATIC_BLOCK) != block)
4383     return;
4384
4385   h = msymbol_hash (name) % HASH_SIZE;
4386   e = XOBNEW (&sym_cache->cache_space, cache_entry);
4387   e->next = sym_cache->root[h];
4388   sym_cache->root[h] = e;
4389   e->name = obstack_strdup (&sym_cache->cache_space, name);
4390   e->sym = sym;
4391   e->domain = domain;
4392   e->block = block;
4393 }
4394 \f
4395                                 /* Symbol Lookup */
4396
4397 /* Return the symbol name match type that should be used used when
4398    searching for all symbols matching LOOKUP_NAME.
4399
4400    LOOKUP_NAME is expected to be a symbol name after transformation
4401    for Ada lookups.  */
4402
4403 static symbol_name_match_type
4404 name_match_type_from_name (const char *lookup_name)
4405 {
4406   return (strstr (lookup_name, "__") == NULL
4407           ? symbol_name_match_type::WILD
4408           : symbol_name_match_type::FULL);
4409 }
4410
4411 /* Return the result of a standard (literal, C-like) lookup of NAME in
4412    given DOMAIN, visible from lexical block BLOCK.  */
4413
4414 static struct symbol *
4415 standard_lookup (const char *name, const struct block *block,
4416                  domain_enum domain)
4417 {
4418   /* Initialize it just to avoid a GCC false warning.  */
4419   struct block_symbol sym = {};
4420
4421   if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4422     return sym.symbol;
4423   ada_lookup_encoded_symbol (name, block, domain, &sym);
4424   cache_symbol (name, domain, sym.symbol, sym.block);
4425   return sym.symbol;
4426 }
4427
4428
4429 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4430    in the symbol fields of SYMS.  We treat enumerals as functions, 
4431    since they contend in overloading in the same way.  */
4432 static int
4433 is_nonfunction (const std::vector<struct block_symbol> &syms)
4434 {
4435   for (const block_symbol &sym : syms)
4436     if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4437         && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
4438             || sym.symbol->aclass () != LOC_CONST))
4439       return 1;
4440
4441   return 0;
4442 }
4443
4444 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4445    struct types.  Otherwise, they may not.  */
4446
4447 static int
4448 equiv_types (struct type *type0, struct type *type1)
4449 {
4450   if (type0 == type1)
4451     return 1;
4452   if (type0 == NULL || type1 == NULL
4453       || type0->code () != type1->code ())
4454     return 0;
4455   if ((type0->code () == TYPE_CODE_STRUCT
4456        || type0->code () == TYPE_CODE_ENUM)
4457       && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4458       && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4459     return 1;
4460
4461   return 0;
4462 }
4463
4464 /* True iff SYM0 represents the same entity as SYM1, or one that is
4465    no more defined than that of SYM1.  */
4466
4467 static int
4468 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4469 {
4470   if (sym0 == sym1)
4471     return 1;
4472   if (sym0->domain () != sym1->domain ()
4473       || sym0->aclass () != sym1->aclass ())
4474     return 0;
4475
4476   switch (sym0->aclass ())
4477     {
4478     case LOC_UNDEF:
4479       return 1;
4480     case LOC_TYPEDEF:
4481       {
4482         struct type *type0 = sym0->type ();
4483         struct type *type1 = sym1->type ();
4484         const char *name0 = sym0->linkage_name ();
4485         const char *name1 = sym1->linkage_name ();
4486         int len0 = strlen (name0);
4487
4488         return
4489           type0->code () == type1->code ()
4490           && (equiv_types (type0, type1)
4491               || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4492                   && startswith (name1 + len0, "___XV")));
4493       }
4494     case LOC_CONST:
4495       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
4496         && equiv_types (sym0->type (), sym1->type ());
4497
4498     case LOC_STATIC:
4499       {
4500         const char *name0 = sym0->linkage_name ();
4501         const char *name1 = sym1->linkage_name ();
4502         return (strcmp (name0, name1) == 0
4503                 && SYMBOL_VALUE_ADDRESS (sym0) == SYMBOL_VALUE_ADDRESS (sym1));
4504       }
4505
4506     default:
4507       return 0;
4508     }
4509 }
4510
4511 /* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4512    records in RESULT.  Do nothing if SYM is a duplicate.  */
4513
4514 static void
4515 add_defn_to_vec (std::vector<struct block_symbol> &result,
4516                  struct symbol *sym,
4517                  const struct block *block)
4518 {
4519   /* Do not try to complete stub types, as the debugger is probably
4520      already scanning all symbols matching a certain name at the
4521      time when this function is called.  Trying to replace the stub
4522      type by its associated full type will cause us to restart a scan
4523      which may lead to an infinite recursion.  Instead, the client
4524      collecting the matching symbols will end up collecting several
4525      matches, with at least one of them complete.  It can then filter
4526      out the stub ones if needed.  */
4527
4528   for (int i = result.size () - 1; i >= 0; i -= 1)
4529     {
4530       if (lesseq_defined_than (sym, result[i].symbol))
4531         return;
4532       else if (lesseq_defined_than (result[i].symbol, sym))
4533         {
4534           result[i].symbol = sym;
4535           result[i].block = block;
4536           return;
4537         }
4538     }
4539
4540   struct block_symbol info;
4541   info.symbol = sym;
4542   info.block = block;
4543   result.push_back (info);
4544 }
4545
4546 /* Return a bound minimal symbol matching NAME according to Ada
4547    decoding rules.  Returns an invalid symbol if there is no such
4548    minimal symbol.  Names prefixed with "standard__" are handled
4549    specially: "standard__" is first stripped off, and only static and
4550    global symbols are searched.  */
4551
4552 struct bound_minimal_symbol
4553 ada_lookup_simple_minsym (const char *name)
4554 {
4555   struct bound_minimal_symbol result;
4556
4557   symbol_name_match_type match_type = name_match_type_from_name (name);
4558   lookup_name_info lookup_name (name, match_type);
4559
4560   symbol_name_matcher_ftype *match_name
4561     = ada_get_symbol_name_matcher (lookup_name);
4562
4563   for (objfile *objfile : current_program_space->objfiles ())
4564     {
4565       for (minimal_symbol *msymbol : objfile->msymbols ())
4566         {
4567           if (match_name (msymbol->linkage_name (), lookup_name, NULL)
4568               && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4569             {
4570               result.minsym = msymbol;
4571               result.objfile = objfile;
4572               break;
4573             }
4574         }
4575     }
4576
4577   return result;
4578 }
4579
4580 /* True if TYPE is definitely an artificial type supplied to a symbol
4581    for which no debugging information was given in the symbol file.  */
4582
4583 static int
4584 is_nondebugging_type (struct type *type)
4585 {
4586   const char *name = ada_type_name (type);
4587
4588   return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4589 }
4590
4591 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4592    that are deemed "identical" for practical purposes.
4593
4594    This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4595    types and that their number of enumerals is identical (in other
4596    words, type1->num_fields () == type2->num_fields ()).  */
4597
4598 static int
4599 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4600 {
4601   int i;
4602
4603   /* The heuristic we use here is fairly conservative.  We consider
4604      that 2 enumerate types are identical if they have the same
4605      number of enumerals and that all enumerals have the same
4606      underlying value and name.  */
4607
4608   /* All enums in the type should have an identical underlying value.  */
4609   for (i = 0; i < type1->num_fields (); i++)
4610     if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
4611       return 0;
4612
4613   /* All enumerals should also have the same name (modulo any numerical
4614      suffix).  */
4615   for (i = 0; i < type1->num_fields (); i++)
4616     {
4617       const char *name_1 = type1->field (i).name ();
4618       const char *name_2 = type2->field (i).name ();
4619       int len_1 = strlen (name_1);
4620       int len_2 = strlen (name_2);
4621
4622       ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4623       ada_remove_trailing_digits (type2->field (i).name (), &len_2);
4624       if (len_1 != len_2
4625           || strncmp (type1->field (i).name (),
4626                       type2->field (i).name (),
4627                       len_1) != 0)
4628         return 0;
4629     }
4630
4631   return 1;
4632 }
4633
4634 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
4635    that are deemed "identical" for practical purposes.  Sometimes,
4636    enumerals are not strictly identical, but their types are so similar
4637    that they can be considered identical.
4638
4639    For instance, consider the following code:
4640
4641       type Color is (Black, Red, Green, Blue, White);
4642       type RGB_Color is new Color range Red .. Blue;
4643
4644    Type RGB_Color is a subrange of an implicit type which is a copy
4645    of type Color. If we call that implicit type RGB_ColorB ("B" is
4646    for "Base Type"), then type RGB_ColorB is a copy of type Color.
4647    As a result, when an expression references any of the enumeral
4648    by name (Eg. "print green"), the expression is technically
4649    ambiguous and the user should be asked to disambiguate. But
4650    doing so would only hinder the user, since it wouldn't matter
4651    what choice he makes, the outcome would always be the same.
4652    So, for practical purposes, we consider them as the same.  */
4653
4654 static int
4655 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
4656 {
4657   int i;
4658
4659   /* Before performing a thorough comparison check of each type,
4660      we perform a series of inexpensive checks.  We expect that these
4661      checks will quickly fail in the vast majority of cases, and thus
4662      help prevent the unnecessary use of a more expensive comparison.
4663      Said comparison also expects us to make some of these checks
4664      (see ada_identical_enum_types_p).  */
4665
4666   /* Quick check: All symbols should have an enum type.  */
4667   for (i = 0; i < syms.size (); i++)
4668     if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
4669       return 0;
4670
4671   /* Quick check: They should all have the same value.  */
4672   for (i = 1; i < syms.size (); i++)
4673     if (SYMBOL_VALUE (syms[i].symbol) != SYMBOL_VALUE (syms[0].symbol))
4674       return 0;
4675
4676   /* Quick check: They should all have the same number of enumerals.  */
4677   for (i = 1; i < syms.size (); i++)
4678     if (syms[i].symbol->type ()->num_fields ()
4679         != syms[0].symbol->type ()->num_fields ())
4680       return 0;
4681
4682   /* All the sanity checks passed, so we might have a set of
4683      identical enumeration types.  Perform a more complete
4684      comparison of the type of each symbol.  */
4685   for (i = 1; i < syms.size (); i++)
4686     if (!ada_identical_enum_types_p (syms[i].symbol->type (),
4687                                      syms[0].symbol->type ()))
4688       return 0;
4689
4690   return 1;
4691 }
4692
4693 /* Remove any non-debugging symbols in SYMS that definitely
4694    duplicate other symbols in the list (The only case I know of where
4695    this happens is when object files containing stabs-in-ecoff are
4696    linked with files containing ordinary ecoff debugging symbols (or no
4697    debugging symbols)).  Modifies SYMS to squeeze out deleted entries.  */
4698
4699 static void
4700 remove_extra_symbols (std::vector<struct block_symbol> *syms)
4701 {
4702   int i, j;
4703
4704   /* We should never be called with less than 2 symbols, as there
4705      cannot be any extra symbol in that case.  But it's easy to
4706      handle, since we have nothing to do in that case.  */
4707   if (syms->size () < 2)
4708     return;
4709
4710   i = 0;
4711   while (i < syms->size ())
4712     {
4713       int remove_p = 0;
4714
4715       /* If two symbols have the same name and one of them is a stub type,
4716          the get rid of the stub.  */
4717
4718       if ((*syms)[i].symbol->type ()->is_stub ()
4719           && (*syms)[i].symbol->linkage_name () != NULL)
4720         {
4721           for (j = 0; j < syms->size (); j++)
4722             {
4723               if (j != i
4724                   && !(*syms)[j].symbol->type ()->is_stub ()
4725                   && (*syms)[j].symbol->linkage_name () != NULL
4726                   && strcmp ((*syms)[i].symbol->linkage_name (),
4727                              (*syms)[j].symbol->linkage_name ()) == 0)
4728                 remove_p = 1;
4729             }
4730         }
4731
4732       /* Two symbols with the same name, same class and same address
4733          should be identical.  */
4734
4735       else if ((*syms)[i].symbol->linkage_name () != NULL
4736           && (*syms)[i].symbol->aclass () == LOC_STATIC
4737           && is_nondebugging_type ((*syms)[i].symbol->type ()))
4738         {
4739           for (j = 0; j < syms->size (); j += 1)
4740             {
4741               if (i != j
4742                   && (*syms)[j].symbol->linkage_name () != NULL
4743                   && strcmp ((*syms)[i].symbol->linkage_name (),
4744                              (*syms)[j].symbol->linkage_name ()) == 0
4745                   && ((*syms)[i].symbol->aclass ()
4746                       == (*syms)[j].symbol->aclass ())
4747                   && SYMBOL_VALUE_ADDRESS ((*syms)[i].symbol)
4748                   == SYMBOL_VALUE_ADDRESS ((*syms)[j].symbol))
4749                 remove_p = 1;
4750             }
4751         }
4752       
4753       if (remove_p)
4754         syms->erase (syms->begin () + i);
4755       else
4756         i += 1;
4757     }
4758
4759   /* If all the remaining symbols are identical enumerals, then
4760      just keep the first one and discard the rest.
4761
4762      Unlike what we did previously, we do not discard any entry
4763      unless they are ALL identical.  This is because the symbol
4764      comparison is not a strict comparison, but rather a practical
4765      comparison.  If all symbols are considered identical, then
4766      we can just go ahead and use the first one and discard the rest.
4767      But if we cannot reduce the list to a single element, we have
4768      to ask the user to disambiguate anyways.  And if we have to
4769      present a multiple-choice menu, it's less confusing if the list
4770      isn't missing some choices that were identical and yet distinct.  */
4771   if (symbols_are_identical_enums (*syms))
4772     syms->resize (1);
4773 }
4774
4775 /* Given a type that corresponds to a renaming entity, use the type name
4776    to extract the scope (package name or function name, fully qualified,
4777    and following the GNAT encoding convention) where this renaming has been
4778    defined.  */
4779
4780 static std::string
4781 xget_renaming_scope (struct type *renaming_type)
4782 {
4783   /* The renaming types adhere to the following convention:
4784      <scope>__<rename>___<XR extension>.
4785      So, to extract the scope, we search for the "___XR" extension,
4786      and then backtrack until we find the first "__".  */
4787
4788   const char *name = renaming_type->name ();
4789   const char *suffix = strstr (name, "___XR");
4790   const char *last;
4791
4792   /* Now, backtrack a bit until we find the first "__".  Start looking
4793      at suffix - 3, as the <rename> part is at least one character long.  */
4794
4795   for (last = suffix - 3; last > name; last--)
4796     if (last[0] == '_' && last[1] == '_')
4797       break;
4798
4799   /* Make a copy of scope and return it.  */
4800   return std::string (name, last);
4801 }
4802
4803 /* Return nonzero if NAME corresponds to a package name.  */
4804
4805 static int
4806 is_package_name (const char *name)
4807 {
4808   /* Here, We take advantage of the fact that no symbols are generated
4809      for packages, while symbols are generated for each function.
4810      So the condition for NAME represent a package becomes equivalent
4811      to NAME not existing in our list of symbols.  There is only one
4812      small complication with library-level functions (see below).  */
4813
4814   /* If it is a function that has not been defined at library level,
4815      then we should be able to look it up in the symbols.  */
4816   if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
4817     return 0;
4818
4819   /* Library-level function names start with "_ada_".  See if function
4820      "_ada_" followed by NAME can be found.  */
4821
4822   /* Do a quick check that NAME does not contain "__", since library-level
4823      functions names cannot contain "__" in them.  */
4824   if (strstr (name, "__") != NULL)
4825     return 0;
4826
4827   std::string fun_name = string_printf ("_ada_%s", name);
4828
4829   return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
4830 }
4831
4832 /* Return nonzero if SYM corresponds to a renaming entity that is
4833    not visible from FUNCTION_NAME.  */
4834
4835 static int
4836 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
4837 {
4838   if (sym->aclass () != LOC_TYPEDEF)
4839     return 0;
4840
4841   std::string scope = xget_renaming_scope (sym->type ());
4842
4843   /* If the rename has been defined in a package, then it is visible.  */
4844   if (is_package_name (scope.c_str ()))
4845     return 0;
4846
4847   /* Check that the rename is in the current function scope by checking
4848      that its name starts with SCOPE.  */
4849
4850   /* If the function name starts with "_ada_", it means that it is
4851      a library-level function.  Strip this prefix before doing the
4852      comparison, as the encoding for the renaming does not contain
4853      this prefix.  */
4854   if (startswith (function_name, "_ada_"))
4855     function_name += 5;
4856
4857   return !startswith (function_name, scope.c_str ());
4858 }
4859
4860 /* Remove entries from SYMS that corresponds to a renaming entity that
4861    is not visible from the function associated with CURRENT_BLOCK or
4862    that is superfluous due to the presence of more specific renaming
4863    information.  Places surviving symbols in the initial entries of
4864    SYMS.
4865
4866    Rationale:
4867    First, in cases where an object renaming is implemented as a
4868    reference variable, GNAT may produce both the actual reference
4869    variable and the renaming encoding.  In this case, we discard the
4870    latter.
4871
4872    Second, GNAT emits a type following a specified encoding for each renaming
4873    entity.  Unfortunately, STABS currently does not support the definition
4874    of types that are local to a given lexical block, so all renamings types
4875    are emitted at library level.  As a consequence, if an application
4876    contains two renaming entities using the same name, and a user tries to
4877    print the value of one of these entities, the result of the ada symbol
4878    lookup will also contain the wrong renaming type.
4879
4880    This function partially covers for this limitation by attempting to
4881    remove from the SYMS list renaming symbols that should be visible
4882    from CURRENT_BLOCK.  However, there does not seem be a 100% reliable
4883    method with the current information available.  The implementation
4884    below has a couple of limitations (FIXME: brobecker-2003-05-12):  
4885    
4886       - When the user tries to print a rename in a function while there
4887         is another rename entity defined in a package:  Normally, the
4888         rename in the function has precedence over the rename in the
4889         package, so the latter should be removed from the list.  This is
4890         currently not the case.
4891         
4892       - This function will incorrectly remove valid renames if
4893         the CURRENT_BLOCK corresponds to a function which symbol name
4894         has been changed by an "Export" pragma.  As a consequence,
4895         the user will be unable to print such rename entities.  */
4896
4897 static void
4898 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
4899                              const struct block *current_block)
4900 {
4901   struct symbol *current_function;
4902   const char *current_function_name;
4903   int i;
4904   int is_new_style_renaming;
4905
4906   /* If there is both a renaming foo___XR... encoded as a variable and
4907      a simple variable foo in the same block, discard the latter.
4908      First, zero out such symbols, then compress.  */
4909   is_new_style_renaming = 0;
4910   for (i = 0; i < syms->size (); i += 1)
4911     {
4912       struct symbol *sym = (*syms)[i].symbol;
4913       const struct block *block = (*syms)[i].block;
4914       const char *name;
4915       const char *suffix;
4916
4917       if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
4918         continue;
4919       name = sym->linkage_name ();
4920       suffix = strstr (name, "___XR");
4921
4922       if (suffix != NULL)
4923         {
4924           int name_len = suffix - name;
4925           int j;
4926
4927           is_new_style_renaming = 1;
4928           for (j = 0; j < syms->size (); j += 1)
4929             if (i != j && (*syms)[j].symbol != NULL
4930                 && strncmp (name, (*syms)[j].symbol->linkage_name (),
4931                             name_len) == 0
4932                 && block == (*syms)[j].block)
4933               (*syms)[j].symbol = NULL;
4934         }
4935     }
4936   if (is_new_style_renaming)
4937     {
4938       int j, k;
4939
4940       for (j = k = 0; j < syms->size (); j += 1)
4941         if ((*syms)[j].symbol != NULL)
4942             {
4943               (*syms)[k] = (*syms)[j];
4944               k += 1;
4945             }
4946       syms->resize (k);
4947       return;
4948     }
4949
4950   /* Extract the function name associated to CURRENT_BLOCK.
4951      Abort if unable to do so.  */
4952
4953   if (current_block == NULL)
4954     return;
4955
4956   current_function = block_linkage_function (current_block);
4957   if (current_function == NULL)
4958     return;
4959
4960   current_function_name = current_function->linkage_name ();
4961   if (current_function_name == NULL)
4962     return;
4963
4964   /* Check each of the symbols, and remove it from the list if it is
4965      a type corresponding to a renaming that is out of the scope of
4966      the current block.  */
4967
4968   i = 0;
4969   while (i < syms->size ())
4970     {
4971       if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
4972           == ADA_OBJECT_RENAMING
4973           && old_renaming_is_invisible ((*syms)[i].symbol,
4974                                         current_function_name))
4975         syms->erase (syms->begin () + i);
4976       else
4977         i += 1;
4978     }
4979 }
4980
4981 /* Add to RESULT all symbols from BLOCK (and its super-blocks)
4982    whose name and domain match LOOKUP_NAME and DOMAIN respectively.
4983
4984    Note: This function assumes that RESULT is empty.  */
4985
4986 static void
4987 ada_add_local_symbols (std::vector<struct block_symbol> &result,
4988                        const lookup_name_info &lookup_name,
4989                        const struct block *block, domain_enum domain)
4990 {
4991   while (block != NULL)
4992     {
4993       ada_add_block_symbols (result, block, lookup_name, domain, NULL);
4994
4995       /* If we found a non-function match, assume that's the one.  We
4996          only check this when finding a function boundary, so that we
4997          can accumulate all results from intervening blocks first.  */
4998       if (BLOCK_FUNCTION (block) != nullptr && is_nonfunction (result))
4999         return;
5000
5001       block = BLOCK_SUPERBLOCK (block);
5002     }
5003 }
5004
5005 /* An object of this type is used as the callback argument when
5006    calling the map_matching_symbols method.  */
5007
5008 struct match_data
5009 {
5010   explicit match_data (std::vector<struct block_symbol> *rp)
5011     : resultp (rp)
5012   {
5013   }
5014   DISABLE_COPY_AND_ASSIGN (match_data);
5015
5016   bool operator() (struct block_symbol *bsym);
5017
5018   struct objfile *objfile = nullptr;
5019   std::vector<struct block_symbol> *resultp;
5020   struct symbol *arg_sym = nullptr;
5021   bool found_sym = false;
5022 };
5023
5024 /* A callback for add_nonlocal_symbols that adds symbol, found in
5025    BSYM, to a list of symbols.  */
5026
5027 bool
5028 match_data::operator() (struct block_symbol *bsym)
5029 {
5030   const struct block *block = bsym->block;
5031   struct symbol *sym = bsym->symbol;
5032
5033   if (sym == NULL)
5034     {
5035       if (!found_sym && arg_sym != NULL)
5036         add_defn_to_vec (*resultp,
5037                          fixup_symbol_section (arg_sym, objfile),
5038                          block);
5039       found_sym = false;
5040       arg_sym = NULL;
5041     }
5042   else 
5043     {
5044       if (sym->aclass () == LOC_UNRESOLVED)
5045         return true;
5046       else if (sym->is_argument ())
5047         arg_sym = sym;
5048       else
5049         {
5050           found_sym = true;
5051           add_defn_to_vec (*resultp,
5052                            fixup_symbol_section (sym, objfile),
5053                            block);
5054         }
5055     }
5056   return true;
5057 }
5058
5059 /* Helper for add_nonlocal_symbols.  Find symbols in DOMAIN which are
5060    targeted by renamings matching LOOKUP_NAME in BLOCK.  Add these
5061    symbols to RESULT.  Return whether we found such symbols.  */
5062
5063 static int
5064 ada_add_block_renamings (std::vector<struct block_symbol> &result,
5065                          const struct block *block,
5066                          const lookup_name_info &lookup_name,
5067                          domain_enum domain)
5068 {
5069   struct using_direct *renaming;
5070   int defns_mark = result.size ();
5071
5072   symbol_name_matcher_ftype *name_match
5073     = ada_get_symbol_name_matcher (lookup_name);
5074
5075   for (renaming = block_using (block);
5076        renaming != NULL;
5077        renaming = renaming->next)
5078     {
5079       const char *r_name;
5080
5081       /* Avoid infinite recursions: skip this renaming if we are actually
5082          already traversing it.
5083
5084          Currently, symbol lookup in Ada don't use the namespace machinery from
5085          C++/Fortran support: skip namespace imports that use them.  */
5086       if (renaming->searched
5087           || (renaming->import_src != NULL
5088               && renaming->import_src[0] != '\0')
5089           || (renaming->import_dest != NULL
5090               && renaming->import_dest[0] != '\0'))
5091         continue;
5092       renaming->searched = 1;
5093
5094       /* TODO: here, we perform another name-based symbol lookup, which can
5095          pull its own multiple overloads.  In theory, we should be able to do
5096          better in this case since, in DWARF, DW_AT_import is a DIE reference,
5097          not a simple name.  But in order to do this, we would need to enhance
5098          the DWARF reader to associate a symbol to this renaming, instead of a
5099          name.  So, for now, we do something simpler: re-use the C++/Fortran
5100          namespace machinery.  */
5101       r_name = (renaming->alias != NULL
5102                 ? renaming->alias
5103                 : renaming->declaration);
5104       if (name_match (r_name, lookup_name, NULL))
5105         {
5106           lookup_name_info decl_lookup_name (renaming->declaration,
5107                                              lookup_name.match_type ());
5108           ada_add_all_symbols (result, block, decl_lookup_name, domain,
5109                                1, NULL);
5110         }
5111       renaming->searched = 0;
5112     }
5113   return result.size () != defns_mark;
5114 }
5115
5116 /* Implements compare_names, but only applying the comparision using
5117    the given CASING.  */
5118
5119 static int
5120 compare_names_with_case (const char *string1, const char *string2,
5121                          enum case_sensitivity casing)
5122 {
5123   while (*string1 != '\0' && *string2 != '\0')
5124     {
5125       char c1, c2;
5126
5127       if (isspace (*string1) || isspace (*string2))
5128         return strcmp_iw_ordered (string1, string2);
5129
5130       if (casing == case_sensitive_off)
5131         {
5132           c1 = tolower (*string1);
5133           c2 = tolower (*string2);
5134         }
5135       else
5136         {
5137           c1 = *string1;
5138           c2 = *string2;
5139         }
5140       if (c1 != c2)
5141         break;
5142
5143       string1 += 1;
5144       string2 += 1;
5145     }
5146
5147   switch (*string1)
5148     {
5149     case '(':
5150       return strcmp_iw_ordered (string1, string2);
5151     case '_':
5152       if (*string2 == '\0')
5153         {
5154           if (is_name_suffix (string1))
5155             return 0;
5156           else
5157             return 1;
5158         }
5159       /* FALLTHROUGH */
5160     default:
5161       if (*string2 == '(')
5162         return strcmp_iw_ordered (string1, string2);
5163       else
5164         {
5165           if (casing == case_sensitive_off)
5166             return tolower (*string1) - tolower (*string2);
5167           else
5168             return *string1 - *string2;
5169         }
5170     }
5171 }
5172
5173 /* Compare STRING1 to STRING2, with results as for strcmp.
5174    Compatible with strcmp_iw_ordered in that...
5175
5176        strcmp_iw_ordered (STRING1, STRING2) <= 0
5177
5178    ... implies...
5179
5180        compare_names (STRING1, STRING2) <= 0
5181
5182    (they may differ as to what symbols compare equal).  */
5183
5184 static int
5185 compare_names (const char *string1, const char *string2)
5186 {
5187   int result;
5188
5189   /* Similar to what strcmp_iw_ordered does, we need to perform
5190      a case-insensitive comparison first, and only resort to
5191      a second, case-sensitive, comparison if the first one was
5192      not sufficient to differentiate the two strings.  */
5193
5194   result = compare_names_with_case (string1, string2, case_sensitive_off);
5195   if (result == 0)
5196     result = compare_names_with_case (string1, string2, case_sensitive_on);
5197
5198   return result;
5199 }
5200
5201 /* Convenience function to get at the Ada encoded lookup name for
5202    LOOKUP_NAME, as a C string.  */
5203
5204 static const char *
5205 ada_lookup_name (const lookup_name_info &lookup_name)
5206 {
5207   return lookup_name.ada ().lookup_name ().c_str ();
5208 }
5209
5210 /* A helper for add_nonlocal_symbols.  Call expand_matching_symbols
5211    for OBJFILE, then walk the objfile's symtabs and update the
5212    results.  */
5213
5214 static void
5215 map_matching_symbols (struct objfile *objfile,
5216                       const lookup_name_info &lookup_name,
5217                       bool is_wild_match,
5218                       domain_enum domain,
5219                       int global,
5220                       match_data &data)
5221 {
5222   data.objfile = objfile;
5223   objfile->expand_matching_symbols (lookup_name, domain, global,
5224                                     is_wild_match ? nullptr : compare_names);
5225
5226   const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5227   for (compunit_symtab *symtab : objfile->compunits ())
5228     {
5229       const struct block *block
5230         = BLOCKVECTOR_BLOCK (symtab->blockvector (), block_kind);
5231       if (!iterate_over_symbols_terminated (block, lookup_name,
5232                                             domain, data))
5233         break;
5234     }
5235 }
5236
5237 /* Add to RESULT all non-local symbols whose name and domain match
5238    LOOKUP_NAME and DOMAIN respectively.  The search is performed on
5239    GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5240    symbols otherwise.  */
5241
5242 static void
5243 add_nonlocal_symbols (std::vector<struct block_symbol> &result,
5244                       const lookup_name_info &lookup_name,
5245                       domain_enum domain, int global)
5246 {
5247   struct match_data data (&result);
5248
5249   bool is_wild_match = lookup_name.ada ().wild_match_p ();
5250
5251   for (objfile *objfile : current_program_space->objfiles ())
5252     {
5253       map_matching_symbols (objfile, lookup_name, is_wild_match, domain,
5254                             global, data);
5255
5256       for (compunit_symtab *cu : objfile->compunits ())
5257         {
5258           const struct block *global_block
5259             = BLOCKVECTOR_BLOCK (cu->blockvector (), GLOBAL_BLOCK);
5260
5261           if (ada_add_block_renamings (result, global_block, lookup_name,
5262                                        domain))
5263             data.found_sym = true;
5264         }
5265     }
5266
5267   if (result.empty () && global && !is_wild_match)
5268     {
5269       const char *name = ada_lookup_name (lookup_name);
5270       std::string bracket_name = std::string ("<_ada_") + name + '>';
5271       lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
5272
5273       for (objfile *objfile : current_program_space->objfiles ())
5274         map_matching_symbols (objfile, name1, false, domain, global, data);
5275     }
5276 }
5277
5278 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5279    FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5280    returning the number of matches.  Add these to RESULT.
5281
5282    When FULL_SEARCH is non-zero, any non-function/non-enumeral
5283    symbol match within the nest of blocks whose innermost member is BLOCK,
5284    is the one match returned (no other matches in that or
5285    enclosing blocks is returned).  If there are any matches in or
5286    surrounding BLOCK, then these alone are returned.
5287
5288    Names prefixed with "standard__" are handled specially:
5289    "standard__" is first stripped off (by the lookup_name
5290    constructor), and only static and global symbols are searched.
5291
5292    If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5293    to lookup global symbols.  */
5294
5295 static void
5296 ada_add_all_symbols (std::vector<struct block_symbol> &result,
5297                      const struct block *block,
5298                      const lookup_name_info &lookup_name,
5299                      domain_enum domain,
5300                      int full_search,
5301                      int *made_global_lookup_p)
5302 {
5303   struct symbol *sym;
5304
5305   if (made_global_lookup_p)
5306     *made_global_lookup_p = 0;
5307
5308   /* Special case: If the user specifies a symbol name inside package
5309      Standard, do a non-wild matching of the symbol name without
5310      the "standard__" prefix.  This was primarily introduced in order
5311      to allow the user to specifically access the standard exceptions
5312      using, for instance, Standard.Constraint_Error when Constraint_Error
5313      is ambiguous (due to the user defining its own Constraint_Error
5314      entity inside its program).  */
5315   if (lookup_name.ada ().standard_p ())
5316     block = NULL;
5317
5318   /* Check the non-global symbols.  If we have ANY match, then we're done.  */
5319
5320   if (block != NULL)
5321     {
5322       if (full_search)
5323         ada_add_local_symbols (result, lookup_name, block, domain);
5324       else
5325         {
5326           /* In the !full_search case we're are being called by
5327              iterate_over_symbols, and we don't want to search
5328              superblocks.  */
5329           ada_add_block_symbols (result, block, lookup_name, domain, NULL);
5330         }
5331       if (!result.empty () || !full_search)
5332         return;
5333     }
5334
5335   /* No non-global symbols found.  Check our cache to see if we have
5336      already performed this search before.  If we have, then return
5337      the same result.  */
5338
5339   if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5340                             domain, &sym, &block))
5341     {
5342       if (sym != NULL)
5343         add_defn_to_vec (result, sym, block);
5344       return;
5345     }
5346
5347   if (made_global_lookup_p)
5348     *made_global_lookup_p = 1;
5349
5350   /* Search symbols from all global blocks.  */
5351  
5352   add_nonlocal_symbols (result, lookup_name, domain, 1);
5353
5354   /* Now add symbols from all per-file blocks if we've gotten no hits
5355      (not strictly correct, but perhaps better than an error).  */
5356
5357   if (result.empty ())
5358     add_nonlocal_symbols (result, lookup_name, domain, 0);
5359 }
5360
5361 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5362    is non-zero, enclosing scope and in global scopes.
5363
5364    Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5365    blocks and symbol tables (if any) in which they were found.
5366
5367    When full_search is non-zero, any non-function/non-enumeral
5368    symbol match within the nest of blocks whose innermost member is BLOCK,
5369    is the one match returned (no other matches in that or
5370    enclosing blocks is returned).  If there are any matches in or
5371    surrounding BLOCK, then these alone are returned.
5372
5373    Names prefixed with "standard__" are handled specially: "standard__"
5374    is first stripped off, and only static and global symbols are searched.  */
5375
5376 static std::vector<struct block_symbol>
5377 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5378                                const struct block *block,
5379                                domain_enum domain,
5380                                int full_search)
5381 {
5382   int syms_from_global_search;
5383   std::vector<struct block_symbol> results;
5384
5385   ada_add_all_symbols (results, block, lookup_name,
5386                        domain, full_search, &syms_from_global_search);
5387
5388   remove_extra_symbols (&results);
5389
5390   if (results.empty () && full_search && syms_from_global_search)
5391     cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5392
5393   if (results.size () == 1 && full_search && syms_from_global_search)
5394     cache_symbol (ada_lookup_name (lookup_name), domain,
5395                   results[0].symbol, results[0].block);
5396
5397   remove_irrelevant_renamings (&results, block);
5398   return results;
5399 }
5400
5401 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5402    in global scopes, returning (SYM,BLOCK) tuples.
5403
5404    See ada_lookup_symbol_list_worker for further details.  */
5405
5406 std::vector<struct block_symbol>
5407 ada_lookup_symbol_list (const char *name, const struct block *block,
5408                         domain_enum domain)
5409 {
5410   symbol_name_match_type name_match_type = name_match_type_from_name (name);
5411   lookup_name_info lookup_name (name, name_match_type);
5412
5413   return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
5414 }
5415
5416 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5417    to 1, but choosing the first symbol found if there are multiple
5418    choices.
5419
5420    The result is stored in *INFO, which must be non-NULL.
5421    If no match is found, INFO->SYM is set to NULL.  */
5422
5423 void
5424 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5425                            domain_enum domain,
5426                            struct block_symbol *info)
5427 {
5428   /* Since we already have an encoded name, wrap it in '<>' to force a
5429      verbatim match.  Otherwise, if the name happens to not look like
5430      an encoded name (because it doesn't include a "__"),
5431      ada_lookup_name_info would re-encode/fold it again, and that
5432      would e.g., incorrectly lowercase object renaming names like
5433      "R28b" -> "r28b".  */
5434   std::string verbatim = add_angle_brackets (name);
5435
5436   gdb_assert (info != NULL);
5437   *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
5438 }
5439
5440 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5441    scope and in global scopes, or NULL if none.  NAME is folded and
5442    encoded first.  Otherwise, the result is as for ada_lookup_symbol_list,
5443    choosing the first symbol if there are multiple choices.  */
5444
5445 struct block_symbol
5446 ada_lookup_symbol (const char *name, const struct block *block0,
5447                    domain_enum domain)
5448 {
5449   std::vector<struct block_symbol> candidates
5450     = ada_lookup_symbol_list (name, block0, domain);
5451
5452   if (candidates.empty ())
5453     return {};
5454
5455   block_symbol info = candidates[0];
5456   info.symbol = fixup_symbol_section (info.symbol, NULL);
5457   return info;
5458 }
5459
5460
5461 /* True iff STR is a possible encoded suffix of a normal Ada name
5462    that is to be ignored for matching purposes.  Suffixes of parallel
5463    names (e.g., XVE) are not included here.  Currently, the possible suffixes
5464    are given by any of the regular expressions:
5465
5466    [.$][0-9]+       [nested subprogram suffix, on platforms such as GNU/Linux]
5467    ___[0-9]+        [nested subprogram suffix, on platforms such as HP/UX]
5468    TKB              [subprogram suffix for task bodies]
5469    _E[0-9]+[bs]$    [protected object entry suffixes]
5470    (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5471
5472    Also, any leading "__[0-9]+" sequence is skipped before the suffix
5473    match is performed.  This sequence is used to differentiate homonyms,
5474    is an optional part of a valid name suffix.  */
5475
5476 static int
5477 is_name_suffix (const char *str)
5478 {
5479   int k;
5480   const char *matching;
5481   const int len = strlen (str);
5482
5483   /* Skip optional leading __[0-9]+.  */
5484
5485   if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5486     {
5487       str += 3;
5488       while (isdigit (str[0]))
5489         str += 1;
5490     }
5491   
5492   /* [.$][0-9]+ */
5493
5494   if (str[0] == '.' || str[0] == '$')
5495     {
5496       matching = str + 1;
5497       while (isdigit (matching[0]))
5498         matching += 1;
5499       if (matching[0] == '\0')
5500         return 1;
5501     }
5502
5503   /* ___[0-9]+ */
5504
5505   if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5506     {
5507       matching = str + 3;
5508       while (isdigit (matching[0]))
5509         matching += 1;
5510       if (matching[0] == '\0')
5511         return 1;
5512     }
5513
5514   /* "TKB" suffixes are used for subprograms implementing task bodies.  */
5515
5516   if (strcmp (str, "TKB") == 0)
5517     return 1;
5518
5519 #if 0
5520   /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5521      with a N at the end.  Unfortunately, the compiler uses the same
5522      convention for other internal types it creates.  So treating
5523      all entity names that end with an "N" as a name suffix causes
5524      some regressions.  For instance, consider the case of an enumerated
5525      type.  To support the 'Image attribute, it creates an array whose
5526      name ends with N.
5527      Having a single character like this as a suffix carrying some
5528      information is a bit risky.  Perhaps we should change the encoding
5529      to be something like "_N" instead.  In the meantime, do not do
5530      the following check.  */
5531   /* Protected Object Subprograms */
5532   if (len == 1 && str [0] == 'N')
5533     return 1;
5534 #endif
5535
5536   /* _E[0-9]+[bs]$ */
5537   if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5538     {
5539       matching = str + 3;
5540       while (isdigit (matching[0]))
5541         matching += 1;
5542       if ((matching[0] == 'b' || matching[0] == 's')
5543           && matching [1] == '\0')
5544         return 1;
5545     }
5546
5547   /* ??? We should not modify STR directly, as we are doing below.  This
5548      is fine in this case, but may become problematic later if we find
5549      that this alternative did not work, and want to try matching
5550      another one from the begining of STR.  Since we modified it, we
5551      won't be able to find the begining of the string anymore!  */
5552   if (str[0] == 'X')
5553     {
5554       str += 1;
5555       while (str[0] != '_' && str[0] != '\0')
5556         {
5557           if (str[0] != 'n' && str[0] != 'b')
5558             return 0;
5559           str += 1;
5560         }
5561     }
5562
5563   if (str[0] == '\000')
5564     return 1;
5565
5566   if (str[0] == '_')
5567     {
5568       if (str[1] != '_' || str[2] == '\000')
5569         return 0;
5570       if (str[2] == '_')
5571         {
5572           if (strcmp (str + 3, "JM") == 0)
5573             return 1;
5574           /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5575              the LJM suffix in favor of the JM one.  But we will
5576              still accept LJM as a valid suffix for a reasonable
5577              amount of time, just to allow ourselves to debug programs
5578              compiled using an older version of GNAT.  */
5579           if (strcmp (str + 3, "LJM") == 0)
5580             return 1;
5581           if (str[3] != 'X')
5582             return 0;
5583           if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5584               || str[4] == 'U' || str[4] == 'P')
5585             return 1;
5586           if (str[4] == 'R' && str[5] != 'T')
5587             return 1;
5588           return 0;
5589         }
5590       if (!isdigit (str[2]))
5591         return 0;
5592       for (k = 3; str[k] != '\0'; k += 1)
5593         if (!isdigit (str[k]) && str[k] != '_')
5594           return 0;
5595       return 1;
5596     }
5597   if (str[0] == '$' && isdigit (str[1]))
5598     {
5599       for (k = 2; str[k] != '\0'; k += 1)
5600         if (!isdigit (str[k]) && str[k] != '_')
5601           return 0;
5602       return 1;
5603     }
5604   return 0;
5605 }
5606
5607 /* Return non-zero if the string starting at NAME and ending before
5608    NAME_END contains no capital letters.  */
5609
5610 static int
5611 is_valid_name_for_wild_match (const char *name0)
5612 {
5613   std::string decoded_name = ada_decode (name0);
5614   int i;
5615
5616   /* If the decoded name starts with an angle bracket, it means that
5617      NAME0 does not follow the GNAT encoding format.  It should then
5618      not be allowed as a possible wild match.  */
5619   if (decoded_name[0] == '<')
5620     return 0;
5621
5622   for (i=0; decoded_name[i] != '\0'; i++)
5623     if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5624       return 0;
5625
5626   return 1;
5627 }
5628
5629 /* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5630    character which could start a simple name.  Assumes that *NAMEP points
5631    somewhere inside the string beginning at NAME0.  */
5632
5633 static int
5634 advance_wild_match (const char **namep, const char *name0, char target0)
5635 {
5636   const char *name = *namep;
5637
5638   while (1)
5639     {
5640       char t0, t1;
5641
5642       t0 = *name;
5643       if (t0 == '_')
5644         {
5645           t1 = name[1];
5646           if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5647             {
5648               name += 1;
5649               if (name == name0 + 5 && startswith (name0, "_ada"))
5650                 break;
5651               else
5652                 name += 1;
5653             }
5654           else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5655                                  || name[2] == target0))
5656             {
5657               name += 2;
5658               break;
5659             }
5660           else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5661             {
5662               /* Names like "pkg__B_N__name", where N is a number, are
5663                  block-local.  We can handle these by simply skipping
5664                  the "B_" here.  */
5665               name += 4;
5666             }
5667           else
5668             return 0;
5669         }
5670       else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5671         name += 1;
5672       else
5673         return 0;
5674     }
5675
5676   *namep = name;
5677   return 1;
5678 }
5679
5680 /* Return true iff NAME encodes a name of the form prefix.PATN.
5681    Ignores any informational suffixes of NAME (i.e., for which
5682    is_name_suffix is true).  Assumes that PATN is a lower-cased Ada
5683    simple name.  */
5684
5685 static bool
5686 wild_match (const char *name, const char *patn)
5687 {
5688   const char *p;
5689   const char *name0 = name;
5690
5691   while (1)
5692     {
5693       const char *match = name;
5694
5695       if (*name == *patn)
5696         {
5697           for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5698             if (*p != *name)
5699               break;
5700           if (*p == '\0' && is_name_suffix (name))
5701             return match == name0 || is_valid_name_for_wild_match (name0);
5702
5703           if (name[-1] == '_')
5704             name -= 1;
5705         }
5706       if (!advance_wild_match (&name, name0, *patn))
5707         return false;
5708     }
5709 }
5710
5711 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
5712    necessary).  OBJFILE is the section containing BLOCK.  */
5713
5714 static void
5715 ada_add_block_symbols (std::vector<struct block_symbol> &result,
5716                        const struct block *block,
5717                        const lookup_name_info &lookup_name,
5718                        domain_enum domain, struct objfile *objfile)
5719 {
5720   struct block_iterator iter;
5721   /* A matching argument symbol, if any.  */
5722   struct symbol *arg_sym;
5723   /* Set true when we find a matching non-argument symbol.  */
5724   bool found_sym;
5725   struct symbol *sym;
5726
5727   arg_sym = NULL;
5728   found_sym = false;
5729   for (sym = block_iter_match_first (block, lookup_name, &iter);
5730        sym != NULL;
5731        sym = block_iter_match_next (lookup_name, &iter))
5732     {
5733       if (symbol_matches_domain (sym->language (), sym->domain (), domain))
5734         {
5735           if (sym->aclass () != LOC_UNRESOLVED)
5736             {
5737               if (sym->is_argument ())
5738                 arg_sym = sym;
5739               else
5740                 {
5741                   found_sym = true;
5742                   add_defn_to_vec (result,
5743                                    fixup_symbol_section (sym, objfile),
5744                                    block);
5745                 }
5746             }
5747         }
5748     }
5749
5750   /* Handle renamings.  */
5751
5752   if (ada_add_block_renamings (result, block, lookup_name, domain))
5753     found_sym = true;
5754
5755   if (!found_sym && arg_sym != NULL)
5756     {
5757       add_defn_to_vec (result,
5758                        fixup_symbol_section (arg_sym, objfile),
5759                        block);
5760     }
5761
5762   if (!lookup_name.ada ().wild_match_p ())
5763     {
5764       arg_sym = NULL;
5765       found_sym = false;
5766       const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
5767       const char *name = ada_lookup_name.c_str ();
5768       size_t name_len = ada_lookup_name.size ();
5769
5770       ALL_BLOCK_SYMBOLS (block, iter, sym)
5771       {
5772         if (symbol_matches_domain (sym->language (),
5773                                    sym->domain (), domain))
5774           {
5775             int cmp;
5776
5777             cmp = (int) '_' - (int) sym->linkage_name ()[0];
5778             if (cmp == 0)
5779               {
5780                 cmp = !startswith (sym->linkage_name (), "_ada_");
5781                 if (cmp == 0)
5782                   cmp = strncmp (name, sym->linkage_name () + 5,
5783                                  name_len);
5784               }
5785
5786             if (cmp == 0
5787                 && is_name_suffix (sym->linkage_name () + name_len + 5))
5788               {
5789                 if (sym->aclass () != LOC_UNRESOLVED)
5790                   {
5791                     if (sym->is_argument ())
5792                       arg_sym = sym;
5793                     else
5794                       {
5795                         found_sym = true;
5796                         add_defn_to_vec (result,
5797                                          fixup_symbol_section (sym, objfile),
5798                                          block);
5799                       }
5800                   }
5801               }
5802           }
5803       }
5804
5805       /* NOTE: This really shouldn't be needed for _ada_ symbols.
5806          They aren't parameters, right?  */
5807       if (!found_sym && arg_sym != NULL)
5808         {
5809           add_defn_to_vec (result,
5810                            fixup_symbol_section (arg_sym, objfile),
5811                            block);
5812         }
5813     }
5814 }
5815 \f
5816
5817                                 /* Symbol Completion */
5818
5819 /* See symtab.h.  */
5820
5821 bool
5822 ada_lookup_name_info::matches
5823   (const char *sym_name,
5824    symbol_name_match_type match_type,
5825    completion_match_result *comp_match_res) const
5826 {
5827   bool match = false;
5828   const char *text = m_encoded_name.c_str ();
5829   size_t text_len = m_encoded_name.size ();
5830
5831   /* First, test against the fully qualified name of the symbol.  */
5832
5833   if (strncmp (sym_name, text, text_len) == 0)
5834     match = true;
5835
5836   std::string decoded_name = ada_decode (sym_name);
5837   if (match && !m_encoded_p)
5838     {
5839       /* One needed check before declaring a positive match is to verify
5840          that iff we are doing a verbatim match, the decoded version
5841          of the symbol name starts with '<'.  Otherwise, this symbol name
5842          is not a suitable completion.  */
5843
5844       bool has_angle_bracket = (decoded_name[0] == '<');
5845       match = (has_angle_bracket == m_verbatim_p);
5846     }
5847
5848   if (match && !m_verbatim_p)
5849     {
5850       /* When doing non-verbatim match, another check that needs to
5851          be done is to verify that the potentially matching symbol name
5852          does not include capital letters, because the ada-mode would
5853          not be able to understand these symbol names without the
5854          angle bracket notation.  */
5855       const char *tmp;
5856
5857       for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
5858       if (*tmp != '\0')
5859         match = false;
5860     }
5861
5862   /* Second: Try wild matching...  */
5863
5864   if (!match && m_wild_match_p)
5865     {
5866       /* Since we are doing wild matching, this means that TEXT
5867          may represent an unqualified symbol name.  We therefore must
5868          also compare TEXT against the unqualified name of the symbol.  */
5869       sym_name = ada_unqualified_name (decoded_name.c_str ());
5870
5871       if (strncmp (sym_name, text, text_len) == 0)
5872         match = true;
5873     }
5874
5875   /* Finally: If we found a match, prepare the result to return.  */
5876
5877   if (!match)
5878     return false;
5879
5880   if (comp_match_res != NULL)
5881     {
5882       std::string &match_str = comp_match_res->match.storage ();
5883
5884       if (!m_encoded_p)
5885         match_str = ada_decode (sym_name);
5886       else
5887         {
5888           if (m_verbatim_p)
5889             match_str = add_angle_brackets (sym_name);
5890           else
5891             match_str = sym_name;
5892
5893         }
5894
5895       comp_match_res->set_match (match_str.c_str ());
5896     }
5897
5898   return true;
5899 }
5900
5901                                 /* Field Access */
5902
5903 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
5904    for tagged types.  */
5905
5906 static int
5907 ada_is_dispatch_table_ptr_type (struct type *type)
5908 {
5909   const char *name;
5910
5911   if (type->code () != TYPE_CODE_PTR)
5912     return 0;
5913
5914   name = TYPE_TARGET_TYPE (type)->name ();
5915   if (name == NULL)
5916     return 0;
5917
5918   return (strcmp (name, "ada__tags__dispatch_table") == 0);
5919 }
5920
5921 /* Return non-zero if TYPE is an interface tag.  */
5922
5923 static int
5924 ada_is_interface_tag (struct type *type)
5925 {
5926   const char *name = type->name ();
5927
5928   if (name == NULL)
5929     return 0;
5930
5931   return (strcmp (name, "ada__tags__interface_tag") == 0);
5932 }
5933
5934 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
5935    to be invisible to users.  */
5936
5937 int
5938 ada_is_ignored_field (struct type *type, int field_num)
5939 {
5940   if (field_num < 0 || field_num > type->num_fields ())
5941     return 1;
5942
5943   /* Check the name of that field.  */
5944   {
5945     const char *name = type->field (field_num).name ();
5946
5947     /* Anonymous field names should not be printed.
5948        brobecker/2007-02-20: I don't think this can actually happen
5949        but we don't want to print the value of anonymous fields anyway.  */
5950     if (name == NULL)
5951       return 1;
5952
5953     /* Normally, fields whose name start with an underscore ("_")
5954        are fields that have been internally generated by the compiler,
5955        and thus should not be printed.  The "_parent" field is special,
5956        however: This is a field internally generated by the compiler
5957        for tagged types, and it contains the components inherited from
5958        the parent type.  This field should not be printed as is, but
5959        should not be ignored either.  */
5960     if (name[0] == '_' && !startswith (name, "_parent"))
5961       return 1;
5962   }
5963
5964   /* If this is the dispatch table of a tagged type or an interface tag,
5965      then ignore.  */
5966   if (ada_is_tagged_type (type, 1)
5967       && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
5968           || ada_is_interface_tag (type->field (field_num).type ())))
5969     return 1;
5970
5971   /* Not a special field, so it should not be ignored.  */
5972   return 0;
5973 }
5974
5975 /* True iff TYPE has a tag field.  If REFOK, then TYPE may also be a
5976    pointer or reference type whose ultimate target has a tag field.  */
5977
5978 int
5979 ada_is_tagged_type (struct type *type, int refok)
5980 {
5981   return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
5982 }
5983
5984 /* True iff TYPE represents the type of X'Tag */
5985
5986 int
5987 ada_is_tag_type (struct type *type)
5988 {
5989   type = ada_check_typedef (type);
5990
5991   if (type == NULL || type->code () != TYPE_CODE_PTR)
5992     return 0;
5993   else
5994     {
5995       const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
5996
5997       return (name != NULL
5998               && strcmp (name, "ada__tags__dispatch_table") == 0);
5999     }
6000 }
6001
6002 /* The type of the tag on VAL.  */
6003
6004 static struct type *
6005 ada_tag_type (struct value *val)
6006 {
6007   return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0);
6008 }
6009
6010 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6011    retired at Ada 05).  */
6012
6013 static int
6014 is_ada95_tag (struct value *tag)
6015 {
6016   return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6017 }
6018
6019 /* The value of the tag on VAL.  */
6020
6021 static struct value *
6022 ada_value_tag (struct value *val)
6023 {
6024   return ada_value_struct_elt (val, "_tag", 0);
6025 }
6026
6027 /* The value of the tag on the object of type TYPE whose contents are
6028    saved at VALADDR, if it is non-null, or is at memory address
6029    ADDRESS.  */
6030
6031 static struct value *
6032 value_tag_from_contents_and_address (struct type *type,
6033                                      const gdb_byte *valaddr,
6034                                      CORE_ADDR address)
6035 {
6036   int tag_byte_offset;
6037   struct type *tag_type;
6038
6039   gdb::array_view<const gdb_byte> contents;
6040   if (valaddr != nullptr)
6041     contents = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
6042   struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6043   if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
6044                          NULL, NULL, NULL))
6045     {
6046       const gdb_byte *valaddr1 = ((valaddr == NULL)
6047                                   ? NULL
6048                                   : valaddr + tag_byte_offset);
6049       CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6050
6051       return value_from_contents_and_address (tag_type, valaddr1, address1);
6052     }
6053   return NULL;
6054 }
6055
6056 static struct type *
6057 type_from_tag (struct value *tag)
6058 {
6059   gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
6060
6061   if (type_name != NULL)
6062     return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
6063   return NULL;
6064 }
6065
6066 /* Given a value OBJ of a tagged type, return a value of this
6067    type at the base address of the object.  The base address, as
6068    defined in Ada.Tags, it is the address of the primary tag of
6069    the object, and therefore where the field values of its full
6070    view can be fetched.  */
6071
6072 struct value *
6073 ada_tag_value_at_base_address (struct value *obj)
6074 {
6075   struct value *val;
6076   LONGEST offset_to_top = 0;
6077   struct type *ptr_type, *obj_type;
6078   struct value *tag;
6079   CORE_ADDR base_address;
6080
6081   obj_type = value_type (obj);
6082
6083   /* It is the responsability of the caller to deref pointers.  */
6084
6085   if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
6086     return obj;
6087
6088   tag = ada_value_tag (obj);
6089   if (!tag)
6090     return obj;
6091
6092   /* Base addresses only appeared with Ada 05 and multiple inheritance.  */
6093
6094   if (is_ada95_tag (tag))
6095     return obj;
6096
6097   ptr_type = language_lookup_primitive_type
6098     (language_def (language_ada), target_gdbarch(), "storage_offset");
6099   ptr_type = lookup_pointer_type (ptr_type);
6100   val = value_cast (ptr_type, tag);
6101   if (!val)
6102     return obj;
6103
6104   /* It is perfectly possible that an exception be raised while
6105      trying to determine the base address, just like for the tag;
6106      see ada_tag_name for more details.  We do not print the error
6107      message for the same reason.  */
6108
6109   try
6110     {
6111       offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6112     }
6113
6114   catch (const gdb_exception_error &e)
6115     {
6116       return obj;
6117     }
6118
6119   /* If offset is null, nothing to do.  */
6120
6121   if (offset_to_top == 0)
6122     return obj;
6123
6124   /* -1 is a special case in Ada.Tags; however, what should be done
6125      is not quite clear from the documentation.  So do nothing for
6126      now.  */
6127
6128   if (offset_to_top == -1)
6129     return obj;
6130
6131   /* OFFSET_TO_TOP used to be a positive value to be subtracted
6132      from the base address.  This was however incompatible with
6133      C++ dispatch table: C++ uses a *negative* value to *add*
6134      to the base address.  Ada's convention has therefore been
6135      changed in GNAT 19.0w 20171023: since then, C++ and Ada
6136      use the same convention.  Here, we support both cases by
6137      checking the sign of OFFSET_TO_TOP.  */
6138
6139   if (offset_to_top > 0)
6140     offset_to_top = -offset_to_top;
6141
6142   base_address = value_address (obj) + offset_to_top;
6143   tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6144
6145   /* Make sure that we have a proper tag at the new address.
6146      Otherwise, offset_to_top is bogus (which can happen when
6147      the object is not initialized yet).  */
6148
6149   if (!tag)
6150     return obj;
6151
6152   obj_type = type_from_tag (tag);
6153
6154   if (!obj_type)
6155     return obj;
6156
6157   return value_from_contents_and_address (obj_type, NULL, base_address);
6158 }
6159
6160 /* Return the "ada__tags__type_specific_data" type.  */
6161
6162 static struct type *
6163 ada_get_tsd_type (struct inferior *inf)
6164 {
6165   struct ada_inferior_data *data = get_ada_inferior_data (inf);
6166
6167   if (data->tsd_type == 0)
6168     data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6169   return data->tsd_type;
6170 }
6171
6172 /* Return the TSD (type-specific data) associated to the given TAG.
6173    TAG is assumed to be the tag of a tagged-type entity.
6174
6175    May return NULL if we are unable to get the TSD.  */
6176
6177 static struct value *
6178 ada_get_tsd_from_tag (struct value *tag)
6179 {
6180   struct value *val;
6181   struct type *type;
6182
6183   /* First option: The TSD is simply stored as a field of our TAG.
6184      Only older versions of GNAT would use this format, but we have
6185      to test it first, because there are no visible markers for
6186      the current approach except the absence of that field.  */
6187
6188   val = ada_value_struct_elt (tag, "tsd", 1);
6189   if (val)
6190     return val;
6191
6192   /* Try the second representation for the dispatch table (in which
6193      there is no explicit 'tsd' field in the referent of the tag pointer,
6194      and instead the tsd pointer is stored just before the dispatch
6195      table.  */
6196
6197   type = ada_get_tsd_type (current_inferior());
6198   if (type == NULL)
6199     return NULL;
6200   type = lookup_pointer_type (lookup_pointer_type (type));
6201   val = value_cast (type, tag);
6202   if (val == NULL)
6203     return NULL;
6204   return value_ind (value_ptradd (val, -1));
6205 }
6206
6207 /* Given the TSD of a tag (type-specific data), return a string
6208    containing the name of the associated type.
6209
6210    May return NULL if we are unable to determine the tag name.  */
6211
6212 static gdb::unique_xmalloc_ptr<char>
6213 ada_tag_name_from_tsd (struct value *tsd)
6214 {
6215   char *p;
6216   struct value *val;
6217
6218   val = ada_value_struct_elt (tsd, "expanded_name", 1);
6219   if (val == NULL)
6220     return NULL;
6221   gdb::unique_xmalloc_ptr<char> buffer
6222     = target_read_string (value_as_address (val), INT_MAX);
6223   if (buffer == nullptr)
6224     return nullptr;
6225
6226   for (p = buffer.get (); *p != '\0'; ++p)
6227     {
6228       if (isalpha (*p))
6229         *p = tolower (*p);
6230     }
6231
6232   return buffer;
6233 }
6234
6235 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6236    a C string.
6237
6238    Return NULL if the TAG is not an Ada tag, or if we were unable to
6239    determine the name of that tag.  */
6240
6241 gdb::unique_xmalloc_ptr<char>
6242 ada_tag_name (struct value *tag)
6243 {
6244   gdb::unique_xmalloc_ptr<char> name;
6245
6246   if (!ada_is_tag_type (value_type (tag)))
6247     return NULL;
6248
6249   /* It is perfectly possible that an exception be raised while trying
6250      to determine the TAG's name, even under normal circumstances:
6251      The associated variable may be uninitialized or corrupted, for
6252      instance. We do not let any exception propagate past this point.
6253      instead we return NULL.
6254
6255      We also do not print the error message either (which often is very
6256      low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6257      the caller print a more meaningful message if necessary.  */
6258   try
6259     {
6260       struct value *tsd = ada_get_tsd_from_tag (tag);
6261
6262       if (tsd != NULL)
6263         name = ada_tag_name_from_tsd (tsd);
6264     }
6265   catch (const gdb_exception_error &e)
6266     {
6267     }
6268
6269   return name;
6270 }
6271
6272 /* The parent type of TYPE, or NULL if none.  */
6273
6274 struct type *
6275 ada_parent_type (struct type *type)
6276 {
6277   int i;
6278
6279   type = ada_check_typedef (type);
6280
6281   if (type == NULL || type->code () != TYPE_CODE_STRUCT)
6282     return NULL;
6283
6284   for (i = 0; i < type->num_fields (); i += 1)
6285     if (ada_is_parent_field (type, i))
6286       {
6287         struct type *parent_type = type->field (i).type ();
6288
6289         /* If the _parent field is a pointer, then dereference it.  */
6290         if (parent_type->code () == TYPE_CODE_PTR)
6291           parent_type = TYPE_TARGET_TYPE (parent_type);
6292         /* If there is a parallel XVS type, get the actual base type.  */
6293         parent_type = ada_get_base_type (parent_type);
6294
6295         return ada_check_typedef (parent_type);
6296       }
6297
6298   return NULL;
6299 }
6300
6301 /* True iff field number FIELD_NUM of structure type TYPE contains the
6302    parent-type (inherited) fields of a derived type.  Assumes TYPE is
6303    a structure type with at least FIELD_NUM+1 fields.  */
6304
6305 int
6306 ada_is_parent_field (struct type *type, int field_num)
6307 {
6308   const char *name = ada_check_typedef (type)->field (field_num).name ();
6309
6310   return (name != NULL
6311           && (startswith (name, "PARENT")
6312               || startswith (name, "_parent")));
6313 }
6314
6315 /* True iff field number FIELD_NUM of structure type TYPE is a
6316    transparent wrapper field (which should be silently traversed when doing
6317    field selection and flattened when printing).  Assumes TYPE is a
6318    structure type with at least FIELD_NUM+1 fields.  Such fields are always
6319    structures.  */
6320
6321 int
6322 ada_is_wrapper_field (struct type *type, int field_num)
6323 {
6324   const char *name = type->field (field_num).name ();
6325
6326   if (name != NULL && strcmp (name, "RETVAL") == 0)
6327     {
6328       /* This happens in functions with "out" or "in out" parameters
6329          which are passed by copy.  For such functions, GNAT describes
6330          the function's return type as being a struct where the return
6331          value is in a field called RETVAL, and where the other "out"
6332          or "in out" parameters are fields of that struct.  This is not
6333          a wrapper.  */
6334       return 0;
6335     }
6336
6337   return (name != NULL
6338           && (startswith (name, "PARENT")
6339               || strcmp (name, "REP") == 0
6340               || startswith (name, "_parent")
6341               || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6342 }
6343
6344 /* True iff field number FIELD_NUM of structure or union type TYPE
6345    is a variant wrapper.  Assumes TYPE is a structure type with at least
6346    FIELD_NUM+1 fields.  */
6347
6348 int
6349 ada_is_variant_part (struct type *type, int field_num)
6350 {
6351   /* Only Ada types are eligible.  */
6352   if (!ADA_TYPE_P (type))
6353     return 0;
6354
6355   struct type *field_type = type->field (field_num).type ();
6356
6357   return (field_type->code () == TYPE_CODE_UNION
6358           || (is_dynamic_field (type, field_num)
6359               && (TYPE_TARGET_TYPE (field_type)->code ()
6360                   == TYPE_CODE_UNION)));
6361 }
6362
6363 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6364    whose discriminants are contained in the record type OUTER_TYPE,
6365    returns the type of the controlling discriminant for the variant.
6366    May return NULL if the type could not be found.  */
6367
6368 struct type *
6369 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6370 {
6371   const char *name = ada_variant_discrim_name (var_type);
6372
6373   return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6374 }
6375
6376 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6377    valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6378    represents a 'when others' clause; otherwise 0.  */
6379
6380 static int
6381 ada_is_others_clause (struct type *type, int field_num)
6382 {
6383   const char *name = type->field (field_num).name ();
6384
6385   return (name != NULL && name[0] == 'O');
6386 }
6387
6388 /* Assuming that TYPE0 is the type of the variant part of a record,
6389    returns the name of the discriminant controlling the variant.
6390    The value is valid until the next call to ada_variant_discrim_name.  */
6391
6392 const char *
6393 ada_variant_discrim_name (struct type *type0)
6394 {
6395   static std::string result;
6396   struct type *type;
6397   const char *name;
6398   const char *discrim_end;
6399   const char *discrim_start;
6400
6401   if (type0->code () == TYPE_CODE_PTR)
6402     type = TYPE_TARGET_TYPE (type0);
6403   else
6404     type = type0;
6405
6406   name = ada_type_name (type);
6407
6408   if (name == NULL || name[0] == '\000')
6409     return "";
6410
6411   for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6412        discrim_end -= 1)
6413     {
6414       if (startswith (discrim_end, "___XVN"))
6415         break;
6416     }
6417   if (discrim_end == name)
6418     return "";
6419
6420   for (discrim_start = discrim_end; discrim_start != name + 3;
6421        discrim_start -= 1)
6422     {
6423       if (discrim_start == name + 1)
6424         return "";
6425       if ((discrim_start > name + 3
6426            && startswith (discrim_start - 3, "___"))
6427           || discrim_start[-1] == '.')
6428         break;
6429     }
6430
6431   result = std::string (discrim_start, discrim_end - discrim_start);
6432   return result.c_str ();
6433 }
6434
6435 /* Scan STR for a subtype-encoded number, beginning at position K.
6436    Put the position of the character just past the number scanned in
6437    *NEW_K, if NEW_K!=NULL.  Put the scanned number in *R, if R!=NULL.
6438    Return 1 if there was a valid number at the given position, and 0
6439    otherwise.  A "subtype-encoded" number consists of the absolute value
6440    in decimal, followed by the letter 'm' to indicate a negative number.
6441    Assumes 0m does not occur.  */
6442
6443 int
6444 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
6445 {
6446   ULONGEST RU;
6447
6448   if (!isdigit (str[k]))
6449     return 0;
6450
6451   /* Do it the hard way so as not to make any assumption about
6452      the relationship of unsigned long (%lu scan format code) and
6453      LONGEST.  */
6454   RU = 0;
6455   while (isdigit (str[k]))
6456     {
6457       RU = RU * 10 + (str[k] - '0');
6458       k += 1;
6459     }
6460
6461   if (str[k] == 'm')
6462     {
6463       if (R != NULL)
6464         *R = (-(LONGEST) (RU - 1)) - 1;
6465       k += 1;
6466     }
6467   else if (R != NULL)
6468     *R = (LONGEST) RU;
6469
6470   /* NOTE on the above: Technically, C does not say what the results of
6471      - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6472      number representable as a LONGEST (although either would probably work
6473      in most implementations).  When RU>0, the locution in the then branch
6474      above is always equivalent to the negative of RU.  */
6475
6476   if (new_k != NULL)
6477     *new_k = k;
6478   return 1;
6479 }
6480
6481 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6482    and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6483    in the range encoded by field FIELD_NUM of TYPE; otherwise 0.  */
6484
6485 static int
6486 ada_in_variant (LONGEST val, struct type *type, int field_num)
6487 {
6488   const char *name = type->field (field_num).name ();
6489   int p;
6490
6491   p = 0;
6492   while (1)
6493     {
6494       switch (name[p])
6495         {
6496         case '\0':
6497           return 0;
6498         case 'S':
6499           {
6500             LONGEST W;
6501
6502             if (!ada_scan_number (name, p + 1, &W, &p))
6503               return 0;
6504             if (val == W)
6505               return 1;
6506             break;
6507           }
6508         case 'R':
6509           {
6510             LONGEST L, U;
6511
6512             if (!ada_scan_number (name, p + 1, &L, &p)
6513                 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6514               return 0;
6515             if (val >= L && val <= U)
6516               return 1;
6517             break;
6518           }
6519         case 'O':
6520           return 1;
6521         default:
6522           return 0;
6523         }
6524     }
6525 }
6526
6527 /* FIXME: Lots of redundancy below.  Try to consolidate.  */
6528
6529 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6530    ARG_TYPE, extract and return the value of one of its (non-static)
6531    fields.  FIELDNO says which field.   Differs from value_primitive_field
6532    only in that it can handle packed values of arbitrary type.  */
6533
6534 struct value *
6535 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
6536                            struct type *arg_type)
6537 {
6538   struct type *type;
6539
6540   arg_type = ada_check_typedef (arg_type);
6541   type = arg_type->field (fieldno).type ();
6542
6543   /* Handle packed fields.  It might be that the field is not packed
6544      relative to its containing structure, but the structure itself is
6545      packed; in this case we must take the bit-field path.  */
6546   if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || value_bitpos (arg1) != 0)
6547     {
6548       int bit_pos = arg_type->field (fieldno).loc_bitpos ();
6549       int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
6550
6551       return ada_value_primitive_packed_val (arg1,
6552                                              value_contents (arg1).data (),
6553                                              offset + bit_pos / 8,
6554                                              bit_pos % 8, bit_size, type);
6555     }
6556   else
6557     return value_primitive_field (arg1, offset, fieldno, arg_type);
6558 }
6559
6560 /* Find field with name NAME in object of type TYPE.  If found, 
6561    set the following for each argument that is non-null:
6562     - *FIELD_TYPE_P to the field's type; 
6563     - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within 
6564       an object of that type;
6565     - *BIT_OFFSET_P to the bit offset modulo byte size of the field; 
6566     - *BIT_SIZE_P to its size in bits if the field is packed, and 
6567       0 otherwise;
6568    If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6569    fields up to but not including the desired field, or by the total
6570    number of fields if not found.   A NULL value of NAME never
6571    matches; the function just counts visible fields in this case.
6572    
6573    Notice that we need to handle when a tagged record hierarchy
6574    has some components with the same name, like in this scenario:
6575
6576       type Top_T is tagged record
6577          N : Integer := 1;
6578          U : Integer := 974;
6579          A : Integer := 48;
6580       end record;
6581
6582       type Middle_T is new Top.Top_T with record
6583          N : Character := 'a';
6584          C : Integer := 3;
6585       end record;
6586
6587      type Bottom_T is new Middle.Middle_T with record
6588         N : Float := 4.0;
6589         C : Character := '5';
6590         X : Integer := 6;
6591         A : Character := 'J';
6592      end record;
6593
6594    Let's say we now have a variable declared and initialized as follow:
6595
6596      TC : Top_A := new Bottom_T;
6597
6598    And then we use this variable to call this function
6599
6600      procedure Assign (Obj: in out Top_T; TV : Integer);
6601
6602    as follow:
6603
6604       Assign (Top_T (B), 12);
6605
6606    Now, we're in the debugger, and we're inside that procedure
6607    then and we want to print the value of obj.c:
6608
6609    Usually, the tagged record or one of the parent type owns the
6610    component to print and there's no issue but in this particular
6611    case, what does it mean to ask for Obj.C? Since the actual
6612    type for object is type Bottom_T, it could mean two things: type
6613    component C from the Middle_T view, but also component C from
6614    Bottom_T.  So in that "undefined" case, when the component is
6615    not found in the non-resolved type (which includes all the
6616    components of the parent type), then resolve it and see if we
6617    get better luck once expanded.
6618
6619    In the case of homonyms in the derived tagged type, we don't
6620    guaranty anything, and pick the one that's easiest for us
6621    to program.
6622
6623    Returns 1 if found, 0 otherwise.  */
6624
6625 static int
6626 find_struct_field (const char *name, struct type *type, int offset,
6627                    struct type **field_type_p,
6628                    int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
6629                    int *index_p)
6630 {
6631   int i;
6632   int parent_offset = -1;
6633
6634   type = ada_check_typedef (type);
6635
6636   if (field_type_p != NULL)
6637     *field_type_p = NULL;
6638   if (byte_offset_p != NULL)
6639     *byte_offset_p = 0;
6640   if (bit_offset_p != NULL)
6641     *bit_offset_p = 0;
6642   if (bit_size_p != NULL)
6643     *bit_size_p = 0;
6644
6645   for (i = 0; i < type->num_fields (); i += 1)
6646     {
6647       /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
6648          type.  However, we only need the values to be correct when
6649          the caller asks for them.  */
6650       int bit_pos = 0, fld_offset = 0;
6651       if (byte_offset_p != nullptr || bit_offset_p != nullptr)
6652         {
6653           bit_pos = type->field (i).loc_bitpos ();
6654           fld_offset = offset + bit_pos / 8;
6655         }
6656
6657       const char *t_field_name = type->field (i).name ();
6658
6659       if (t_field_name == NULL)
6660         continue;
6661
6662       else if (ada_is_parent_field (type, i))
6663         {
6664           /* This is a field pointing us to the parent type of a tagged
6665              type.  As hinted in this function's documentation, we give
6666              preference to fields in the current record first, so what
6667              we do here is just record the index of this field before
6668              we skip it.  If it turns out we couldn't find our field
6669              in the current record, then we'll get back to it and search
6670              inside it whether the field might exist in the parent.  */
6671
6672           parent_offset = i;
6673           continue;
6674         }
6675
6676       else if (name != NULL && field_name_match (t_field_name, name))
6677         {
6678           int bit_size = TYPE_FIELD_BITSIZE (type, i);
6679
6680           if (field_type_p != NULL)
6681             *field_type_p = type->field (i).type ();
6682           if (byte_offset_p != NULL)
6683             *byte_offset_p = fld_offset;
6684           if (bit_offset_p != NULL)
6685             *bit_offset_p = bit_pos % 8;
6686           if (bit_size_p != NULL)
6687             *bit_size_p = bit_size;
6688           return 1;
6689         }
6690       else if (ada_is_wrapper_field (type, i))
6691         {
6692           if (find_struct_field (name, type->field (i).type (), fld_offset,
6693                                  field_type_p, byte_offset_p, bit_offset_p,
6694                                  bit_size_p, index_p))
6695             return 1;
6696         }
6697       else if (ada_is_variant_part (type, i))
6698         {
6699           /* PNH: Wait.  Do we ever execute this section, or is ARG always of 
6700              fixed type?? */
6701           int j;
6702           struct type *field_type
6703             = ada_check_typedef (type->field (i).type ());
6704
6705           for (j = 0; j < field_type->num_fields (); j += 1)
6706             {
6707               if (find_struct_field (name, field_type->field (j).type (),
6708                                      fld_offset
6709                                      + field_type->field (j).loc_bitpos () / 8,
6710                                      field_type_p, byte_offset_p,
6711                                      bit_offset_p, bit_size_p, index_p))
6712                 return 1;
6713             }
6714         }
6715       else if (index_p != NULL)
6716         *index_p += 1;
6717     }
6718
6719   /* Field not found so far.  If this is a tagged type which
6720      has a parent, try finding that field in the parent now.  */
6721
6722   if (parent_offset != -1)
6723     {
6724       /* As above, only compute the offset when truly needed.  */
6725       int fld_offset = offset;
6726       if (byte_offset_p != nullptr || bit_offset_p != nullptr)
6727         {
6728           int bit_pos = type->field (parent_offset).loc_bitpos ();
6729           fld_offset += bit_pos / 8;
6730         }
6731
6732       if (find_struct_field (name, type->field (parent_offset).type (),
6733                              fld_offset, field_type_p, byte_offset_p,
6734                              bit_offset_p, bit_size_p, index_p))
6735         return 1;
6736     }
6737
6738   return 0;
6739 }
6740
6741 /* Number of user-visible fields in record type TYPE.  */
6742
6743 static int
6744 num_visible_fields (struct type *type)
6745 {
6746   int n;
6747
6748   n = 0;
6749   find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
6750   return n;
6751 }
6752
6753 /* Look for a field NAME in ARG.  Adjust the address of ARG by OFFSET bytes,
6754    and search in it assuming it has (class) type TYPE.
6755    If found, return value, else return NULL.
6756
6757    Searches recursively through wrapper fields (e.g., '_parent').
6758
6759    In the case of homonyms in the tagged types, please refer to the
6760    long explanation in find_struct_field's function documentation.  */
6761
6762 static struct value *
6763 ada_search_struct_field (const char *name, struct value *arg, int offset,
6764                          struct type *type)
6765 {
6766   int i;
6767   int parent_offset = -1;
6768
6769   type = ada_check_typedef (type);
6770   for (i = 0; i < type->num_fields (); i += 1)
6771     {
6772       const char *t_field_name = type->field (i).name ();
6773
6774       if (t_field_name == NULL)
6775         continue;
6776
6777       else if (ada_is_parent_field (type, i))
6778         {
6779           /* This is a field pointing us to the parent type of a tagged
6780              type.  As hinted in this function's documentation, we give
6781              preference to fields in the current record first, so what
6782              we do here is just record the index of this field before
6783              we skip it.  If it turns out we couldn't find our field
6784              in the current record, then we'll get back to it and search
6785              inside it whether the field might exist in the parent.  */
6786
6787           parent_offset = i;
6788           continue;
6789         }
6790
6791       else if (field_name_match (t_field_name, name))
6792         return ada_value_primitive_field (arg, offset, i, type);
6793
6794       else if (ada_is_wrapper_field (type, i))
6795         {
6796           struct value *v =     /* Do not let indent join lines here.  */
6797             ada_search_struct_field (name, arg,
6798                                      offset + type->field (i).loc_bitpos () / 8,
6799                                      type->field (i).type ());
6800
6801           if (v != NULL)
6802             return v;
6803         }
6804
6805       else if (ada_is_variant_part (type, i))
6806         {
6807           /* PNH: Do we ever get here?  See find_struct_field.  */
6808           int j;
6809           struct type *field_type = ada_check_typedef (type->field (i).type ());
6810           int var_offset = offset + type->field (i).loc_bitpos () / 8;
6811
6812           for (j = 0; j < field_type->num_fields (); j += 1)
6813             {
6814               struct value *v = ada_search_struct_field /* Force line
6815                                                            break.  */
6816                 (name, arg,
6817                  var_offset + field_type->field (j).loc_bitpos () / 8,
6818                  field_type->field (j).type ());
6819
6820               if (v != NULL)
6821                 return v;
6822             }
6823         }
6824     }
6825
6826   /* Field not found so far.  If this is a tagged type which
6827      has a parent, try finding that field in the parent now.  */
6828
6829   if (parent_offset != -1)
6830     {
6831       struct value *v = ada_search_struct_field (
6832         name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
6833         type->field (parent_offset).type ());
6834
6835       if (v != NULL)
6836         return v;
6837     }
6838
6839   return NULL;
6840 }
6841
6842 static struct value *ada_index_struct_field_1 (int *, struct value *,
6843                                                int, struct type *);
6844
6845
6846 /* Return field #INDEX in ARG, where the index is that returned by
6847  * find_struct_field through its INDEX_P argument.  Adjust the address
6848  * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
6849  * If found, return value, else return NULL.  */
6850
6851 static struct value *
6852 ada_index_struct_field (int index, struct value *arg, int offset,
6853                         struct type *type)
6854 {
6855   return ada_index_struct_field_1 (&index, arg, offset, type);
6856 }
6857
6858
6859 /* Auxiliary function for ada_index_struct_field.  Like
6860  * ada_index_struct_field, but takes index from *INDEX_P and modifies
6861  * *INDEX_P.  */
6862
6863 static struct value *
6864 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
6865                           struct type *type)
6866 {
6867   int i;
6868   type = ada_check_typedef (type);
6869
6870   for (i = 0; i < type->num_fields (); i += 1)
6871     {
6872       if (type->field (i).name () == NULL)
6873         continue;
6874       else if (ada_is_wrapper_field (type, i))
6875         {
6876           struct value *v =     /* Do not let indent join lines here.  */
6877             ada_index_struct_field_1 (index_p, arg,
6878                                       offset + type->field (i).loc_bitpos () / 8,
6879                                       type->field (i).type ());
6880
6881           if (v != NULL)
6882             return v;
6883         }
6884
6885       else if (ada_is_variant_part (type, i))
6886         {
6887           /* PNH: Do we ever get here?  See ada_search_struct_field,
6888              find_struct_field.  */
6889           error (_("Cannot assign this kind of variant record"));
6890         }
6891       else if (*index_p == 0)
6892         return ada_value_primitive_field (arg, offset, i, type);
6893       else
6894         *index_p -= 1;
6895     }
6896   return NULL;
6897 }
6898
6899 /* Return a string representation of type TYPE.  */
6900
6901 static std::string
6902 type_as_string (struct type *type)
6903 {
6904   string_file tmp_stream;
6905
6906   type_print (type, "", &tmp_stream, -1);
6907
6908   return tmp_stream.release ();
6909 }
6910
6911 /* Given a type TYPE, look up the type of the component of type named NAME.
6912    If DISPP is non-null, add its byte displacement from the beginning of a
6913    structure (pointed to by a value) of type TYPE to *DISPP (does not
6914    work for packed fields).
6915
6916    Matches any field whose name has NAME as a prefix, possibly
6917    followed by "___".
6918
6919    TYPE can be either a struct or union.  If REFOK, TYPE may also 
6920    be a (pointer or reference)+ to a struct or union, and the
6921    ultimate target type will be searched.
6922
6923    Looks recursively into variant clauses and parent types.
6924
6925    In the case of homonyms in the tagged types, please refer to the
6926    long explanation in find_struct_field's function documentation.
6927
6928    If NOERR is nonzero, return NULL if NAME is not suitably defined or
6929    TYPE is not a type of the right kind.  */
6930
6931 static struct type *
6932 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
6933                             int noerr)
6934 {
6935   int i;
6936   int parent_offset = -1;
6937
6938   if (name == NULL)
6939     goto BadName;
6940
6941   if (refok && type != NULL)
6942     while (1)
6943       {
6944         type = ada_check_typedef (type);
6945         if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
6946           break;
6947         type = TYPE_TARGET_TYPE (type);
6948       }
6949
6950   if (type == NULL
6951       || (type->code () != TYPE_CODE_STRUCT
6952           && type->code () != TYPE_CODE_UNION))
6953     {
6954       if (noerr)
6955         return NULL;
6956
6957       error (_("Type %s is not a structure or union type"),
6958              type != NULL ? type_as_string (type).c_str () : _("(null)"));
6959     }
6960
6961   type = to_static_fixed_type (type);
6962
6963   for (i = 0; i < type->num_fields (); i += 1)
6964     {
6965       const char *t_field_name = type->field (i).name ();
6966       struct type *t;
6967
6968       if (t_field_name == NULL)
6969         continue;
6970
6971       else if (ada_is_parent_field (type, i))
6972         {
6973           /* This is a field pointing us to the parent type of a tagged
6974              type.  As hinted in this function's documentation, we give
6975              preference to fields in the current record first, so what
6976              we do here is just record the index of this field before
6977              we skip it.  If it turns out we couldn't find our field
6978              in the current record, then we'll get back to it and search
6979              inside it whether the field might exist in the parent.  */
6980
6981           parent_offset = i;
6982           continue;
6983         }
6984
6985       else if (field_name_match (t_field_name, name))
6986         return type->field (i).type ();
6987
6988       else if (ada_is_wrapper_field (type, i))
6989         {
6990           t = ada_lookup_struct_elt_type (type->field (i).type (), name,
6991                                           0, 1);
6992           if (t != NULL)
6993             return t;
6994         }
6995
6996       else if (ada_is_variant_part (type, i))
6997         {
6998           int j;
6999           struct type *field_type = ada_check_typedef (type->field (i).type ());
7000
7001           for (j = field_type->num_fields () - 1; j >= 0; j -= 1)
7002             {
7003               /* FIXME pnh 2008/01/26: We check for a field that is
7004                  NOT wrapped in a struct, since the compiler sometimes
7005                  generates these for unchecked variant types.  Revisit
7006                  if the compiler changes this practice.  */
7007               const char *v_field_name = field_type->field (j).name ();
7008
7009               if (v_field_name != NULL 
7010                   && field_name_match (v_field_name, name))
7011                 t = field_type->field (j).type ();
7012               else
7013                 t = ada_lookup_struct_elt_type (field_type->field (j).type (),
7014                                                 name, 0, 1);
7015
7016               if (t != NULL)
7017                 return t;
7018             }
7019         }
7020
7021     }
7022
7023     /* Field not found so far.  If this is a tagged type which
7024        has a parent, try finding that field in the parent now.  */
7025
7026     if (parent_offset != -1)
7027       {
7028         struct type *t;
7029
7030         t = ada_lookup_struct_elt_type (type->field (parent_offset).type (),
7031                                         name, 0, 1);
7032         if (t != NULL)
7033           return t;
7034       }
7035
7036 BadName:
7037   if (!noerr)
7038     {
7039       const char *name_str = name != NULL ? name : _("<null>");
7040
7041       error (_("Type %s has no component named %s"),
7042              type_as_string (type).c_str (), name_str);
7043     }
7044
7045   return NULL;
7046 }
7047
7048 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7049    within a value of type OUTER_TYPE, return true iff VAR_TYPE
7050    represents an unchecked union (that is, the variant part of a
7051    record that is named in an Unchecked_Union pragma).  */
7052
7053 static int
7054 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7055 {
7056   const char *discrim_name = ada_variant_discrim_name (var_type);
7057
7058   return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7059 }
7060
7061
7062 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7063    within OUTER, determine which variant clause (field number in VAR_TYPE,
7064    numbering from 0) is applicable.  Returns -1 if none are.  */
7065
7066 int
7067 ada_which_variant_applies (struct type *var_type, struct value *outer)
7068 {
7069   int others_clause;
7070   int i;
7071   const char *discrim_name = ada_variant_discrim_name (var_type);
7072   struct value *discrim;
7073   LONGEST discrim_val;
7074
7075   /* Using plain value_from_contents_and_address here causes problems
7076      because we will end up trying to resolve a type that is currently
7077      being constructed.  */
7078   discrim = ada_value_struct_elt (outer, discrim_name, 1);
7079   if (discrim == NULL)
7080     return -1;
7081   discrim_val = value_as_long (discrim);
7082
7083   others_clause = -1;
7084   for (i = 0; i < var_type->num_fields (); i += 1)
7085     {
7086       if (ada_is_others_clause (var_type, i))
7087         others_clause = i;
7088       else if (ada_in_variant (discrim_val, var_type, i))
7089         return i;
7090     }
7091
7092   return others_clause;
7093 }
7094 \f
7095
7096
7097                                 /* Dynamic-Sized Records */
7098
7099 /* Strategy: The type ostensibly attached to a value with dynamic size
7100    (i.e., a size that is not statically recorded in the debugging
7101    data) does not accurately reflect the size or layout of the value.
7102    Our strategy is to convert these values to values with accurate,
7103    conventional types that are constructed on the fly.  */
7104
7105 /* There is a subtle and tricky problem here.  In general, we cannot
7106    determine the size of dynamic records without its data.  However,
7107    the 'struct value' data structure, which GDB uses to represent
7108    quantities in the inferior process (the target), requires the size
7109    of the type at the time of its allocation in order to reserve space
7110    for GDB's internal copy of the data.  That's why the
7111    'to_fixed_xxx_type' routines take (target) addresses as parameters,
7112    rather than struct value*s.
7113
7114    However, GDB's internal history variables ($1, $2, etc.) are
7115    struct value*s containing internal copies of the data that are not, in
7116    general, the same as the data at their corresponding addresses in
7117    the target.  Fortunately, the types we give to these values are all
7118    conventional, fixed-size types (as per the strategy described
7119    above), so that we don't usually have to perform the
7120    'to_fixed_xxx_type' conversions to look at their values.
7121    Unfortunately, there is one exception: if one of the internal
7122    history variables is an array whose elements are unconstrained
7123    records, then we will need to create distinct fixed types for each
7124    element selected.  */
7125
7126 /* The upshot of all of this is that many routines take a (type, host
7127    address, target address) triple as arguments to represent a value.
7128    The host address, if non-null, is supposed to contain an internal
7129    copy of the relevant data; otherwise, the program is to consult the
7130    target at the target address.  */
7131
7132 /* Assuming that VAL0 represents a pointer value, the result of
7133    dereferencing it.  Differs from value_ind in its treatment of
7134    dynamic-sized types.  */
7135
7136 struct value *
7137 ada_value_ind (struct value *val0)
7138 {
7139   struct value *val = value_ind (val0);
7140
7141   if (ada_is_tagged_type (value_type (val), 0))
7142     val = ada_tag_value_at_base_address (val);
7143
7144   return ada_to_fixed_value (val);
7145 }
7146
7147 /* The value resulting from dereferencing any "reference to"
7148    qualifiers on VAL0.  */
7149
7150 static struct value *
7151 ada_coerce_ref (struct value *val0)
7152 {
7153   if (value_type (val0)->code () == TYPE_CODE_REF)
7154     {
7155       struct value *val = val0;
7156
7157       val = coerce_ref (val);
7158
7159       if (ada_is_tagged_type (value_type (val), 0))
7160         val = ada_tag_value_at_base_address (val);
7161
7162       return ada_to_fixed_value (val);
7163     }
7164   else
7165     return val0;
7166 }
7167
7168 /* Return the bit alignment required for field #F of template type TYPE.  */
7169
7170 static unsigned int
7171 field_alignment (struct type *type, int f)
7172 {
7173   const char *name = type->field (f).name ();
7174   int len;
7175   int align_offset;
7176
7177   /* The field name should never be null, unless the debugging information
7178      is somehow malformed.  In this case, we assume the field does not
7179      require any alignment.  */
7180   if (name == NULL)
7181     return 1;
7182
7183   len = strlen (name);
7184
7185   if (!isdigit (name[len - 1]))
7186     return 1;
7187
7188   if (isdigit (name[len - 2]))
7189     align_offset = len - 2;
7190   else
7191     align_offset = len - 1;
7192
7193   if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7194     return TARGET_CHAR_BIT;
7195
7196   return atoi (name + align_offset) * TARGET_CHAR_BIT;
7197 }
7198
7199 /* Find a typedef or tag symbol named NAME.  Ignores ambiguity.  */
7200
7201 static struct symbol *
7202 ada_find_any_type_symbol (const char *name)
7203 {
7204   struct symbol *sym;
7205
7206   sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7207   if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
7208     return sym;
7209
7210   sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7211   return sym;
7212 }
7213
7214 /* Find a type named NAME.  Ignores ambiguity.  This routine will look
7215    solely for types defined by debug info, it will not search the GDB
7216    primitive types.  */
7217
7218 static struct type *
7219 ada_find_any_type (const char *name)
7220 {
7221   struct symbol *sym = ada_find_any_type_symbol (name);
7222
7223   if (sym != NULL)
7224     return sym->type ();
7225
7226   return NULL;
7227 }
7228
7229 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7230    associated with NAME_SYM's name.  NAME_SYM may itself be a renaming
7231    symbol, in which case it is returned.  Otherwise, this looks for
7232    symbols whose name is that of NAME_SYM suffixed with  "___XR".
7233    Return symbol if found, and NULL otherwise.  */
7234
7235 static bool
7236 ada_is_renaming_symbol (struct symbol *name_sym)
7237 {
7238   const char *name = name_sym->linkage_name ();
7239   return strstr (name, "___XR") != NULL;
7240 }
7241
7242 /* Because of GNAT encoding conventions, several GDB symbols may match a
7243    given type name.  If the type denoted by TYPE0 is to be preferred to
7244    that of TYPE1 for purposes of type printing, return non-zero;
7245    otherwise return 0.  */
7246
7247 int
7248 ada_prefer_type (struct type *type0, struct type *type1)
7249 {
7250   if (type1 == NULL)
7251     return 1;
7252   else if (type0 == NULL)
7253     return 0;
7254   else if (type1->code () == TYPE_CODE_VOID)
7255     return 1;
7256   else if (type0->code () == TYPE_CODE_VOID)
7257     return 0;
7258   else if (type1->name () == NULL && type0->name () != NULL)
7259     return 1;
7260   else if (ada_is_constrained_packed_array_type (type0))
7261     return 1;
7262   else if (ada_is_array_descriptor_type (type0)
7263            && !ada_is_array_descriptor_type (type1))
7264     return 1;
7265   else
7266     {
7267       const char *type0_name = type0->name ();
7268       const char *type1_name = type1->name ();
7269
7270       if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7271           && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7272         return 1;
7273     }
7274   return 0;
7275 }
7276
7277 /* The name of TYPE, which is its TYPE_NAME.  Null if TYPE is
7278    null.  */
7279
7280 const char *
7281 ada_type_name (struct type *type)
7282 {
7283   if (type == NULL)
7284     return NULL;
7285   return type->name ();
7286 }
7287
7288 /* Search the list of "descriptive" types associated to TYPE for a type
7289    whose name is NAME.  */
7290
7291 static struct type *
7292 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7293 {
7294   struct type *result, *tmp;
7295
7296   if (ada_ignore_descriptive_types_p)
7297     return NULL;
7298
7299   /* If there no descriptive-type info, then there is no parallel type
7300      to be found.  */
7301   if (!HAVE_GNAT_AUX_INFO (type))
7302     return NULL;
7303
7304   result = TYPE_DESCRIPTIVE_TYPE (type);
7305   while (result != NULL)
7306     {
7307       const char *result_name = ada_type_name (result);
7308
7309       if (result_name == NULL)
7310         {
7311           warning (_("unexpected null name on descriptive type"));
7312           return NULL;
7313         }
7314
7315       /* If the names match, stop.  */
7316       if (strcmp (result_name, name) == 0)
7317         break;
7318
7319       /* Otherwise, look at the next item on the list, if any.  */
7320       if (HAVE_GNAT_AUX_INFO (result))
7321         tmp = TYPE_DESCRIPTIVE_TYPE (result);
7322       else
7323         tmp = NULL;
7324
7325       /* If not found either, try after having resolved the typedef.  */
7326       if (tmp != NULL)
7327         result = tmp;
7328       else
7329         {
7330           result = check_typedef (result);
7331           if (HAVE_GNAT_AUX_INFO (result))
7332             result = TYPE_DESCRIPTIVE_TYPE (result);
7333           else
7334             result = NULL;
7335         }
7336     }
7337
7338   /* If we didn't find a match, see whether this is a packed array.  With
7339      older compilers, the descriptive type information is either absent or
7340      irrelevant when it comes to packed arrays so the above lookup fails.
7341      Fall back to using a parallel lookup by name in this case.  */
7342   if (result == NULL && ada_is_constrained_packed_array_type (type))
7343     return ada_find_any_type (name);
7344
7345   return result;
7346 }
7347
7348 /* Find a parallel type to TYPE with the specified NAME, using the
7349    descriptive type taken from the debugging information, if available,
7350    and otherwise using the (slower) name-based method.  */
7351
7352 static struct type *
7353 ada_find_parallel_type_with_name (struct type *type, const char *name)
7354 {
7355   struct type *result = NULL;
7356
7357   if (HAVE_GNAT_AUX_INFO (type))
7358     result = find_parallel_type_by_descriptive_type (type, name);
7359   else
7360     result = ada_find_any_type (name);
7361
7362   return result;
7363 }
7364
7365 /* Same as above, but specify the name of the parallel type by appending
7366    SUFFIX to the name of TYPE.  */
7367
7368 struct type *
7369 ada_find_parallel_type (struct type *type, const char *suffix)
7370 {
7371   char *name;
7372   const char *type_name = ada_type_name (type);
7373   int len;
7374
7375   if (type_name == NULL)
7376     return NULL;
7377
7378   len = strlen (type_name);
7379
7380   name = (char *) alloca (len + strlen (suffix) + 1);
7381
7382   strcpy (name, type_name);
7383   strcpy (name + len, suffix);
7384
7385   return ada_find_parallel_type_with_name (type, name);
7386 }
7387
7388 /* If TYPE is a variable-size record type, return the corresponding template
7389    type describing its fields.  Otherwise, return NULL.  */
7390
7391 static struct type *
7392 dynamic_template_type (struct type *type)
7393 {
7394   type = ada_check_typedef (type);
7395
7396   if (type == NULL || type->code () != TYPE_CODE_STRUCT
7397       || ada_type_name (type) == NULL)
7398     return NULL;
7399   else
7400     {
7401       int len = strlen (ada_type_name (type));
7402
7403       if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
7404         return type;
7405       else
7406         return ada_find_parallel_type (type, "___XVE");
7407     }
7408 }
7409
7410 /* Assuming that TEMPL_TYPE is a union or struct type, returns
7411    non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size.  */
7412
7413 static int
7414 is_dynamic_field (struct type *templ_type, int field_num)
7415 {
7416   const char *name = templ_type->field (field_num).name ();
7417
7418   return name != NULL
7419     && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
7420     && strstr (name, "___XVL") != NULL;
7421 }
7422
7423 /* The index of the variant field of TYPE, or -1 if TYPE does not
7424    represent a variant record type.  */
7425
7426 static int
7427 variant_field_index (struct type *type)
7428 {
7429   int f;
7430
7431   if (type == NULL || type->code () != TYPE_CODE_STRUCT)
7432     return -1;
7433
7434   for (f = 0; f < type->num_fields (); f += 1)
7435     {
7436       if (ada_is_variant_part (type, f))
7437         return f;
7438     }
7439   return -1;
7440 }
7441
7442 /* A record type with no fields.  */
7443
7444 static struct type *
7445 empty_record (struct type *templ)
7446 {
7447   struct type *type = alloc_type_copy (templ);
7448
7449   type->set_code (TYPE_CODE_STRUCT);
7450   INIT_NONE_SPECIFIC (type);
7451   type->set_name ("<empty>");
7452   TYPE_LENGTH (type) = 0;
7453   return type;
7454 }
7455
7456 /* An ordinary record type (with fixed-length fields) that describes
7457    the value of type TYPE at VALADDR or ADDRESS (see comments at
7458    the beginning of this section) VAL according to GNAT conventions.
7459    DVAL0 should describe the (portion of a) record that contains any
7460    necessary discriminants.  It should be NULL if value_type (VAL) is
7461    an outer-level type (i.e., as opposed to a branch of a variant.)  A
7462    variant field (unless unchecked) is replaced by a particular branch
7463    of the variant.
7464
7465    If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7466    length are not statically known are discarded.  As a consequence,
7467    VALADDR, ADDRESS and DVAL0 are ignored.
7468
7469    NOTE: Limitations: For now, we assume that dynamic fields and
7470    variants occupy whole numbers of bytes.  However, they need not be
7471    byte-aligned.  */
7472
7473 struct type *
7474 ada_template_to_fixed_record_type_1 (struct type *type,
7475                                      const gdb_byte *valaddr,
7476                                      CORE_ADDR address, struct value *dval0,
7477                                      int keep_dynamic_fields)
7478 {
7479   struct value *mark = value_mark ();
7480   struct value *dval;
7481   struct type *rtype;
7482   int nfields, bit_len;
7483   int variant_field;
7484   long off;
7485   int fld_bit_len;
7486   int f;
7487
7488   /* Compute the number of fields in this record type that are going
7489      to be processed: unless keep_dynamic_fields, this includes only
7490      fields whose position and length are static will be processed.  */
7491   if (keep_dynamic_fields)
7492     nfields = type->num_fields ();
7493   else
7494     {
7495       nfields = 0;
7496       while (nfields < type->num_fields ()
7497              && !ada_is_variant_part (type, nfields)
7498              && !is_dynamic_field (type, nfields))
7499         nfields++;
7500     }
7501
7502   rtype = alloc_type_copy (type);
7503   rtype->set_code (TYPE_CODE_STRUCT);
7504   INIT_NONE_SPECIFIC (rtype);
7505   rtype->set_num_fields (nfields);
7506   rtype->set_fields
7507    ((struct field *) TYPE_ZALLOC (rtype, nfields * sizeof (struct field)));
7508   rtype->set_name (ada_type_name (type));
7509   rtype->set_is_fixed_instance (true);
7510
7511   off = 0;
7512   bit_len = 0;
7513   variant_field = -1;
7514
7515   for (f = 0; f < nfields; f += 1)
7516     {
7517       off = align_up (off, field_alignment (type, f))
7518         + type->field (f).loc_bitpos ();
7519       rtype->field (f).set_loc_bitpos (off);
7520       TYPE_FIELD_BITSIZE (rtype, f) = 0;
7521
7522       if (ada_is_variant_part (type, f))
7523         {
7524           variant_field = f;
7525           fld_bit_len = 0;
7526         }
7527       else if (is_dynamic_field (type, f))
7528         {
7529           const gdb_byte *field_valaddr = valaddr;
7530           CORE_ADDR field_address = address;
7531           struct type *field_type =
7532             TYPE_TARGET_TYPE (type->field (f).type ());
7533
7534           if (dval0 == NULL)
7535             {
7536               /* Using plain value_from_contents_and_address here
7537                  causes problems because we will end up trying to
7538                  resolve a type that is currently being
7539                  constructed.  */
7540               dval = value_from_contents_and_address_unresolved (rtype,
7541                                                                  valaddr,
7542                                                                  address);
7543               rtype = value_type (dval);
7544             }
7545           else
7546             dval = dval0;
7547
7548           /* If the type referenced by this field is an aligner type, we need
7549              to unwrap that aligner type, because its size might not be set.
7550              Keeping the aligner type would cause us to compute the wrong
7551              size for this field, impacting the offset of the all the fields
7552              that follow this one.  */
7553           if (ada_is_aligner_type (field_type))
7554             {
7555               long field_offset = type->field (f).loc_bitpos ();
7556
7557               field_valaddr = cond_offset_host (field_valaddr, field_offset);
7558               field_address = cond_offset_target (field_address, field_offset);
7559               field_type = ada_aligned_type (field_type);
7560             }
7561
7562           field_valaddr = cond_offset_host (field_valaddr,
7563                                             off / TARGET_CHAR_BIT);
7564           field_address = cond_offset_target (field_address,
7565                                               off / TARGET_CHAR_BIT);
7566
7567           /* Get the fixed type of the field.  Note that, in this case,
7568              we do not want to get the real type out of the tag: if
7569              the current field is the parent part of a tagged record,
7570              we will get the tag of the object.  Clearly wrong: the real
7571              type of the parent is not the real type of the child.  We
7572              would end up in an infinite loop.  */
7573           field_type = ada_get_base_type (field_type);
7574           field_type = ada_to_fixed_type (field_type, field_valaddr,
7575                                           field_address, dval, 0);
7576
7577           rtype->field (f).set_type (field_type);
7578           rtype->field (f).set_name (type->field (f).name ());
7579           /* The multiplication can potentially overflow.  But because
7580              the field length has been size-checked just above, and
7581              assuming that the maximum size is a reasonable value,
7582              an overflow should not happen in practice.  So rather than
7583              adding overflow recovery code to this already complex code,
7584              we just assume that it's not going to happen.  */
7585           fld_bit_len =
7586             TYPE_LENGTH (rtype->field (f).type ()) * TARGET_CHAR_BIT;
7587         }
7588       else
7589         {
7590           /* Note: If this field's type is a typedef, it is important
7591              to preserve the typedef layer.
7592
7593              Otherwise, we might be transforming a typedef to a fat
7594              pointer (encoding a pointer to an unconstrained array),
7595              into a basic fat pointer (encoding an unconstrained
7596              array).  As both types are implemented using the same
7597              structure, the typedef is the only clue which allows us
7598              to distinguish between the two options.  Stripping it
7599              would prevent us from printing this field appropriately.  */
7600           rtype->field (f).set_type (type->field (f).type ());
7601           rtype->field (f).set_name (type->field (f).name ());
7602           if (TYPE_FIELD_BITSIZE (type, f) > 0)
7603             fld_bit_len =
7604               TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7605           else
7606             {
7607               struct type *field_type = type->field (f).type ();
7608
7609               /* We need to be careful of typedefs when computing
7610                  the length of our field.  If this is a typedef,
7611                  get the length of the target type, not the length
7612                  of the typedef.  */
7613               if (field_type->code () == TYPE_CODE_TYPEDEF)
7614                 field_type = ada_typedef_target_type (field_type);
7615
7616               fld_bit_len =
7617                 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
7618             }
7619         }
7620       if (off + fld_bit_len > bit_len)
7621         bit_len = off + fld_bit_len;
7622       off += fld_bit_len;
7623       TYPE_LENGTH (rtype) =
7624         align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7625     }
7626
7627   /* We handle the variant part, if any, at the end because of certain
7628      odd cases in which it is re-ordered so as NOT to be the last field of
7629      the record.  This can happen in the presence of representation
7630      clauses.  */
7631   if (variant_field >= 0)
7632     {
7633       struct type *branch_type;
7634
7635       off = rtype->field (variant_field).loc_bitpos ();
7636
7637       if (dval0 == NULL)
7638         {
7639           /* Using plain value_from_contents_and_address here causes
7640              problems because we will end up trying to resolve a type
7641              that is currently being constructed.  */
7642           dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7643                                                              address);
7644           rtype = value_type (dval);
7645         }
7646       else
7647         dval = dval0;
7648
7649       branch_type =
7650         to_fixed_variant_branch_type
7651         (type->field (variant_field).type (),
7652          cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7653          cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
7654       if (branch_type == NULL)
7655         {
7656           for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7657             rtype->field (f - 1) = rtype->field (f);
7658           rtype->set_num_fields (rtype->num_fields () - 1);
7659         }
7660       else
7661         {
7662           rtype->field (variant_field).set_type (branch_type);
7663           rtype->field (variant_field).set_name ("S");
7664           fld_bit_len =
7665             TYPE_LENGTH (rtype->field (variant_field).type ()) *
7666             TARGET_CHAR_BIT;
7667           if (off + fld_bit_len > bit_len)
7668             bit_len = off + fld_bit_len;
7669           TYPE_LENGTH (rtype) =
7670             align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
7671         }
7672     }
7673
7674   /* According to exp_dbug.ads, the size of TYPE for variable-size records
7675      should contain the alignment of that record, which should be a strictly
7676      positive value.  If null or negative, then something is wrong, most
7677      probably in the debug info.  In that case, we don't round up the size
7678      of the resulting type.  If this record is not part of another structure,
7679      the current RTYPE length might be good enough for our purposes.  */
7680   if (TYPE_LENGTH (type) <= 0)
7681     {
7682       if (rtype->name ())
7683         warning (_("Invalid type size for `%s' detected: %s."),
7684                  rtype->name (), pulongest (TYPE_LENGTH (type)));
7685       else
7686         warning (_("Invalid type size for <unnamed> detected: %s."),
7687                  pulongest (TYPE_LENGTH (type)));
7688     }
7689   else
7690     {
7691       TYPE_LENGTH (rtype) = align_up (TYPE_LENGTH (rtype),
7692                                       TYPE_LENGTH (type));
7693     }
7694
7695   value_free_to_mark (mark);
7696   return rtype;
7697 }
7698
7699 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7700    of 1.  */
7701
7702 static struct type *
7703 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
7704                                CORE_ADDR address, struct value *dval0)
7705 {
7706   return ada_template_to_fixed_record_type_1 (type, valaddr,
7707                                               address, dval0, 1);
7708 }
7709
7710 /* An ordinary record type in which ___XVL-convention fields and
7711    ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7712    static approximations, containing all possible fields.  Uses
7713    no runtime values.  Useless for use in values, but that's OK,
7714    since the results are used only for type determinations.   Works on both
7715    structs and unions.  Representation note: to save space, we memorize
7716    the result of this function in the TYPE_TARGET_TYPE of the
7717    template type.  */
7718
7719 static struct type *
7720 template_to_static_fixed_type (struct type *type0)
7721 {
7722   struct type *type;
7723   int nfields;
7724   int f;
7725
7726   /* No need no do anything if the input type is already fixed.  */
7727   if (type0->is_fixed_instance ())
7728     return type0;
7729
7730   /* Likewise if we already have computed the static approximation.  */
7731   if (TYPE_TARGET_TYPE (type0) != NULL)
7732     return TYPE_TARGET_TYPE (type0);
7733
7734   /* Don't clone TYPE0 until we are sure we are going to need a copy.  */
7735   type = type0;
7736   nfields = type0->num_fields ();
7737
7738   /* Whether or not we cloned TYPE0, cache the result so that we don't do
7739      recompute all over next time.  */
7740   TYPE_TARGET_TYPE (type0) = type;
7741
7742   for (f = 0; f < nfields; f += 1)
7743     {
7744       struct type *field_type = type0->field (f).type ();
7745       struct type *new_type;
7746
7747       if (is_dynamic_field (type0, f))
7748         {
7749           field_type = ada_check_typedef (field_type);
7750           new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
7751         }
7752       else
7753         new_type = static_unwrap_type (field_type);
7754
7755       if (new_type != field_type)
7756         {
7757           /* Clone TYPE0 only the first time we get a new field type.  */
7758           if (type == type0)
7759             {
7760               TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
7761               type->set_code (type0->code ());
7762               INIT_NONE_SPECIFIC (type);
7763               type->set_num_fields (nfields);
7764
7765               field *fields =
7766                 ((struct field *)
7767                  TYPE_ALLOC (type, nfields * sizeof (struct field)));
7768               memcpy (fields, type0->fields (),
7769                       sizeof (struct field) * nfields);
7770               type->set_fields (fields);
7771
7772               type->set_name (ada_type_name (type0));
7773               type->set_is_fixed_instance (true);
7774               TYPE_LENGTH (type) = 0;
7775             }
7776           type->field (f).set_type (new_type);
7777           type->field (f).set_name (type0->field (f).name ());
7778         }
7779     }
7780
7781   return type;
7782 }
7783
7784 /* Given an object of type TYPE whose contents are at VALADDR and
7785    whose address in memory is ADDRESS, returns a revision of TYPE,
7786    which should be a non-dynamic-sized record, in which the variant
7787    part, if any, is replaced with the appropriate branch.  Looks
7788    for discriminant values in DVAL0, which can be NULL if the record
7789    contains the necessary discriminant values.  */
7790
7791 static struct type *
7792 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
7793                                    CORE_ADDR address, struct value *dval0)
7794 {
7795   struct value *mark = value_mark ();
7796   struct value *dval;
7797   struct type *rtype;
7798   struct type *branch_type;
7799   int nfields = type->num_fields ();
7800   int variant_field = variant_field_index (type);
7801
7802   if (variant_field == -1)
7803     return type;
7804
7805   if (dval0 == NULL)
7806     {
7807       dval = value_from_contents_and_address (type, valaddr, address);
7808       type = value_type (dval);
7809     }
7810   else
7811     dval = dval0;
7812
7813   rtype = alloc_type_copy (type);
7814   rtype->set_code (TYPE_CODE_STRUCT);
7815   INIT_NONE_SPECIFIC (rtype);
7816   rtype->set_num_fields (nfields);
7817
7818   field *fields =
7819     (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
7820   memcpy (fields, type->fields (), sizeof (struct field) * nfields);
7821   rtype->set_fields (fields);
7822
7823   rtype->set_name (ada_type_name (type));
7824   rtype->set_is_fixed_instance (true);
7825   TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
7826
7827   branch_type = to_fixed_variant_branch_type
7828     (type->field (variant_field).type (),
7829      cond_offset_host (valaddr,
7830                        type->field (variant_field).loc_bitpos ()
7831                        / TARGET_CHAR_BIT),
7832      cond_offset_target (address,
7833                          type->field (variant_field).loc_bitpos ()
7834                          / TARGET_CHAR_BIT), dval);
7835   if (branch_type == NULL)
7836     {
7837       int f;
7838
7839       for (f = variant_field + 1; f < nfields; f += 1)
7840         rtype->field (f - 1) = rtype->field (f);
7841       rtype->set_num_fields (rtype->num_fields () - 1);
7842     }
7843   else
7844     {
7845       rtype->field (variant_field).set_type (branch_type);
7846       rtype->field (variant_field).set_name ("S");
7847       TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
7848       TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
7849     }
7850   TYPE_LENGTH (rtype) -= TYPE_LENGTH (type->field (variant_field).type ());
7851
7852   value_free_to_mark (mark);
7853   return rtype;
7854 }
7855
7856 /* An ordinary record type (with fixed-length fields) that describes
7857    the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
7858    beginning of this section].   Any necessary discriminants' values
7859    should be in DVAL, a record value; it may be NULL if the object
7860    at ADDR itself contains any necessary discriminant values.
7861    Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
7862    values from the record are needed.  Except in the case that DVAL,
7863    VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
7864    unchecked) is replaced by a particular branch of the variant.
7865
7866    NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
7867    is questionable and may be removed.  It can arise during the
7868    processing of an unconstrained-array-of-record type where all the
7869    variant branches have exactly the same size.  This is because in
7870    such cases, the compiler does not bother to use the XVS convention
7871    when encoding the record.  I am currently dubious of this
7872    shortcut and suspect the compiler should be altered.  FIXME.  */
7873
7874 static struct type *
7875 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
7876                       CORE_ADDR address, struct value *dval)
7877 {
7878   struct type *templ_type;
7879
7880   if (type0->is_fixed_instance ())
7881     return type0;
7882
7883   templ_type = dynamic_template_type (type0);
7884
7885   if (templ_type != NULL)
7886     return template_to_fixed_record_type (templ_type, valaddr, address, dval);
7887   else if (variant_field_index (type0) >= 0)
7888     {
7889       if (dval == NULL && valaddr == NULL && address == 0)
7890         return type0;
7891       return to_record_with_fixed_variant_part (type0, valaddr, address,
7892                                                 dval);
7893     }
7894   else
7895     {
7896       type0->set_is_fixed_instance (true);
7897       return type0;
7898     }
7899
7900 }
7901
7902 /* An ordinary record type (with fixed-length fields) that describes
7903    the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
7904    union type.  Any necessary discriminants' values should be in DVAL,
7905    a record value.  That is, this routine selects the appropriate
7906    branch of the union at ADDR according to the discriminant value
7907    indicated in the union's type name.  Returns VAR_TYPE0 itself if
7908    it represents a variant subject to a pragma Unchecked_Union.  */
7909
7910 static struct type *
7911 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
7912                               CORE_ADDR address, struct value *dval)
7913 {
7914   int which;
7915   struct type *templ_type;
7916   struct type *var_type;
7917
7918   if (var_type0->code () == TYPE_CODE_PTR)
7919     var_type = TYPE_TARGET_TYPE (var_type0);
7920   else
7921     var_type = var_type0;
7922
7923   templ_type = ada_find_parallel_type (var_type, "___XVU");
7924
7925   if (templ_type != NULL)
7926     var_type = templ_type;
7927
7928   if (is_unchecked_variant (var_type, value_type (dval)))
7929       return var_type0;
7930   which = ada_which_variant_applies (var_type, dval);
7931
7932   if (which < 0)
7933     return empty_record (var_type);
7934   else if (is_dynamic_field (var_type, which))
7935     return to_fixed_record_type
7936       (TYPE_TARGET_TYPE (var_type->field (which).type ()),
7937        valaddr, address, dval);
7938   else if (variant_field_index (var_type->field (which).type ()) >= 0)
7939     return
7940       to_fixed_record_type
7941       (var_type->field (which).type (), valaddr, address, dval);
7942   else
7943     return var_type->field (which).type ();
7944 }
7945
7946 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
7947    ENCODING_TYPE, a type following the GNAT conventions for discrete
7948    type encodings, only carries redundant information.  */
7949
7950 static int
7951 ada_is_redundant_range_encoding (struct type *range_type,
7952                                  struct type *encoding_type)
7953 {
7954   const char *bounds_str;
7955   int n;
7956   LONGEST lo, hi;
7957
7958   gdb_assert (range_type->code () == TYPE_CODE_RANGE);
7959
7960   if (get_base_type (range_type)->code ()
7961       != get_base_type (encoding_type)->code ())
7962     {
7963       /* The compiler probably used a simple base type to describe
7964          the range type instead of the range's actual base type,
7965          expecting us to get the real base type from the encoding
7966          anyway.  In this situation, the encoding cannot be ignored
7967          as redundant.  */
7968       return 0;
7969     }
7970
7971   if (is_dynamic_type (range_type))
7972     return 0;
7973
7974   if (encoding_type->name () == NULL)
7975     return 0;
7976
7977   bounds_str = strstr (encoding_type->name (), "___XDLU_");
7978   if (bounds_str == NULL)
7979     return 0;
7980
7981   n = 8; /* Skip "___XDLU_".  */
7982   if (!ada_scan_number (bounds_str, n, &lo, &n))
7983     return 0;
7984   if (range_type->bounds ()->low.const_val () != lo)
7985     return 0;
7986
7987   n += 2; /* Skip the "__" separator between the two bounds.  */
7988   if (!ada_scan_number (bounds_str, n, &hi, &n))
7989     return 0;
7990   if (range_type->bounds ()->high.const_val () != hi)
7991     return 0;
7992
7993   return 1;
7994 }
7995
7996 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
7997    a type following the GNAT encoding for describing array type
7998    indices, only carries redundant information.  */
7999
8000 static int
8001 ada_is_redundant_index_type_desc (struct type *array_type,
8002                                   struct type *desc_type)
8003 {
8004   struct type *this_layer = check_typedef (array_type);
8005   int i;
8006
8007   for (i = 0; i < desc_type->num_fields (); i++)
8008     {
8009       if (!ada_is_redundant_range_encoding (this_layer->index_type (),
8010                                             desc_type->field (i).type ()))
8011         return 0;
8012       this_layer = check_typedef (TYPE_TARGET_TYPE (this_layer));
8013     }
8014
8015   return 1;
8016 }
8017
8018 /* Assuming that TYPE0 is an array type describing the type of a value
8019    at ADDR, and that DVAL describes a record containing any
8020    discriminants used in TYPE0, returns a type for the value that
8021    contains no dynamic components (that is, no components whose sizes
8022    are determined by run-time quantities).  Unless IGNORE_TOO_BIG is
8023    true, gives an error message if the resulting type's size is over
8024    varsize_limit.  */
8025
8026 static struct type *
8027 to_fixed_array_type (struct type *type0, struct value *dval,
8028                      int ignore_too_big)
8029 {
8030   struct type *index_type_desc;
8031   struct type *result;
8032   int constrained_packed_array_p;
8033   static const char *xa_suffix = "___XA";
8034
8035   type0 = ada_check_typedef (type0);
8036   if (type0->is_fixed_instance ())
8037     return type0;
8038
8039   constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8040   if (constrained_packed_array_p)
8041     {
8042       type0 = decode_constrained_packed_array_type (type0);
8043       if (type0 == nullptr)
8044         error (_("could not decode constrained packed array type"));
8045     }
8046
8047   index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8048
8049   /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8050      encoding suffixed with 'P' may still be generated.  If so,
8051      it should be used to find the XA type.  */
8052
8053   if (index_type_desc == NULL)
8054     {
8055       const char *type_name = ada_type_name (type0);
8056
8057       if (type_name != NULL)
8058         {
8059           const int len = strlen (type_name);
8060           char *name = (char *) alloca (len + strlen (xa_suffix));
8061
8062           if (type_name[len - 1] == 'P')
8063             {
8064               strcpy (name, type_name);
8065               strcpy (name + len - 1, xa_suffix);
8066               index_type_desc = ada_find_parallel_type_with_name (type0, name);
8067             }
8068         }
8069     }
8070
8071   ada_fixup_array_indexes_type (index_type_desc);
8072   if (index_type_desc != NULL
8073       && ada_is_redundant_index_type_desc (type0, index_type_desc))
8074     {
8075       /* Ignore this ___XA parallel type, as it does not bring any
8076          useful information.  This allows us to avoid creating fixed
8077          versions of the array's index types, which would be identical
8078          to the original ones.  This, in turn, can also help avoid
8079          the creation of fixed versions of the array itself.  */
8080       index_type_desc = NULL;
8081     }
8082
8083   if (index_type_desc == NULL)
8084     {
8085       struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
8086
8087       /* NOTE: elt_type---the fixed version of elt_type0---should never
8088          depend on the contents of the array in properly constructed
8089          debugging data.  */
8090       /* Create a fixed version of the array element type.
8091          We're not providing the address of an element here,
8092          and thus the actual object value cannot be inspected to do
8093          the conversion.  This should not be a problem, since arrays of
8094          unconstrained objects are not allowed.  In particular, all
8095          the elements of an array of a tagged type should all be of
8096          the same type specified in the debugging info.  No need to
8097          consult the object tag.  */
8098       struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8099
8100       /* Make sure we always create a new array type when dealing with
8101          packed array types, since we're going to fix-up the array
8102          type length and element bitsize a little further down.  */
8103       if (elt_type0 == elt_type && !constrained_packed_array_p)
8104         result = type0;
8105       else
8106         result = create_array_type (alloc_type_copy (type0),
8107                                     elt_type, type0->index_type ());
8108     }
8109   else
8110     {
8111       int i;
8112       struct type *elt_type0;
8113
8114       elt_type0 = type0;
8115       for (i = index_type_desc->num_fields (); i > 0; i -= 1)
8116         elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8117
8118       /* NOTE: result---the fixed version of elt_type0---should never
8119          depend on the contents of the array in properly constructed
8120          debugging data.  */
8121       /* Create a fixed version of the array element type.
8122          We're not providing the address of an element here,
8123          and thus the actual object value cannot be inspected to do
8124          the conversion.  This should not be a problem, since arrays of
8125          unconstrained objects are not allowed.  In particular, all
8126          the elements of an array of a tagged type should all be of
8127          the same type specified in the debugging info.  No need to
8128          consult the object tag.  */
8129       result =
8130         ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8131
8132       elt_type0 = type0;
8133       for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
8134         {
8135           struct type *range_type =
8136             to_fixed_range_type (index_type_desc->field (i).type (), dval);
8137
8138           result = create_array_type (alloc_type_copy (elt_type0),
8139                                       result, range_type);
8140           elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8141         }
8142     }
8143
8144   /* We want to preserve the type name.  This can be useful when
8145      trying to get the type name of a value that has already been
8146      printed (for instance, if the user did "print VAR; whatis $".  */
8147   result->set_name (type0->name ());
8148
8149   if (constrained_packed_array_p)
8150     {
8151       /* So far, the resulting type has been created as if the original
8152          type was a regular (non-packed) array type.  As a result, the
8153          bitsize of the array elements needs to be set again, and the array
8154          length needs to be recomputed based on that bitsize.  */
8155       int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
8156       int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8157
8158       TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8159       TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
8160       if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
8161         TYPE_LENGTH (result)++;
8162     }
8163
8164   result->set_is_fixed_instance (true);
8165   return result;
8166 }
8167
8168
8169 /* A standard type (containing no dynamically sized components)
8170    corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8171    DVAL describes a record containing any discriminants used in TYPE0,
8172    and may be NULL if there are none, or if the object of type TYPE at
8173    ADDRESS or in VALADDR contains these discriminants.
8174    
8175    If CHECK_TAG is not null, in the case of tagged types, this function
8176    attempts to locate the object's tag and use it to compute the actual
8177    type.  However, when ADDRESS is null, we cannot use it to determine the
8178    location of the tag, and therefore compute the tagged type's actual type.
8179    So we return the tagged type without consulting the tag.  */
8180    
8181 static struct type *
8182 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
8183                    CORE_ADDR address, struct value *dval, int check_tag)
8184 {
8185   type = ada_check_typedef (type);
8186
8187   /* Only un-fixed types need to be handled here.  */
8188   if (!HAVE_GNAT_AUX_INFO (type))
8189     return type;
8190
8191   switch (type->code ())
8192     {
8193     default:
8194       return type;
8195     case TYPE_CODE_STRUCT:
8196       {
8197         struct type *static_type = to_static_fixed_type (type);
8198         struct type *fixed_record_type =
8199           to_fixed_record_type (type, valaddr, address, NULL);
8200
8201         /* If STATIC_TYPE is a tagged type and we know the object's address,
8202            then we can determine its tag, and compute the object's actual
8203            type from there.  Note that we have to use the fixed record
8204            type (the parent part of the record may have dynamic fields
8205            and the way the location of _tag is expressed may depend on
8206            them).  */
8207
8208         if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8209           {
8210             struct value *tag =
8211               value_tag_from_contents_and_address
8212               (fixed_record_type,
8213                valaddr,
8214                address);
8215             struct type *real_type = type_from_tag (tag);
8216             struct value *obj =
8217               value_from_contents_and_address (fixed_record_type,
8218                                                valaddr,
8219                                                address);
8220             fixed_record_type = value_type (obj);
8221             if (real_type != NULL)
8222               return to_fixed_record_type
8223                 (real_type, NULL,
8224                  value_address (ada_tag_value_at_base_address (obj)), NULL);
8225           }
8226
8227         /* Check to see if there is a parallel ___XVZ variable.
8228            If there is, then it provides the actual size of our type.  */
8229         else if (ada_type_name (fixed_record_type) != NULL)
8230           {
8231             const char *name = ada_type_name (fixed_record_type);
8232             char *xvz_name
8233               = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
8234             bool xvz_found = false;
8235             LONGEST size;
8236
8237             xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
8238             try
8239               {
8240                 xvz_found = get_int_var_value (xvz_name, size);
8241               }
8242             catch (const gdb_exception_error &except)
8243               {
8244                 /* We found the variable, but somehow failed to read
8245                    its value.  Rethrow the same error, but with a little
8246                    bit more information, to help the user understand
8247                    what went wrong (Eg: the variable might have been
8248                    optimized out).  */
8249                 throw_error (except.error,
8250                              _("unable to read value of %s (%s)"),
8251                              xvz_name, except.what ());
8252               }
8253
8254             if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
8255               {
8256                 fixed_record_type = copy_type (fixed_record_type);
8257                 TYPE_LENGTH (fixed_record_type) = size;
8258
8259                 /* The FIXED_RECORD_TYPE may have be a stub.  We have
8260                    observed this when the debugging info is STABS, and
8261                    apparently it is something that is hard to fix.
8262
8263                    In practice, we don't need the actual type definition
8264                    at all, because the presence of the XVZ variable allows us
8265                    to assume that there must be a XVS type as well, which we
8266                    should be able to use later, when we need the actual type
8267                    definition.
8268
8269                    In the meantime, pretend that the "fixed" type we are
8270                    returning is NOT a stub, because this can cause trouble
8271                    when using this type to create new types targeting it.
8272                    Indeed, the associated creation routines often check
8273                    whether the target type is a stub and will try to replace
8274                    it, thus using a type with the wrong size.  This, in turn,
8275                    might cause the new type to have the wrong size too.
8276                    Consider the case of an array, for instance, where the size
8277                    of the array is computed from the number of elements in
8278                    our array multiplied by the size of its element.  */
8279                 fixed_record_type->set_is_stub (false);
8280               }
8281           }
8282         return fixed_record_type;
8283       }
8284     case TYPE_CODE_ARRAY:
8285       return to_fixed_array_type (type, dval, 1);
8286     case TYPE_CODE_UNION:
8287       if (dval == NULL)
8288         return type;
8289       else
8290         return to_fixed_variant_branch_type (type, valaddr, address, dval);
8291     }
8292 }
8293
8294 /* The same as ada_to_fixed_type_1, except that it preserves the type
8295    if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
8296
8297    The typedef layer needs be preserved in order to differentiate between
8298    arrays and array pointers when both types are implemented using the same
8299    fat pointer.  In the array pointer case, the pointer is encoded as
8300    a typedef of the pointer type.  For instance, considering:
8301
8302           type String_Access is access String;
8303           S1 : String_Access := null;
8304
8305    To the debugger, S1 is defined as a typedef of type String.  But
8306    to the user, it is a pointer.  So if the user tries to print S1,
8307    we should not dereference the array, but print the array address
8308    instead.
8309
8310    If we didn't preserve the typedef layer, we would lose the fact that
8311    the type is to be presented as a pointer (needs de-reference before
8312    being printed).  And we would also use the source-level type name.  */
8313
8314 struct type *
8315 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
8316                    CORE_ADDR address, struct value *dval, int check_tag)
8317
8318 {
8319   struct type *fixed_type =
8320     ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8321
8322   /*  If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8323       then preserve the typedef layer.
8324
8325       Implementation note: We can only check the main-type portion of
8326       the TYPE and FIXED_TYPE, because eliminating the typedef layer
8327       from TYPE now returns a type that has the same instance flags
8328       as TYPE.  For instance, if TYPE is a "typedef const", and its
8329       target type is a "struct", then the typedef elimination will return
8330       a "const" version of the target type.  See check_typedef for more
8331       details about how the typedef layer elimination is done.
8332
8333       brobecker/2010-11-19: It seems to me that the only case where it is
8334       useful to preserve the typedef layer is when dealing with fat pointers.
8335       Perhaps, we could add a check for that and preserve the typedef layer
8336       only in that situation.  But this seems unnecessary so far, probably
8337       because we call check_typedef/ada_check_typedef pretty much everywhere.
8338       */
8339   if (type->code () == TYPE_CODE_TYPEDEF
8340       && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
8341           == TYPE_MAIN_TYPE (fixed_type)))
8342     return type;
8343
8344   return fixed_type;
8345 }
8346
8347 /* A standard (static-sized) type corresponding as well as possible to
8348    TYPE0, but based on no runtime data.  */
8349
8350 static struct type *
8351 to_static_fixed_type (struct type *type0)
8352 {
8353   struct type *type;
8354
8355   if (type0 == NULL)
8356     return NULL;
8357
8358   if (type0->is_fixed_instance ())
8359     return type0;
8360
8361   type0 = ada_check_typedef (type0);
8362
8363   switch (type0->code ())
8364     {
8365     default:
8366       return type0;
8367     case TYPE_CODE_STRUCT:
8368       type = dynamic_template_type (type0);
8369       if (type != NULL)
8370         return template_to_static_fixed_type (type);
8371       else
8372         return template_to_static_fixed_type (type0);
8373     case TYPE_CODE_UNION:
8374       type = ada_find_parallel_type (type0, "___XVU");
8375       if (type != NULL)
8376         return template_to_static_fixed_type (type);
8377       else
8378         return template_to_static_fixed_type (type0);
8379     }
8380 }
8381
8382 /* A static approximation of TYPE with all type wrappers removed.  */
8383
8384 static struct type *
8385 static_unwrap_type (struct type *type)
8386 {
8387   if (ada_is_aligner_type (type))
8388     {
8389       struct type *type1 = ada_check_typedef (type)->field (0).type ();
8390       if (ada_type_name (type1) == NULL)
8391         type1->set_name (ada_type_name (type));
8392
8393       return static_unwrap_type (type1);
8394     }
8395   else
8396     {
8397       struct type *raw_real_type = ada_get_base_type (type);
8398
8399       if (raw_real_type == type)
8400         return type;
8401       else
8402         return to_static_fixed_type (raw_real_type);
8403     }
8404 }
8405
8406 /* In some cases, incomplete and private types require
8407    cross-references that are not resolved as records (for example,
8408       type Foo;
8409       type FooP is access Foo;
8410       V: FooP;
8411       type Foo is array ...;
8412    ).  In these cases, since there is no mechanism for producing
8413    cross-references to such types, we instead substitute for FooP a
8414    stub enumeration type that is nowhere resolved, and whose tag is
8415    the name of the actual type.  Call these types "non-record stubs".  */
8416
8417 /* A type equivalent to TYPE that is not a non-record stub, if one
8418    exists, otherwise TYPE.  */
8419
8420 struct type *
8421 ada_check_typedef (struct type *type)
8422 {
8423   if (type == NULL)
8424     return NULL;
8425
8426   /* If our type is an access to an unconstrained array, which is encoded
8427      as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
8428      We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8429      what allows us to distinguish between fat pointers that represent
8430      array types, and fat pointers that represent array access types
8431      (in both cases, the compiler implements them as fat pointers).  */
8432   if (ada_is_access_to_unconstrained_array (type))
8433     return type;
8434
8435   type = check_typedef (type);
8436   if (type == NULL || type->code () != TYPE_CODE_ENUM
8437       || !type->is_stub ()
8438       || type->name () == NULL)
8439     return type;
8440   else
8441     {
8442       const char *name = type->name ();
8443       struct type *type1 = ada_find_any_type (name);
8444
8445       if (type1 == NULL)
8446         return type;
8447
8448       /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8449          stubs pointing to arrays, as we don't create symbols for array
8450          types, only for the typedef-to-array types).  If that's the case,
8451          strip the typedef layer.  */
8452       if (type1->code () == TYPE_CODE_TYPEDEF)
8453         type1 = ada_check_typedef (type1);
8454
8455       return type1;
8456     }
8457 }
8458
8459 /* A value representing the data at VALADDR/ADDRESS as described by
8460    type TYPE0, but with a standard (static-sized) type that correctly
8461    describes it.  If VAL0 is not NULL and TYPE0 already is a standard
8462    type, then return VAL0 [this feature is simply to avoid redundant
8463    creation of struct values].  */
8464
8465 static struct value *
8466 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
8467                            struct value *val0)
8468 {
8469   struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
8470
8471   if (type == type0 && val0 != NULL)
8472     return val0;
8473
8474   if (VALUE_LVAL (val0) != lval_memory)
8475     {
8476       /* Our value does not live in memory; it could be a convenience
8477          variable, for instance.  Create a not_lval value using val0's
8478          contents.  */
8479       return value_from_contents (type, value_contents (val0).data ());
8480     }
8481
8482   return value_from_contents_and_address (type, 0, address);
8483 }
8484
8485 /* A value representing VAL, but with a standard (static-sized) type
8486    that correctly describes it.  Does not necessarily create a new
8487    value.  */
8488
8489 struct value *
8490 ada_to_fixed_value (struct value *val)
8491 {
8492   val = unwrap_value (val);
8493   val = ada_to_fixed_value_create (value_type (val), value_address (val), val);
8494   return val;
8495 }
8496 \f
8497
8498 /* Attributes */
8499
8500 /* Table mapping attribute numbers to names.
8501    NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h.  */
8502
8503 static const char * const attribute_names[] = {
8504   "<?>",
8505
8506   "first",
8507   "last",
8508   "length",
8509   "image",
8510   "max",
8511   "min",
8512   "modulus",
8513   "pos",
8514   "size",
8515   "tag",
8516   "val",
8517   0
8518 };
8519
8520 static const char *
8521 ada_attribute_name (enum exp_opcode n)
8522 {
8523   if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8524     return attribute_names[n - OP_ATR_FIRST + 1];
8525   else
8526     return attribute_names[0];
8527 }
8528
8529 /* Evaluate the 'POS attribute applied to ARG.  */
8530
8531 static LONGEST
8532 pos_atr (struct value *arg)
8533 {
8534   struct value *val = coerce_ref (arg);
8535   struct type *type = value_type (val);
8536
8537   if (!discrete_type_p (type))
8538     error (_("'POS only defined on discrete types"));
8539
8540   gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8541   if (!result.has_value ())
8542     error (_("enumeration value is invalid: can't find 'POS"));
8543
8544   return *result;
8545 }
8546
8547 struct value *
8548 ada_pos_atr (struct type *expect_type,
8549              struct expression *exp,
8550              enum noside noside, enum exp_opcode op,
8551              struct value *arg)
8552 {
8553   struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8554   if (noside == EVAL_AVOID_SIDE_EFFECTS)
8555     return value_zero (type, not_lval);
8556   return value_from_longest (type, pos_atr (arg));
8557 }
8558
8559 /* Evaluate the TYPE'VAL attribute applied to ARG.  */
8560
8561 static struct value *
8562 val_atr (struct type *type, LONGEST val)
8563 {
8564   gdb_assert (discrete_type_p (type));
8565   if (type->code () == TYPE_CODE_RANGE)
8566     type = TYPE_TARGET_TYPE (type);
8567   if (type->code () == TYPE_CODE_ENUM)
8568     {
8569       if (val < 0 || val >= type->num_fields ())
8570         error (_("argument to 'VAL out of range"));
8571       val = type->field (val).loc_enumval ();
8572     }
8573   return value_from_longest (type, val);
8574 }
8575
8576 struct value *
8577 ada_val_atr (enum noside noside, struct type *type, struct value *arg)
8578 {
8579   if (noside == EVAL_AVOID_SIDE_EFFECTS)
8580     return value_zero (type, not_lval);
8581
8582   if (!discrete_type_p (type))
8583     error (_("'VAL only defined on discrete types"));
8584   if (!integer_type_p (value_type (arg)))
8585     error (_("'VAL requires integral argument"));
8586
8587   return val_atr (type, value_as_long (arg));
8588 }
8589 \f
8590
8591                                 /* Evaluation */
8592
8593 /* True if TYPE appears to be an Ada character type.
8594    [At the moment, this is true only for Character and Wide_Character;
8595    It is a heuristic test that could stand improvement].  */
8596
8597 bool
8598 ada_is_character_type (struct type *type)
8599 {
8600   const char *name;
8601
8602   /* If the type code says it's a character, then assume it really is,
8603      and don't check any further.  */
8604   if (type->code () == TYPE_CODE_CHAR)
8605     return true;
8606   
8607   /* Otherwise, assume it's a character type iff it is a discrete type
8608      with a known character type name.  */
8609   name = ada_type_name (type);
8610   return (name != NULL
8611           && (type->code () == TYPE_CODE_INT
8612               || type->code () == TYPE_CODE_RANGE)
8613           && (strcmp (name, "character") == 0
8614               || strcmp (name, "wide_character") == 0
8615               || strcmp (name, "wide_wide_character") == 0
8616               || strcmp (name, "unsigned char") == 0));
8617 }
8618
8619 /* True if TYPE appears to be an Ada string type.  */
8620
8621 bool
8622 ada_is_string_type (struct type *type)
8623 {
8624   type = ada_check_typedef (type);
8625   if (type != NULL
8626       && type->code () != TYPE_CODE_PTR
8627       && (ada_is_simple_array_type (type)
8628           || ada_is_array_descriptor_type (type))
8629       && ada_array_arity (type) == 1)
8630     {
8631       struct type *elttype = ada_array_element_type (type, 1);
8632
8633       return ada_is_character_type (elttype);
8634     }
8635   else
8636     return false;
8637 }
8638
8639 /* The compiler sometimes provides a parallel XVS type for a given
8640    PAD type.  Normally, it is safe to follow the PAD type directly,
8641    but older versions of the compiler have a bug that causes the offset
8642    of its "F" field to be wrong.  Following that field in that case
8643    would lead to incorrect results, but this can be worked around
8644    by ignoring the PAD type and using the associated XVS type instead.
8645
8646    Set to True if the debugger should trust the contents of PAD types.
8647    Otherwise, ignore the PAD type if there is a parallel XVS type.  */
8648 static bool trust_pad_over_xvs = true;
8649
8650 /* True if TYPE is a struct type introduced by the compiler to force the
8651    alignment of a value.  Such types have a single field with a
8652    distinctive name.  */
8653
8654 int
8655 ada_is_aligner_type (struct type *type)
8656 {
8657   type = ada_check_typedef (type);
8658
8659   if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
8660     return 0;
8661
8662   return (type->code () == TYPE_CODE_STRUCT
8663           && type->num_fields () == 1
8664           && strcmp (type->field (0).name (), "F") == 0);
8665 }
8666
8667 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
8668    the parallel type.  */
8669
8670 struct type *
8671 ada_get_base_type (struct type *raw_type)
8672 {
8673   struct type *real_type_namer;
8674   struct type *raw_real_type;
8675
8676   if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
8677     return raw_type;
8678
8679   if (ada_is_aligner_type (raw_type))
8680     /* The encoding specifies that we should always use the aligner type.
8681        So, even if this aligner type has an associated XVS type, we should
8682        simply ignore it.
8683
8684        According to the compiler gurus, an XVS type parallel to an aligner
8685        type may exist because of a stabs limitation.  In stabs, aligner
8686        types are empty because the field has a variable-sized type, and
8687        thus cannot actually be used as an aligner type.  As a result,
8688        we need the associated parallel XVS type to decode the type.
8689        Since the policy in the compiler is to not change the internal
8690        representation based on the debugging info format, we sometimes
8691        end up having a redundant XVS type parallel to the aligner type.  */
8692     return raw_type;
8693
8694   real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
8695   if (real_type_namer == NULL
8696       || real_type_namer->code () != TYPE_CODE_STRUCT
8697       || real_type_namer->num_fields () != 1)
8698     return raw_type;
8699
8700   if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
8701     {
8702       /* This is an older encoding form where the base type needs to be
8703          looked up by name.  We prefer the newer encoding because it is
8704          more efficient.  */
8705       raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
8706       if (raw_real_type == NULL)
8707         return raw_type;
8708       else
8709         return raw_real_type;
8710     }
8711
8712   /* The field in our XVS type is a reference to the base type.  */
8713   return TYPE_TARGET_TYPE (real_type_namer->field (0).type ());
8714 }
8715
8716 /* The type of value designated by TYPE, with all aligners removed.  */
8717
8718 struct type *
8719 ada_aligned_type (struct type *type)
8720 {
8721   if (ada_is_aligner_type (type))
8722     return ada_aligned_type (type->field (0).type ());
8723   else
8724     return ada_get_base_type (type);
8725 }
8726
8727
8728 /* The address of the aligned value in an object at address VALADDR
8729    having type TYPE.  Assumes ada_is_aligner_type (TYPE).  */
8730
8731 const gdb_byte *
8732 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
8733 {
8734   if (ada_is_aligner_type (type))
8735     return ada_aligned_value_addr
8736       (type->field (0).type (),
8737        valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
8738   else
8739     return valaddr;
8740 }
8741
8742
8743
8744 /* The printed representation of an enumeration literal with encoded
8745    name NAME.  The value is good to the next call of ada_enum_name.  */
8746 const char *
8747 ada_enum_name (const char *name)
8748 {
8749   static std::string storage;
8750   const char *tmp;
8751
8752   /* First, unqualify the enumeration name:
8753      1. Search for the last '.' character.  If we find one, then skip
8754      all the preceding characters, the unqualified name starts
8755      right after that dot.
8756      2. Otherwise, we may be debugging on a target where the compiler
8757      translates dots into "__".  Search forward for double underscores,
8758      but stop searching when we hit an overloading suffix, which is
8759      of the form "__" followed by digits.  */
8760
8761   tmp = strrchr (name, '.');
8762   if (tmp != NULL)
8763     name = tmp + 1;
8764   else
8765     {
8766       while ((tmp = strstr (name, "__")) != NULL)
8767         {
8768           if (isdigit (tmp[2]))
8769             break;
8770           else
8771             name = tmp + 2;
8772         }
8773     }
8774
8775   if (name[0] == 'Q')
8776     {
8777       int v;
8778
8779       if (name[1] == 'U' || name[1] == 'W')
8780         {
8781           int offset = 2;
8782           if (name[1] == 'W' && name[2] == 'W')
8783             {
8784               /* Also handle the QWW case.  */
8785               ++offset;
8786             }
8787           if (sscanf (name + offset, "%x", &v) != 1)
8788             return name;
8789         }
8790       else if (((name[1] >= '0' && name[1] <= '9')
8791                 || (name[1] >= 'a' && name[1] <= 'z'))
8792                && name[2] == '\0')
8793         {
8794           storage = string_printf ("'%c'", name[1]);
8795           return storage.c_str ();
8796         }
8797       else
8798         return name;
8799
8800       if (isascii (v) && isprint (v))
8801         storage = string_printf ("'%c'", v);
8802       else if (name[1] == 'U')
8803         storage = string_printf ("'[\"%02x\"]'", v);
8804       else if (name[2] != 'W')
8805         storage = string_printf ("'[\"%04x\"]'", v);
8806       else
8807         storage = string_printf ("'[\"%06x\"]'", v);
8808
8809       return storage.c_str ();
8810     }
8811   else
8812     {
8813       tmp = strstr (name, "__");
8814       if (tmp == NULL)
8815         tmp = strstr (name, "$");
8816       if (tmp != NULL)
8817         {
8818           storage = std::string (name, tmp - name);
8819           return storage.c_str ();
8820         }
8821
8822       return name;
8823     }
8824 }
8825
8826 /* If VAL is wrapped in an aligner or subtype wrapper, return the
8827    value it wraps.  */
8828
8829 static struct value *
8830 unwrap_value (struct value *val)
8831 {
8832   struct type *type = ada_check_typedef (value_type (val));
8833
8834   if (ada_is_aligner_type (type))
8835     {
8836       struct value *v = ada_value_struct_elt (val, "F", 0);
8837       struct type *val_type = ada_check_typedef (value_type (v));
8838
8839       if (ada_type_name (val_type) == NULL)
8840         val_type->set_name (ada_type_name (type));
8841
8842       return unwrap_value (v);
8843     }
8844   else
8845     {
8846       struct type *raw_real_type =
8847         ada_check_typedef (ada_get_base_type (type));
8848
8849       /* If there is no parallel XVS or XVE type, then the value is
8850          already unwrapped.  Return it without further modification.  */
8851       if ((type == raw_real_type)
8852           && ada_find_parallel_type (type, "___XVE") == NULL)
8853         return val;
8854
8855       return
8856         coerce_unspec_val_to_type
8857         (val, ada_to_fixed_type (raw_real_type, 0,
8858                                  value_address (val),
8859                                  NULL, 1));
8860     }
8861 }
8862
8863 /* Given two array types T1 and T2, return nonzero iff both arrays
8864    contain the same number of elements.  */
8865
8866 static int
8867 ada_same_array_size_p (struct type *t1, struct type *t2)
8868 {
8869   LONGEST lo1, hi1, lo2, hi2;
8870
8871   /* Get the array bounds in order to verify that the size of
8872      the two arrays match.  */
8873   if (!get_array_bounds (t1, &lo1, &hi1)
8874       || !get_array_bounds (t2, &lo2, &hi2))
8875     error (_("unable to determine array bounds"));
8876
8877   /* To make things easier for size comparison, normalize a bit
8878      the case of empty arrays by making sure that the difference
8879      between upper bound and lower bound is always -1.  */
8880   if (lo1 > hi1)
8881     hi1 = lo1 - 1;
8882   if (lo2 > hi2)
8883     hi2 = lo2 - 1;
8884
8885   return (hi1 - lo1 == hi2 - lo2);
8886 }
8887
8888 /* Assuming that VAL is an array of integrals, and TYPE represents
8889    an array with the same number of elements, but with wider integral
8890    elements, return an array "casted" to TYPE.  In practice, this
8891    means that the returned array is built by casting each element
8892    of the original array into TYPE's (wider) element type.  */
8893
8894 static struct value *
8895 ada_promote_array_of_integrals (struct type *type, struct value *val)
8896 {
8897   struct type *elt_type = TYPE_TARGET_TYPE (type);
8898   LONGEST lo, hi;
8899   LONGEST i;
8900
8901   /* Verify that both val and type are arrays of scalars, and
8902      that the size of val's elements is smaller than the size
8903      of type's element.  */
8904   gdb_assert (type->code () == TYPE_CODE_ARRAY);
8905   gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
8906   gdb_assert (value_type (val)->code () == TYPE_CODE_ARRAY);
8907   gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
8908   gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
8909               > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));
8910
8911   if (!get_array_bounds (type, &lo, &hi))
8912     error (_("unable to determine array bounds"));
8913
8914   value *res = allocate_value (type);
8915   gdb::array_view<gdb_byte> res_contents = value_contents_writeable (res);
8916
8917   /* Promote each array element.  */
8918   for (i = 0; i < hi - lo + 1; i++)
8919     {
8920       struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
8921       int elt_len = TYPE_LENGTH (elt_type);
8922
8923       copy (value_contents_all (elt), res_contents.slice (elt_len * i, elt_len));
8924     }
8925
8926   return res;
8927 }
8928
8929 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
8930    return the converted value.  */
8931
8932 static struct value *
8933 coerce_for_assign (struct type *type, struct value *val)
8934 {
8935   struct type *type2 = value_type (val);
8936
8937   if (type == type2)
8938     return val;
8939
8940   type2 = ada_check_typedef (type2);
8941   type = ada_check_typedef (type);
8942
8943   if (type2->code () == TYPE_CODE_PTR
8944       && type->code () == TYPE_CODE_ARRAY)
8945     {
8946       val = ada_value_ind (val);
8947       type2 = value_type (val);
8948     }
8949
8950   if (type2->code () == TYPE_CODE_ARRAY
8951       && type->code () == TYPE_CODE_ARRAY)
8952     {
8953       if (!ada_same_array_size_p (type, type2))
8954         error (_("cannot assign arrays of different length"));
8955
8956       if (is_integral_type (TYPE_TARGET_TYPE (type))
8957           && is_integral_type (TYPE_TARGET_TYPE (type2))
8958           && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
8959                < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
8960         {
8961           /* Allow implicit promotion of the array elements to
8962              a wider type.  */
8963           return ada_promote_array_of_integrals (type, val);
8964         }
8965
8966       if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
8967           != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
8968         error (_("Incompatible types in assignment"));
8969       deprecated_set_value_type (val, type);
8970     }
8971   return val;
8972 }
8973
8974 static struct value *
8975 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
8976 {
8977   struct value *val;
8978   struct type *type1, *type2;
8979   LONGEST v, v1, v2;
8980
8981   arg1 = coerce_ref (arg1);
8982   arg2 = coerce_ref (arg2);
8983   type1 = get_base_type (ada_check_typedef (value_type (arg1)));
8984   type2 = get_base_type (ada_check_typedef (value_type (arg2)));
8985
8986   if (type1->code () != TYPE_CODE_INT
8987       || type2->code () != TYPE_CODE_INT)
8988     return value_binop (arg1, arg2, op);
8989
8990   switch (op)
8991     {
8992     case BINOP_MOD:
8993     case BINOP_DIV:
8994     case BINOP_REM:
8995       break;
8996     default:
8997       return value_binop (arg1, arg2, op);
8998     }
8999
9000   v2 = value_as_long (arg2);
9001   if (v2 == 0)
9002     {
9003       const char *name;
9004       if (op == BINOP_MOD)
9005         name = "mod";
9006       else if (op == BINOP_DIV)
9007         name = "/";
9008       else
9009         {
9010           gdb_assert (op == BINOP_REM);
9011           name = "rem";
9012         }
9013
9014       error (_("second operand of %s must not be zero."), name);
9015     }
9016
9017   if (type1->is_unsigned () || op == BINOP_MOD)
9018     return value_binop (arg1, arg2, op);
9019
9020   v1 = value_as_long (arg1);
9021   switch (op)
9022     {
9023     case BINOP_DIV:
9024       v = v1 / v2;
9025       if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
9026         v += v > 0 ? -1 : 1;
9027       break;
9028     case BINOP_REM:
9029       v = v1 % v2;
9030       if (v * v1 < 0)
9031         v -= v2;
9032       break;
9033     default:
9034       /* Should not reach this point.  */
9035       v = 0;
9036     }
9037
9038   val = allocate_value (type1);
9039   store_unsigned_integer (value_contents_raw (val).data (),
9040                           TYPE_LENGTH (value_type (val)),
9041                           type_byte_order (type1), v);
9042   return val;
9043 }
9044
9045 static int
9046 ada_value_equal (struct value *arg1, struct value *arg2)
9047 {
9048   if (ada_is_direct_array_type (value_type (arg1))
9049       || ada_is_direct_array_type (value_type (arg2)))
9050     {
9051       struct type *arg1_type, *arg2_type;
9052
9053       /* Automatically dereference any array reference before
9054          we attempt to perform the comparison.  */
9055       arg1 = ada_coerce_ref (arg1);
9056       arg2 = ada_coerce_ref (arg2);
9057
9058       arg1 = ada_coerce_to_simple_array (arg1);
9059       arg2 = ada_coerce_to_simple_array (arg2);
9060
9061       arg1_type = ada_check_typedef (value_type (arg1));
9062       arg2_type = ada_check_typedef (value_type (arg2));
9063
9064       if (arg1_type->code () != TYPE_CODE_ARRAY
9065           || arg2_type->code () != TYPE_CODE_ARRAY)
9066         error (_("Attempt to compare array with non-array"));
9067       /* FIXME: The following works only for types whose
9068          representations use all bits (no padding or undefined bits)
9069          and do not have user-defined equality.  */
9070       return (TYPE_LENGTH (arg1_type) == TYPE_LENGTH (arg2_type)
9071               && memcmp (value_contents (arg1).data (),
9072                          value_contents (arg2).data (),
9073                          TYPE_LENGTH (arg1_type)) == 0);
9074     }
9075   return value_equal (arg1, arg2);
9076 }
9077
9078 namespace expr
9079 {
9080
9081 bool
9082 check_objfile (const std::unique_ptr<ada_component> &comp,
9083                struct objfile *objfile)
9084 {
9085   return comp->uses_objfile (objfile);
9086 }
9087
9088 /* Assign the result of evaluating ARG starting at *POS to the INDEXth
9089    component of LHS (a simple array or a record).  Does not modify the
9090    inferior's memory, nor does it modify LHS (unless LHS ==
9091    CONTAINER).  */
9092
9093 static void
9094 assign_component (struct value *container, struct value *lhs, LONGEST index,
9095                   struct expression *exp, operation_up &arg)
9096 {
9097   scoped_value_mark mark;
9098
9099   struct value *elt;
9100   struct type *lhs_type = check_typedef (value_type (lhs));
9101
9102   if (lhs_type->code () == TYPE_CODE_ARRAY)
9103     {
9104       struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9105       struct value *index_val = value_from_longest (index_type, index);
9106
9107       elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9108     }
9109   else
9110     {
9111       elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9112       elt = ada_to_fixed_value (elt);
9113     }
9114
9115   ada_aggregate_operation *ag_op
9116     = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9117   if (ag_op != nullptr)
9118     ag_op->assign_aggregate (container, elt, exp);
9119   else
9120     value_assign_to_component (container, elt,
9121                                arg->evaluate (nullptr, exp,
9122                                               EVAL_NORMAL));
9123 }
9124
9125 bool
9126 ada_aggregate_component::uses_objfile (struct objfile *objfile)
9127 {
9128   for (const auto &item : m_components)
9129     if (item->uses_objfile (objfile))
9130       return true;
9131   return false;
9132 }
9133
9134 void
9135 ada_aggregate_component::dump (ui_file *stream, int depth)
9136 {
9137   fprintf_filtered (stream, _("%*sAggregate\n"), depth, "");
9138   for (const auto &item : m_components)
9139     item->dump (stream, depth + 1);
9140 }
9141
9142 void
9143 ada_aggregate_component::assign (struct value *container,
9144                                  struct value *lhs, struct expression *exp,
9145                                  std::vector<LONGEST> &indices,
9146                                  LONGEST low, LONGEST high)
9147 {
9148   for (auto &item : m_components)
9149     item->assign (container, lhs, exp, indices, low, high);
9150 }
9151
9152 /* See ada-exp.h.  */
9153
9154 value *
9155 ada_aggregate_operation::assign_aggregate (struct value *container,
9156                                            struct value *lhs,
9157                                            struct expression *exp)
9158 {
9159   struct type *lhs_type;
9160   LONGEST low_index, high_index;
9161
9162   container = ada_coerce_ref (container);
9163   if (ada_is_direct_array_type (value_type (container)))
9164     container = ada_coerce_to_simple_array (container);
9165   lhs = ada_coerce_ref (lhs);
9166   if (!deprecated_value_modifiable (lhs))
9167     error (_("Left operand of assignment is not a modifiable lvalue."));
9168
9169   lhs_type = check_typedef (value_type (lhs));
9170   if (ada_is_direct_array_type (lhs_type))
9171     {
9172       lhs = ada_coerce_to_simple_array (lhs);
9173       lhs_type = check_typedef (value_type (lhs));
9174       low_index = lhs_type->bounds ()->low.const_val ();
9175       high_index = lhs_type->bounds ()->high.const_val ();
9176     }
9177   else if (lhs_type->code () == TYPE_CODE_STRUCT)
9178     {
9179       low_index = 0;
9180       high_index = num_visible_fields (lhs_type) - 1;
9181     }
9182   else
9183     error (_("Left-hand side must be array or record."));
9184
9185   std::vector<LONGEST> indices (4);
9186   indices[0] = indices[1] = low_index - 1;
9187   indices[2] = indices[3] = high_index + 1;
9188
9189   std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9190                                    low_index, high_index);
9191
9192   return container;
9193 }
9194
9195 bool
9196 ada_positional_component::uses_objfile (struct objfile *objfile)
9197 {
9198   return m_op->uses_objfile (objfile);
9199 }
9200
9201 void
9202 ada_positional_component::dump (ui_file *stream, int depth)
9203 {
9204   fprintf_filtered (stream, _("%*sPositional, index = %d\n"),
9205                     depth, "", m_index);
9206   m_op->dump (stream, depth + 1);
9207 }
9208
9209 /* Assign into the component of LHS indexed by the OP_POSITIONAL
9210    construct, given that the positions are relative to lower bound
9211    LOW, where HIGH is the upper bound.  Record the position in
9212    INDICES.  CONTAINER is as for assign_aggregate.  */
9213 void
9214 ada_positional_component::assign (struct value *container,
9215                                   struct value *lhs, struct expression *exp,
9216                                   std::vector<LONGEST> &indices,
9217                                   LONGEST low, LONGEST high)
9218 {
9219   LONGEST ind = m_index + low;
9220
9221   if (ind - 1 == high)
9222     warning (_("Extra components in aggregate ignored."));
9223   if (ind <= high)
9224     {
9225       add_component_interval (ind, ind, indices);
9226       assign_component (container, lhs, ind, exp, m_op);
9227     }
9228 }
9229
9230 bool
9231 ada_discrete_range_association::uses_objfile (struct objfile *objfile)
9232 {
9233   return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9234 }
9235
9236 void
9237 ada_discrete_range_association::dump (ui_file *stream, int depth)
9238 {
9239   fprintf_filtered (stream, _("%*sDiscrete range:\n"), depth, "");
9240   m_low->dump (stream, depth + 1);
9241   m_high->dump (stream, depth + 1);
9242 }
9243
9244 void
9245 ada_discrete_range_association::assign (struct value *container,
9246                                         struct value *lhs,
9247                                         struct expression *exp,
9248                                         std::vector<LONGEST> &indices,
9249                                         LONGEST low, LONGEST high,
9250                                         operation_up &op)
9251 {
9252   LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9253   LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9254
9255   if (lower <= upper && (lower < low || upper > high))
9256     error (_("Index in component association out of bounds."));
9257
9258   add_component_interval (lower, upper, indices);
9259   while (lower <= upper)
9260     {
9261       assign_component (container, lhs, lower, exp, op);
9262       lower += 1;
9263     }
9264 }
9265
9266 bool
9267 ada_name_association::uses_objfile (struct objfile *objfile)
9268 {
9269   return m_val->uses_objfile (objfile);
9270 }
9271
9272 void
9273 ada_name_association::dump (ui_file *stream, int depth)
9274 {
9275   fprintf_filtered (stream, _("%*sName:\n"), depth, "");
9276   m_val->dump (stream, depth + 1);
9277 }
9278
9279 void
9280 ada_name_association::assign (struct value *container,
9281                               struct value *lhs,
9282                               struct expression *exp,
9283                               std::vector<LONGEST> &indices,
9284                               LONGEST low, LONGEST high,
9285                               operation_up &op)
9286 {
9287   int index;
9288
9289   if (ada_is_direct_array_type (value_type (lhs)))
9290     index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9291                                                             EVAL_NORMAL)));
9292   else
9293     {
9294       ada_string_operation *strop
9295         = dynamic_cast<ada_string_operation *> (m_val.get ());
9296
9297       const char *name;
9298       if (strop != nullptr)
9299         name = strop->get_name ();
9300       else
9301         {
9302           ada_var_value_operation *vvo
9303             = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9304           if (vvo != nullptr)
9305             error (_("Invalid record component association."));
9306           name = vvo->get_symbol ()->natural_name ();
9307         }
9308
9309       index = 0;
9310       if (! find_struct_field (name, value_type (lhs), 0,
9311                                NULL, NULL, NULL, NULL, &index))
9312         error (_("Unknown component name: %s."), name);
9313     }
9314
9315   add_component_interval (index, index, indices);
9316   assign_component (container, lhs, index, exp, op);
9317 }
9318
9319 bool
9320 ada_choices_component::uses_objfile (struct objfile *objfile)
9321 {
9322   if (m_op->uses_objfile (objfile))
9323     return true;
9324   for (const auto &item : m_assocs)
9325     if (item->uses_objfile (objfile))
9326       return true;
9327   return false;
9328 }
9329
9330 void
9331 ada_choices_component::dump (ui_file *stream, int depth)
9332 {
9333   fprintf_filtered (stream, _("%*sChoices:\n"), depth, "");
9334   m_op->dump (stream, depth + 1);
9335   for (const auto &item : m_assocs)
9336     item->dump (stream, depth + 1);
9337 }
9338
9339 /* Assign into the components of LHS indexed by the OP_CHOICES
9340    construct at *POS, updating *POS past the construct, given that
9341    the allowable indices are LOW..HIGH.  Record the indices assigned
9342    to in INDICES.  CONTAINER is as for assign_aggregate.  */
9343 void
9344 ada_choices_component::assign (struct value *container,
9345                                struct value *lhs, struct expression *exp,
9346                                std::vector<LONGEST> &indices,
9347                                LONGEST low, LONGEST high)
9348 {
9349   for (auto &item : m_assocs)
9350     item->assign (container, lhs, exp, indices, low, high, m_op);
9351 }
9352
9353 bool
9354 ada_others_component::uses_objfile (struct objfile *objfile)
9355 {
9356   return m_op->uses_objfile (objfile);
9357 }
9358
9359 void
9360 ada_others_component::dump (ui_file *stream, int depth)
9361 {
9362   fprintf_filtered (stream, _("%*sOthers:\n"), depth, "");
9363   m_op->dump (stream, depth + 1);
9364 }
9365
9366 /* Assign the value of the expression in the OP_OTHERS construct in
9367    EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9368    have not been previously assigned.  The index intervals already assigned
9369    are in INDICES.  CONTAINER is as for assign_aggregate.  */
9370 void
9371 ada_others_component::assign (struct value *container,
9372                               struct value *lhs, struct expression *exp,
9373                               std::vector<LONGEST> &indices,
9374                               LONGEST low, LONGEST high)
9375 {
9376   int num_indices = indices.size ();
9377   for (int i = 0; i < num_indices - 2; i += 2)
9378     {
9379       for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9380         assign_component (container, lhs, ind, exp, m_op);
9381     }
9382 }
9383
9384 struct value *
9385 ada_assign_operation::evaluate (struct type *expect_type,
9386                                 struct expression *exp,
9387                                 enum noside noside)
9388 {
9389   value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9390
9391   ada_aggregate_operation *ag_op
9392     = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9393   if (ag_op != nullptr)
9394     {
9395       if (noside != EVAL_NORMAL)
9396         return arg1;
9397
9398       arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
9399       return ada_value_assign (arg1, arg1);
9400     }
9401   /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9402      except if the lhs of our assignment is a convenience variable.
9403      In the case of assigning to a convenience variable, the lhs
9404      should be exactly the result of the evaluation of the rhs.  */
9405   struct type *type = value_type (arg1);
9406   if (VALUE_LVAL (arg1) == lval_internalvar)
9407     type = NULL;
9408   value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
9409   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9410     return arg1;
9411   if (VALUE_LVAL (arg1) == lval_internalvar)
9412     {
9413       /* Nothing.  */
9414     }
9415   else
9416     arg2 = coerce_for_assign (value_type (arg1), arg2);
9417   return ada_value_assign (arg1, arg2);
9418 }
9419
9420 } /* namespace expr */
9421
9422 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
9423    [ INDICES[0] .. INDICES[1] ],...  The resulting intervals do not
9424    overlap.  */
9425 static void
9426 add_component_interval (LONGEST low, LONGEST high, 
9427                         std::vector<LONGEST> &indices)
9428 {
9429   int i, j;
9430
9431   int size = indices.size ();
9432   for (i = 0; i < size; i += 2) {
9433     if (high >= indices[i] && low <= indices[i + 1])
9434       {
9435         int kh;
9436
9437         for (kh = i + 2; kh < size; kh += 2)
9438           if (high < indices[kh])
9439             break;
9440         if (low < indices[i])
9441           indices[i] = low;
9442         indices[i + 1] = indices[kh - 1];
9443         if (high > indices[i + 1])
9444           indices[i + 1] = high;
9445         memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9446         indices.resize (kh - i - 2);
9447         return;
9448       }
9449     else if (high < indices[i])
9450       break;
9451   }
9452         
9453   indices.resize (indices.size () + 2);
9454   for (j = indices.size () - 1; j >= i + 2; j -= 1)
9455     indices[j] = indices[j - 2];
9456   indices[i] = low;
9457   indices[i + 1] = high;
9458 }
9459
9460 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9461    is different.  */
9462
9463 static struct value *
9464 ada_value_cast (struct type *type, struct value *arg2)
9465 {
9466   if (type == ada_check_typedef (value_type (arg2)))
9467     return arg2;
9468
9469   return value_cast (type, arg2);
9470 }
9471
9472 /*  Evaluating Ada expressions, and printing their result.
9473     ------------------------------------------------------
9474
9475     1. Introduction:
9476     ----------------
9477
9478     We usually evaluate an Ada expression in order to print its value.
9479     We also evaluate an expression in order to print its type, which
9480     happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9481     but we'll focus mostly on the EVAL_NORMAL phase.  In practice, the
9482     EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9483     the evaluation compared to the EVAL_NORMAL, but is otherwise very
9484     similar.
9485
9486     Evaluating expressions is a little more complicated for Ada entities
9487     than it is for entities in languages such as C.  The main reason for
9488     this is that Ada provides types whose definition might be dynamic.
9489     One example of such types is variant records.  Or another example
9490     would be an array whose bounds can only be known at run time.
9491
9492     The following description is a general guide as to what should be
9493     done (and what should NOT be done) in order to evaluate an expression
9494     involving such types, and when.  This does not cover how the semantic
9495     information is encoded by GNAT as this is covered separatly.  For the
9496     document used as the reference for the GNAT encoding, see exp_dbug.ads
9497     in the GNAT sources.
9498
9499     Ideally, we should embed each part of this description next to its
9500     associated code.  Unfortunately, the amount of code is so vast right
9501     now that it's hard to see whether the code handling a particular
9502     situation might be duplicated or not.  One day, when the code is
9503     cleaned up, this guide might become redundant with the comments
9504     inserted in the code, and we might want to remove it.
9505
9506     2. ``Fixing'' an Entity, the Simple Case:
9507     -----------------------------------------
9508
9509     When evaluating Ada expressions, the tricky issue is that they may
9510     reference entities whose type contents and size are not statically
9511     known.  Consider for instance a variant record:
9512
9513        type Rec (Empty : Boolean := True) is record
9514           case Empty is
9515              when True => null;
9516              when False => Value : Integer;
9517           end case;
9518        end record;
9519        Yes : Rec := (Empty => False, Value => 1);
9520        No  : Rec := (empty => True);
9521
9522     The size and contents of that record depends on the value of the
9523     descriminant (Rec.Empty).  At this point, neither the debugging
9524     information nor the associated type structure in GDB are able to
9525     express such dynamic types.  So what the debugger does is to create
9526     "fixed" versions of the type that applies to the specific object.
9527     We also informally refer to this operation as "fixing" an object,
9528     which means creating its associated fixed type.
9529
9530     Example: when printing the value of variable "Yes" above, its fixed
9531     type would look like this:
9532
9533        type Rec is record
9534           Empty : Boolean;
9535           Value : Integer;
9536        end record;
9537
9538     On the other hand, if we printed the value of "No", its fixed type
9539     would become:
9540
9541        type Rec is record
9542           Empty : Boolean;
9543        end record;
9544
9545     Things become a little more complicated when trying to fix an entity
9546     with a dynamic type that directly contains another dynamic type,
9547     such as an array of variant records, for instance.  There are
9548     two possible cases: Arrays, and records.
9549
9550     3. ``Fixing'' Arrays:
9551     ---------------------
9552
9553     The type structure in GDB describes an array in terms of its bounds,
9554     and the type of its elements.  By design, all elements in the array
9555     have the same type and we cannot represent an array of variant elements
9556     using the current type structure in GDB.  When fixing an array,
9557     we cannot fix the array element, as we would potentially need one
9558     fixed type per element of the array.  As a result, the best we can do
9559     when fixing an array is to produce an array whose bounds and size
9560     are correct (allowing us to read it from memory), but without having
9561     touched its element type.  Fixing each element will be done later,
9562     when (if) necessary.
9563
9564     Arrays are a little simpler to handle than records, because the same
9565     amount of memory is allocated for each element of the array, even if
9566     the amount of space actually used by each element differs from element
9567     to element.  Consider for instance the following array of type Rec:
9568
9569        type Rec_Array is array (1 .. 2) of Rec;
9570
9571     The actual amount of memory occupied by each element might be different
9572     from element to element, depending on the value of their discriminant.
9573     But the amount of space reserved for each element in the array remains
9574     fixed regardless.  So we simply need to compute that size using
9575     the debugging information available, from which we can then determine
9576     the array size (we multiply the number of elements of the array by
9577     the size of each element).
9578
9579     The simplest case is when we have an array of a constrained element
9580     type. For instance, consider the following type declarations:
9581
9582         type Bounded_String (Max_Size : Integer) is
9583            Length : Integer;
9584            Buffer : String (1 .. Max_Size);
9585         end record;
9586         type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
9587
9588     In this case, the compiler describes the array as an array of
9589     variable-size elements (identified by its XVS suffix) for which
9590     the size can be read in the parallel XVZ variable.
9591
9592     In the case of an array of an unconstrained element type, the compiler
9593     wraps the array element inside a private PAD type.  This type should not
9594     be shown to the user, and must be "unwrap"'ed before printing.  Note
9595     that we also use the adjective "aligner" in our code to designate
9596     these wrapper types.
9597
9598     In some cases, the size allocated for each element is statically
9599     known.  In that case, the PAD type already has the correct size,
9600     and the array element should remain unfixed.
9601
9602     But there are cases when this size is not statically known.
9603     For instance, assuming that "Five" is an integer variable:
9604
9605         type Dynamic is array (1 .. Five) of Integer;
9606         type Wrapper (Has_Length : Boolean := False) is record
9607            Data : Dynamic;
9608            case Has_Length is
9609               when True => Length : Integer;
9610               when False => null;
9611            end case;
9612         end record;
9613         type Wrapper_Array is array (1 .. 2) of Wrapper;
9614
9615         Hello : Wrapper_Array := (others => (Has_Length => True,
9616                                              Data => (others => 17),
9617                                              Length => 1));
9618
9619
9620     The debugging info would describe variable Hello as being an
9621     array of a PAD type.  The size of that PAD type is not statically
9622     known, but can be determined using a parallel XVZ variable.
9623     In that case, a copy of the PAD type with the correct size should
9624     be used for the fixed array.
9625
9626     3. ``Fixing'' record type objects:
9627     ----------------------------------
9628
9629     Things are slightly different from arrays in the case of dynamic
9630     record types.  In this case, in order to compute the associated
9631     fixed type, we need to determine the size and offset of each of
9632     its components.  This, in turn, requires us to compute the fixed
9633     type of each of these components.
9634
9635     Consider for instance the example:
9636
9637         type Bounded_String (Max_Size : Natural) is record
9638            Str : String (1 .. Max_Size);
9639            Length : Natural;
9640         end record;
9641         My_String : Bounded_String (Max_Size => 10);
9642
9643     In that case, the position of field "Length" depends on the size
9644     of field Str, which itself depends on the value of the Max_Size
9645     discriminant.  In order to fix the type of variable My_String,
9646     we need to fix the type of field Str.  Therefore, fixing a variant
9647     record requires us to fix each of its components.
9648
9649     However, if a component does not have a dynamic size, the component
9650     should not be fixed.  In particular, fields that use a PAD type
9651     should not fixed.  Here is an example where this might happen
9652     (assuming type Rec above):
9653
9654        type Container (Big : Boolean) is record
9655           First : Rec;
9656           After : Integer;
9657           case Big is
9658              when True => Another : Integer;
9659              when False => null;
9660           end case;
9661        end record;
9662        My_Container : Container := (Big => False,
9663                                     First => (Empty => True),
9664                                     After => 42);
9665
9666     In that example, the compiler creates a PAD type for component First,
9667     whose size is constant, and then positions the component After just
9668     right after it.  The offset of component After is therefore constant
9669     in this case.
9670
9671     The debugger computes the position of each field based on an algorithm
9672     that uses, among other things, the actual position and size of the field
9673     preceding it.  Let's now imagine that the user is trying to print
9674     the value of My_Container.  If the type fixing was recursive, we would
9675     end up computing the offset of field After based on the size of the
9676     fixed version of field First.  And since in our example First has
9677     only one actual field, the size of the fixed type is actually smaller
9678     than the amount of space allocated to that field, and thus we would
9679     compute the wrong offset of field After.
9680
9681     To make things more complicated, we need to watch out for dynamic
9682     components of variant records (identified by the ___XVL suffix in
9683     the component name).  Even if the target type is a PAD type, the size
9684     of that type might not be statically known.  So the PAD type needs
9685     to be unwrapped and the resulting type needs to be fixed.  Otherwise,
9686     we might end up with the wrong size for our component.  This can be
9687     observed with the following type declarations:
9688
9689         type Octal is new Integer range 0 .. 7;
9690         type Octal_Array is array (Positive range <>) of Octal;
9691         pragma Pack (Octal_Array);
9692
9693         type Octal_Buffer (Size : Positive) is record
9694            Buffer : Octal_Array (1 .. Size);
9695            Length : Integer;
9696         end record;
9697
9698     In that case, Buffer is a PAD type whose size is unset and needs
9699     to be computed by fixing the unwrapped type.
9700
9701     4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
9702     ----------------------------------------------------------
9703
9704     Lastly, when should the sub-elements of an entity that remained unfixed
9705     thus far, be actually fixed?
9706
9707     The answer is: Only when referencing that element.  For instance
9708     when selecting one component of a record, this specific component
9709     should be fixed at that point in time.  Or when printing the value
9710     of a record, each component should be fixed before its value gets
9711     printed.  Similarly for arrays, the element of the array should be
9712     fixed when printing each element of the array, or when extracting
9713     one element out of that array.  On the other hand, fixing should
9714     not be performed on the elements when taking a slice of an array!
9715
9716     Note that one of the side effects of miscomputing the offset and
9717     size of each field is that we end up also miscomputing the size
9718     of the containing type.  This can have adverse results when computing
9719     the value of an entity.  GDB fetches the value of an entity based
9720     on the size of its type, and thus a wrong size causes GDB to fetch
9721     the wrong amount of memory.  In the case where the computed size is
9722     too small, GDB fetches too little data to print the value of our
9723     entity.  Results in this case are unpredictable, as we usually read
9724     past the buffer containing the data =:-o.  */
9725
9726 /* A helper function for TERNOP_IN_RANGE.  */
9727
9728 static value *
9729 eval_ternop_in_range (struct type *expect_type, struct expression *exp,
9730                       enum noside noside,
9731                       value *arg1, value *arg2, value *arg3)
9732 {
9733   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9734   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9735   struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
9736   return
9737     value_from_longest (type,
9738                         (value_less (arg1, arg3)
9739                          || value_equal (arg1, arg3))
9740                         && (value_less (arg2, arg1)
9741                             || value_equal (arg2, arg1)));
9742 }
9743
9744 /* A helper function for UNOP_NEG.  */
9745
9746 value *
9747 ada_unop_neg (struct type *expect_type,
9748               struct expression *exp,
9749               enum noside noside, enum exp_opcode op,
9750               struct value *arg1)
9751 {
9752   unop_promote (exp->language_defn, exp->gdbarch, &arg1);
9753   return value_neg (arg1);
9754 }
9755
9756 /* A helper function for UNOP_IN_RANGE.  */
9757
9758 value *
9759 ada_unop_in_range (struct type *expect_type,
9760                    struct expression *exp,
9761                    enum noside noside, enum exp_opcode op,
9762                    struct value *arg1, struct type *type)
9763 {
9764   struct value *arg2, *arg3;
9765   switch (type->code ())
9766     {
9767     default:
9768       lim_warning (_("Membership test incompletely implemented; "
9769                      "always returns true"));
9770       type = language_bool_type (exp->language_defn, exp->gdbarch);
9771       return value_from_longest (type, (LONGEST) 1);
9772
9773     case TYPE_CODE_RANGE:
9774       arg2 = value_from_longest (type,
9775                                  type->bounds ()->low.const_val ());
9776       arg3 = value_from_longest (type,
9777                                  type->bounds ()->high.const_val ());
9778       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9779       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9780       type = language_bool_type (exp->language_defn, exp->gdbarch);
9781       return
9782         value_from_longest (type,
9783                             (value_less (arg1, arg3)
9784                              || value_equal (arg1, arg3))
9785                             && (value_less (arg2, arg1)
9786                                 || value_equal (arg2, arg1)));
9787     }
9788 }
9789
9790 /* A helper function for OP_ATR_TAG.  */
9791
9792 value *
9793 ada_atr_tag (struct type *expect_type,
9794              struct expression *exp,
9795              enum noside noside, enum exp_opcode op,
9796              struct value *arg1)
9797 {
9798   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9799     return value_zero (ada_tag_type (arg1), not_lval);
9800
9801   return ada_value_tag (arg1);
9802 }
9803
9804 /* A helper function for OP_ATR_SIZE.  */
9805
9806 value *
9807 ada_atr_size (struct type *expect_type,
9808               struct expression *exp,
9809               enum noside noside, enum exp_opcode op,
9810               struct value *arg1)
9811 {
9812   struct type *type = value_type (arg1);
9813
9814   /* If the argument is a reference, then dereference its type, since
9815      the user is really asking for the size of the actual object,
9816      not the size of the pointer.  */
9817   if (type->code () == TYPE_CODE_REF)
9818     type = TYPE_TARGET_TYPE (type);
9819
9820   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9821     return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
9822   else
9823     return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
9824                                TARGET_CHAR_BIT * TYPE_LENGTH (type));
9825 }
9826
9827 /* A helper function for UNOP_ABS.  */
9828
9829 value *
9830 ada_abs (struct type *expect_type,
9831          struct expression *exp,
9832          enum noside noside, enum exp_opcode op,
9833          struct value *arg1)
9834 {
9835   unop_promote (exp->language_defn, exp->gdbarch, &arg1);
9836   if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
9837     return value_neg (arg1);
9838   else
9839     return arg1;
9840 }
9841
9842 /* A helper function for BINOP_MUL.  */
9843
9844 value *
9845 ada_mult_binop (struct type *expect_type,
9846                 struct expression *exp,
9847                 enum noside noside, enum exp_opcode op,
9848                 struct value *arg1, struct value *arg2)
9849 {
9850   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9851     {
9852       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9853       return value_zero (value_type (arg1), not_lval);
9854     }
9855   else
9856     {
9857       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9858       return ada_value_binop (arg1, arg2, op);
9859     }
9860 }
9861
9862 /* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL.  */
9863
9864 value *
9865 ada_equal_binop (struct type *expect_type,
9866                  struct expression *exp,
9867                  enum noside noside, enum exp_opcode op,
9868                  struct value *arg1, struct value *arg2)
9869 {
9870   int tem;
9871   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9872     tem = 0;
9873   else
9874     {
9875       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9876       tem = ada_value_equal (arg1, arg2);
9877     }
9878   if (op == BINOP_NOTEQUAL)
9879     tem = !tem;
9880   struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
9881   return value_from_longest (type, (LONGEST) tem);
9882 }
9883
9884 /* A helper function for TERNOP_SLICE.  */
9885
9886 value *
9887 ada_ternop_slice (struct expression *exp,
9888                   enum noside noside,
9889                   struct value *array, struct value *low_bound_val,
9890                   struct value *high_bound_val)
9891 {
9892   LONGEST low_bound;
9893   LONGEST high_bound;
9894
9895   low_bound_val = coerce_ref (low_bound_val);
9896   high_bound_val = coerce_ref (high_bound_val);
9897   low_bound = value_as_long (low_bound_val);
9898   high_bound = value_as_long (high_bound_val);
9899
9900   /* If this is a reference to an aligner type, then remove all
9901      the aligners.  */
9902   if (value_type (array)->code () == TYPE_CODE_REF
9903       && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
9904     TYPE_TARGET_TYPE (value_type (array)) =
9905       ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
9906
9907   if (ada_is_any_packed_array_type (value_type (array)))
9908     error (_("cannot slice a packed array"));
9909
9910   /* If this is a reference to an array or an array lvalue,
9911      convert to a pointer.  */
9912   if (value_type (array)->code () == TYPE_CODE_REF
9913       || (value_type (array)->code () == TYPE_CODE_ARRAY
9914           && VALUE_LVAL (array) == lval_memory))
9915     array = value_addr (array);
9916
9917   if (noside == EVAL_AVOID_SIDE_EFFECTS
9918       && ada_is_array_descriptor_type (ada_check_typedef
9919                                        (value_type (array))))
9920     return empty_array (ada_type_of_array (array, 0), low_bound,
9921                         high_bound);
9922
9923   array = ada_coerce_to_simple_array_ptr (array);
9924
9925   /* If we have more than one level of pointer indirection,
9926      dereference the value until we get only one level.  */
9927   while (value_type (array)->code () == TYPE_CODE_PTR
9928          && (TYPE_TARGET_TYPE (value_type (array))->code ()
9929              == TYPE_CODE_PTR))
9930     array = value_ind (array);
9931
9932   /* Make sure we really do have an array type before going further,
9933      to avoid a SEGV when trying to get the index type or the target
9934      type later down the road if the debug info generated by
9935      the compiler is incorrect or incomplete.  */
9936   if (!ada_is_simple_array_type (value_type (array)))
9937     error (_("cannot take slice of non-array"));
9938
9939   if (ada_check_typedef (value_type (array))->code ()
9940       == TYPE_CODE_PTR)
9941     {
9942       struct type *type0 = ada_check_typedef (value_type (array));
9943
9944       if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
9945         return empty_array (TYPE_TARGET_TYPE (type0), low_bound, high_bound);
9946       else
9947         {
9948           struct type *arr_type0 =
9949             to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
9950
9951           return ada_value_slice_from_ptr (array, arr_type0,
9952                                            longest_to_int (low_bound),
9953                                            longest_to_int (high_bound));
9954         }
9955     }
9956   else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9957     return array;
9958   else if (high_bound < low_bound)
9959     return empty_array (value_type (array), low_bound, high_bound);
9960   else
9961     return ada_value_slice (array, longest_to_int (low_bound),
9962                             longest_to_int (high_bound));
9963 }
9964
9965 /* A helper function for BINOP_IN_BOUNDS.  */
9966
9967 value *
9968 ada_binop_in_bounds (struct expression *exp, enum noside noside,
9969                      struct value *arg1, struct value *arg2, int n)
9970 {
9971   if (noside == EVAL_AVOID_SIDE_EFFECTS)
9972     {
9973       struct type *type = language_bool_type (exp->language_defn,
9974                                               exp->gdbarch);
9975       return value_zero (type, not_lval);
9976     }
9977
9978   struct type *type = ada_index_type (value_type (arg2), n, "range");
9979   if (!type)
9980     type = value_type (arg1);
9981
9982   value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
9983   arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
9984
9985   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9986   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
9987   type = language_bool_type (exp->language_defn, exp->gdbarch);
9988   return value_from_longest (type,
9989                              (value_less (arg1, arg3)
9990                               || value_equal (arg1, arg3))
9991                              && (value_less (arg2, arg1)
9992                                  || value_equal (arg2, arg1)));
9993 }
9994
9995 /* A helper function for some attribute operations.  */
9996
9997 static value *
9998 ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
9999               struct value *arg1, struct type *type_arg, int tem)
10000 {
10001   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10002     {
10003       if (type_arg == NULL)
10004         type_arg = value_type (arg1);
10005
10006       if (ada_is_constrained_packed_array_type (type_arg))
10007         type_arg = decode_constrained_packed_array_type (type_arg);
10008
10009       if (!discrete_type_p (type_arg))
10010         {
10011           switch (op)
10012             {
10013             default:          /* Should never happen.  */
10014               error (_("unexpected attribute encountered"));
10015             case OP_ATR_FIRST:
10016             case OP_ATR_LAST:
10017               type_arg = ada_index_type (type_arg, tem,
10018                                          ada_attribute_name (op));
10019               break;
10020             case OP_ATR_LENGTH:
10021               type_arg = builtin_type (exp->gdbarch)->builtin_int;
10022               break;
10023             }
10024         }
10025
10026       return value_zero (type_arg, not_lval);
10027     }
10028   else if (type_arg == NULL)
10029     {
10030       arg1 = ada_coerce_ref (arg1);
10031
10032       if (ada_is_constrained_packed_array_type (value_type (arg1)))
10033         arg1 = ada_coerce_to_simple_array (arg1);
10034
10035       struct type *type;
10036       if (op == OP_ATR_LENGTH)
10037         type = builtin_type (exp->gdbarch)->builtin_int;
10038       else
10039         {
10040           type = ada_index_type (value_type (arg1), tem,
10041                                  ada_attribute_name (op));
10042           if (type == NULL)
10043             type = builtin_type (exp->gdbarch)->builtin_int;
10044         }
10045
10046       switch (op)
10047         {
10048         default:          /* Should never happen.  */
10049           error (_("unexpected attribute encountered"));
10050         case OP_ATR_FIRST:
10051           return value_from_longest
10052             (type, ada_array_bound (arg1, tem, 0));
10053         case OP_ATR_LAST:
10054           return value_from_longest
10055             (type, ada_array_bound (arg1, tem, 1));
10056         case OP_ATR_LENGTH:
10057           return value_from_longest
10058             (type, ada_array_length (arg1, tem));
10059         }
10060     }
10061   else if (discrete_type_p (type_arg))
10062     {
10063       struct type *range_type;
10064       const char *name = ada_type_name (type_arg);
10065
10066       range_type = NULL;
10067       if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10068         range_type = to_fixed_range_type (type_arg, NULL);
10069       if (range_type == NULL)
10070         range_type = type_arg;
10071       switch (op)
10072         {
10073         default:
10074           error (_("unexpected attribute encountered"));
10075         case OP_ATR_FIRST:
10076           return value_from_longest 
10077             (range_type, ada_discrete_type_low_bound (range_type));
10078         case OP_ATR_LAST:
10079           return value_from_longest
10080             (range_type, ada_discrete_type_high_bound (range_type));
10081         case OP_ATR_LENGTH:
10082           error (_("the 'length attribute applies only to array types"));
10083         }
10084     }
10085   else if (type_arg->code () == TYPE_CODE_FLT)
10086     error (_("unimplemented type attribute"));
10087   else
10088     {
10089       LONGEST low, high;
10090
10091       if (ada_is_constrained_packed_array_type (type_arg))
10092         type_arg = decode_constrained_packed_array_type (type_arg);
10093
10094       struct type *type;
10095       if (op == OP_ATR_LENGTH)
10096         type = builtin_type (exp->gdbarch)->builtin_int;
10097       else
10098         {
10099           type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10100           if (type == NULL)
10101             type = builtin_type (exp->gdbarch)->builtin_int;
10102         }
10103
10104       switch (op)
10105         {
10106         default:
10107           error (_("unexpected attribute encountered"));
10108         case OP_ATR_FIRST:
10109           low = ada_array_bound_from_type (type_arg, tem, 0);
10110           return value_from_longest (type, low);
10111         case OP_ATR_LAST:
10112           high = ada_array_bound_from_type (type_arg, tem, 1);
10113           return value_from_longest (type, high);
10114         case OP_ATR_LENGTH:
10115           low = ada_array_bound_from_type (type_arg, tem, 0);
10116           high = ada_array_bound_from_type (type_arg, tem, 1);
10117           return value_from_longest (type, high - low + 1);
10118         }
10119     }
10120 }
10121
10122 /* A helper function for OP_ATR_MIN and OP_ATR_MAX.  */
10123
10124 struct value *
10125 ada_binop_minmax (struct type *expect_type,
10126                   struct expression *exp,
10127                   enum noside noside, enum exp_opcode op,
10128                   struct value *arg1, struct value *arg2)
10129 {
10130   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10131     return value_zero (value_type (arg1), not_lval);
10132   else
10133     {
10134       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10135       return value_binop (arg1, arg2, op);
10136     }
10137 }
10138
10139 /* A helper function for BINOP_EXP.  */
10140
10141 struct value *
10142 ada_binop_exp (struct type *expect_type,
10143                struct expression *exp,
10144                enum noside noside, enum exp_opcode op,
10145                struct value *arg1, struct value *arg2)
10146 {
10147   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10148     return value_zero (value_type (arg1), not_lval);
10149   else
10150     {
10151       /* For integer exponentiation operations,
10152          only promote the first argument.  */
10153       if (is_integral_type (value_type (arg2)))
10154         unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10155       else
10156         binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10157
10158       return value_binop (arg1, arg2, op);
10159     }
10160 }
10161
10162 namespace expr
10163 {
10164
10165 /* See ada-exp.h.  */
10166
10167 operation_up
10168 ada_resolvable::replace (operation_up &&owner,
10169                          struct expression *exp,
10170                          bool deprocedure_p,
10171                          bool parse_completion,
10172                          innermost_block_tracker *tracker,
10173                          struct type *context_type)
10174 {
10175   if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10176     return (make_operation<ada_funcall_operation>
10177             (std::move (owner),
10178              std::vector<operation_up> ()));
10179   return std::move (owner);
10180 }
10181
10182 /* Convert the character literal whose value would be VAL to the
10183    appropriate value of type TYPE, if there is a translation.
10184    Otherwise return VAL.  Hence, in an enumeration type ('A', 'B'),
10185    the literal 'A' (VAL == 65), returns 0.  */
10186
10187 static LONGEST
10188 convert_char_literal (struct type *type, LONGEST val)
10189 {
10190   char name[12];
10191   int f;
10192
10193   if (type == NULL)
10194     return val;
10195   type = check_typedef (type);
10196   if (type->code () != TYPE_CODE_ENUM)
10197     return val;
10198
10199   if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10200     xsnprintf (name, sizeof (name), "Q%c", (int) val);
10201   else if (val >= 0 && val < 256)
10202     xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10203   else if (val >= 0 && val < 0x10000)
10204     xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
10205   else
10206     xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
10207   size_t len = strlen (name);
10208   for (f = 0; f < type->num_fields (); f += 1)
10209     {
10210       /* Check the suffix because an enum constant in a package will
10211          have a name like "pkg__QUxx".  This is safe enough because we
10212          already have the correct type, and because mangling means
10213          there can't be clashes.  */
10214       const char *ename = type->field (f).name ();
10215       size_t elen = strlen (ename);
10216
10217       if (elen >= len && strcmp (name, ename + elen - len) == 0)
10218         return type->field (f).loc_enumval ();
10219     }
10220   return val;
10221 }
10222
10223 /* See ada-exp.h.  */
10224
10225 operation_up
10226 ada_char_operation::replace (operation_up &&owner,
10227                              struct expression *exp,
10228                              bool deprocedure_p,
10229                              bool parse_completion,
10230                              innermost_block_tracker *tracker,
10231                              struct type *context_type)
10232 {
10233   operation_up result = std::move (owner);
10234
10235   if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10236     {
10237       gdb_assert (result.get () == this);
10238       std::get<0> (m_storage) = context_type;
10239       std::get<1> (m_storage)
10240         = convert_char_literal (context_type, std::get<1> (m_storage));
10241     }
10242
10243   return make_operation<ada_wrapped_operation> (std::move (result));
10244 }
10245
10246 value *
10247 ada_wrapped_operation::evaluate (struct type *expect_type,
10248                                  struct expression *exp,
10249                                  enum noside noside)
10250 {
10251   value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10252   if (noside == EVAL_NORMAL)
10253     result = unwrap_value (result);
10254
10255   /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10256      then we need to perform the conversion manually, because
10257      evaluate_subexp_standard doesn't do it.  This conversion is
10258      necessary in Ada because the different kinds of float/fixed
10259      types in Ada have different representations.
10260
10261      Similarly, we need to perform the conversion from OP_LONG
10262      ourselves.  */
10263   if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10264     result = ada_value_cast (expect_type, result);
10265
10266   return result;
10267 }
10268
10269 value *
10270 ada_string_operation::evaluate (struct type *expect_type,
10271                                 struct expression *exp,
10272                                 enum noside noside)
10273 {
10274   value *result = string_operation::evaluate (expect_type, exp, noside);
10275   /* The result type will have code OP_STRING, bashed there from 
10276      OP_ARRAY.  Bash it back.  */
10277   if (value_type (result)->code () == TYPE_CODE_STRING)
10278     value_type (result)->set_code (TYPE_CODE_ARRAY);
10279   return result;
10280 }
10281
10282 value *
10283 ada_qual_operation::evaluate (struct type *expect_type,
10284                               struct expression *exp,
10285                               enum noside noside)
10286 {
10287   struct type *type = std::get<1> (m_storage);
10288   return std::get<0> (m_storage)->evaluate (type, exp, noside);
10289 }
10290
10291 value *
10292 ada_ternop_range_operation::evaluate (struct type *expect_type,
10293                                       struct expression *exp,
10294                                       enum noside noside)
10295 {
10296   value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10297   value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10298   value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10299   return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10300 }
10301
10302 value *
10303 ada_binop_addsub_operation::evaluate (struct type *expect_type,
10304                                       struct expression *exp,
10305                                       enum noside noside)
10306 {
10307   value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10308   value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10309
10310   auto do_op = [=] (LONGEST x, LONGEST y)
10311     {
10312       if (std::get<0> (m_storage) == BINOP_ADD)
10313         return x + y;
10314       return x - y;
10315     };
10316
10317   if (value_type (arg1)->code () == TYPE_CODE_PTR)
10318     return (value_from_longest
10319             (value_type (arg1),
10320              do_op (value_as_long (arg1), value_as_long (arg2))));
10321   if (value_type (arg2)->code () == TYPE_CODE_PTR)
10322     return (value_from_longest
10323             (value_type (arg2),
10324              do_op (value_as_long (arg1), value_as_long (arg2))));
10325   /* Preserve the original type for use by the range case below.
10326      We cannot cast the result to a reference type, so if ARG1 is
10327      a reference type, find its underlying type.  */
10328   struct type *type = value_type (arg1);
10329   while (type->code () == TYPE_CODE_REF)
10330     type = TYPE_TARGET_TYPE (type);
10331   binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10332   arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10333   /* We need to special-case the result with a range.
10334      This is done for the benefit of "ptype".  gdb's Ada support
10335      historically used the LHS to set the result type here, so
10336      preserve this behavior.  */
10337   if (type->code () == TYPE_CODE_RANGE)
10338     arg1 = value_cast (type, arg1);
10339   return arg1;
10340 }
10341
10342 value *
10343 ada_unop_atr_operation::evaluate (struct type *expect_type,
10344                                   struct expression *exp,
10345                                   enum noside noside)
10346 {
10347   struct type *type_arg = nullptr;
10348   value *val = nullptr;
10349
10350   if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10351     {
10352       value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10353                                                       EVAL_AVOID_SIDE_EFFECTS);
10354       type_arg = value_type (tem);
10355     }
10356   else
10357     val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10358
10359   return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10360                        val, type_arg, std::get<2> (m_storage));
10361 }
10362
10363 value *
10364 ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10365                                                  struct expression *exp,
10366                                                  enum noside noside)
10367 {
10368   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10369     return value_zero (expect_type, not_lval);
10370
10371   const bound_minimal_symbol &b = std::get<0> (m_storage);
10372   value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
10373
10374   val = ada_value_cast (expect_type, val);
10375
10376   /* Follow the Ada language semantics that do not allow taking
10377      an address of the result of a cast (view conversion in Ada).  */
10378   if (VALUE_LVAL (val) == lval_memory)
10379     {
10380       if (value_lazy (val))
10381         value_fetch_lazy (val);
10382       VALUE_LVAL (val) = not_lval;
10383     }
10384   return val;
10385 }
10386
10387 value *
10388 ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10389                                             struct expression *exp,
10390                                             enum noside noside)
10391 {
10392   value *val = evaluate_var_value (noside,
10393                                    std::get<0> (m_storage).block,
10394                                    std::get<0> (m_storage).symbol);
10395
10396   val = ada_value_cast (expect_type, val);
10397
10398   /* Follow the Ada language semantics that do not allow taking
10399      an address of the result of a cast (view conversion in Ada).  */
10400   if (VALUE_LVAL (val) == lval_memory)
10401     {
10402       if (value_lazy (val))
10403         value_fetch_lazy (val);
10404       VALUE_LVAL (val) = not_lval;
10405     }
10406   return val;
10407 }
10408
10409 value *
10410 ada_var_value_operation::evaluate (struct type *expect_type,
10411                                    struct expression *exp,
10412                                    enum noside noside)
10413 {
10414   symbol *sym = std::get<0> (m_storage).symbol;
10415
10416   if (sym->domain () == UNDEF_DOMAIN)
10417     /* Only encountered when an unresolved symbol occurs in a
10418        context other than a function call, in which case, it is
10419        invalid.  */
10420     error (_("Unexpected unresolved symbol, %s, during evaluation"),
10421            sym->print_name ());
10422
10423   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10424     {
10425       struct type *type = static_unwrap_type (sym->type ());
10426       /* Check to see if this is a tagged type.  We also need to handle
10427          the case where the type is a reference to a tagged type, but
10428          we have to be careful to exclude pointers to tagged types.
10429          The latter should be shown as usual (as a pointer), whereas
10430          a reference should mostly be transparent to the user.  */
10431       if (ada_is_tagged_type (type, 0)
10432           || (type->code () == TYPE_CODE_REF
10433               && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
10434         {
10435           /* Tagged types are a little special in the fact that the real
10436              type is dynamic and can only be determined by inspecting the
10437              object's tag.  This means that we need to get the object's
10438              value first (EVAL_NORMAL) and then extract the actual object
10439              type from its tag.
10440
10441              Note that we cannot skip the final step where we extract
10442              the object type from its tag, because the EVAL_NORMAL phase
10443              results in dynamic components being resolved into fixed ones.
10444              This can cause problems when trying to print the type
10445              description of tagged types whose parent has a dynamic size:
10446              We use the type name of the "_parent" component in order
10447              to print the name of the ancestor type in the type description.
10448              If that component had a dynamic size, the resolution into
10449              a fixed type would result in the loss of that type name,
10450              thus preventing us from printing the name of the ancestor
10451              type in the type description.  */
10452           value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
10453
10454           if (type->code () != TYPE_CODE_REF)
10455             {
10456               struct type *actual_type;
10457
10458               actual_type = type_from_tag (ada_value_tag (arg1));
10459               if (actual_type == NULL)
10460                 /* If, for some reason, we were unable to determine
10461                    the actual type from the tag, then use the static
10462                    approximation that we just computed as a fallback.
10463                    This can happen if the debugging information is
10464                    incomplete, for instance.  */
10465                 actual_type = type;
10466               return value_zero (actual_type, not_lval);
10467             }
10468           else
10469             {
10470               /* In the case of a ref, ada_coerce_ref takes care
10471                  of determining the actual type.  But the evaluation
10472                  should return a ref as it should be valid to ask
10473                  for its address; so rebuild a ref after coerce.  */
10474               arg1 = ada_coerce_ref (arg1);
10475               return value_ref (arg1, TYPE_CODE_REF);
10476             }
10477         }
10478
10479       /* Records and unions for which GNAT encodings have been
10480          generated need to be statically fixed as well.
10481          Otherwise, non-static fixing produces a type where
10482          all dynamic properties are removed, which prevents "ptype"
10483          from being able to completely describe the type.
10484          For instance, a case statement in a variant record would be
10485          replaced by the relevant components based on the actual
10486          value of the discriminants.  */
10487       if ((type->code () == TYPE_CODE_STRUCT
10488            && dynamic_template_type (type) != NULL)
10489           || (type->code () == TYPE_CODE_UNION
10490               && ada_find_parallel_type (type, "___XVU") != NULL))
10491         return value_zero (to_static_fixed_type (type), not_lval);
10492     }
10493
10494   value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10495   return ada_to_fixed_value (arg1);
10496 }
10497
10498 bool
10499 ada_var_value_operation::resolve (struct expression *exp,
10500                                   bool deprocedure_p,
10501                                   bool parse_completion,
10502                                   innermost_block_tracker *tracker,
10503                                   struct type *context_type)
10504 {
10505   symbol *sym = std::get<0> (m_storage).symbol;
10506   if (sym->domain () == UNDEF_DOMAIN)
10507     {
10508       block_symbol resolved
10509         = ada_resolve_variable (sym, std::get<0> (m_storage).block,
10510                                 context_type, parse_completion,
10511                                 deprocedure_p, tracker);
10512       std::get<0> (m_storage) = resolved;
10513     }
10514
10515   if (deprocedure_p
10516       && (std::get<0> (m_storage).symbol->type ()->code ()
10517           == TYPE_CODE_FUNC))
10518     return true;
10519
10520   return false;
10521 }
10522
10523 value *
10524 ada_atr_val_operation::evaluate (struct type *expect_type,
10525                                  struct expression *exp,
10526                                  enum noside noside)
10527 {
10528   value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10529   return ada_val_atr (noside, std::get<0> (m_storage), arg);
10530 }
10531
10532 value *
10533 ada_unop_ind_operation::evaluate (struct type *expect_type,
10534                                   struct expression *exp,
10535                                   enum noside noside)
10536 {
10537   value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10538
10539   struct type *type = ada_check_typedef (value_type (arg1));
10540   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10541     {
10542       if (ada_is_array_descriptor_type (type))
10543         /* GDB allows dereferencing GNAT array descriptors.  */
10544         {
10545           struct type *arrType = ada_type_of_array (arg1, 0);
10546
10547           if (arrType == NULL)
10548             error (_("Attempt to dereference null array pointer."));
10549           return value_at_lazy (arrType, 0);
10550         }
10551       else if (type->code () == TYPE_CODE_PTR
10552                || type->code () == TYPE_CODE_REF
10553                /* In C you can dereference an array to get the 1st elt.  */
10554                || type->code () == TYPE_CODE_ARRAY)
10555         {
10556           /* As mentioned in the OP_VAR_VALUE case, tagged types can
10557              only be determined by inspecting the object's tag.
10558              This means that we need to evaluate completely the
10559              expression in order to get its type.  */
10560
10561           if ((type->code () == TYPE_CODE_REF
10562                || type->code () == TYPE_CODE_PTR)
10563               && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
10564             {
10565               arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
10566                                                         EVAL_NORMAL);
10567               type = value_type (ada_value_ind (arg1));
10568             }
10569           else
10570             {
10571               type = to_static_fixed_type
10572                 (ada_aligned_type
10573                  (ada_check_typedef (TYPE_TARGET_TYPE (type))));
10574             }
10575           return value_zero (type, lval_memory);
10576         }
10577       else if (type->code () == TYPE_CODE_INT)
10578         {
10579           /* GDB allows dereferencing an int.  */
10580           if (expect_type == NULL)
10581             return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10582                                lval_memory);
10583           else
10584             {
10585               expect_type =
10586                 to_static_fixed_type (ada_aligned_type (expect_type));
10587               return value_zero (expect_type, lval_memory);
10588             }
10589         }
10590       else
10591         error (_("Attempt to take contents of a non-pointer value."));
10592     }
10593   arg1 = ada_coerce_ref (arg1);     /* FIXME: What is this for??  */
10594   type = ada_check_typedef (value_type (arg1));
10595
10596   if (type->code () == TYPE_CODE_INT)
10597     /* GDB allows dereferencing an int.  If we were given
10598        the expect_type, then use that as the target type.
10599        Otherwise, assume that the target type is an int.  */
10600     {
10601       if (expect_type != NULL)
10602         return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
10603                                           arg1));
10604       else
10605         return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
10606                               (CORE_ADDR) value_as_address (arg1));
10607     }
10608
10609   if (ada_is_array_descriptor_type (type))
10610     /* GDB allows dereferencing GNAT array descriptors.  */
10611     return ada_coerce_to_simple_array (arg1);
10612   else
10613     return ada_value_ind (arg1);
10614 }
10615
10616 value *
10617 ada_structop_operation::evaluate (struct type *expect_type,
10618                                   struct expression *exp,
10619                                   enum noside noside)
10620 {
10621   value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10622   const char *str = std::get<1> (m_storage).c_str ();
10623   if (noside == EVAL_AVOID_SIDE_EFFECTS)
10624     {
10625       struct type *type;
10626       struct type *type1 = value_type (arg1);
10627
10628       if (ada_is_tagged_type (type1, 1))
10629         {
10630           type = ada_lookup_struct_elt_type (type1, str, 1, 1);
10631
10632           /* If the field is not found, check if it exists in the
10633              extension of this object's type. This means that we
10634              need to evaluate completely the expression.  */
10635
10636           if (type == NULL)
10637             {
10638               arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
10639                                                         EVAL_NORMAL);
10640               arg1 = ada_value_struct_elt (arg1, str, 0);
10641               arg1 = unwrap_value (arg1);
10642               type = value_type (ada_to_fixed_value (arg1));
10643             }
10644         }
10645       else
10646         type = ada_lookup_struct_elt_type (type1, str, 1, 0);
10647
10648       return value_zero (ada_aligned_type (type), lval_memory);
10649     }
10650   else
10651     {
10652       arg1 = ada_value_struct_elt (arg1, str, 0);
10653       arg1 = unwrap_value (arg1);
10654       return ada_to_fixed_value (arg1);
10655     }
10656 }
10657
10658 value *
10659 ada_funcall_operation::evaluate (struct type *expect_type,
10660                                  struct expression *exp,
10661                                  enum noside noside)
10662 {
10663   const std::vector<operation_up> &args_up = std::get<1> (m_storage);
10664   int nargs = args_up.size ();
10665   std::vector<value *> argvec (nargs);
10666   operation_up &callee_op = std::get<0> (m_storage);
10667
10668   ada_var_value_operation *avv
10669     = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
10670   if (avv != nullptr
10671       && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
10672     error (_("Unexpected unresolved symbol, %s, during evaluation"),
10673            avv->get_symbol ()->print_name ());
10674
10675   value *callee = callee_op->evaluate (nullptr, exp, noside);
10676   for (int i = 0; i < args_up.size (); ++i)
10677     argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
10678
10679   if (ada_is_constrained_packed_array_type
10680       (desc_base_type (value_type (callee))))
10681     callee = ada_coerce_to_simple_array (callee);
10682   else if (value_type (callee)->code () == TYPE_CODE_ARRAY
10683            && TYPE_FIELD_BITSIZE (value_type (callee), 0) != 0)
10684     /* This is a packed array that has already been fixed, and
10685        therefore already coerced to a simple array.  Nothing further
10686        to do.  */
10687     ;
10688   else if (value_type (callee)->code () == TYPE_CODE_REF)
10689     {
10690       /* Make sure we dereference references so that all the code below
10691          feels like it's really handling the referenced value.  Wrapping
10692          types (for alignment) may be there, so make sure we strip them as
10693          well.  */
10694       callee = ada_to_fixed_value (coerce_ref (callee));
10695     }
10696   else if (value_type (callee)->code () == TYPE_CODE_ARRAY
10697            && VALUE_LVAL (callee) == lval_memory)
10698     callee = value_addr (callee);
10699
10700   struct type *type = ada_check_typedef (value_type (callee));
10701
10702   /* Ada allows us to implicitly dereference arrays when subscripting
10703      them.  So, if this is an array typedef (encoding use for array
10704      access types encoded as fat pointers), strip it now.  */
10705   if (type->code () == TYPE_CODE_TYPEDEF)
10706     type = ada_typedef_target_type (type);
10707
10708   if (type->code () == TYPE_CODE_PTR)
10709     {
10710       switch (ada_check_typedef (TYPE_TARGET_TYPE (type))->code ())
10711         {
10712         case TYPE_CODE_FUNC:
10713           type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10714           break;
10715         case TYPE_CODE_ARRAY:
10716           break;
10717         case TYPE_CODE_STRUCT:
10718           if (noside != EVAL_AVOID_SIDE_EFFECTS)
10719             callee = ada_value_ind (callee);
10720           type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10721           break;
10722         default:
10723           error (_("cannot subscript or call something of type `%s'"),
10724                  ada_type_name (value_type (callee)));
10725           break;
10726         }
10727     }
10728
10729   switch (type->code ())
10730     {
10731     case TYPE_CODE_FUNC:
10732       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10733         {
10734           if (TYPE_TARGET_TYPE (type) == NULL)
10735             error_call_unknown_return_type (NULL);
10736           return allocate_value (TYPE_TARGET_TYPE (type));
10737         }
10738       return call_function_by_hand (callee, NULL, argvec);
10739     case TYPE_CODE_INTERNAL_FUNCTION:
10740       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10741         /* We don't know anything about what the internal
10742            function might return, but we have to return
10743            something.  */
10744         return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10745                            not_lval);
10746       else
10747         return call_internal_function (exp->gdbarch, exp->language_defn,
10748                                        callee, nargs,
10749                                        argvec.data ());
10750
10751     case TYPE_CODE_STRUCT:
10752       {
10753         int arity;
10754
10755         arity = ada_array_arity (type);
10756         type = ada_array_element_type (type, nargs);
10757         if (type == NULL)
10758           error (_("cannot subscript or call a record"));
10759         if (arity != nargs)
10760           error (_("wrong number of subscripts; expecting %d"), arity);
10761         if (noside == EVAL_AVOID_SIDE_EFFECTS)
10762           return value_zero (ada_aligned_type (type), lval_memory);
10763         return
10764           unwrap_value (ada_value_subscript
10765                         (callee, nargs, argvec.data ()));
10766       }
10767     case TYPE_CODE_ARRAY:
10768       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10769         {
10770           type = ada_array_element_type (type, nargs);
10771           if (type == NULL)
10772             error (_("element type of array unknown"));
10773           else
10774             return value_zero (ada_aligned_type (type), lval_memory);
10775         }
10776       return
10777         unwrap_value (ada_value_subscript
10778                       (ada_coerce_to_simple_array (callee),
10779                        nargs, argvec.data ()));
10780     case TYPE_CODE_PTR:     /* Pointer to array */
10781       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10782         {
10783           type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
10784           type = ada_array_element_type (type, nargs);
10785           if (type == NULL)
10786             error (_("element type of array unknown"));
10787           else
10788             return value_zero (ada_aligned_type (type), lval_memory);
10789         }
10790       return
10791         unwrap_value (ada_value_ptr_subscript (callee, nargs,
10792                                                argvec.data ()));
10793
10794     default:
10795       error (_("Attempt to index or call something other than an "
10796                "array or function"));
10797     }
10798 }
10799
10800 bool
10801 ada_funcall_operation::resolve (struct expression *exp,
10802                                 bool deprocedure_p,
10803                                 bool parse_completion,
10804                                 innermost_block_tracker *tracker,
10805                                 struct type *context_type)
10806 {
10807   operation_up &callee_op = std::get<0> (m_storage);
10808
10809   ada_var_value_operation *avv
10810     = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
10811   if (avv == nullptr)
10812     return false;
10813
10814   symbol *sym = avv->get_symbol ();
10815   if (sym->domain () != UNDEF_DOMAIN)
10816     return false;
10817
10818   const std::vector<operation_up> &args_up = std::get<1> (m_storage);
10819   int nargs = args_up.size ();
10820   std::vector<value *> argvec (nargs);
10821
10822   for (int i = 0; i < args_up.size (); ++i)
10823     argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
10824
10825   const block *block = avv->get_block ();
10826   block_symbol resolved
10827     = ada_resolve_funcall (sym, block,
10828                            context_type, parse_completion,
10829                            nargs, argvec.data (),
10830                            tracker);
10831
10832   std::get<0> (m_storage)
10833     = make_operation<ada_var_value_operation> (resolved);
10834   return false;
10835 }
10836
10837 bool
10838 ada_ternop_slice_operation::resolve (struct expression *exp,
10839                                      bool deprocedure_p,
10840                                      bool parse_completion,
10841                                      innermost_block_tracker *tracker,
10842                                      struct type *context_type)
10843 {
10844   /* Historically this check was done during resolution, so we
10845      continue that here.  */
10846   value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
10847                                                 EVAL_AVOID_SIDE_EFFECTS);
10848   if (ada_is_any_packed_array_type (value_type (v)))
10849     error (_("cannot slice a packed array"));
10850   return false;
10851 }
10852
10853 }
10854
10855 \f
10856
10857 /* Return non-zero iff TYPE represents a System.Address type.  */
10858
10859 int
10860 ada_is_system_address_type (struct type *type)
10861 {
10862   return (type->name () && strcmp (type->name (), "system__address") == 0);
10863 }
10864
10865 \f
10866
10867                                 /* Range types */
10868
10869 /* Scan STR beginning at position K for a discriminant name, and
10870    return the value of that discriminant field of DVAL in *PX.  If
10871    PNEW_K is not null, put the position of the character beyond the
10872    name scanned in *PNEW_K.  Return 1 if successful; return 0 and do
10873    not alter *PX and *PNEW_K if unsuccessful.  */
10874
10875 static int
10876 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
10877                     int *pnew_k)
10878 {
10879   static std::string storage;
10880   const char *pstart, *pend, *bound;
10881   struct value *bound_val;
10882
10883   if (dval == NULL || str == NULL || str[k] == '\0')
10884     return 0;
10885
10886   pstart = str + k;
10887   pend = strstr (pstart, "__");
10888   if (pend == NULL)
10889     {
10890       bound = pstart;
10891       k += strlen (bound);
10892     }
10893   else
10894     {
10895       int len = pend - pstart;
10896
10897       /* Strip __ and beyond.  */
10898       storage = std::string (pstart, len);
10899       bound = storage.c_str ();
10900       k = pend - str;
10901     }
10902
10903   bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
10904   if (bound_val == NULL)
10905     return 0;
10906
10907   *px = value_as_long (bound_val);
10908   if (pnew_k != NULL)
10909     *pnew_k = k;
10910   return 1;
10911 }
10912
10913 /* Value of variable named NAME.  Only exact matches are considered.
10914    If no such variable found, then if ERR_MSG is null, returns 0, and
10915    otherwise causes an error with message ERR_MSG.  */
10916
10917 static struct value *
10918 get_var_value (const char *name, const char *err_msg)
10919 {
10920   std::string quoted_name = add_angle_brackets (name);
10921
10922   lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
10923
10924   std::vector<struct block_symbol> syms
10925     = ada_lookup_symbol_list_worker (lookup_name,
10926                                      get_selected_block (0),
10927                                      VAR_DOMAIN, 1);
10928
10929   if (syms.size () != 1)
10930     {
10931       if (err_msg == NULL)
10932         return 0;
10933       else
10934         error (("%s"), err_msg);
10935     }
10936
10937   return value_of_variable (syms[0].symbol, syms[0].block);
10938 }
10939
10940 /* Value of integer variable named NAME in the current environment.
10941    If no such variable is found, returns false.  Otherwise, sets VALUE
10942    to the variable's value and returns true.  */
10943
10944 bool
10945 get_int_var_value (const char *name, LONGEST &value)
10946 {
10947   struct value *var_val = get_var_value (name, 0);
10948
10949   if (var_val == 0)
10950     return false;
10951
10952   value = value_as_long (var_val);
10953   return true;
10954 }
10955
10956
10957 /* Return a range type whose base type is that of the range type named
10958    NAME in the current environment, and whose bounds are calculated
10959    from NAME according to the GNAT range encoding conventions.
10960    Extract discriminant values, if needed, from DVAL.  ORIG_TYPE is the
10961    corresponding range type from debug information; fall back to using it
10962    if symbol lookup fails.  If a new type must be created, allocate it
10963    like ORIG_TYPE was.  The bounds information, in general, is encoded
10964    in NAME, the base type given in the named range type.  */
10965
10966 static struct type *
10967 to_fixed_range_type (struct type *raw_type, struct value *dval)
10968 {
10969   const char *name;
10970   struct type *base_type;
10971   const char *subtype_info;
10972
10973   gdb_assert (raw_type != NULL);
10974   gdb_assert (raw_type->name () != NULL);
10975
10976   if (raw_type->code () == TYPE_CODE_RANGE)
10977     base_type = TYPE_TARGET_TYPE (raw_type);
10978   else
10979     base_type = raw_type;
10980
10981   name = raw_type->name ();
10982   subtype_info = strstr (name, "___XD");
10983   if (subtype_info == NULL)
10984     {
10985       LONGEST L = ada_discrete_type_low_bound (raw_type);
10986       LONGEST U = ada_discrete_type_high_bound (raw_type);
10987
10988       if (L < INT_MIN || U > INT_MAX)
10989         return raw_type;
10990       else
10991         return create_static_range_type (alloc_type_copy (raw_type), raw_type,
10992                                          L, U);
10993     }
10994   else
10995     {
10996       int prefix_len = subtype_info - name;
10997       LONGEST L, U;
10998       struct type *type;
10999       const char *bounds_str;
11000       int n;
11001
11002       subtype_info += 5;
11003       bounds_str = strchr (subtype_info, '_');
11004       n = 1;
11005
11006       if (*subtype_info == 'L')
11007         {
11008           if (!ada_scan_number (bounds_str, n, &L, &n)
11009               && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11010             return raw_type;
11011           if (bounds_str[n] == '_')
11012             n += 2;
11013           else if (bounds_str[n] == '.')     /* FIXME? SGI Workshop kludge.  */
11014             n += 1;
11015           subtype_info += 1;
11016         }
11017       else
11018         {
11019           std::string name_buf = std::string (name, prefix_len) + "___L";
11020           if (!get_int_var_value (name_buf.c_str (), L))
11021             {
11022               lim_warning (_("Unknown lower bound, using 1."));
11023               L = 1;
11024             }
11025         }
11026
11027       if (*subtype_info == 'U')
11028         {
11029           if (!ada_scan_number (bounds_str, n, &U, &n)
11030               && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11031             return raw_type;
11032         }
11033       else
11034         {
11035           std::string name_buf = std::string (name, prefix_len) + "___U";
11036           if (!get_int_var_value (name_buf.c_str (), U))
11037             {
11038               lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11039               U = L;
11040             }
11041         }
11042
11043       type = create_static_range_type (alloc_type_copy (raw_type),
11044                                        base_type, L, U);
11045       /* create_static_range_type alters the resulting type's length
11046          to match the size of the base_type, which is not what we want.
11047          Set it back to the original range type's length.  */
11048       TYPE_LENGTH (type) = TYPE_LENGTH (raw_type);
11049       type->set_name (name);
11050       return type;
11051     }
11052 }
11053
11054 /* True iff NAME is the name of a range type.  */
11055
11056 int
11057 ada_is_range_type_name (const char *name)
11058 {
11059   return (name != NULL && strstr (name, "___XD"));
11060 }
11061 \f
11062
11063                                 /* Modular types */
11064
11065 /* True iff TYPE is an Ada modular type.  */
11066
11067 int
11068 ada_is_modular_type (struct type *type)
11069 {
11070   struct type *subranged_type = get_base_type (type);
11071
11072   return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
11073           && subranged_type->code () == TYPE_CODE_INT
11074           && subranged_type->is_unsigned ());
11075 }
11076
11077 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE.  */
11078
11079 ULONGEST
11080 ada_modulus (struct type *type)
11081 {
11082   const dynamic_prop &high = type->bounds ()->high;
11083
11084   if (high.kind () == PROP_CONST)
11085     return (ULONGEST) high.const_val () + 1;
11086
11087   /* If TYPE is unresolved, the high bound might be a location list.  Return
11088      0, for lack of a better value to return.  */
11089   return 0;
11090 }
11091 \f
11092
11093 /* Ada exception catchpoint support:
11094    ---------------------------------
11095
11096    We support 3 kinds of exception catchpoints:
11097      . catchpoints on Ada exceptions
11098      . catchpoints on unhandled Ada exceptions
11099      . catchpoints on failed assertions
11100
11101    Exceptions raised during failed assertions, or unhandled exceptions
11102    could perfectly be caught with the general catchpoint on Ada exceptions.
11103    However, we can easily differentiate these two special cases, and having
11104    the option to distinguish these two cases from the rest can be useful
11105    to zero-in on certain situations.
11106
11107    Exception catchpoints are a specialized form of breakpoint,
11108    since they rely on inserting breakpoints inside known routines
11109    of the GNAT runtime.  The implementation therefore uses a standard
11110    breakpoint structure of the BP_BREAKPOINT type, but with its own set
11111    of breakpoint_ops.
11112
11113    Support in the runtime for exception catchpoints have been changed
11114    a few times already, and these changes affect the implementation
11115    of these catchpoints.  In order to be able to support several
11116    variants of the runtime, we use a sniffer that will determine
11117    the runtime variant used by the program being debugged.  */
11118
11119 /* Ada's standard exceptions.
11120
11121    The Ada 83 standard also defined Numeric_Error.  But there so many
11122    situations where it was unclear from the Ada 83 Reference Manual
11123    (RM) whether Constraint_Error or Numeric_Error should be raised,
11124    that the ARG (Ada Rapporteur Group) eventually issued a Binding
11125    Interpretation saying that anytime the RM says that Numeric_Error
11126    should be raised, the implementation may raise Constraint_Error.
11127    Ada 95 went one step further and pretty much removed Numeric_Error
11128    from the list of standard exceptions (it made it a renaming of
11129    Constraint_Error, to help preserve compatibility when compiling
11130    an Ada83 compiler). As such, we do not include Numeric_Error from
11131    this list of standard exceptions.  */
11132
11133 static const char * const standard_exc[] = {
11134   "constraint_error",
11135   "program_error",
11136   "storage_error",
11137   "tasking_error"
11138 };
11139
11140 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11141
11142 /* A structure that describes how to support exception catchpoints
11143    for a given executable.  */
11144
11145 struct exception_support_info
11146 {
11147    /* The name of the symbol to break on in order to insert
11148       a catchpoint on exceptions.  */
11149    const char *catch_exception_sym;
11150
11151    /* The name of the symbol to break on in order to insert
11152       a catchpoint on unhandled exceptions.  */
11153    const char *catch_exception_unhandled_sym;
11154
11155    /* The name of the symbol to break on in order to insert
11156       a catchpoint on failed assertions.  */
11157    const char *catch_assert_sym;
11158
11159    /* The name of the symbol to break on in order to insert
11160       a catchpoint on exception handling.  */
11161    const char *catch_handlers_sym;
11162
11163    /* Assuming that the inferior just triggered an unhandled exception
11164       catchpoint, this function is responsible for returning the address
11165       in inferior memory where the name of that exception is stored.
11166       Return zero if the address could not be computed.  */
11167    ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11168 };
11169
11170 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11171 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11172
11173 /* The following exception support info structure describes how to
11174    implement exception catchpoints with the latest version of the
11175    Ada runtime (as of 2019-08-??).  */
11176
11177 static const struct exception_support_info default_exception_support_info =
11178 {
11179   "__gnat_debug_raise_exception", /* catch_exception_sym */
11180   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11181   "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11182   "__gnat_begin_handler_v1", /* catch_handlers_sym */
11183   ada_unhandled_exception_name_addr
11184 };
11185
11186 /* The following exception support info structure describes how to
11187    implement exception catchpoints with an earlier version of the
11188    Ada runtime (as of 2007-03-06) using v0 of the EH ABI.  */
11189
11190 static const struct exception_support_info exception_support_info_v0 =
11191 {
11192   "__gnat_debug_raise_exception", /* catch_exception_sym */
11193   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11194   "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11195   "__gnat_begin_handler", /* catch_handlers_sym */
11196   ada_unhandled_exception_name_addr
11197 };
11198
11199 /* The following exception support info structure describes how to
11200    implement exception catchpoints with a slightly older version
11201    of the Ada runtime.  */
11202
11203 static const struct exception_support_info exception_support_info_fallback =
11204 {
11205   "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11206   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11207   "system__assertions__raise_assert_failure",  /* catch_assert_sym */
11208   "__gnat_begin_handler", /* catch_handlers_sym */
11209   ada_unhandled_exception_name_addr_from_raise
11210 };
11211
11212 /* Return nonzero if we can detect the exception support routines
11213    described in EINFO.
11214
11215    This function errors out if an abnormal situation is detected
11216    (for instance, if we find the exception support routines, but
11217    that support is found to be incomplete).  */
11218
11219 static int
11220 ada_has_this_exception_support (const struct exception_support_info *einfo)
11221 {
11222   struct symbol *sym;
11223
11224   /* The symbol we're looking up is provided by a unit in the GNAT runtime
11225      that should be compiled with debugging information.  As a result, we
11226      expect to find that symbol in the symtabs.  */
11227
11228   sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11229   if (sym == NULL)
11230     {
11231       /* Perhaps we did not find our symbol because the Ada runtime was
11232          compiled without debugging info, or simply stripped of it.
11233          It happens on some GNU/Linux distributions for instance, where
11234          users have to install a separate debug package in order to get
11235          the runtime's debugging info.  In that situation, let the user
11236          know why we cannot insert an Ada exception catchpoint.
11237
11238          Note: Just for the purpose of inserting our Ada exception
11239          catchpoint, we could rely purely on the associated minimal symbol.
11240          But we would be operating in degraded mode anyway, since we are
11241          still lacking the debugging info needed later on to extract
11242          the name of the exception being raised (this name is printed in
11243          the catchpoint message, and is also used when trying to catch
11244          a specific exception).  We do not handle this case for now.  */
11245       struct bound_minimal_symbol msym
11246         = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11247
11248       if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
11249         error (_("Your Ada runtime appears to be missing some debugging "
11250                  "information.\nCannot insert Ada exception catchpoint "
11251                  "in this configuration."));
11252
11253       return 0;
11254     }
11255
11256   /* Make sure that the symbol we found corresponds to a function.  */
11257
11258   if (sym->aclass () != LOC_BLOCK)
11259     {
11260       error (_("Symbol \"%s\" is not a function (class = %d)"),
11261              sym->linkage_name (), sym->aclass ());
11262       return 0;
11263     }
11264
11265   sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11266   if (sym == NULL)
11267     {
11268       struct bound_minimal_symbol msym
11269         = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11270
11271       if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
11272         error (_("Your Ada runtime appears to be missing some debugging "
11273                  "information.\nCannot insert Ada exception catchpoint "
11274                  "in this configuration."));
11275
11276       return 0;
11277     }
11278
11279   /* Make sure that the symbol we found corresponds to a function.  */
11280
11281   if (sym->aclass () != LOC_BLOCK)
11282     {
11283       error (_("Symbol \"%s\" is not a function (class = %d)"),
11284              sym->linkage_name (), sym->aclass ());
11285       return 0;
11286     }
11287
11288   return 1;
11289 }
11290
11291 /* Inspect the Ada runtime and determine which exception info structure
11292    should be used to provide support for exception catchpoints.
11293
11294    This function will always set the per-inferior exception_info,
11295    or raise an error.  */
11296
11297 static void
11298 ada_exception_support_info_sniffer (void)
11299 {
11300   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11301
11302   /* If the exception info is already known, then no need to recompute it.  */
11303   if (data->exception_info != NULL)
11304     return;
11305
11306   /* Check the latest (default) exception support info.  */
11307   if (ada_has_this_exception_support (&default_exception_support_info))
11308     {
11309       data->exception_info = &default_exception_support_info;
11310       return;
11311     }
11312
11313   /* Try the v0 exception suport info.  */
11314   if (ada_has_this_exception_support (&exception_support_info_v0))
11315     {
11316       data->exception_info = &exception_support_info_v0;
11317       return;
11318     }
11319
11320   /* Try our fallback exception suport info.  */
11321   if (ada_has_this_exception_support (&exception_support_info_fallback))
11322     {
11323       data->exception_info = &exception_support_info_fallback;
11324       return;
11325     }
11326
11327   /* Sometimes, it is normal for us to not be able to find the routine
11328      we are looking for.  This happens when the program is linked with
11329      the shared version of the GNAT runtime, and the program has not been
11330      started yet.  Inform the user of these two possible causes if
11331      applicable.  */
11332
11333   if (ada_update_initial_language (language_unknown) != language_ada)
11334     error (_("Unable to insert catchpoint.  Is this an Ada main program?"));
11335
11336   /* If the symbol does not exist, then check that the program is
11337      already started, to make sure that shared libraries have been
11338      loaded.  If it is not started, this may mean that the symbol is
11339      in a shared library.  */
11340
11341   if (inferior_ptid.pid () == 0)
11342     error (_("Unable to insert catchpoint. Try to start the program first."));
11343
11344   /* At this point, we know that we are debugging an Ada program and
11345      that the inferior has been started, but we still are not able to
11346      find the run-time symbols.  That can mean that we are in
11347      configurable run time mode, or that a-except as been optimized
11348      out by the linker...  In any case, at this point it is not worth
11349      supporting this feature.  */
11350
11351   error (_("Cannot insert Ada exception catchpoints in this configuration."));
11352 }
11353
11354 /* True iff FRAME is very likely to be that of a function that is
11355    part of the runtime system.  This is all very heuristic, but is
11356    intended to be used as advice as to what frames are uninteresting
11357    to most users.  */
11358
11359 static int
11360 is_known_support_routine (struct frame_info *frame)
11361 {
11362   enum language func_lang;
11363   int i;
11364   const char *fullname;
11365
11366   /* If this code does not have any debugging information (no symtab),
11367      This cannot be any user code.  */
11368
11369   symtab_and_line sal = find_frame_sal (frame);
11370   if (sal.symtab == NULL)
11371     return 1;
11372
11373   /* If there is a symtab, but the associated source file cannot be
11374      located, then assume this is not user code:  Selecting a frame
11375      for which we cannot display the code would not be very helpful
11376      for the user.  This should also take care of case such as VxWorks
11377      where the kernel has some debugging info provided for a few units.  */
11378
11379   fullname = symtab_to_fullname (sal.symtab);
11380   if (access (fullname, R_OK) != 0)
11381     return 1;
11382
11383   /* Check the unit filename against the Ada runtime file naming.
11384      We also check the name of the objfile against the name of some
11385      known system libraries that sometimes come with debugging info
11386      too.  */
11387
11388   for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11389     {
11390       re_comp (known_runtime_file_name_patterns[i]);
11391       if (re_exec (lbasename (sal.symtab->filename)))
11392         return 1;
11393       if (sal.symtab->objfile () != NULL
11394           && re_exec (objfile_name (sal.symtab->objfile ())))
11395         return 1;
11396     }
11397
11398   /* Check whether the function is a GNAT-generated entity.  */
11399
11400   gdb::unique_xmalloc_ptr<char> func_name
11401     = find_frame_funname (frame, &func_lang, NULL);
11402   if (func_name == NULL)
11403     return 1;
11404
11405   for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11406     {
11407       re_comp (known_auxiliary_function_name_patterns[i]);
11408       if (re_exec (func_name.get ()))
11409         return 1;
11410     }
11411
11412   return 0;
11413 }
11414
11415 /* Find the first frame that contains debugging information and that is not
11416    part of the Ada run-time, starting from FI and moving upward.  */
11417
11418 void
11419 ada_find_printable_frame (struct frame_info *fi)
11420 {
11421   for (; fi != NULL; fi = get_prev_frame (fi))
11422     {
11423       if (!is_known_support_routine (fi))
11424         {
11425           select_frame (fi);
11426           break;
11427         }
11428     }
11429
11430 }
11431
11432 /* Assuming that the inferior just triggered an unhandled exception
11433    catchpoint, return the address in inferior memory where the name
11434    of the exception is stored.
11435    
11436    Return zero if the address could not be computed.  */
11437
11438 static CORE_ADDR
11439 ada_unhandled_exception_name_addr (void)
11440 {
11441   return parse_and_eval_address ("e.full_name");
11442 }
11443
11444 /* Same as ada_unhandled_exception_name_addr, except that this function
11445    should be used when the inferior uses an older version of the runtime,
11446    where the exception name needs to be extracted from a specific frame
11447    several frames up in the callstack.  */
11448
11449 static CORE_ADDR
11450 ada_unhandled_exception_name_addr_from_raise (void)
11451 {
11452   int frame_level;
11453   struct frame_info *fi;
11454   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11455
11456   /* To determine the name of this exception, we need to select
11457      the frame corresponding to RAISE_SYM_NAME.  This frame is
11458      at least 3 levels up, so we simply skip the first 3 frames
11459      without checking the name of their associated function.  */
11460   fi = get_current_frame ();
11461   for (frame_level = 0; frame_level < 3; frame_level += 1)
11462     if (fi != NULL)
11463       fi = get_prev_frame (fi); 
11464
11465   while (fi != NULL)
11466     {
11467       enum language func_lang;
11468
11469       gdb::unique_xmalloc_ptr<char> func_name
11470         = find_frame_funname (fi, &func_lang, NULL);
11471       if (func_name != NULL)
11472         {
11473           if (strcmp (func_name.get (),
11474                       data->exception_info->catch_exception_sym) == 0)
11475             break; /* We found the frame we were looking for...  */
11476         }
11477       fi = get_prev_frame (fi);
11478     }
11479
11480   if (fi == NULL)
11481     return 0;
11482
11483   select_frame (fi);
11484   return parse_and_eval_address ("id.full_name");
11485 }
11486
11487 /* Assuming the inferior just triggered an Ada exception catchpoint
11488    (of any type), return the address in inferior memory where the name
11489    of the exception is stored, if applicable.
11490
11491    Assumes the selected frame is the current frame.
11492
11493    Return zero if the address could not be computed, or if not relevant.  */
11494
11495 static CORE_ADDR
11496 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
11497                            struct breakpoint *b)
11498 {
11499   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11500
11501   switch (ex)
11502     {
11503       case ada_catch_exception:
11504         return (parse_and_eval_address ("e.full_name"));
11505         break;
11506
11507       case ada_catch_exception_unhandled:
11508         return data->exception_info->unhandled_exception_name_addr ();
11509         break;
11510
11511       case ada_catch_handlers:
11512         return 0;  /* The runtimes does not provide access to the exception
11513                       name.  */
11514         break;
11515
11516       case ada_catch_assert:
11517         return 0;  /* Exception name is not relevant in this case.  */
11518         break;
11519
11520       default:
11521         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11522         break;
11523     }
11524
11525   return 0; /* Should never be reached.  */
11526 }
11527
11528 /* Assuming the inferior is stopped at an exception catchpoint,
11529    return the message which was associated to the exception, if
11530    available.  Return NULL if the message could not be retrieved.
11531
11532    Note: The exception message can be associated to an exception
11533    either through the use of the Raise_Exception function, or
11534    more simply (Ada 2005 and later), via:
11535
11536        raise Exception_Name with "exception message";
11537
11538    */
11539
11540 static gdb::unique_xmalloc_ptr<char>
11541 ada_exception_message_1 (void)
11542 {
11543   struct value *e_msg_val;
11544   int e_msg_len;
11545
11546   /* For runtimes that support this feature, the exception message
11547      is passed as an unbounded string argument called "message".  */
11548   e_msg_val = parse_and_eval ("message");
11549   if (e_msg_val == NULL)
11550     return NULL; /* Exception message not supported.  */
11551
11552   e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11553   gdb_assert (e_msg_val != NULL);
11554   e_msg_len = TYPE_LENGTH (value_type (e_msg_val));
11555
11556   /* If the message string is empty, then treat it as if there was
11557      no exception message.  */
11558   if (e_msg_len <= 0)
11559     return NULL;
11560
11561   gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
11562   read_memory (value_address (e_msg_val), (gdb_byte *) e_msg.get (),
11563                e_msg_len);
11564   e_msg.get ()[e_msg_len] = '\0';
11565
11566   return e_msg;
11567 }
11568
11569 /* Same as ada_exception_message_1, except that all exceptions are
11570    contained here (returning NULL instead).  */
11571
11572 static gdb::unique_xmalloc_ptr<char>
11573 ada_exception_message (void)
11574 {
11575   gdb::unique_xmalloc_ptr<char> e_msg;
11576
11577   try
11578     {
11579       e_msg = ada_exception_message_1 ();
11580     }
11581   catch (const gdb_exception_error &e)
11582     {
11583       e_msg.reset (nullptr);
11584     }
11585
11586   return e_msg;
11587 }
11588
11589 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
11590    any error that ada_exception_name_addr_1 might cause to be thrown.
11591    When an error is intercepted, a warning with the error message is printed,
11592    and zero is returned.  */
11593
11594 static CORE_ADDR
11595 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
11596                          struct breakpoint *b)
11597 {
11598   CORE_ADDR result = 0;
11599
11600   try
11601     {
11602       result = ada_exception_name_addr_1 (ex, b);
11603     }
11604
11605   catch (const gdb_exception_error &e)
11606     {
11607       warning (_("failed to get exception name: %s"), e.what ());
11608       return 0;
11609     }
11610
11611   return result;
11612 }
11613
11614 static std::string ada_exception_catchpoint_cond_string
11615   (const char *excep_string,
11616    enum ada_exception_catchpoint_kind ex);
11617
11618 /* Ada catchpoints.
11619
11620    In the case of catchpoints on Ada exceptions, the catchpoint will
11621    stop the target on every exception the program throws.  When a user
11622    specifies the name of a specific exception, we translate this
11623    request into a condition expression (in text form), and then parse
11624    it into an expression stored in each of the catchpoint's locations.
11625    We then use this condition to check whether the exception that was
11626    raised is the one the user is interested in.  If not, then the
11627    target is resumed again.  We store the name of the requested
11628    exception, in order to be able to re-set the condition expression
11629    when symbols change.  */
11630
11631 /* An instance of this type is used to represent an Ada catchpoint
11632    breakpoint location.  */
11633
11634 class ada_catchpoint_location : public bp_location
11635 {
11636 public:
11637   ada_catchpoint_location (breakpoint *owner)
11638     : bp_location (owner, bp_loc_software_breakpoint)
11639   {}
11640
11641   /* The condition that checks whether the exception that was raised
11642      is the specific exception the user specified on catchpoint
11643      creation.  */
11644   expression_up excep_cond_expr;
11645 };
11646
11647 /* An instance of this type is used to represent an Ada catchpoint.  */
11648
11649 struct ada_catchpoint : public breakpoint
11650 {
11651   explicit ada_catchpoint (enum ada_exception_catchpoint_kind kind)
11652     : m_kind (kind)
11653   {
11654   }
11655
11656   /* The name of the specific exception the user specified.  */
11657   std::string excep_string;
11658
11659   /* What kind of catchpoint this is.  */
11660   enum ada_exception_catchpoint_kind m_kind;
11661 };
11662
11663 /* Parse the exception condition string in the context of each of the
11664    catchpoint's locations, and store them for later evaluation.  */
11665
11666 static void
11667 create_excep_cond_exprs (struct ada_catchpoint *c,
11668                          enum ada_exception_catchpoint_kind ex)
11669 {
11670   /* Nothing to do if there's no specific exception to catch.  */
11671   if (c->excep_string.empty ())
11672     return;
11673
11674   /* Same if there are no locations... */
11675   if (c->loc == NULL)
11676     return;
11677
11678   /* Compute the condition expression in text form, from the specific
11679      expection we want to catch.  */
11680   std::string cond_string
11681     = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
11682
11683   /* Iterate over all the catchpoint's locations, and parse an
11684      expression for each.  */
11685   for (bp_location *bl : c->locations ())
11686     {
11687       struct ada_catchpoint_location *ada_loc
11688         = (struct ada_catchpoint_location *) bl;
11689       expression_up exp;
11690
11691       if (!bl->shlib_disabled)
11692         {
11693           const char *s;
11694
11695           s = cond_string.c_str ();
11696           try
11697             {
11698               exp = parse_exp_1 (&s, bl->address,
11699                                  block_for_pc (bl->address),
11700                                  0);
11701             }
11702           catch (const gdb_exception_error &e)
11703             {
11704               warning (_("failed to reevaluate internal exception condition "
11705                          "for catchpoint %d: %s"),
11706                        c->number, e.what ());
11707             }
11708         }
11709
11710       ada_loc->excep_cond_expr = std::move (exp);
11711     }
11712 }
11713
11714 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
11715    structure for all exception catchpoint kinds.  */
11716
11717 static struct bp_location *
11718 allocate_location_exception (struct breakpoint *self)
11719 {
11720   return new ada_catchpoint_location (self);
11721 }
11722
11723 /* Implement the RE_SET method in the breakpoint_ops structure for all
11724    exception catchpoint kinds.  */
11725
11726 static void
11727 re_set_exception (struct breakpoint *b)
11728 {
11729   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11730
11731   /* Call the base class's method.  This updates the catchpoint's
11732      locations.  */
11733   bkpt_breakpoint_ops.re_set (b);
11734
11735   /* Reparse the exception conditional expressions.  One for each
11736      location.  */
11737   create_excep_cond_exprs (c, c->m_kind);
11738 }
11739
11740 /* Returns true if we should stop for this breakpoint hit.  If the
11741    user specified a specific exception, we only want to cause a stop
11742    if the program thrown that exception.  */
11743
11744 static bool
11745 should_stop_exception (const struct bp_location *bl)
11746 {
11747   struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
11748   const struct ada_catchpoint_location *ada_loc
11749     = (const struct ada_catchpoint_location *) bl;
11750   bool stop;
11751
11752   struct internalvar *var = lookup_internalvar ("_ada_exception");
11753   if (c->m_kind == ada_catch_assert)
11754     clear_internalvar (var);
11755   else
11756     {
11757       try
11758         {
11759           const char *expr;
11760
11761           if (c->m_kind == ada_catch_handlers)
11762             expr = ("GNAT_GCC_exception_Access(gcc_exception)"
11763                     ".all.occurrence.id");
11764           else
11765             expr = "e";
11766
11767           struct value *exc = parse_and_eval (expr);
11768           set_internalvar (var, exc);
11769         }
11770       catch (const gdb_exception_error &ex)
11771         {
11772           clear_internalvar (var);
11773         }
11774     }
11775
11776   /* With no specific exception, should always stop.  */
11777   if (c->excep_string.empty ())
11778     return true;
11779
11780   if (ada_loc->excep_cond_expr == NULL)
11781     {
11782       /* We will have a NULL expression if back when we were creating
11783          the expressions, this location's had failed to parse.  */
11784       return true;
11785     }
11786
11787   stop = true;
11788   try
11789     {
11790       struct value *mark;
11791
11792       mark = value_mark ();
11793       stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
11794       value_free_to_mark (mark);
11795     }
11796   catch (const gdb_exception &ex)
11797     {
11798       exception_fprintf (gdb_stderr, ex,
11799                          _("Error in testing exception condition:\n"));
11800     }
11801
11802   return stop;
11803 }
11804
11805 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
11806    for all exception catchpoint kinds.  */
11807
11808 static void
11809 check_status_exception (bpstat *bs)
11810 {
11811   bs->stop = should_stop_exception (bs->bp_location_at.get ());
11812 }
11813
11814 /* Implement the PRINT_IT method in the breakpoint_ops structure
11815    for all exception catchpoint kinds.  */
11816
11817 static enum print_stop_action
11818 print_it_exception (bpstat *bs)
11819 {
11820   struct ui_out *uiout = current_uiout;
11821   struct breakpoint *b = bs->breakpoint_at;
11822
11823   annotate_catchpoint (b->number);
11824
11825   if (uiout->is_mi_like_p ())
11826     {
11827       uiout->field_string ("reason",
11828                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11829       uiout->field_string ("disp", bpdisp_text (b->disposition));
11830     }
11831
11832   uiout->text (b->disposition == disp_del
11833                ? "\nTemporary catchpoint " : "\nCatchpoint ");
11834   uiout->field_signed ("bkptno", b->number);
11835   uiout->text (", ");
11836
11837   /* ada_exception_name_addr relies on the selected frame being the
11838      current frame.  Need to do this here because this function may be
11839      called more than once when printing a stop, and below, we'll
11840      select the first frame past the Ada run-time (see
11841      ada_find_printable_frame).  */
11842   select_frame (get_current_frame ());
11843
11844   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11845   switch (c->m_kind)
11846     {
11847       case ada_catch_exception:
11848       case ada_catch_exception_unhandled:
11849       case ada_catch_handlers:
11850         {
11851           const CORE_ADDR addr = ada_exception_name_addr (c->m_kind, b);
11852           char exception_name[256];
11853
11854           if (addr != 0)
11855             {
11856               read_memory (addr, (gdb_byte *) exception_name,
11857                            sizeof (exception_name) - 1);
11858               exception_name [sizeof (exception_name) - 1] = '\0';
11859             }
11860           else
11861             {
11862               /* For some reason, we were unable to read the exception
11863                  name.  This could happen if the Runtime was compiled
11864                  without debugging info, for instance.  In that case,
11865                  just replace the exception name by the generic string
11866                  "exception" - it will read as "an exception" in the
11867                  notification we are about to print.  */
11868               memcpy (exception_name, "exception", sizeof ("exception"));
11869             }
11870           /* In the case of unhandled exception breakpoints, we print
11871              the exception name as "unhandled EXCEPTION_NAME", to make
11872              it clearer to the user which kind of catchpoint just got
11873              hit.  We used ui_out_text to make sure that this extra
11874              info does not pollute the exception name in the MI case.  */
11875           if (c->m_kind == ada_catch_exception_unhandled)
11876             uiout->text ("unhandled ");
11877           uiout->field_string ("exception-name", exception_name);
11878         }
11879         break;
11880       case ada_catch_assert:
11881         /* In this case, the name of the exception is not really
11882            important.  Just print "failed assertion" to make it clearer
11883            that his program just hit an assertion-failure catchpoint.
11884            We used ui_out_text because this info does not belong in
11885            the MI output.  */
11886         uiout->text ("failed assertion");
11887         break;
11888     }
11889
11890   gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
11891   if (exception_message != NULL)
11892     {
11893       uiout->text (" (");
11894       uiout->field_string ("exception-message", exception_message.get ());
11895       uiout->text (")");
11896     }
11897
11898   uiout->text (" at ");
11899   ada_find_printable_frame (get_current_frame ());
11900
11901   return PRINT_SRC_AND_LOC;
11902 }
11903
11904 /* Implement the PRINT_ONE method in the breakpoint_ops structure
11905    for all exception catchpoint kinds.  */
11906
11907 static void
11908 print_one_exception (struct breakpoint *b, struct bp_location **last_loc)
11909
11910   struct ui_out *uiout = current_uiout;
11911   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11912   struct value_print_options opts;
11913
11914   get_user_print_options (&opts);
11915
11916   if (opts.addressprint)
11917     uiout->field_skip ("addr");
11918
11919   annotate_field (5);
11920   switch (c->m_kind)
11921     {
11922       case ada_catch_exception:
11923         if (!c->excep_string.empty ())
11924           {
11925             std::string msg = string_printf (_("`%s' Ada exception"),
11926                                              c->excep_string.c_str ());
11927
11928             uiout->field_string ("what", msg);
11929           }
11930         else
11931           uiout->field_string ("what", "all Ada exceptions");
11932         
11933         break;
11934
11935       case ada_catch_exception_unhandled:
11936         uiout->field_string ("what", "unhandled Ada exceptions");
11937         break;
11938       
11939       case ada_catch_handlers:
11940         if (!c->excep_string.empty ())
11941           {
11942             uiout->field_fmt ("what",
11943                               _("`%s' Ada exception handlers"),
11944                               c->excep_string.c_str ());
11945           }
11946         else
11947           uiout->field_string ("what", "all Ada exceptions handlers");
11948         break;
11949
11950       case ada_catch_assert:
11951         uiout->field_string ("what", "failed Ada assertions");
11952         break;
11953
11954       default:
11955         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11956         break;
11957     }
11958 }
11959
11960 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
11961    for all exception catchpoint kinds.  */
11962
11963 static void
11964 print_mention_exception (struct breakpoint *b)
11965 {
11966   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11967   struct ui_out *uiout = current_uiout;
11968
11969   uiout->text (b->disposition == disp_del ? _("Temporary catchpoint ")
11970                                                  : _("Catchpoint "));
11971   uiout->field_signed ("bkptno", b->number);
11972   uiout->text (": ");
11973
11974   switch (c->m_kind)
11975     {
11976       case ada_catch_exception:
11977         if (!c->excep_string.empty ())
11978           {
11979             std::string info = string_printf (_("`%s' Ada exception"),
11980                                               c->excep_string.c_str ());
11981             uiout->text (info);
11982           }
11983         else
11984           uiout->text (_("all Ada exceptions"));
11985         break;
11986
11987       case ada_catch_exception_unhandled:
11988         uiout->text (_("unhandled Ada exceptions"));
11989         break;
11990
11991       case ada_catch_handlers:
11992         if (!c->excep_string.empty ())
11993           {
11994             std::string info
11995               = string_printf (_("`%s' Ada exception handlers"),
11996                                c->excep_string.c_str ());
11997             uiout->text (info);
11998           }
11999         else
12000           uiout->text (_("all Ada exceptions handlers"));
12001         break;
12002
12003       case ada_catch_assert:
12004         uiout->text (_("failed Ada assertions"));
12005         break;
12006
12007       default:
12008         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12009         break;
12010     }
12011 }
12012
12013 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
12014    for all exception catchpoint kinds.  */
12015
12016 static void
12017 print_recreate_exception (struct breakpoint *b, struct ui_file *fp)
12018 {
12019   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12020
12021   switch (c->m_kind)
12022     {
12023       case ada_catch_exception:
12024         fprintf_filtered (fp, "catch exception");
12025         if (!c->excep_string.empty ())
12026           fprintf_filtered (fp, " %s", c->excep_string.c_str ());
12027         break;
12028
12029       case ada_catch_exception_unhandled:
12030         fprintf_filtered (fp, "catch exception unhandled");
12031         break;
12032
12033       case ada_catch_handlers:
12034         fprintf_filtered (fp, "catch handlers");
12035         break;
12036
12037       case ada_catch_assert:
12038         fprintf_filtered (fp, "catch assert");
12039         break;
12040
12041       default:
12042         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12043     }
12044   print_recreate_thread (b, fp);
12045 }
12046
12047 /* Virtual table for breakpoint type.  */
12048 static struct breakpoint_ops catch_exception_breakpoint_ops;
12049
12050 /* See ada-lang.h.  */
12051
12052 bool
12053 is_ada_exception_catchpoint (breakpoint *bp)
12054 {
12055   return bp->ops == &catch_exception_breakpoint_ops;
12056 }
12057
12058 /* Split the arguments specified in a "catch exception" command.  
12059    Set EX to the appropriate catchpoint type.
12060    Set EXCEP_STRING to the name of the specific exception if
12061    specified by the user.
12062    IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12063    "catch handlers" command.  False otherwise.
12064    If a condition is found at the end of the arguments, the condition
12065    expression is stored in COND_STRING (memory must be deallocated
12066    after use).  Otherwise COND_STRING is set to NULL.  */
12067
12068 static void
12069 catch_ada_exception_command_split (const char *args,
12070                                    bool is_catch_handlers_cmd,
12071                                    enum ada_exception_catchpoint_kind *ex,
12072                                    std::string *excep_string,
12073                                    std::string *cond_string)
12074 {
12075   std::string exception_name;
12076
12077   exception_name = extract_arg (&args);
12078   if (exception_name == "if")
12079     {
12080       /* This is not an exception name; this is the start of a condition
12081          expression for a catchpoint on all exceptions.  So, "un-get"
12082          this token, and set exception_name to NULL.  */
12083       exception_name.clear ();
12084       args -= 2;
12085     }
12086
12087   /* Check to see if we have a condition.  */
12088
12089   args = skip_spaces (args);
12090   if (startswith (args, "if")
12091       && (isspace (args[2]) || args[2] == '\0'))
12092     {
12093       args += 2;
12094       args = skip_spaces (args);
12095
12096       if (args[0] == '\0')
12097         error (_("Condition missing after `if' keyword"));
12098       *cond_string = args;
12099
12100       args += strlen (args);
12101     }
12102
12103   /* Check that we do not have any more arguments.  Anything else
12104      is unexpected.  */
12105
12106   if (args[0] != '\0')
12107     error (_("Junk at end of expression"));
12108
12109   if (is_catch_handlers_cmd)
12110     {
12111       /* Catch handling of exceptions.  */
12112       *ex = ada_catch_handlers;
12113       *excep_string = exception_name;
12114     }
12115   else if (exception_name.empty ())
12116     {
12117       /* Catch all exceptions.  */
12118       *ex = ada_catch_exception;
12119       excep_string->clear ();
12120     }
12121   else if (exception_name == "unhandled")
12122     {
12123       /* Catch unhandled exceptions.  */
12124       *ex = ada_catch_exception_unhandled;
12125       excep_string->clear ();
12126     }
12127   else
12128     {
12129       /* Catch a specific exception.  */
12130       *ex = ada_catch_exception;
12131       *excep_string = exception_name;
12132     }
12133 }
12134
12135 /* Return the name of the symbol on which we should break in order to
12136    implement a catchpoint of the EX kind.  */
12137
12138 static const char *
12139 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12140 {
12141   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12142
12143   gdb_assert (data->exception_info != NULL);
12144
12145   switch (ex)
12146     {
12147       case ada_catch_exception:
12148         return (data->exception_info->catch_exception_sym);
12149         break;
12150       case ada_catch_exception_unhandled:
12151         return (data->exception_info->catch_exception_unhandled_sym);
12152         break;
12153       case ada_catch_assert:
12154         return (data->exception_info->catch_assert_sym);
12155         break;
12156       case ada_catch_handlers:
12157         return (data->exception_info->catch_handlers_sym);
12158         break;
12159       default:
12160         internal_error (__FILE__, __LINE__,
12161                         _("unexpected catchpoint kind (%d)"), ex);
12162     }
12163 }
12164
12165 /* Return the condition that will be used to match the current exception
12166    being raised with the exception that the user wants to catch.  This
12167    assumes that this condition is used when the inferior just triggered
12168    an exception catchpoint.
12169    EX: the type of catchpoints used for catching Ada exceptions.  */
12170
12171 static std::string
12172 ada_exception_catchpoint_cond_string (const char *excep_string,
12173                                       enum ada_exception_catchpoint_kind ex)
12174 {
12175   bool is_standard_exc = false;
12176   std::string result;
12177
12178   if (ex == ada_catch_handlers)
12179     {
12180       /* For exception handlers catchpoints, the condition string does
12181          not use the same parameter as for the other exceptions.  */
12182       result = ("long_integer (GNAT_GCC_exception_Access"
12183                 "(gcc_exception).all.occurrence.id)");
12184     }
12185   else
12186     result = "long_integer (e)";
12187
12188   /* The standard exceptions are a special case.  They are defined in
12189      runtime units that have been compiled without debugging info; if
12190      EXCEP_STRING is the not-fully-qualified name of a standard
12191      exception (e.g. "constraint_error") then, during the evaluation
12192      of the condition expression, the symbol lookup on this name would
12193      *not* return this standard exception.  The catchpoint condition
12194      may then be set only on user-defined exceptions which have the
12195      same not-fully-qualified name (e.g. my_package.constraint_error).
12196
12197      To avoid this unexcepted behavior, these standard exceptions are
12198      systematically prefixed by "standard".  This means that "catch
12199      exception constraint_error" is rewritten into "catch exception
12200      standard.constraint_error".
12201
12202      If an exception named constraint_error is defined in another package of
12203      the inferior program, then the only way to specify this exception as a
12204      breakpoint condition is to use its fully-qualified named:
12205      e.g. my_package.constraint_error.  */
12206
12207   for (const char *name : standard_exc)
12208     {
12209       if (strcmp (name, excep_string) == 0)
12210         {
12211           is_standard_exc = true;
12212           break;
12213         }
12214     }
12215
12216   result += " = ";
12217
12218   if (is_standard_exc)
12219     string_appendf (result, "long_integer (&standard.%s)", excep_string);
12220   else
12221     string_appendf (result, "long_integer (&%s)", excep_string);
12222
12223   return result;
12224 }
12225
12226 /* Return the symtab_and_line that should be used to insert an exception
12227    catchpoint of the TYPE kind.
12228
12229    ADDR_STRING returns the name of the function where the real
12230    breakpoint that implements the catchpoints is set, depending on the
12231    type of catchpoint we need to create.  */
12232
12233 static struct symtab_and_line
12234 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
12235                    std::string *addr_string, const struct breakpoint_ops **ops)
12236 {
12237   const char *sym_name;
12238   struct symbol *sym;
12239
12240   /* First, find out which exception support info to use.  */
12241   ada_exception_support_info_sniffer ();
12242
12243   /* Then lookup the function on which we will break in order to catch
12244      the Ada exceptions requested by the user.  */
12245   sym_name = ada_exception_sym_name (ex);
12246   sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12247
12248   if (sym == NULL)
12249     error (_("Catchpoint symbol not found: %s"), sym_name);
12250
12251   if (sym->aclass () != LOC_BLOCK)
12252     error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
12253
12254   /* Set ADDR_STRING.  */
12255   *addr_string = sym_name;
12256
12257   /* Set OPS.  */
12258   *ops = &catch_exception_breakpoint_ops;
12259
12260   return find_function_start_sal (sym, 1);
12261 }
12262
12263 /* Create an Ada exception catchpoint.
12264
12265    EX_KIND is the kind of exception catchpoint to be created.
12266
12267    If EXCEPT_STRING is empty, this catchpoint is expected to trigger
12268    for all exceptions.  Otherwise, EXCEPT_STRING indicates the name
12269    of the exception to which this catchpoint applies.
12270
12271    COND_STRING, if not empty, is the catchpoint condition.
12272
12273    TEMPFLAG, if nonzero, means that the underlying breakpoint
12274    should be temporary.
12275
12276    FROM_TTY is the usual argument passed to all commands implementations.  */
12277
12278 void
12279 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12280                                  enum ada_exception_catchpoint_kind ex_kind,
12281                                  const std::string &excep_string,
12282                                  const std::string &cond_string,
12283                                  int tempflag,
12284                                  int disabled,
12285                                  int from_tty)
12286 {
12287   std::string addr_string;
12288   const struct breakpoint_ops *ops = NULL;
12289   struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string, &ops);
12290
12291   std::unique_ptr<ada_catchpoint> c (new ada_catchpoint (ex_kind));
12292   init_ada_exception_breakpoint (c.get (), gdbarch, sal, addr_string.c_str (),
12293                                  ops, tempflag, disabled, from_tty);
12294   c->excep_string = excep_string;
12295   create_excep_cond_exprs (c.get (), ex_kind);
12296   if (!cond_string.empty ())
12297     set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
12298   install_breakpoint (0, std::move (c), 1);
12299 }
12300
12301 /* Implement the "catch exception" command.  */
12302
12303 static void
12304 catch_ada_exception_command (const char *arg_entry, int from_tty,
12305                              struct cmd_list_element *command)
12306 {
12307   const char *arg = arg_entry;
12308   struct gdbarch *gdbarch = get_current_arch ();
12309   int tempflag;
12310   enum ada_exception_catchpoint_kind ex_kind;
12311   std::string excep_string;
12312   std::string cond_string;
12313
12314   tempflag = command->context () == CATCH_TEMPORARY;
12315
12316   if (!arg)
12317     arg = "";
12318   catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
12319                                      &cond_string);
12320   create_ada_exception_catchpoint (gdbarch, ex_kind,
12321                                    excep_string, cond_string,
12322                                    tempflag, 1 /* enabled */,
12323                                    from_tty);
12324 }
12325
12326 /* Implement the "catch handlers" command.  */
12327
12328 static void
12329 catch_ada_handlers_command (const char *arg_entry, int from_tty,
12330                             struct cmd_list_element *command)
12331 {
12332   const char *arg = arg_entry;
12333   struct gdbarch *gdbarch = get_current_arch ();
12334   int tempflag;
12335   enum ada_exception_catchpoint_kind ex_kind;
12336   std::string excep_string;
12337   std::string cond_string;
12338
12339   tempflag = command->context () == CATCH_TEMPORARY;
12340
12341   if (!arg)
12342     arg = "";
12343   catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
12344                                      &cond_string);
12345   create_ada_exception_catchpoint (gdbarch, ex_kind,
12346                                    excep_string, cond_string,
12347                                    tempflag, 1 /* enabled */,
12348                                    from_tty);
12349 }
12350
12351 /* Completion function for the Ada "catch" commands.  */
12352
12353 static void
12354 catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12355                      const char *text, const char *word)
12356 {
12357   std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12358
12359   for (const ada_exc_info &info : exceptions)
12360     {
12361       if (startswith (info.name, word))
12362         tracker.add_completion (make_unique_xstrdup (info.name));
12363     }
12364 }
12365
12366 /* Split the arguments specified in a "catch assert" command.
12367
12368    ARGS contains the command's arguments (or the empty string if
12369    no arguments were passed).
12370
12371    If ARGS contains a condition, set COND_STRING to that condition
12372    (the memory needs to be deallocated after use).  */
12373
12374 static void
12375 catch_ada_assert_command_split (const char *args, std::string &cond_string)
12376 {
12377   args = skip_spaces (args);
12378
12379   /* Check whether a condition was provided.  */
12380   if (startswith (args, "if")
12381       && (isspace (args[2]) || args[2] == '\0'))
12382     {
12383       args += 2;
12384       args = skip_spaces (args);
12385       if (args[0] == '\0')
12386         error (_("condition missing after `if' keyword"));
12387       cond_string.assign (args);
12388     }
12389
12390   /* Otherwise, there should be no other argument at the end of
12391      the command.  */
12392   else if (args[0] != '\0')
12393     error (_("Junk at end of arguments."));
12394 }
12395
12396 /* Implement the "catch assert" command.  */
12397
12398 static void
12399 catch_assert_command (const char *arg_entry, int from_tty,
12400                       struct cmd_list_element *command)
12401 {
12402   const char *arg = arg_entry;
12403   struct gdbarch *gdbarch = get_current_arch ();
12404   int tempflag;
12405   std::string cond_string;
12406
12407   tempflag = command->context () == CATCH_TEMPORARY;
12408
12409   if (!arg)
12410     arg = "";
12411   catch_ada_assert_command_split (arg, cond_string);
12412   create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12413                                    "", cond_string,
12414                                    tempflag, 1 /* enabled */,
12415                                    from_tty);
12416 }
12417
12418 /* Return non-zero if the symbol SYM is an Ada exception object.  */
12419
12420 static int
12421 ada_is_exception_sym (struct symbol *sym)
12422 {
12423   const char *type_name = sym->type ()->name ();
12424
12425   return (sym->aclass () != LOC_TYPEDEF
12426           && sym->aclass () != LOC_BLOCK
12427           && sym->aclass () != LOC_CONST
12428           && sym->aclass () != LOC_UNRESOLVED
12429           && type_name != NULL && strcmp (type_name, "exception") == 0);
12430 }
12431
12432 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12433    Ada exception object.  This matches all exceptions except the ones
12434    defined by the Ada language.  */
12435
12436 static int
12437 ada_is_non_standard_exception_sym (struct symbol *sym)
12438 {
12439   if (!ada_is_exception_sym (sym))
12440     return 0;
12441
12442   for (const char *name : standard_exc)
12443     if (strcmp (sym->linkage_name (), name) == 0)
12444       return 0;  /* A standard exception.  */
12445
12446   /* Numeric_Error is also a standard exception, so exclude it.
12447      See the STANDARD_EXC description for more details as to why
12448      this exception is not listed in that array.  */
12449   if (strcmp (sym->linkage_name (), "numeric_error") == 0)
12450     return 0;
12451
12452   return 1;
12453 }
12454
12455 /* A helper function for std::sort, comparing two struct ada_exc_info
12456    objects.
12457
12458    The comparison is determined first by exception name, and then
12459    by exception address.  */
12460
12461 bool
12462 ada_exc_info::operator< (const ada_exc_info &other) const
12463 {
12464   int result;
12465
12466   result = strcmp (name, other.name);
12467   if (result < 0)
12468     return true;
12469   if (result == 0 && addr < other.addr)
12470     return true;
12471   return false;
12472 }
12473
12474 bool
12475 ada_exc_info::operator== (const ada_exc_info &other) const
12476 {
12477   return addr == other.addr && strcmp (name, other.name) == 0;
12478 }
12479
12480 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12481    routine, but keeping the first SKIP elements untouched.
12482
12483    All duplicates are also removed.  */
12484
12485 static void
12486 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
12487                                       int skip)
12488 {
12489   std::sort (exceptions->begin () + skip, exceptions->end ());
12490   exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12491                      exceptions->end ());
12492 }
12493
12494 /* Add all exceptions defined by the Ada standard whose name match
12495    a regular expression.
12496
12497    If PREG is not NULL, then this regexp_t object is used to
12498    perform the symbol name matching.  Otherwise, no name-based
12499    filtering is performed.
12500
12501    EXCEPTIONS is a vector of exceptions to which matching exceptions
12502    gets pushed.  */
12503
12504 static void
12505 ada_add_standard_exceptions (compiled_regex *preg,
12506                              std::vector<ada_exc_info> *exceptions)
12507 {
12508   for (const char *name : standard_exc)
12509     {
12510       if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
12511         {
12512           struct bound_minimal_symbol msymbol
12513             = ada_lookup_simple_minsym (name);
12514
12515           if (msymbol.minsym != NULL)
12516             {
12517               struct ada_exc_info info
12518                 = {name, BMSYMBOL_VALUE_ADDRESS (msymbol)};
12519
12520               exceptions->push_back (info);
12521             }
12522         }
12523     }
12524 }
12525
12526 /* Add all Ada exceptions defined locally and accessible from the given
12527    FRAME.
12528
12529    If PREG is not NULL, then this regexp_t object is used to
12530    perform the symbol name matching.  Otherwise, no name-based
12531    filtering is performed.
12532
12533    EXCEPTIONS is a vector of exceptions to which matching exceptions
12534    gets pushed.  */
12535
12536 static void
12537 ada_add_exceptions_from_frame (compiled_regex *preg,
12538                                struct frame_info *frame,
12539                                std::vector<ada_exc_info> *exceptions)
12540 {
12541   const struct block *block = get_frame_block (frame, 0);
12542
12543   while (block != 0)
12544     {
12545       struct block_iterator iter;
12546       struct symbol *sym;
12547
12548       ALL_BLOCK_SYMBOLS (block, iter, sym)
12549         {
12550           switch (sym->aclass ())
12551             {
12552             case LOC_TYPEDEF:
12553             case LOC_BLOCK:
12554             case LOC_CONST:
12555               break;
12556             default:
12557               if (ada_is_exception_sym (sym))
12558                 {
12559                   struct ada_exc_info info = {sym->print_name (),
12560                                               SYMBOL_VALUE_ADDRESS (sym)};
12561
12562                   exceptions->push_back (info);
12563                 }
12564             }
12565         }
12566       if (BLOCK_FUNCTION (block) != NULL)
12567         break;
12568       block = BLOCK_SUPERBLOCK (block);
12569     }
12570 }
12571
12572 /* Return true if NAME matches PREG or if PREG is NULL.  */
12573
12574 static bool
12575 name_matches_regex (const char *name, compiled_regex *preg)
12576 {
12577   return (preg == NULL
12578           || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
12579 }
12580
12581 /* Add all exceptions defined globally whose name name match
12582    a regular expression, excluding standard exceptions.
12583
12584    The reason we exclude standard exceptions is that they need
12585    to be handled separately: Standard exceptions are defined inside
12586    a runtime unit which is normally not compiled with debugging info,
12587    and thus usually do not show up in our symbol search.  However,
12588    if the unit was in fact built with debugging info, we need to
12589    exclude them because they would duplicate the entry we found
12590    during the special loop that specifically searches for those
12591    standard exceptions.
12592
12593    If PREG is not NULL, then this regexp_t object is used to
12594    perform the symbol name matching.  Otherwise, no name-based
12595    filtering is performed.
12596
12597    EXCEPTIONS is a vector of exceptions to which matching exceptions
12598    gets pushed.  */
12599
12600 static void
12601 ada_add_global_exceptions (compiled_regex *preg,
12602                            std::vector<ada_exc_info> *exceptions)
12603 {
12604   /* In Ada, the symbol "search name" is a linkage name, whereas the
12605      regular expression used to do the matching refers to the natural
12606      name.  So match against the decoded name.  */
12607   expand_symtabs_matching (NULL,
12608                            lookup_name_info::match_any (),
12609                            [&] (const char *search_name)
12610                            {
12611                              std::string decoded = ada_decode (search_name);
12612                              return name_matches_regex (decoded.c_str (), preg);
12613                            },
12614                            NULL,
12615                            SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
12616                            VARIABLES_DOMAIN);
12617
12618   for (objfile *objfile : current_program_space->objfiles ())
12619     {
12620       for (compunit_symtab *s : objfile->compunits ())
12621         {
12622           const struct blockvector *bv = s->blockvector ();
12623           int i;
12624
12625           for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
12626             {
12627               const struct block *b = BLOCKVECTOR_BLOCK (bv, i);
12628               struct block_iterator iter;
12629               struct symbol *sym;
12630
12631               ALL_BLOCK_SYMBOLS (b, iter, sym)
12632                 if (ada_is_non_standard_exception_sym (sym)
12633                     && name_matches_regex (sym->natural_name (), preg))
12634                   {
12635                     struct ada_exc_info info
12636                       = {sym->print_name (), SYMBOL_VALUE_ADDRESS (sym)};
12637
12638                     exceptions->push_back (info);
12639                   }
12640             }
12641         }
12642     }
12643 }
12644
12645 /* Implements ada_exceptions_list with the regular expression passed
12646    as a regex_t, rather than a string.
12647
12648    If not NULL, PREG is used to filter out exceptions whose names
12649    do not match.  Otherwise, all exceptions are listed.  */
12650
12651 static std::vector<ada_exc_info>
12652 ada_exceptions_list_1 (compiled_regex *preg)
12653 {
12654   std::vector<ada_exc_info> result;
12655   int prev_len;
12656
12657   /* First, list the known standard exceptions.  These exceptions
12658      need to be handled separately, as they are usually defined in
12659      runtime units that have been compiled without debugging info.  */
12660
12661   ada_add_standard_exceptions (preg, &result);
12662
12663   /* Next, find all exceptions whose scope is local and accessible
12664      from the currently selected frame.  */
12665
12666   if (has_stack_frames ())
12667     {
12668       prev_len = result.size ();
12669       ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
12670                                      &result);
12671       if (result.size () > prev_len)
12672         sort_remove_dups_ada_exceptions_list (&result, prev_len);
12673     }
12674
12675   /* Add all exceptions whose scope is global.  */
12676
12677   prev_len = result.size ();
12678   ada_add_global_exceptions (preg, &result);
12679   if (result.size () > prev_len)
12680     sort_remove_dups_ada_exceptions_list (&result, prev_len);
12681
12682   return result;
12683 }
12684
12685 /* Return a vector of ada_exc_info.
12686
12687    If REGEXP is NULL, all exceptions are included in the result.
12688    Otherwise, it should contain a valid regular expression,
12689    and only the exceptions whose names match that regular expression
12690    are included in the result.
12691
12692    The exceptions are sorted in the following order:
12693      - Standard exceptions (defined by the Ada language), in
12694        alphabetical order;
12695      - Exceptions only visible from the current frame, in
12696        alphabetical order;
12697      - Exceptions whose scope is global, in alphabetical order.  */
12698
12699 std::vector<ada_exc_info>
12700 ada_exceptions_list (const char *regexp)
12701 {
12702   if (regexp == NULL)
12703     return ada_exceptions_list_1 (NULL);
12704
12705   compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
12706   return ada_exceptions_list_1 (&reg);
12707 }
12708
12709 /* Implement the "info exceptions" command.  */
12710
12711 static void
12712 info_exceptions_command (const char *regexp, int from_tty)
12713 {
12714   struct gdbarch *gdbarch = get_current_arch ();
12715
12716   std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
12717
12718   if (regexp != NULL)
12719     printf_filtered
12720       (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
12721   else
12722     printf_filtered (_("All defined Ada exceptions:\n"));
12723
12724   for (const ada_exc_info &info : exceptions)
12725     printf_filtered ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
12726 }
12727
12728 \f
12729                                 /* Language vector */
12730
12731 /* symbol_name_matcher_ftype adapter for wild_match.  */
12732
12733 static bool
12734 do_wild_match (const char *symbol_search_name,
12735                const lookup_name_info &lookup_name,
12736                completion_match_result *comp_match_res)
12737 {
12738   return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
12739 }
12740
12741 /* symbol_name_matcher_ftype adapter for full_match.  */
12742
12743 static bool
12744 do_full_match (const char *symbol_search_name,
12745                const lookup_name_info &lookup_name,
12746                completion_match_result *comp_match_res)
12747 {
12748   const char *lname = lookup_name.ada ().lookup_name ().c_str ();
12749
12750   /* If both symbols start with "_ada_", just let the loop below
12751      handle the comparison.  However, if only the symbol name starts
12752      with "_ada_", skip the prefix and let the match proceed as
12753      usual.  */
12754   if (startswith (symbol_search_name, "_ada_")
12755       && !startswith (lname, "_ada"))
12756     symbol_search_name += 5;
12757
12758   int uscore_count = 0;
12759   while (*lname != '\0')
12760     {
12761       if (*symbol_search_name != *lname)
12762         {
12763           if (*symbol_search_name == 'B' && uscore_count == 2
12764               && symbol_search_name[1] == '_')
12765             {
12766               symbol_search_name += 2;
12767               while (isdigit (*symbol_search_name))
12768                 ++symbol_search_name;
12769               if (symbol_search_name[0] == '_'
12770                   && symbol_search_name[1] == '_')
12771                 {
12772                   symbol_search_name += 2;
12773                   continue;
12774                 }
12775             }
12776           return false;
12777         }
12778
12779       if (*symbol_search_name == '_')
12780         ++uscore_count;
12781       else
12782         uscore_count = 0;
12783
12784       ++symbol_search_name;
12785       ++lname;
12786     }
12787
12788   return is_name_suffix (symbol_search_name);
12789 }
12790
12791 /* symbol_name_matcher_ftype for exact (verbatim) matches.  */
12792
12793 static bool
12794 do_exact_match (const char *symbol_search_name,
12795                 const lookup_name_info &lookup_name,
12796                 completion_match_result *comp_match_res)
12797 {
12798   return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
12799 }
12800
12801 /* Build the Ada lookup name for LOOKUP_NAME.  */
12802
12803 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
12804 {
12805   gdb::string_view user_name = lookup_name.name ();
12806
12807   if (!user_name.empty () && user_name[0] == '<')
12808     {
12809       if (user_name.back () == '>')
12810         m_encoded_name
12811           = gdb::to_string (user_name.substr (1, user_name.size () - 2));
12812       else
12813         m_encoded_name
12814           = gdb::to_string (user_name.substr (1, user_name.size () - 1));
12815       m_encoded_p = true;
12816       m_verbatim_p = true;
12817       m_wild_match_p = false;
12818       m_standard_p = false;
12819     }
12820   else
12821     {
12822       m_verbatim_p = false;
12823
12824       m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
12825
12826       if (!m_encoded_p)
12827         {
12828           const char *folded = ada_fold_name (user_name);
12829           m_encoded_name = ada_encode_1 (folded, false);
12830           if (m_encoded_name.empty ())
12831             m_encoded_name = gdb::to_string (user_name);
12832         }
12833       else
12834         m_encoded_name = gdb::to_string (user_name);
12835
12836       /* Handle the 'package Standard' special case.  See description
12837          of m_standard_p.  */
12838       if (startswith (m_encoded_name.c_str (), "standard__"))
12839         {
12840           m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
12841           m_standard_p = true;
12842         }
12843       else
12844         m_standard_p = false;
12845
12846       /* If the name contains a ".", then the user is entering a fully
12847          qualified entity name, and the match must not be done in wild
12848          mode.  Similarly, if the user wants to complete what looks
12849          like an encoded name, the match must not be done in wild
12850          mode.  Also, in the standard__ special case always do
12851          non-wild matching.  */
12852       m_wild_match_p
12853         = (lookup_name.match_type () != symbol_name_match_type::FULL
12854            && !m_encoded_p
12855            && !m_standard_p
12856            && user_name.find ('.') == std::string::npos);
12857     }
12858 }
12859
12860 /* symbol_name_matcher_ftype method for Ada.  This only handles
12861    completion mode.  */
12862
12863 static bool
12864 ada_symbol_name_matches (const char *symbol_search_name,
12865                          const lookup_name_info &lookup_name,
12866                          completion_match_result *comp_match_res)
12867 {
12868   return lookup_name.ada ().matches (symbol_search_name,
12869                                      lookup_name.match_type (),
12870                                      comp_match_res);
12871 }
12872
12873 /* A name matcher that matches the symbol name exactly, with
12874    strcmp.  */
12875
12876 static bool
12877 literal_symbol_name_matcher (const char *symbol_search_name,
12878                              const lookup_name_info &lookup_name,
12879                              completion_match_result *comp_match_res)
12880 {
12881   gdb::string_view name_view = lookup_name.name ();
12882
12883   if (lookup_name.completion_mode ()
12884       ? (strncmp (symbol_search_name, name_view.data (),
12885                   name_view.size ()) == 0)
12886       : symbol_search_name == name_view)
12887     {
12888       if (comp_match_res != NULL)
12889         comp_match_res->set_match (symbol_search_name);
12890       return true;
12891     }
12892   else
12893     return false;
12894 }
12895
12896 /* Implement the "get_symbol_name_matcher" language_defn method for
12897    Ada.  */
12898
12899 static symbol_name_matcher_ftype *
12900 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
12901 {
12902   if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
12903     return literal_symbol_name_matcher;
12904
12905   if (lookup_name.completion_mode ())
12906     return ada_symbol_name_matches;
12907   else
12908     {
12909       if (lookup_name.ada ().wild_match_p ())
12910         return do_wild_match;
12911       else if (lookup_name.ada ().verbatim_p ())
12912         return do_exact_match;
12913       else
12914         return do_full_match;
12915     }
12916 }
12917
12918 /* Class representing the Ada language.  */
12919
12920 class ada_language : public language_defn
12921 {
12922 public:
12923   ada_language ()
12924     : language_defn (language_ada)
12925   { /* Nothing.  */ }
12926
12927   /* See language.h.  */
12928
12929   const char *name () const override
12930   { return "ada"; }
12931
12932   /* See language.h.  */
12933
12934   const char *natural_name () const override
12935   { return "Ada"; }
12936
12937   /* See language.h.  */
12938
12939   const std::vector<const char *> &filename_extensions () const override
12940   {
12941     static const std::vector<const char *> extensions
12942       = { ".adb", ".ads", ".a", ".ada", ".dg" };
12943     return extensions;
12944   }
12945
12946   /* Print an array element index using the Ada syntax.  */
12947
12948   void print_array_index (struct type *index_type,
12949                           LONGEST index,
12950                           struct ui_file *stream,
12951                           const value_print_options *options) const override
12952   {
12953     struct value *index_value = val_atr (index_type, index);
12954
12955     value_print (index_value, stream, options);
12956     fprintf_filtered (stream, " => ");
12957   }
12958
12959   /* Implement the "read_var_value" language_defn method for Ada.  */
12960
12961   struct value *read_var_value (struct symbol *var,
12962                                 const struct block *var_block,
12963                                 struct frame_info *frame) const override
12964   {
12965     /* The only case where default_read_var_value is not sufficient
12966        is when VAR is a renaming...  */
12967     if (frame != nullptr)
12968       {
12969         const struct block *frame_block = get_frame_block (frame, NULL);
12970         if (frame_block != nullptr && ada_is_renaming_symbol (var))
12971           return ada_read_renaming_var_value (var, frame_block);
12972       }
12973
12974     /* This is a typical case where we expect the default_read_var_value
12975        function to work.  */
12976     return language_defn::read_var_value (var, var_block, frame);
12977   }
12978
12979   /* See language.h.  */
12980   virtual bool symbol_printing_suppressed (struct symbol *symbol) const override
12981   {
12982     return symbol->artificial;
12983   }
12984
12985   /* See language.h.  */
12986   void language_arch_info (struct gdbarch *gdbarch,
12987                            struct language_arch_info *lai) const override
12988   {
12989     const struct builtin_type *builtin = builtin_type (gdbarch);
12990
12991     /* Helper function to allow shorter lines below.  */
12992     auto add = [&] (struct type *t)
12993     {
12994       lai->add_primitive_type (t);
12995     };
12996
12997     add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
12998                             0, "integer"));
12999     add (arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
13000                             0, "long_integer"));
13001     add (arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
13002                             0, "short_integer"));
13003     struct type *char_type = arch_character_type (gdbarch, TARGET_CHAR_BIT,
13004                                                   1, "character");
13005     lai->set_string_char_type (char_type);
13006     add (char_type);
13007     add (arch_character_type (gdbarch, 16, 1, "wide_character"));
13008     add (arch_character_type (gdbarch, 32, 1, "wide_wide_character"));
13009     add (arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
13010                           "float", gdbarch_float_format (gdbarch)));
13011     add (arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
13012                           "long_float", gdbarch_double_format (gdbarch)));
13013     add (arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
13014                             0, "long_long_integer"));
13015     add (arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
13016                           "long_long_float",
13017                           gdbarch_long_double_format (gdbarch)));
13018     add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13019                             0, "natural"));
13020     add (arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
13021                             0, "positive"));
13022     add (builtin->builtin_void);
13023
13024     struct type *system_addr_ptr
13025       = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
13026                                         "void"));
13027     system_addr_ptr->set_name ("system__address");
13028     add (system_addr_ptr);
13029
13030     /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13031        type.  This is a signed integral type whose size is the same as
13032        the size of addresses.  */
13033     unsigned int addr_length = TYPE_LENGTH (system_addr_ptr);
13034     add (arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
13035                             "storage_offset"));
13036
13037     lai->set_bool_type (builtin->builtin_bool);
13038   }
13039
13040   /* See language.h.  */
13041
13042   bool iterate_over_symbols
13043         (const struct block *block, const lookup_name_info &name,
13044          domain_enum domain,
13045          gdb::function_view<symbol_found_callback_ftype> callback) const override
13046   {
13047     std::vector<struct block_symbol> results
13048       = ada_lookup_symbol_list_worker (name, block, domain, 0);
13049     for (block_symbol &sym : results)
13050       {
13051         if (!callback (&sym))
13052           return false;
13053       }
13054
13055     return true;
13056   }
13057
13058   /* See language.h.  */
13059   bool sniff_from_mangled_name
13060        (const char *mangled,
13061         gdb::unique_xmalloc_ptr<char> *out) const override
13062   {
13063     std::string demangled = ada_decode (mangled);
13064
13065     *out = NULL;
13066
13067     if (demangled != mangled && demangled[0] != '<')
13068       {
13069         /* Set the gsymbol language to Ada, but still return 0.
13070            Two reasons for that:
13071
13072            1. For Ada, we prefer computing the symbol's decoded name
13073            on the fly rather than pre-compute it, in order to save
13074            memory (Ada projects are typically very large).
13075
13076            2. There are some areas in the definition of the GNAT
13077            encoding where, with a bit of bad luck, we might be able
13078            to decode a non-Ada symbol, generating an incorrect
13079            demangled name (Eg: names ending with "TB" for instance
13080            are identified as task bodies and so stripped from
13081            the decoded name returned).
13082
13083            Returning true, here, but not setting *DEMANGLED, helps us get
13084            a little bit of the best of both worlds.  Because we're last,
13085            we should not affect any of the other languages that were
13086            able to demangle the symbol before us; we get to correctly
13087            tag Ada symbols as such; and even if we incorrectly tagged a
13088            non-Ada symbol, which should be rare, any routing through the
13089            Ada language should be transparent (Ada tries to behave much
13090            like C/C++ with non-Ada symbols).  */
13091         return true;
13092       }
13093
13094     return false;
13095   }
13096
13097   /* See language.h.  */
13098
13099   gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13100                                                  int options) const override
13101   {
13102     return make_unique_xstrdup (ada_decode (mangled).c_str ());
13103   }
13104
13105   /* See language.h.  */
13106
13107   void print_type (struct type *type, const char *varstring,
13108                    struct ui_file *stream, int show, int level,
13109                    const struct type_print_options *flags) const override
13110   {
13111     ada_print_type (type, varstring, stream, show, level, flags);
13112   }
13113
13114   /* See language.h.  */
13115
13116   const char *word_break_characters (void) const override
13117   {
13118     return ada_completer_word_break_characters;
13119   }
13120
13121   /* See language.h.  */
13122
13123   void collect_symbol_completion_matches (completion_tracker &tracker,
13124                                           complete_symbol_mode mode,
13125                                           symbol_name_match_type name_match_type,
13126                                           const char *text, const char *word,
13127                                           enum type_code code) const override
13128   {
13129     struct symbol *sym;
13130     const struct block *b, *surrounding_static_block = 0;
13131     struct block_iterator iter;
13132
13133     gdb_assert (code == TYPE_CODE_UNDEF);
13134
13135     lookup_name_info lookup_name (text, name_match_type, true);
13136
13137     /* First, look at the partial symtab symbols.  */
13138     expand_symtabs_matching (NULL,
13139                              lookup_name,
13140                              NULL,
13141                              NULL,
13142                              SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
13143                              ALL_DOMAIN);
13144
13145     /* At this point scan through the misc symbol vectors and add each
13146        symbol you find to the list.  Eventually we want to ignore
13147        anything that isn't a text symbol (everything else will be
13148        handled by the psymtab code above).  */
13149
13150     for (objfile *objfile : current_program_space->objfiles ())
13151       {
13152         for (minimal_symbol *msymbol : objfile->msymbols ())
13153           {
13154             QUIT;
13155
13156             if (completion_skip_symbol (mode, msymbol))
13157               continue;
13158
13159             language symbol_language = msymbol->language ();
13160
13161             /* Ada minimal symbols won't have their language set to Ada.  If
13162                we let completion_list_add_name compare using the
13163                default/C-like matcher, then when completing e.g., symbols in a
13164                package named "pck", we'd match internal Ada symbols like
13165                "pckS", which are invalid in an Ada expression, unless you wrap
13166                them in '<' '>' to request a verbatim match.
13167
13168                Unfortunately, some Ada encoded names successfully demangle as
13169                C++ symbols (using an old mangling scheme), such as "name__2Xn"
13170                -> "Xn::name(void)" and thus some Ada minimal symbols end up
13171                with the wrong language set.  Paper over that issue here.  */
13172             if (symbol_language == language_auto
13173                 || symbol_language == language_cplus)
13174               symbol_language = language_ada;
13175
13176             completion_list_add_name (tracker,
13177                                       symbol_language,
13178                                       msymbol->linkage_name (),
13179                                       lookup_name, text, word);
13180           }
13181       }
13182
13183     /* Search upwards from currently selected frame (so that we can
13184        complete on local vars.  */
13185
13186     for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
13187       {
13188         if (!BLOCK_SUPERBLOCK (b))
13189           surrounding_static_block = b;   /* For elmin of dups */
13190
13191         ALL_BLOCK_SYMBOLS (b, iter, sym)
13192           {
13193             if (completion_skip_symbol (mode, sym))
13194               continue;
13195
13196             completion_list_add_name (tracker,
13197                                       sym->language (),
13198                                       sym->linkage_name (),
13199                                       lookup_name, text, word);
13200           }
13201       }
13202
13203     /* Go through the symtabs and check the externs and statics for
13204        symbols which match.  */
13205
13206     for (objfile *objfile : current_program_space->objfiles ())
13207       {
13208         for (compunit_symtab *s : objfile->compunits ())
13209           {
13210             QUIT;
13211             b = BLOCKVECTOR_BLOCK (s->blockvector (), GLOBAL_BLOCK);
13212             ALL_BLOCK_SYMBOLS (b, iter, sym)
13213               {
13214                 if (completion_skip_symbol (mode, sym))
13215                   continue;
13216
13217                 completion_list_add_name (tracker,
13218                                           sym->language (),
13219                                           sym->linkage_name (),
13220                                           lookup_name, text, word);
13221               }
13222           }
13223       }
13224
13225     for (objfile *objfile : current_program_space->objfiles ())
13226       {
13227         for (compunit_symtab *s : objfile->compunits ())
13228           {
13229             QUIT;
13230             b = BLOCKVECTOR_BLOCK (s->blockvector (), STATIC_BLOCK);
13231             /* Don't do this block twice.  */
13232             if (b == surrounding_static_block)
13233               continue;
13234             ALL_BLOCK_SYMBOLS (b, iter, sym)
13235               {
13236                 if (completion_skip_symbol (mode, sym))
13237                   continue;
13238
13239                 completion_list_add_name (tracker,
13240                                           sym->language (),
13241                                           sym->linkage_name (),
13242                                           lookup_name, text, word);
13243               }
13244           }
13245       }
13246   }
13247
13248   /* See language.h.  */
13249
13250   gdb::unique_xmalloc_ptr<char> watch_location_expression
13251         (struct type *type, CORE_ADDR addr) const override
13252   {
13253     type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
13254     std::string name = type_to_string (type);
13255     return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
13256   }
13257
13258   /* See language.h.  */
13259
13260   void value_print (struct value *val, struct ui_file *stream,
13261                     const struct value_print_options *options) const override
13262   {
13263     return ada_value_print (val, stream, options);
13264   }
13265
13266   /* See language.h.  */
13267
13268   void value_print_inner
13269         (struct value *val, struct ui_file *stream, int recurse,
13270          const struct value_print_options *options) const override
13271   {
13272     return ada_value_print_inner (val, stream, recurse, options);
13273   }
13274
13275   /* See language.h.  */
13276
13277   struct block_symbol lookup_symbol_nonlocal
13278         (const char *name, const struct block *block,
13279          const domain_enum domain) const override
13280   {
13281     struct block_symbol sym;
13282
13283     sym = ada_lookup_symbol (name, block_static_block (block), domain);
13284     if (sym.symbol != NULL)
13285       return sym;
13286
13287     /* If we haven't found a match at this point, try the primitive
13288        types.  In other languages, this search is performed before
13289        searching for global symbols in order to short-circuit that
13290        global-symbol search if it happens that the name corresponds
13291        to a primitive type.  But we cannot do the same in Ada, because
13292        it is perfectly legitimate for a program to declare a type which
13293        has the same name as a standard type.  If looking up a type in
13294        that situation, we have traditionally ignored the primitive type
13295        in favor of user-defined types.  This is why, unlike most other
13296        languages, we search the primitive types this late and only after
13297        having searched the global symbols without success.  */
13298
13299     if (domain == VAR_DOMAIN)
13300       {
13301         struct gdbarch *gdbarch;
13302
13303         if (block == NULL)
13304           gdbarch = target_gdbarch ();
13305         else
13306           gdbarch = block_gdbarch (block);
13307         sym.symbol
13308           = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13309         if (sym.symbol != NULL)
13310           return sym;
13311       }
13312
13313     return {};
13314   }
13315
13316   /* See language.h.  */
13317
13318   int parser (struct parser_state *ps) const override
13319   {
13320     warnings_issued = 0;
13321     return ada_parse (ps);
13322   }
13323
13324   /* See language.h.  */
13325
13326   void emitchar (int ch, struct type *chtype,
13327                  struct ui_file *stream, int quoter) const override
13328   {
13329     ada_emit_char (ch, chtype, stream, quoter, 1);
13330   }
13331
13332   /* See language.h.  */
13333
13334   void printchar (int ch, struct type *chtype,
13335                   struct ui_file *stream) const override
13336   {
13337     ada_printchar (ch, chtype, stream);
13338   }
13339
13340   /* See language.h.  */
13341
13342   void printstr (struct ui_file *stream, struct type *elttype,
13343                  const gdb_byte *string, unsigned int length,
13344                  const char *encoding, int force_ellipses,
13345                  const struct value_print_options *options) const override
13346   {
13347     ada_printstr (stream, elttype, string, length, encoding,
13348                   force_ellipses, options);
13349   }
13350
13351   /* See language.h.  */
13352
13353   void print_typedef (struct type *type, struct symbol *new_symbol,
13354                       struct ui_file *stream) const override
13355   {
13356     ada_print_typedef (type, new_symbol, stream);
13357   }
13358
13359   /* See language.h.  */
13360
13361   bool is_string_type_p (struct type *type) const override
13362   {
13363     return ada_is_string_type (type);
13364   }
13365
13366   /* See language.h.  */
13367
13368   const char *struct_too_deep_ellipsis () const override
13369   { return "(...)"; }
13370
13371   /* See language.h.  */
13372
13373   bool c_style_arrays_p () const override
13374   { return false; }
13375
13376   /* See language.h.  */
13377
13378   bool store_sym_names_in_linkage_form_p () const override
13379   { return true; }
13380
13381   /* See language.h.  */
13382
13383   const struct lang_varobj_ops *varobj_ops () const override
13384   { return &ada_varobj_ops; }
13385
13386 protected:
13387   /* See language.h.  */
13388
13389   symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13390         (const lookup_name_info &lookup_name) const override
13391   {
13392     return ada_get_symbol_name_matcher (lookup_name);
13393   }
13394 };
13395
13396 /* Single instance of the Ada language class.  */
13397
13398 static ada_language ada_language_defn;
13399
13400 /* Command-list for the "set/show ada" prefix command.  */
13401 static struct cmd_list_element *set_ada_list;
13402 static struct cmd_list_element *show_ada_list;
13403
13404 static void
13405 initialize_ada_catchpoint_ops (void)
13406 {
13407   struct breakpoint_ops *ops;
13408
13409   initialize_breakpoint_ops ();
13410
13411   ops = &catch_exception_breakpoint_ops;
13412   *ops = bkpt_breakpoint_ops;
13413   ops->allocate_location = allocate_location_exception;
13414   ops->re_set = re_set_exception;
13415   ops->check_status = check_status_exception;
13416   ops->print_it = print_it_exception;
13417   ops->print_one = print_one_exception;
13418   ops->print_mention = print_mention_exception;
13419   ops->print_recreate = print_recreate_exception;
13420 }
13421
13422 /* This module's 'new_objfile' observer.  */
13423
13424 static void
13425 ada_new_objfile_observer (struct objfile *objfile)
13426 {
13427   ada_clear_symbol_cache ();
13428 }
13429
13430 /* This module's 'free_objfile' observer.  */
13431
13432 static void
13433 ada_free_objfile_observer (struct objfile *objfile)
13434 {
13435   ada_clear_symbol_cache ();
13436 }
13437
13438 void _initialize_ada_language ();
13439 void
13440 _initialize_ada_language ()
13441 {
13442   initialize_ada_catchpoint_ops ();
13443
13444   add_setshow_prefix_cmd
13445     ("ada", no_class,
13446      _("Prefix command for changing Ada-specific settings."),
13447      _("Generic command for showing Ada-specific settings."),
13448      &set_ada_list, &show_ada_list,
13449      &setlist, &showlist);
13450
13451   add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
13452                            &trust_pad_over_xvs, _("\
13453 Enable or disable an optimization trusting PAD types over XVS types."), _("\
13454 Show whether an optimization trusting PAD types over XVS types is activated."),
13455                            _("\
13456 This is related to the encoding used by the GNAT compiler.  The debugger\n\
13457 should normally trust the contents of PAD types, but certain older versions\n\
13458 of GNAT have a bug that sometimes causes the information in the PAD type\n\
13459 to be incorrect.  Turning this setting \"off\" allows the debugger to\n\
13460 work around this bug.  It is always safe to turn this option \"off\", but\n\
13461 this incurs a slight performance penalty, so it is recommended to NOT change\n\
13462 this option to \"off\" unless necessary."),
13463                             NULL, NULL, &set_ada_list, &show_ada_list);
13464
13465   add_setshow_boolean_cmd ("print-signatures", class_vars,
13466                            &print_signatures, _("\
13467 Enable or disable the output of formal and return types for functions in the \
13468 overloads selection menu."), _("\
13469 Show whether the output of formal and return types for functions in the \
13470 overloads selection menu is activated."),
13471                            NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13472
13473   add_catch_command ("exception", _("\
13474 Catch Ada exceptions, when raised.\n\
13475 Usage: catch exception [ARG] [if CONDITION]\n\
13476 Without any argument, stop when any Ada exception is raised.\n\
13477 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13478 being raised does not have a handler (and will therefore lead to the task's\n\
13479 termination).\n\
13480 Otherwise, the catchpoint only stops when the name of the exception being\n\
13481 raised is the same as ARG.\n\
13482 CONDITION is a boolean expression that is evaluated to see whether the\n\
13483 exception should cause a stop."),
13484                      catch_ada_exception_command,
13485                      catch_ada_completer,
13486                      CATCH_PERMANENT,
13487                      CATCH_TEMPORARY);
13488
13489   add_catch_command ("handlers", _("\
13490 Catch Ada exceptions, when handled.\n\
13491 Usage: catch handlers [ARG] [if CONDITION]\n\
13492 Without any argument, stop when any Ada exception is handled.\n\
13493 With an argument, catch only exceptions with the given name.\n\
13494 CONDITION is a boolean expression that is evaluated to see whether the\n\
13495 exception should cause a stop."),
13496                      catch_ada_handlers_command,
13497                      catch_ada_completer,
13498                      CATCH_PERMANENT,
13499                      CATCH_TEMPORARY);
13500   add_catch_command ("assert", _("\
13501 Catch failed Ada assertions, when raised.\n\
13502 Usage: catch assert [if CONDITION]\n\
13503 CONDITION is a boolean expression that is evaluated to see whether the\n\
13504 exception should cause a stop."),
13505                      catch_assert_command,
13506                      NULL,
13507                      CATCH_PERMANENT,
13508                      CATCH_TEMPORARY);
13509
13510   add_info ("exceptions", info_exceptions_command,
13511             _("\
13512 List all Ada exception names.\n\
13513 Usage: info exceptions [REGEXP]\n\
13514 If a regular expression is passed as an argument, only those matching\n\
13515 the regular expression are listed."));
13516
13517   add_setshow_prefix_cmd ("ada", class_maintenance,
13518                           _("Set Ada maintenance-related variables."),
13519                           _("Show Ada maintenance-related variables."),
13520                           &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
13521                           &maintenance_set_cmdlist, &maintenance_show_cmdlist);
13522
13523   add_setshow_boolean_cmd
13524     ("ignore-descriptive-types", class_maintenance,
13525      &ada_ignore_descriptive_types_p,
13526      _("Set whether descriptive types generated by GNAT should be ignored."),
13527      _("Show whether descriptive types generated by GNAT should be ignored."),
13528      _("\
13529 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
13530 DWARF attribute."),
13531      NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
13532
13533   decoded_names_store = htab_create_alloc (256, htab_hash_string,
13534                                            htab_eq_string,
13535                                            NULL, xcalloc, xfree);
13536
13537   /* The ada-lang observers.  */
13538   gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
13539   gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
13540   gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
13541 }
This page took 0.786321 seconds and 4 git commands to generate.