]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/ada-lang.c
Unify arch_pointer_type and init_pointer_type
[thirdparty/binutils-gdb.git] / gdb / ada-lang.c
CommitLineData
6e681866 1/* Ada language support routines for GDB, the GNU debugger.
10a2c479 2
213516ef 3 Copyright (C) 1992-2023 Free Software Foundation, Inc.
14f9c5c9 4
a9762ec7 5 This file is part of GDB.
14f9c5c9 6
a9762ec7
JB
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.
14f9c5c9 11
a9762ec7
JB
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.
14f9c5c9 16
a9762ec7
JB
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/>. */
14f9c5c9 19
96d887e8 20
4c4b4cd2 21#include "defs.h"
14f9c5c9 22#include <ctype.h>
d322d6d6 23#include "gdbsupport/gdb_regex.h"
4de283e4
TT
24#include "frame.h"
25#include "symtab.h"
26#include "gdbtypes.h"
14f9c5c9 27#include "gdbcmd.h"
4de283e4
TT
28#include "expression.h"
29#include "parser-defs.h"
30#include "language.h"
31#include "varobj.h"
4de283e4
TT
32#include "inferior.h"
33#include "symfile.h"
34#include "objfiles.h"
35#include "breakpoint.h"
14f9c5c9 36#include "gdbcore.h"
4c4b4cd2 37#include "hashtab.h"
bf31fd38 38#include "gdbsupport/gdb_obstack.h"
4de283e4
TT
39#include "ada-lang.h"
40#include "completer.h"
4de283e4
TT
41#include "ui-out.h"
42#include "block.h"
04714b91 43#include "infcall.h"
4de283e4
TT
44#include "annotate.h"
45#include "valprint.h"
d55e5aa6 46#include "source.h"
4de283e4 47#include "observable.h"
692465f1 48#include "stack.h"
79d43c61 49#include "typeprint.h"
4de283e4 50#include "namespace.h"
7f6aba03 51#include "cli/cli-style.h"
0f8e2034 52#include "cli/cli-decode.h"
4de283e4 53
40bc484c 54#include "value.h"
4de283e4
TT
55#include "mi/mi-common.h"
56#include "arch-utils.h"
57#include "cli/cli-utils.h"
268a13a5
TT
58#include "gdbsupport/function-view.h"
59#include "gdbsupport/byte-vector.h"
4de283e4 60#include <algorithm>
03070ee9 61#include "ada-exp.h"
315e4ebb 62#include "charset.h"
013a623f 63#include "ax-gdb.h"
ccefe4c4 64
4c4b4cd2 65/* Define whether or not the C operator '/' truncates towards zero for
0963b4bd 66 differently signed operands (truncation direction is undefined in C).
4c4b4cd2
PH
67 Copied from valarith.c. */
68
69#ifndef TRUNCATION_TOWARDS_ZERO
70#define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
71#endif
72
d2e4a39e 73static struct type *desc_base_type (struct type *);
14f9c5c9 74
d2e4a39e 75static struct type *desc_bounds_type (struct type *);
14f9c5c9 76
d2e4a39e 77static struct value *desc_bounds (struct value *);
14f9c5c9 78
d2e4a39e 79static int fat_pntr_bounds_bitpos (struct type *);
14f9c5c9 80
d2e4a39e 81static int fat_pntr_bounds_bitsize (struct type *);
14f9c5c9 82
556bdfd4 83static struct type *desc_data_target_type (struct type *);
14f9c5c9 84
d2e4a39e 85static struct value *desc_data (struct value *);
14f9c5c9 86
d2e4a39e 87static int fat_pntr_data_bitpos (struct type *);
14f9c5c9 88
d2e4a39e 89static int fat_pntr_data_bitsize (struct type *);
14f9c5c9 90
d2e4a39e 91static struct value *desc_one_bound (struct value *, int, int);
14f9c5c9 92
d2e4a39e 93static int desc_bound_bitpos (struct type *, int, int);
14f9c5c9 94
d2e4a39e 95static int desc_bound_bitsize (struct type *, int, int);
14f9c5c9 96
d2e4a39e 97static struct type *desc_index_type (struct type *, int);
14f9c5c9 98
d2e4a39e 99static int desc_arity (struct type *);
14f9c5c9 100
d2e4a39e 101static int ada_args_match (struct symbol *, struct value **, int);
14f9c5c9 102
40bc484c 103static struct value *make_array_descriptor (struct type *, struct value *);
14f9c5c9 104
d1183b06 105static void ada_add_block_symbols (std::vector<struct block_symbol> &,
b5ec771e
PA
106 const struct block *,
107 const lookup_name_info &lookup_name,
108 domain_enum, struct objfile *);
14f9c5c9 109
d1183b06
TT
110static void ada_add_all_symbols (std::vector<struct block_symbol> &,
111 const struct block *,
b5ec771e
PA
112 const lookup_name_info &lookup_name,
113 domain_enum, int, int *);
22cee43f 114
d1183b06 115static int is_nonfunction (const std::vector<struct block_symbol> &);
14f9c5c9 116
d1183b06
TT
117static void add_defn_to_vec (std::vector<struct block_symbol> &,
118 struct symbol *,
dda83cd7 119 const struct block *);
14f9c5c9 120
d2e4a39e 121static int possible_user_operator_p (enum exp_opcode, struct value **);
14f9c5c9 122
4c4b4cd2 123static const char *ada_decoded_op_name (enum exp_opcode);
14f9c5c9 124
d2e4a39e 125static int numeric_type_p (struct type *);
14f9c5c9 126
d2e4a39e 127static int integer_type_p (struct type *);
14f9c5c9 128
d2e4a39e 129static int scalar_type_p (struct type *);
14f9c5c9 130
d2e4a39e 131static int discrete_type_p (struct type *);
14f9c5c9 132
a121b7c1 133static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
dda83cd7 134 int, int);
4c4b4cd2 135
b4ba55a1 136static struct type *ada_find_parallel_type_with_name (struct type *,
dda83cd7 137 const char *);
b4ba55a1 138
d2e4a39e 139static int is_dynamic_field (struct type *, int);
14f9c5c9 140
10a2c479 141static struct type *to_fixed_variant_branch_type (struct type *,
fc1a4b47 142 const gdb_byte *,
dda83cd7 143 CORE_ADDR, struct value *);
4c4b4cd2
PH
144
145static struct type *to_fixed_array_type (struct type *, struct value *, int);
14f9c5c9 146
28c85d6c 147static struct type *to_fixed_range_type (struct type *, struct value *);
14f9c5c9 148
d2e4a39e 149static struct type *to_static_fixed_type (struct type *);
f192137b 150static struct type *static_unwrap_type (struct type *type);
14f9c5c9 151
d2e4a39e 152static struct value *unwrap_value (struct value *);
14f9c5c9 153
ad82864c 154static struct type *constrained_packed_array_type (struct type *, long *);
14f9c5c9 155
ad82864c 156static struct type *decode_constrained_packed_array_type (struct type *);
14f9c5c9 157
ad82864c
JB
158static long decode_packed_array_bitsize (struct type *);
159
160static struct value *decode_constrained_packed_array (struct value *);
161
ad82864c 162static int ada_is_unconstrained_packed_array_type (struct type *);
14f9c5c9 163
d2e4a39e 164static struct value *value_subscript_packed (struct value *, int,
dda83cd7 165 struct value **);
14f9c5c9 166
4c4b4cd2 167static struct value *coerce_unspec_val_to_type (struct value *,
dda83cd7 168 struct type *);
14f9c5c9 169
d2e4a39e 170static int lesseq_defined_than (struct symbol *, struct symbol *);
14f9c5c9 171
d2e4a39e 172static int equiv_types (struct type *, struct type *);
14f9c5c9 173
d2e4a39e 174static int is_name_suffix (const char *);
14f9c5c9 175
59c8a30b 176static int advance_wild_match (const char **, const char *, char);
73589123 177
b5ec771e 178static bool wild_match (const char *name, const char *patn);
14f9c5c9 179
d2e4a39e 180static struct value *ada_coerce_ref (struct value *);
14f9c5c9 181
4c4b4cd2
PH
182static LONGEST pos_atr (struct value *);
183
53a47a3e
TT
184static struct value *val_atr (struct type *, LONGEST);
185
4c4b4cd2 186static struct symbol *standard_lookup (const char *, const struct block *,
dda83cd7 187 domain_enum);
14f9c5c9 188
108d56a4 189static struct value *ada_search_struct_field (const char *, struct value *, int,
dda83cd7 190 struct type *);
4c4b4cd2 191
0d5cff50 192static int find_struct_field (const char *, struct type *, int,
dda83cd7 193 struct type **, int *, int *, int *, int *);
4c4b4cd2 194
d1183b06 195static int ada_resolve_function (std::vector<struct block_symbol> &,
dda83cd7 196 struct value **, int, const char *,
7056f312 197 struct type *, bool);
4c4b4cd2 198
4c4b4cd2
PH
199static int ada_is_direct_array_type (struct type *);
200
52ce6436
PH
201static struct value *ada_index_struct_field (int, struct value *, int,
202 struct type *);
203
cf608cc4 204static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
52ce6436
PH
205
206
852dff6c 207static struct type *ada_find_any_type (const char *name);
b5ec771e
PA
208
209static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
210 (const lookup_name_info &lookup_name);
211
4c4b4cd2
PH
212\f
213
315e4ebb
TT
214/* The character set used for source files. */
215static const char *ada_source_charset;
216
217/* The string "UTF-8". This is here so we can check for the UTF-8
218 charset using == rather than strcmp. */
219static const char ada_utf8[] = "UTF-8";
220
221/* Each entry in the UTF-32 case-folding table is of this form. */
222struct utf8_entry
223{
224 /* The start and end, inclusive, of this range of codepoints. */
225 uint32_t start, end;
226 /* The delta to apply to get the upper-case form. 0 if this is
227 already upper-case. */
228 int upper_delta;
229 /* The delta to apply to get the lower-case form. 0 if this is
230 already lower-case. */
231 int lower_delta;
232
233 bool operator< (uint32_t val) const
234 {
235 return end < val;
236 }
237};
238
239static const utf8_entry ada_case_fold[] =
240{
241#include "ada-casefold.h"
242};
243
244\f
245
ee01b665
JB
246/* The result of a symbol lookup to be stored in our symbol cache. */
247
248struct cache_entry
249{
250 /* The name used to perform the lookup. */
251 const char *name;
252 /* The namespace used during the lookup. */
fe978cb0 253 domain_enum domain;
ee01b665
JB
254 /* The symbol returned by the lookup, or NULL if no matching symbol
255 was found. */
256 struct symbol *sym;
257 /* The block where the symbol was found, or NULL if no matching
258 symbol was found. */
259 const struct block *block;
260 /* A pointer to the next entry with the same hash. */
261 struct cache_entry *next;
262};
263
264/* The Ada symbol cache, used to store the result of Ada-mode symbol
265 lookups in the course of executing the user's commands.
266
267 The cache is implemented using a simple, fixed-sized hash.
268 The size is fixed on the grounds that there are not likely to be
269 all that many symbols looked up during any given session, regardless
270 of the size of the symbol table. If we decide to go to a resizable
271 table, let's just use the stuff from libiberty instead. */
272
273#define HASH_SIZE 1009
274
275struct ada_symbol_cache
276{
277 /* An obstack used to store the entries in our cache. */
bdcccc56 278 struct auto_obstack cache_space;
ee01b665
JB
279
280 /* The root of the hash table used to implement our symbol cache. */
bdcccc56 281 struct cache_entry *root[HASH_SIZE] {};
ee01b665
JB
282};
283
67cb5b2d 284static const char ada_completer_word_break_characters[] =
4c4b4cd2
PH
285#ifdef VMS
286 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
287#else
14f9c5c9 288 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
4c4b4cd2 289#endif
14f9c5c9 290
4c4b4cd2 291/* The name of the symbol to use to get the name of the main subprogram. */
76a01679 292static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
4c4b4cd2 293 = "__gnat_ada_main_program_name";
14f9c5c9 294
4c4b4cd2
PH
295/* Limit on the number of warnings to raise per expression evaluation. */
296static int warning_limit = 2;
297
298/* Number of warning messages issued; reset to 0 by cleanups after
299 expression evaluation. */
300static int warnings_issued = 0;
301
27087b7f 302static const char * const known_runtime_file_name_patterns[] = {
4c4b4cd2
PH
303 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
304};
305
27087b7f 306static const char * const known_auxiliary_function_name_patterns[] = {
4c4b4cd2
PH
307 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
308};
309
c6044dd1
JB
310/* Maintenance-related settings for this module. */
311
312static struct cmd_list_element *maint_set_ada_cmdlist;
313static struct cmd_list_element *maint_show_ada_cmdlist;
314
c6044dd1
JB
315/* The "maintenance ada set/show ignore-descriptive-type" value. */
316
491144b5 317static bool ada_ignore_descriptive_types_p = false;
c6044dd1 318
e802dbe0
JB
319 /* Inferior-specific data. */
320
321/* Per-inferior data for this module. */
322
323struct ada_inferior_data
324{
325 /* The ada__tags__type_specific_data type, which is used when decoding
326 tagged types. With older versions of GNAT, this type was directly
327 accessible through a component ("tsd") in the object tag. But this
328 is no longer the case, so we cache it for each inferior. */
f37b313d 329 struct type *tsd_type = nullptr;
3eecfa55
JB
330
331 /* The exception_support_info data. This data is used to determine
332 how to implement support for Ada exception catchpoints in a given
333 inferior. */
f37b313d 334 const struct exception_support_info *exception_info = nullptr;
e802dbe0
JB
335};
336
337/* Our key to this module's inferior data. */
08b8a139 338static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
e802dbe0
JB
339
340/* Return our inferior data for the given inferior (INF).
341
342 This function always returns a valid pointer to an allocated
343 ada_inferior_data structure. If INF's inferior data has not
344 been previously set, this functions creates a new one with all
345 fields set to zero, sets INF's inferior to it, and then returns
346 a pointer to that newly allocated ada_inferior_data. */
347
348static struct ada_inferior_data *
349get_ada_inferior_data (struct inferior *inf)
350{
351 struct ada_inferior_data *data;
352
f37b313d 353 data = ada_inferior_data.get (inf);
e802dbe0 354 if (data == NULL)
f37b313d 355 data = ada_inferior_data.emplace (inf);
e802dbe0
JB
356
357 return data;
358}
359
360/* Perform all necessary cleanups regarding our module's inferior data
361 that is required after the inferior INF just exited. */
362
363static void
364ada_inferior_exit (struct inferior *inf)
365{
f37b313d 366 ada_inferior_data.clear (inf);
e802dbe0
JB
367}
368
ee01b665
JB
369
370 /* program-space-specific data. */
371
372/* This module's per-program-space data. */
373struct ada_pspace_data
374{
375 /* The Ada symbol cache. */
bdcccc56 376 std::unique_ptr<ada_symbol_cache> sym_cache;
ee01b665
JB
377};
378
379/* Key to our per-program-space data. */
08b8a139
TT
380static const registry<program_space>::key<ada_pspace_data>
381 ada_pspace_data_handle;
ee01b665
JB
382
383/* Return this module's data for the given program space (PSPACE).
384 If not is found, add a zero'ed one now.
385
386 This function always returns a valid object. */
387
388static struct ada_pspace_data *
389get_ada_pspace_data (struct program_space *pspace)
390{
391 struct ada_pspace_data *data;
392
f37b313d 393 data = ada_pspace_data_handle.get (pspace);
ee01b665 394 if (data == NULL)
f37b313d 395 data = ada_pspace_data_handle.emplace (pspace);
ee01b665
JB
396
397 return data;
398}
399
dda83cd7 400 /* Utilities */
4c4b4cd2 401
720d1a40 402/* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
eed9788b 403 all typedef layers have been peeled. Otherwise, return TYPE.
720d1a40
JB
404
405 Normally, we really expect a typedef type to only have 1 typedef layer.
406 In other words, we really expect the target type of a typedef type to be
407 a non-typedef type. This is particularly true for Ada units, because
408 the language does not have a typedef vs not-typedef distinction.
409 In that respect, the Ada compiler has been trying to eliminate as many
410 typedef definitions in the debugging information, since they generally
411 do not bring any extra information (we still use typedef under certain
412 circumstances related mostly to the GNAT encoding).
413
414 Unfortunately, we have seen situations where the debugging information
415 generated by the compiler leads to such multiple typedef layers. For
416 instance, consider the following example with stabs:
417
418 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
419 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
420
421 This is an error in the debugging information which causes type
422 pck__float_array___XUP to be defined twice, and the second time,
423 it is defined as a typedef of a typedef.
424
425 This is on the fringe of legality as far as debugging information is
426 concerned, and certainly unexpected. But it is easy to handle these
427 situations correctly, so we can afford to be lenient in this case. */
428
429static struct type *
430ada_typedef_target_type (struct type *type)
431{
78134374 432 while (type->code () == TYPE_CODE_TYPEDEF)
27710edb 433 type = type->target_type ();
720d1a40
JB
434 return type;
435}
436
41d27058
JB
437/* Given DECODED_NAME a string holding a symbol name in its
438 decoded form (ie using the Ada dotted notation), returns
439 its unqualified name. */
440
441static const char *
442ada_unqualified_name (const char *decoded_name)
443{
2b0f535a
JB
444 const char *result;
445
446 /* If the decoded name starts with '<', it means that the encoded
447 name does not follow standard naming conventions, and thus that
448 it is not your typical Ada symbol name. Trying to unqualify it
449 is therefore pointless and possibly erroneous. */
450 if (decoded_name[0] == '<')
451 return decoded_name;
452
453 result = strrchr (decoded_name, '.');
41d27058
JB
454 if (result != NULL)
455 result++; /* Skip the dot... */
456 else
457 result = decoded_name;
458
459 return result;
460}
461
39e7af3e 462/* Return a string starting with '<', followed by STR, and '>'. */
41d27058 463
39e7af3e 464static std::string
41d27058
JB
465add_angle_brackets (const char *str)
466{
39e7af3e 467 return string_printf ("<%s>", str);
41d27058 468}
96d887e8 469
14f9c5c9 470/* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
4c4b4cd2 471 suffix of FIELD_NAME beginning "___". */
14f9c5c9
AS
472
473static int
ebf56fd3 474field_name_match (const char *field_name, const char *target)
14f9c5c9
AS
475{
476 int len = strlen (target);
5b4ee69b 477
d2e4a39e 478 return
4c4b4cd2
PH
479 (strncmp (field_name, target, len) == 0
480 && (field_name[len] == '\0'
dda83cd7
SM
481 || (startswith (field_name + len, "___")
482 && strcmp (field_name + strlen (field_name) - 6,
483 "___XVN") != 0)));
14f9c5c9
AS
484}
485
486
872c8b51
JB
487/* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
488 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
489 and return its index. This function also handles fields whose name
490 have ___ suffixes because the compiler sometimes alters their name
491 by adding such a suffix to represent fields with certain constraints.
492 If the field could not be found, return a negative number if
493 MAYBE_MISSING is set. Otherwise raise an error. */
4c4b4cd2
PH
494
495int
496ada_get_field_index (const struct type *type, const char *field_name,
dda83cd7 497 int maybe_missing)
4c4b4cd2
PH
498{
499 int fieldno;
872c8b51
JB
500 struct type *struct_type = check_typedef ((struct type *) type);
501
1f704f76 502 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
33d16dd9 503 if (field_name_match (struct_type->field (fieldno).name (), field_name))
4c4b4cd2
PH
504 return fieldno;
505
506 if (!maybe_missing)
323e0a4a 507 error (_("Unable to find field %s in struct %s. Aborting"),
dda83cd7 508 field_name, struct_type->name ());
4c4b4cd2
PH
509
510 return -1;
511}
512
513/* The length of the prefix of NAME prior to any "___" suffix. */
14f9c5c9
AS
514
515int
d2e4a39e 516ada_name_prefix_len (const char *name)
14f9c5c9
AS
517{
518 if (name == NULL)
519 return 0;
d2e4a39e 520 else
14f9c5c9 521 {
d2e4a39e 522 const char *p = strstr (name, "___");
5b4ee69b 523
14f9c5c9 524 if (p == NULL)
dda83cd7 525 return strlen (name);
14f9c5c9 526 else
dda83cd7 527 return p - name;
14f9c5c9
AS
528 }
529}
530
4c4b4cd2
PH
531/* Return non-zero if SUFFIX is a suffix of STR.
532 Return zero if STR is null. */
533
14f9c5c9 534static int
d2e4a39e 535is_suffix (const char *str, const char *suffix)
14f9c5c9
AS
536{
537 int len1, len2;
5b4ee69b 538
14f9c5c9
AS
539 if (str == NULL)
540 return 0;
541 len1 = strlen (str);
542 len2 = strlen (suffix);
4c4b4cd2 543 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
14f9c5c9
AS
544}
545
4c4b4cd2
PH
546/* The contents of value VAL, treated as a value of type TYPE. The
547 result is an lval in memory if VAL is. */
14f9c5c9 548
d2e4a39e 549static struct value *
4c4b4cd2 550coerce_unspec_val_to_type (struct value *val, struct type *type)
14f9c5c9 551{
61ee279c 552 type = ada_check_typedef (type);
d0c97917 553 if (val->type () == type)
4c4b4cd2 554 return val;
d2e4a39e 555 else
14f9c5c9 556 {
4c4b4cd2
PH
557 struct value *result;
558
d00664db 559 if (val->optimized_out ())
b27556e3 560 result = value::allocate_optimized_out (type);
3ee3b270 561 else if (val->lazy ()
f73e424f 562 /* Be careful not to make a lazy not_lval value. */
736355f2 563 || (val->lval () != not_lval
d0c97917 564 && type->length () > val->type ()->length ()))
cbe793af 565 result = value::allocate_lazy (type);
41e8491f
JK
566 else
567 {
317c3ed9 568 result = value::allocate (type);
6c49729e 569 val->contents_copy (result, 0, 0, type->length ());
41e8491f 570 }
8181b7b6 571 result->set_component_location (val);
f49d5fa2 572 result->set_bitsize (val->bitsize ());
5011c493 573 result->set_bitpos (val->bitpos ());
736355f2 574 if (result->lval () == lval_memory)
9feb2d07 575 result->set_address (val->address ());
14f9c5c9
AS
576 return result;
577 }
578}
579
fc1a4b47
AC
580static const gdb_byte *
581cond_offset_host (const gdb_byte *valaddr, long offset)
14f9c5c9
AS
582{
583 if (valaddr == NULL)
584 return NULL;
585 else
586 return valaddr + offset;
587}
588
589static CORE_ADDR
ebf56fd3 590cond_offset_target (CORE_ADDR address, long offset)
14f9c5c9
AS
591{
592 if (address == 0)
593 return 0;
d2e4a39e 594 else
14f9c5c9
AS
595 return address + offset;
596}
597
4c4b4cd2
PH
598/* Issue a warning (as for the definition of warning in utils.c, but
599 with exactly one argument rather than ...), unless the limit on the
600 number of warnings has passed during the evaluation of the current
601 expression. */
a2249542 602
77109804
AC
603/* FIXME: cagney/2004-10-10: This function is mimicking the behavior
604 provided by "complaint". */
a0b31db1 605static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
77109804 606
14f9c5c9 607static void
a2249542 608lim_warning (const char *format, ...)
14f9c5c9 609{
a2249542 610 va_list args;
a2249542 611
5b4ee69b 612 va_start (args, format);
4c4b4cd2
PH
613 warnings_issued += 1;
614 if (warnings_issued <= warning_limit)
a2249542
MK
615 vwarning (format, args);
616
617 va_end (args);
4c4b4cd2
PH
618}
619
0963b4bd 620/* Maximum value of a SIZE-byte signed integer type. */
4c4b4cd2 621static LONGEST
c3e5cd34 622max_of_size (int size)
4c4b4cd2 623{
76a01679 624 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
5b4ee69b 625
76a01679 626 return top_bit | (top_bit - 1);
4c4b4cd2
PH
627}
628
0963b4bd 629/* Minimum value of a SIZE-byte signed integer type. */
4c4b4cd2 630static LONGEST
c3e5cd34 631min_of_size (int size)
4c4b4cd2 632{
c3e5cd34 633 return -max_of_size (size) - 1;
4c4b4cd2
PH
634}
635
0963b4bd 636/* Maximum value of a SIZE-byte unsigned integer type. */
4c4b4cd2 637static ULONGEST
c3e5cd34 638umax_of_size (int size)
4c4b4cd2 639{
76a01679 640 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
5b4ee69b 641
76a01679 642 return top_bit | (top_bit - 1);
4c4b4cd2
PH
643}
644
0963b4bd 645/* Maximum value of integral type T, as a signed quantity. */
c3e5cd34
PH
646static LONGEST
647max_of_type (struct type *t)
4c4b4cd2 648{
c6d940a9 649 if (t->is_unsigned ())
df86565b 650 return (LONGEST) umax_of_size (t->length ());
c3e5cd34 651 else
df86565b 652 return max_of_size (t->length ());
c3e5cd34
PH
653}
654
0963b4bd 655/* Minimum value of integral type T, as a signed quantity. */
c3e5cd34
PH
656static LONGEST
657min_of_type (struct type *t)
658{
c6d940a9 659 if (t->is_unsigned ())
c3e5cd34
PH
660 return 0;
661 else
df86565b 662 return min_of_size (t->length ());
4c4b4cd2
PH
663}
664
665/* The largest value in the domain of TYPE, a discrete type, as an integer. */
43bbcdc2
PH
666LONGEST
667ada_discrete_type_high_bound (struct type *type)
4c4b4cd2 668{
b249d2c2 669 type = resolve_dynamic_type (type, {}, 0);
78134374 670 switch (type->code ())
4c4b4cd2
PH
671 {
672 case TYPE_CODE_RANGE:
d1fd641e
SM
673 {
674 const dynamic_prop &high = type->bounds ()->high;
675
676 if (high.kind () == PROP_CONST)
677 return high.const_val ();
678 else
679 {
680 gdb_assert (high.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 }
4c4b4cd2 688 case TYPE_CODE_ENUM:
970db518 689 return type->field (type->num_fields () - 1).loc_enumval ();
690cc4eb
PH
690 case TYPE_CODE_BOOL:
691 return 1;
692 case TYPE_CODE_CHAR:
76a01679 693 case TYPE_CODE_INT:
690cc4eb 694 return max_of_type (type);
4c4b4cd2 695 default:
43bbcdc2 696 error (_("Unexpected type in ada_discrete_type_high_bound."));
4c4b4cd2
PH
697 }
698}
699
14e75d8e 700/* The smallest value in the domain of TYPE, a discrete type, as an integer. */
43bbcdc2
PH
701LONGEST
702ada_discrete_type_low_bound (struct type *type)
4c4b4cd2 703{
b249d2c2 704 type = resolve_dynamic_type (type, {}, 0);
78134374 705 switch (type->code ())
4c4b4cd2
PH
706 {
707 case TYPE_CODE_RANGE:
d1fd641e
SM
708 {
709 const dynamic_prop &low = type->bounds ()->low;
710
711 if (low.kind () == PROP_CONST)
712 return low.const_val ();
713 else
714 {
715 gdb_assert (low.kind () == PROP_UNDEFINED);
716
717 /* This happens when trying to evaluate a type's dynamic bound
718 without a live target. There is nothing relevant for us to
719 return here, so return 0. */
720 return 0;
721 }
722 }
4c4b4cd2 723 case TYPE_CODE_ENUM:
970db518 724 return type->field (0).loc_enumval ();
690cc4eb
PH
725 case TYPE_CODE_BOOL:
726 return 0;
727 case TYPE_CODE_CHAR:
76a01679 728 case TYPE_CODE_INT:
690cc4eb 729 return min_of_type (type);
4c4b4cd2 730 default:
43bbcdc2 731 error (_("Unexpected type in ada_discrete_type_low_bound."));
4c4b4cd2
PH
732 }
733}
734
735/* The identity on non-range types. For range types, the underlying
76a01679 736 non-range scalar type. */
4c4b4cd2
PH
737
738static struct type *
18af8284 739get_base_type (struct type *type)
4c4b4cd2 740{
78134374 741 while (type != NULL && type->code () == TYPE_CODE_RANGE)
4c4b4cd2 742 {
27710edb 743 if (type == type->target_type () || type->target_type () == NULL)
dda83cd7 744 return type;
27710edb 745 type = type->target_type ();
4c4b4cd2
PH
746 }
747 return type;
14f9c5c9 748}
41246937
JB
749
750/* Return a decoded version of the given VALUE. This means returning
751 a value whose type is obtained by applying all the GNAT-specific
85102364 752 encodings, making the resulting type a static but standard description
41246937
JB
753 of the initial type. */
754
755struct value *
756ada_get_decoded_value (struct value *value)
757{
d0c97917 758 struct type *type = ada_check_typedef (value->type ());
41246937
JB
759
760 if (ada_is_array_descriptor_type (type)
761 || (ada_is_constrained_packed_array_type (type)
dda83cd7 762 && type->code () != TYPE_CODE_PTR))
41246937 763 {
78134374 764 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
dda83cd7 765 value = ada_coerce_to_simple_array_ptr (value);
41246937 766 else
dda83cd7 767 value = ada_coerce_to_simple_array (value);
41246937
JB
768 }
769 else
770 value = ada_to_fixed_value (value);
771
772 return value;
773}
774
775/* Same as ada_get_decoded_value, but with the given TYPE.
776 Because there is no associated actual value for this type,
777 the resulting type might be a best-effort approximation in
778 the case of dynamic types. */
779
780struct type *
781ada_get_decoded_type (struct type *type)
782{
783 type = to_static_fixed_type (type);
784 if (ada_is_constrained_packed_array_type (type))
785 type = ada_coerce_to_simple_array_type (type);
786 return type;
787}
788
4c4b4cd2 789\f
76a01679 790
dda83cd7 791 /* Language Selection */
14f9c5c9
AS
792
793/* If the main program is in Ada, return language_ada, otherwise return LANG
ccefe4c4 794 (the main program is in Ada iif the adainit symbol is found). */
d2e4a39e 795
de93309a 796static enum language
ccefe4c4 797ada_update_initial_language (enum language lang)
14f9c5c9 798{
cafb3438 799 if (lookup_minimal_symbol ("adainit", NULL, NULL).minsym != NULL)
4c4b4cd2 800 return language_ada;
14f9c5c9
AS
801
802 return lang;
803}
96d887e8
PH
804
805/* If the main procedure is written in Ada, then return its name.
806 The result is good until the next call. Return NULL if the main
807 procedure doesn't appear to be in Ada. */
808
6f63b61d
TT
809const char *
810ada_main_name ()
96d887e8 811{
3b7344d5 812 struct bound_minimal_symbol msym;
e83e4e24 813 static gdb::unique_xmalloc_ptr<char> main_program_name;
6c038f32 814
96d887e8
PH
815 /* For Ada, the name of the main procedure is stored in a specific
816 string constant, generated by the binder. Look for that symbol,
817 extract its address, and then read that string. If we didn't find
818 that string, then most probably the main procedure is not written
819 in Ada. */
820 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
821
3b7344d5 822 if (msym.minsym != NULL)
96d887e8 823 {
4aeddc50 824 CORE_ADDR main_program_name_addr = msym.value_address ();
96d887e8 825 if (main_program_name_addr == 0)
dda83cd7 826 error (_("Invalid address for Ada main program name."));
96d887e8 827
66920317 828 main_program_name = target_read_string (main_program_name_addr, 1024);
e83e4e24 829 return main_program_name.get ();
96d887e8
PH
830 }
831
832 /* The main procedure doesn't seem to be in Ada. */
833 return NULL;
834}
14f9c5c9 835\f
dda83cd7 836 /* Symbols */
d2e4a39e 837
4c4b4cd2
PH
838/* Table of Ada operators and their GNAT-encoded names. Last entry is pair
839 of NULLs. */
14f9c5c9 840
d2e4a39e
AS
841const struct ada_opname_map ada_opname_table[] = {
842 {"Oadd", "\"+\"", BINOP_ADD},
843 {"Osubtract", "\"-\"", BINOP_SUB},
844 {"Omultiply", "\"*\"", BINOP_MUL},
845 {"Odivide", "\"/\"", BINOP_DIV},
846 {"Omod", "\"mod\"", BINOP_MOD},
847 {"Orem", "\"rem\"", BINOP_REM},
848 {"Oexpon", "\"**\"", BINOP_EXP},
849 {"Olt", "\"<\"", BINOP_LESS},
850 {"Ole", "\"<=\"", BINOP_LEQ},
851 {"Ogt", "\">\"", BINOP_GTR},
852 {"Oge", "\">=\"", BINOP_GEQ},
853 {"Oeq", "\"=\"", BINOP_EQUAL},
854 {"One", "\"/=\"", BINOP_NOTEQUAL},
855 {"Oand", "\"and\"", BINOP_BITWISE_AND},
856 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
857 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
858 {"Oconcat", "\"&\"", BINOP_CONCAT},
859 {"Oabs", "\"abs\"", UNOP_ABS},
860 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
861 {"Oadd", "\"+\"", UNOP_PLUS},
862 {"Osubtract", "\"-\"", UNOP_NEG},
863 {NULL, NULL}
14f9c5c9
AS
864};
865
965bc1df
TT
866/* If STR is a decoded version of a compiler-provided suffix (like the
867 "[cold]" in "symbol[cold]"), return true. Otherwise, return
868 false. */
869
870static bool
871is_compiler_suffix (const char *str)
872{
873 gdb_assert (*str == '[');
874 ++str;
875 while (*str != '\0' && isalpha (*str))
876 ++str;
877 /* We accept a missing "]" in order to support completion. */
878 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
879}
880
315e4ebb
TT
881/* Append a non-ASCII character to RESULT. */
882static void
883append_hex_encoded (std::string &result, uint32_t one_char)
884{
885 if (one_char <= 0xff)
886 {
887 result.append ("U");
888 result.append (phex (one_char, 1));
889 }
890 else if (one_char <= 0xffff)
891 {
892 result.append ("W");
893 result.append (phex (one_char, 2));
894 }
895 else
896 {
897 result.append ("WW");
898 result.append (phex (one_char, 4));
899 }
900}
901
902/* Return a string that is a copy of the data in STORAGE, with
903 non-ASCII characters replaced by the appropriate hex encoding. A
904 template is used because, for UTF-8, we actually want to work with
905 UTF-32 codepoints. */
906template<typename T>
907std::string
908copy_and_hex_encode (struct obstack *storage)
909{
910 const T *chars = (T *) obstack_base (storage);
911 int num_chars = obstack_object_size (storage) / sizeof (T);
912 std::string result;
913 for (int i = 0; i < num_chars; ++i)
914 {
915 if (chars[i] <= 0x7f)
916 {
917 /* The host character set has to be a superset of ASCII, as
918 are all the other character sets we can use. */
919 result.push_back (chars[i]);
920 }
921 else
922 append_hex_encoded (result, chars[i]);
923 }
924 return result;
925}
926
5c4258f4 927/* The "encoded" form of DECODED, according to GNAT conventions. If
b5ec771e 928 THROW_ERRORS, throw an error if invalid operator name is found.
5c4258f4 929 Otherwise, return the empty string in that case. */
4c4b4cd2 930
5c4258f4 931static std::string
b5ec771e 932ada_encode_1 (const char *decoded, bool throw_errors)
14f9c5c9 933{
4c4b4cd2 934 if (decoded == NULL)
5c4258f4 935 return {};
14f9c5c9 936
5c4258f4 937 std::string encoding_buffer;
315e4ebb 938 bool saw_non_ascii = false;
5c4258f4 939 for (const char *p = decoded; *p != '\0'; p += 1)
14f9c5c9 940 {
315e4ebb
TT
941 if ((*p & 0x80) != 0)
942 saw_non_ascii = true;
943
cdc7bb92 944 if (*p == '.')
5c4258f4 945 encoding_buffer.append ("__");
965bc1df
TT
946 else if (*p == '[' && is_compiler_suffix (p))
947 {
948 encoding_buffer = encoding_buffer + "." + (p + 1);
949 if (encoding_buffer.back () == ']')
950 encoding_buffer.pop_back ();
951 break;
952 }
14f9c5c9 953 else if (*p == '"')
dda83cd7
SM
954 {
955 const struct ada_opname_map *mapping;
956
957 for (mapping = ada_opname_table;
958 mapping->encoded != NULL
959 && !startswith (p, mapping->decoded); mapping += 1)
960 ;
961 if (mapping->encoded == NULL)
b5ec771e
PA
962 {
963 if (throw_errors)
964 error (_("invalid Ada operator name: %s"), p);
965 else
5c4258f4 966 return {};
b5ec771e 967 }
5c4258f4 968 encoding_buffer.append (mapping->encoded);
dda83cd7
SM
969 break;
970 }
d2e4a39e 971 else
5c4258f4 972 encoding_buffer.push_back (*p);
14f9c5c9
AS
973 }
974
315e4ebb
TT
975 /* If a non-ASCII character is seen, we must convert it to the
976 appropriate hex form. As this is more expensive, we keep track
977 of whether it is even necessary. */
978 if (saw_non_ascii)
979 {
980 auto_obstack storage;
981 bool is_utf8 = ada_source_charset == ada_utf8;
982 try
983 {
984 convert_between_encodings
985 (host_charset (),
986 is_utf8 ? HOST_UTF32 : ada_source_charset,
987 (const gdb_byte *) encoding_buffer.c_str (),
988 encoding_buffer.length (), 1,
989 &storage, translit_none);
990 }
991 catch (const gdb_exception &)
992 {
993 static bool warned = false;
994
995 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
996 might like to know why. */
997 if (!warned)
998 {
999 warned = true;
1000 warning (_("charset conversion failure for '%s'.\n"
1001 "You may have the wrong value for 'set ada source-charset'."),
1002 encoding_buffer.c_str ());
1003 }
1004
1005 /* We don't try to recover from errors. */
1006 return encoding_buffer;
1007 }
1008
1009 if (is_utf8)
1010 return copy_and_hex_encode<uint32_t> (&storage);
1011 return copy_and_hex_encode<gdb_byte> (&storage);
1012 }
1013
4c4b4cd2 1014 return encoding_buffer;
14f9c5c9
AS
1015}
1016
315e4ebb
TT
1017/* Find the entry for C in the case-folding table. Return nullptr if
1018 the entry does not cover C. */
1019static const utf8_entry *
1020find_case_fold_entry (uint32_t c)
b5ec771e 1021{
315e4ebb
TT
1022 auto iter = std::lower_bound (std::begin (ada_case_fold),
1023 std::end (ada_case_fold),
1024 c);
1025 if (iter == std::end (ada_case_fold)
1026 || c < iter->start
1027 || c > iter->end)
1028 return nullptr;
1029 return &*iter;
b5ec771e
PA
1030}
1031
14f9c5c9 1032/* Return NAME folded to lower case, or, if surrounded by single
315e4ebb
TT
1033 quotes, unfolded, but with the quotes stripped away. If
1034 THROW_ON_ERROR is true, encoding failures will throw an exception
1035 rather than emitting a warning. Result good to next call. */
4c4b4cd2 1036
5f9febe0 1037static const char *
315e4ebb 1038ada_fold_name (gdb::string_view name, bool throw_on_error = false)
14f9c5c9 1039{
5f9febe0 1040 static std::string fold_storage;
14f9c5c9 1041
6a780b67 1042 if (!name.empty () && name[0] == '\'')
01573d73 1043 fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
14f9c5c9
AS
1044 else
1045 {
315e4ebb
TT
1046 /* Why convert to UTF-32 and implement our own case-folding,
1047 rather than convert to wchar_t and use the platform's
1048 functions? I'm glad you asked.
1049
1050 The main problem is that GNAT implements an unusual rule for
1051 case folding. For ASCII letters, letters in single-byte
1052 encodings (such as ISO-8859-*), and Unicode letters that fit
1053 in a single byte (i.e., code point is <= 0xff), the letter is
1054 folded to lower case. Other Unicode letters are folded to
1055 upper case.
1056
1057 This rule means that the code must be able to examine the
1058 value of the character. And, some hosts do not use Unicode
1059 for wchar_t, so examining the value of such characters is
1060 forbidden. */
1061 auto_obstack storage;
1062 try
1063 {
1064 convert_between_encodings
1065 (host_charset (), HOST_UTF32,
1066 (const gdb_byte *) name.data (),
1067 name.length (), 1,
1068 &storage, translit_none);
1069 }
1070 catch (const gdb_exception &)
1071 {
1072 if (throw_on_error)
1073 throw;
1074
1075 static bool warned = false;
1076
1077 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1078 might like to know why. */
1079 if (!warned)
1080 {
1081 warned = true;
1082 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1083 "This normally should not happen, please file a bug report."),
1084 gdb::to_string (name).c_str (), host_charset ());
1085 }
1086
1087 /* We don't try to recover from errors; just return the
1088 original string. */
1089 fold_storage = gdb::to_string (name);
1090 return fold_storage.c_str ();
1091 }
1092
1093 bool is_utf8 = ada_source_charset == ada_utf8;
1094 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1095 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1096 for (int i = 0; i < num_chars; ++i)
1097 {
1098 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1099 if (entry != nullptr)
1100 {
1101 uint32_t low = chars[i] + entry->lower_delta;
1102 if (!is_utf8 || low <= 0xff)
1103 chars[i] = low;
1104 else
1105 chars[i] = chars[i] + entry->upper_delta;
1106 }
1107 }
1108
1109 /* Now convert back to ordinary characters. */
1110 auto_obstack reconverted;
1111 try
1112 {
1113 convert_between_encodings (HOST_UTF32,
1114 host_charset (),
1115 (const gdb_byte *) chars,
1116 num_chars * sizeof (uint32_t),
1117 sizeof (uint32_t),
1118 &reconverted,
1119 translit_none);
1120 obstack_1grow (&reconverted, '\0');
1121 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1122 }
1123 catch (const gdb_exception &)
1124 {
1125 if (throw_on_error)
1126 throw;
1127
1128 static bool warned = false;
1129
1130 /* Converting back from UTF-32 shouldn't normally fail, but
1131 there are some host encodings without upper/lower
1132 equivalence. */
1133 if (!warned)
1134 {
1135 warned = true;
1136 warning (_("could not convert the lower-cased variant of '%s'\n"
1137 "from UTF-32 to the host encoding (%s)."),
1138 gdb::to_string (name).c_str (), host_charset ());
1139 }
1140
1141 /* We don't try to recover from errors; just return the
1142 original string. */
1143 fold_storage = gdb::to_string (name);
1144 }
14f9c5c9
AS
1145 }
1146
5f9febe0 1147 return fold_storage.c_str ();
14f9c5c9
AS
1148}
1149
5fea9794
TT
1150/* The "encoded" form of DECODED, according to GNAT conventions. If
1151 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1152 with <...> quoting are not folded in any case. */
315e4ebb
TT
1153
1154std::string
5fea9794 1155ada_encode (const char *decoded, bool fold)
315e4ebb 1156{
5fea9794 1157 if (fold && decoded[0] != '<')
315e4ebb
TT
1158 decoded = ada_fold_name (decoded);
1159 return ada_encode_1 (decoded, true);
1160}
1161
529cad9c
PH
1162/* Return nonzero if C is either a digit or a lowercase alphabet character. */
1163
1164static int
1165is_lower_alphanum (const char c)
1166{
1167 return (isdigit (c) || (isalpha (c) && islower (c)));
1168}
1169
c90092fe
JB
1170/* ENCODED is the linkage name of a symbol and LEN contains its length.
1171 This function saves in LEN the length of that same symbol name but
1172 without either of these suffixes:
29480c32
JB
1173 . .{DIGIT}+
1174 . ${DIGIT}+
1175 . ___{DIGIT}+
1176 . __{DIGIT}+.
c90092fe 1177
29480c32
JB
1178 These are suffixes introduced by the compiler for entities such as
1179 nested subprogram for instance, in order to avoid name clashes.
1180 They do not serve any purpose for the debugger. */
1181
1182static void
1183ada_remove_trailing_digits (const char *encoded, int *len)
1184{
1185 if (*len > 1 && isdigit (encoded[*len - 1]))
1186 {
1187 int i = *len - 2;
5b4ee69b 1188
29480c32 1189 while (i > 0 && isdigit (encoded[i]))
dda83cd7 1190 i--;
29480c32 1191 if (i >= 0 && encoded[i] == '.')
dda83cd7 1192 *len = i;
29480c32 1193 else if (i >= 0 && encoded[i] == '$')
dda83cd7 1194 *len = i;
61012eef 1195 else if (i >= 2 && startswith (encoded + i - 2, "___"))
dda83cd7 1196 *len = i - 2;
61012eef 1197 else if (i >= 1 && startswith (encoded + i - 1, "__"))
dda83cd7 1198 *len = i - 1;
29480c32
JB
1199 }
1200}
1201
1202/* Remove the suffix introduced by the compiler for protected object
1203 subprograms. */
1204
1205static void
1206ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1207{
1208 /* Remove trailing N. */
1209
1210 /* Protected entry subprograms are broken into two
1211 separate subprograms: The first one is unprotected, and has
1212 a 'N' suffix; the second is the protected version, and has
0963b4bd 1213 the 'P' suffix. The second calls the first one after handling
29480c32
JB
1214 the protection. Since the P subprograms are internally generated,
1215 we leave these names undecoded, giving the user a clue that this
1216 entity is internal. */
1217
1218 if (*len > 1
1219 && encoded[*len - 1] == 'N'
1220 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1221 *len = *len - 1;
1222}
1223
965bc1df
TT
1224/* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1225 then update *LEN to remove the suffix and return the offset of the
1226 character just past the ".". Otherwise, return -1. */
1227
1228static int
1229remove_compiler_suffix (const char *encoded, int *len)
1230{
1231 int offset = *len - 1;
1232 while (offset > 0 && isalpha (encoded[offset]))
1233 --offset;
1234 if (offset > 0 && encoded[offset] == '.')
1235 {
1236 *len = offset;
1237 return offset + 1;
1238 }
1239 return -1;
1240}
1241
315e4ebb
TT
1242/* Convert an ASCII hex string to a number. Reads exactly N
1243 characters from STR. Returns true on success, false if one of the
1244 digits was not a hex digit. */
1245static bool
1246convert_hex (const char *str, int n, uint32_t *out)
1247{
1248 uint32_t result = 0;
1249
1250 for (int i = 0; i < n; ++i)
1251 {
1252 if (!isxdigit (str[i]))
1253 return false;
1254 result <<= 4;
1255 result |= fromhex (str[i]);
1256 }
1257
1258 *out = result;
1259 return true;
1260}
1261
1262/* Convert a wide character from its ASCII hex representation in STR
1263 (consisting of exactly N characters) to the host encoding,
1264 appending the resulting bytes to OUT. If N==2 and the Ada source
1265 charset is not UTF-8, then hex refers to an encoding in the
1266 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1267 Return false and do not modify OUT on conversion failure. */
1268static bool
1269convert_from_hex_encoded (std::string &out, const char *str, int n)
1270{
1271 uint32_t value;
1272
1273 if (!convert_hex (str, n, &value))
1274 return false;
1275 try
1276 {
1277 auto_obstack bytes;
1278 /* In the 'U' case, the hex digits encode the character in the
1279 Ada source charset. However, if the source charset is UTF-8,
1280 this really means it is a single-byte UTF-32 character. */
1281 if (n == 2 && ada_source_charset != ada_utf8)
1282 {
1283 gdb_byte one_char = (gdb_byte) value;
1284
1285 convert_between_encodings (ada_source_charset, host_charset (),
1286 &one_char,
1287 sizeof (one_char), sizeof (one_char),
1288 &bytes, translit_none);
1289 }
1290 else
1291 convert_between_encodings (HOST_UTF32, host_charset (),
1292 (const gdb_byte *) &value,
1293 sizeof (value), sizeof (value),
1294 &bytes, translit_none);
1295 obstack_1grow (&bytes, '\0');
1296 out.append ((const char *) obstack_base (&bytes));
1297 }
1298 catch (const gdb_exception &)
1299 {
1300 /* On failure, the caller will just let the encoded form
1301 through, which seems basically reasonable. */
1302 return false;
1303 }
1304
1305 return true;
1306}
1307
8a3df5ac 1308/* See ada-lang.h. */
14f9c5c9 1309
f945dedf 1310std::string
5c94f938 1311ada_decode (const char *encoded, bool wrap, bool operators)
14f9c5c9 1312{
36f5ca53 1313 int i;
14f9c5c9 1314 int len0;
d2e4a39e 1315 const char *p;
14f9c5c9 1316 int at_start_name;
f945dedf 1317 std::string decoded;
965bc1df 1318 int suffix = -1;
d2e4a39e 1319
0d81f350
JG
1320 /* With function descriptors on PPC64, the value of a symbol named
1321 ".FN", if it exists, is the entry point of the function "FN". */
1322 if (encoded[0] == '.')
1323 encoded += 1;
1324
29480c32
JB
1325 /* The name of the Ada main procedure starts with "_ada_".
1326 This prefix is not part of the decoded name, so skip this part
1327 if we see this prefix. */
61012eef 1328 if (startswith (encoded, "_ada_"))
4c4b4cd2 1329 encoded += 5;
81eaa506
TT
1330 /* The "___ghost_" prefix is used for ghost entities. Normally
1331 these aren't preserved but when they are, it's useful to see
1332 them. */
1333 if (startswith (encoded, "___ghost_"))
1334 encoded += 9;
14f9c5c9 1335
29480c32
JB
1336 /* If the name starts with '_', then it is not a properly encoded
1337 name, so do not attempt to decode it. Similarly, if the name
1338 starts with '<', the name should not be decoded. */
4c4b4cd2 1339 if (encoded[0] == '_' || encoded[0] == '<')
14f9c5c9
AS
1340 goto Suppress;
1341
4c4b4cd2 1342 len0 = strlen (encoded);
4c4b4cd2 1343
965bc1df
TT
1344 suffix = remove_compiler_suffix (encoded, &len0);
1345
29480c32
JB
1346 ada_remove_trailing_digits (encoded, &len0);
1347 ada_remove_po_subprogram_suffix (encoded, &len0);
529cad9c 1348
4c4b4cd2
PH
1349 /* Remove the ___X.* suffix if present. Do not forget to verify that
1350 the suffix is located before the current "end" of ENCODED. We want
1351 to avoid re-matching parts of ENCODED that have previously been
1352 marked as discarded (by decrementing LEN0). */
1353 p = strstr (encoded, "___");
1354 if (p != NULL && p - encoded < len0 - 3)
14f9c5c9
AS
1355 {
1356 if (p[3] == 'X')
dda83cd7 1357 len0 = p - encoded;
14f9c5c9 1358 else
dda83cd7 1359 goto Suppress;
14f9c5c9 1360 }
4c4b4cd2 1361
29480c32
JB
1362 /* Remove any trailing TKB suffix. It tells us that this symbol
1363 is for the body of a task, but that information does not actually
1364 appear in the decoded name. */
1365
61012eef 1366 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
14f9c5c9 1367 len0 -= 3;
76a01679 1368
a10967fa
JB
1369 /* Remove any trailing TB suffix. The TB suffix is slightly different
1370 from the TKB suffix because it is used for non-anonymous task
1371 bodies. */
1372
61012eef 1373 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
a10967fa
JB
1374 len0 -= 2;
1375
29480c32
JB
1376 /* Remove trailing "B" suffixes. */
1377 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1378
61012eef 1379 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
14f9c5c9
AS
1380 len0 -= 1;
1381
29480c32
JB
1382 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1383
4c4b4cd2 1384 if (len0 > 1 && isdigit (encoded[len0 - 1]))
d2e4a39e 1385 {
4c4b4cd2
PH
1386 i = len0 - 2;
1387 while ((i >= 0 && isdigit (encoded[i]))
dda83cd7
SM
1388 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1389 i -= 1;
4c4b4cd2 1390 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
dda83cd7 1391 len0 = i - 1;
4c4b4cd2 1392 else if (encoded[i] == '$')
dda83cd7 1393 len0 = i;
d2e4a39e 1394 }
14f9c5c9 1395
29480c32
JB
1396 /* The first few characters that are not alphabetic are not part
1397 of any encoding we use, so we can copy them over verbatim. */
1398
36f5ca53
TT
1399 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1400 decoded.push_back (encoded[i]);
14f9c5c9
AS
1401
1402 at_start_name = 1;
1403 while (i < len0)
1404 {
29480c32 1405 /* Is this a symbol function? */
5c94f938 1406 if (operators && at_start_name && encoded[i] == 'O')
dda83cd7
SM
1407 {
1408 int k;
1409
1410 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1411 {
1412 int op_len = strlen (ada_opname_table[k].encoded);
1413 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1414 op_len - 1) == 0)
1415 && !isalnum (encoded[i + op_len]))
1416 {
36f5ca53 1417 decoded.append (ada_opname_table[k].decoded);
dda83cd7
SM
1418 at_start_name = 0;
1419 i += op_len;
dda83cd7
SM
1420 break;
1421 }
1422 }
1423 if (ada_opname_table[k].encoded != NULL)
1424 continue;
1425 }
14f9c5c9
AS
1426 at_start_name = 0;
1427
529cad9c 1428 /* Replace "TK__" with "__", which will eventually be translated
dda83cd7 1429 into "." (just below). */
529cad9c 1430
61012eef 1431 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
dda83cd7 1432 i += 2;
529cad9c 1433
29480c32 1434 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
dda83cd7
SM
1435 be translated into "." (just below). These are internal names
1436 generated for anonymous blocks inside which our symbol is nested. */
29480c32
JB
1437
1438 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
dda83cd7
SM
1439 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1440 && isdigit (encoded [i+4]))
1441 {
1442 int k = i + 5;
1443
1444 while (k < len0 && isdigit (encoded[k]))
1445 k++; /* Skip any extra digit. */
1446
1447 /* Double-check that the "__B_{DIGITS}+" sequence we found
1448 is indeed followed by "__". */
1449 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1450 i = k;
1451 }
29480c32 1452
529cad9c
PH
1453 /* Remove _E{DIGITS}+[sb] */
1454
1455 /* Just as for protected object subprograms, there are 2 categories
dda83cd7
SM
1456 of subprograms created by the compiler for each entry. The first
1457 one implements the actual entry code, and has a suffix following
1458 the convention above; the second one implements the barrier and
1459 uses the same convention as above, except that the 'E' is replaced
1460 by a 'B'.
529cad9c 1461
dda83cd7
SM
1462 Just as above, we do not decode the name of barrier functions
1463 to give the user a clue that the code he is debugging has been
1464 internally generated. */
529cad9c
PH
1465
1466 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
dda83cd7
SM
1467 && isdigit (encoded[i+2]))
1468 {
1469 int k = i + 3;
1470
1471 while (k < len0 && isdigit (encoded[k]))
1472 k++;
1473
1474 if (k < len0
1475 && (encoded[k] == 'b' || encoded[k] == 's'))
1476 {
1477 k++;
1478 /* Just as an extra precaution, make sure that if this
1479 suffix is followed by anything else, it is a '_'.
1480 Otherwise, we matched this sequence by accident. */
1481 if (k == len0
1482 || (k < len0 && encoded[k] == '_'))
1483 i = k;
1484 }
1485 }
529cad9c
PH
1486
1487 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
dda83cd7 1488 the GNAT front-end in protected object subprograms. */
529cad9c
PH
1489
1490 if (i < len0 + 3
dda83cd7
SM
1491 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1492 {
1493 /* Backtrack a bit up until we reach either the begining of
1494 the encoded name, or "__". Make sure that we only find
1495 digits or lowercase characters. */
1496 const char *ptr = encoded + i - 1;
1497
1498 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1499 ptr--;
1500 if (ptr < encoded
1501 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1502 i++;
1503 }
529cad9c 1504
315e4ebb
TT
1505 if (i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1506 {
1507 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1508 {
1509 i += 3;
1510 continue;
1511 }
1512 }
1513 else if (i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1514 {
1515 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1516 {
1517 i += 5;
1518 continue;
1519 }
1520 }
1521 else if (i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1522 && isxdigit (encoded[i + 2]))
1523 {
1524 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1525 {
1526 i += 10;
1527 continue;
1528 }
1529 }
1530
4c4b4cd2 1531 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
dda83cd7
SM
1532 {
1533 /* This is a X[bn]* sequence not separated from the previous
1534 part of the name with a non-alpha-numeric character (in other
1535 words, immediately following an alpha-numeric character), then
1536 verify that it is placed at the end of the encoded name. If
1537 not, then the encoding is not valid and we should abort the
1538 decoding. Otherwise, just skip it, it is used in body-nested
1539 package names. */
1540 do
1541 i += 1;
1542 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1543 if (i < len0)
1544 goto Suppress;
1545 }
cdc7bb92 1546 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
dda83cd7
SM
1547 {
1548 /* Replace '__' by '.'. */
36f5ca53 1549 decoded.push_back ('.');
dda83cd7
SM
1550 at_start_name = 1;
1551 i += 2;
dda83cd7 1552 }
14f9c5c9 1553 else
dda83cd7
SM
1554 {
1555 /* It's a character part of the decoded name, so just copy it
1556 over. */
36f5ca53 1557 decoded.push_back (encoded[i]);
dda83cd7 1558 i += 1;
dda83cd7 1559 }
14f9c5c9 1560 }
14f9c5c9 1561
29480c32
JB
1562 /* Decoded names should never contain any uppercase character.
1563 Double-check this, and abort the decoding if we find one. */
1564
5c94f938
TT
1565 if (operators)
1566 {
1567 for (i = 0; i < decoded.length(); ++i)
1568 if (isupper (decoded[i]) || decoded[i] == ' ')
1569 goto Suppress;
1570 }
14f9c5c9 1571
965bc1df
TT
1572 /* If the compiler added a suffix, append it now. */
1573 if (suffix >= 0)
1574 decoded = decoded + "[" + &encoded[suffix] + "]";
1575
f945dedf 1576 return decoded;
14f9c5c9
AS
1577
1578Suppress:
8a3df5ac
TT
1579 if (!wrap)
1580 return {};
1581
4c4b4cd2 1582 if (encoded[0] == '<')
f945dedf 1583 decoded = encoded;
14f9c5c9 1584 else
f945dedf 1585 decoded = '<' + std::string(encoded) + '>';
4c4b4cd2 1586 return decoded;
4c4b4cd2
PH
1587}
1588
1589/* Table for keeping permanent unique copies of decoded names. Once
1590 allocated, names in this table are never released. While this is a
1591 storage leak, it should not be significant unless there are massive
1592 changes in the set of decoded names in successive versions of a
1593 symbol table loaded during a single session. */
1594static struct htab *decoded_names_store;
1595
1596/* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1597 in the language-specific part of GSYMBOL, if it has not been
1598 previously computed. Tries to save the decoded name in the same
1599 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1600 in any case, the decoded symbol has a lifetime at least that of
0963b4bd 1601 GSYMBOL).
4c4b4cd2
PH
1602 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1603 const, but nevertheless modified to a semantically equivalent form
0963b4bd 1604 when a decoded name is cached in it. */
4c4b4cd2 1605
45e6c716 1606const char *
f85f34ed 1607ada_decode_symbol (const struct general_symbol_info *arg)
4c4b4cd2 1608{
f85f34ed
TT
1609 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1610 const char **resultp =
615b3f62 1611 &gsymbol->language_specific.demangled_name;
5b4ee69b 1612
f85f34ed 1613 if (!gsymbol->ada_mangled)
4c4b4cd2 1614 {
4d4eaa30 1615 std::string decoded = ada_decode (gsymbol->linkage_name ());
f85f34ed 1616 struct obstack *obstack = gsymbol->language_specific.obstack;
5b4ee69b 1617
f85f34ed 1618 gsymbol->ada_mangled = 1;
5b4ee69b 1619
f85f34ed 1620 if (obstack != NULL)
f945dedf 1621 *resultp = obstack_strdup (obstack, decoded.c_str ());
f85f34ed 1622 else
dda83cd7 1623 {
f85f34ed
TT
1624 /* Sometimes, we can't find a corresponding objfile, in
1625 which case, we put the result on the heap. Since we only
1626 decode when needed, we hope this usually does not cause a
1627 significant memory leak (FIXME). */
1628
dda83cd7
SM
1629 char **slot = (char **) htab_find_slot (decoded_names_store,
1630 decoded.c_str (), INSERT);
5b4ee69b 1631
dda83cd7
SM
1632 if (*slot == NULL)
1633 *slot = xstrdup (decoded.c_str ());
1634 *resultp = *slot;
1635 }
4c4b4cd2 1636 }
14f9c5c9 1637
4c4b4cd2
PH
1638 return *resultp;
1639}
76a01679 1640
14f9c5c9 1641\f
d2e4a39e 1642
dda83cd7 1643 /* Arrays */
14f9c5c9 1644
28c85d6c
JB
1645/* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1646 generated by the GNAT compiler to describe the index type used
1647 for each dimension of an array, check whether it follows the latest
1648 known encoding. If not, fix it up to conform to the latest encoding.
1649 Otherwise, do nothing. This function also does nothing if
1650 INDEX_DESC_TYPE is NULL.
1651
85102364 1652 The GNAT encoding used to describe the array index type evolved a bit.
28c85d6c
JB
1653 Initially, the information would be provided through the name of each
1654 field of the structure type only, while the type of these fields was
1655 described as unspecified and irrelevant. The debugger was then expected
1656 to perform a global type lookup using the name of that field in order
1657 to get access to the full index type description. Because these global
1658 lookups can be very expensive, the encoding was later enhanced to make
1659 the global lookup unnecessary by defining the field type as being
1660 the full index type description.
1661
1662 The purpose of this routine is to allow us to support older versions
1663 of the compiler by detecting the use of the older encoding, and by
1664 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1665 we essentially replace each field's meaningless type by the associated
1666 index subtype). */
1667
1668void
1669ada_fixup_array_indexes_type (struct type *index_desc_type)
1670{
1671 int i;
1672
1673 if (index_desc_type == NULL)
1674 return;
1f704f76 1675 gdb_assert (index_desc_type->num_fields () > 0);
28c85d6c
JB
1676
1677 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1678 to check one field only, no need to check them all). If not, return
1679 now.
1680
1681 If our INDEX_DESC_TYPE was generated using the older encoding,
1682 the field type should be a meaningless integer type whose name
1683 is not equal to the field name. */
940da03e
SM
1684 if (index_desc_type->field (0).type ()->name () != NULL
1685 && strcmp (index_desc_type->field (0).type ()->name (),
33d16dd9 1686 index_desc_type->field (0).name ()) == 0)
28c85d6c
JB
1687 return;
1688
1689 /* Fixup each field of INDEX_DESC_TYPE. */
1f704f76 1690 for (i = 0; i < index_desc_type->num_fields (); i++)
28c85d6c 1691 {
33d16dd9 1692 const char *name = index_desc_type->field (i).name ();
28c85d6c
JB
1693 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1694
1695 if (raw_type)
5d14b6e5 1696 index_desc_type->field (i).set_type (raw_type);
28c85d6c
JB
1697 }
1698}
1699
4c4b4cd2
PH
1700/* The desc_* routines return primitive portions of array descriptors
1701 (fat pointers). */
14f9c5c9
AS
1702
1703/* The descriptor or array type, if any, indicated by TYPE; removes
4c4b4cd2
PH
1704 level of indirection, if needed. */
1705
d2e4a39e
AS
1706static struct type *
1707desc_base_type (struct type *type)
14f9c5c9
AS
1708{
1709 if (type == NULL)
1710 return NULL;
61ee279c 1711 type = ada_check_typedef (type);
78134374 1712 if (type->code () == TYPE_CODE_TYPEDEF)
720d1a40
JB
1713 type = ada_typedef_target_type (type);
1714
1265e4aa 1715 if (type != NULL
78134374 1716 && (type->code () == TYPE_CODE_PTR
dda83cd7 1717 || type->code () == TYPE_CODE_REF))
27710edb 1718 return ada_check_typedef (type->target_type ());
14f9c5c9
AS
1719 else
1720 return type;
1721}
1722
4c4b4cd2
PH
1723/* True iff TYPE indicates a "thin" array pointer type. */
1724
14f9c5c9 1725static int
d2e4a39e 1726is_thin_pntr (struct type *type)
14f9c5c9 1727{
d2e4a39e 1728 return
14f9c5c9
AS
1729 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1730 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1731}
1732
4c4b4cd2
PH
1733/* The descriptor type for thin pointer type TYPE. */
1734
d2e4a39e
AS
1735static struct type *
1736thin_descriptor_type (struct type *type)
14f9c5c9 1737{
d2e4a39e 1738 struct type *base_type = desc_base_type (type);
5b4ee69b 1739
14f9c5c9
AS
1740 if (base_type == NULL)
1741 return NULL;
1742 if (is_suffix (ada_type_name (base_type), "___XVE"))
1743 return base_type;
d2e4a39e 1744 else
14f9c5c9 1745 {
d2e4a39e 1746 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
5b4ee69b 1747
14f9c5c9 1748 if (alt_type == NULL)
dda83cd7 1749 return base_type;
14f9c5c9 1750 else
dda83cd7 1751 return alt_type;
14f9c5c9
AS
1752 }
1753}
1754
4c4b4cd2
PH
1755/* A pointer to the array data for thin-pointer value VAL. */
1756
d2e4a39e
AS
1757static struct value *
1758thin_data_pntr (struct value *val)
14f9c5c9 1759{
d0c97917 1760 struct type *type = ada_check_typedef (val->type ());
556bdfd4 1761 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
5b4ee69b 1762
556bdfd4
UW
1763 data_type = lookup_pointer_type (data_type);
1764
78134374 1765 if (type->code () == TYPE_CODE_PTR)
cda03344 1766 return value_cast (data_type, val->copy ());
d2e4a39e 1767 else
9feb2d07 1768 return value_from_longest (data_type, val->address ());
14f9c5c9
AS
1769}
1770
4c4b4cd2
PH
1771/* True iff TYPE indicates a "thick" array pointer type. */
1772
14f9c5c9 1773static int
d2e4a39e 1774is_thick_pntr (struct type *type)
14f9c5c9
AS
1775{
1776 type = desc_base_type (type);
78134374 1777 return (type != NULL && type->code () == TYPE_CODE_STRUCT
dda83cd7 1778 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
14f9c5c9
AS
1779}
1780
4c4b4cd2
PH
1781/* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1782 pointer to one, the type of its bounds data; otherwise, NULL. */
76a01679 1783
d2e4a39e
AS
1784static struct type *
1785desc_bounds_type (struct type *type)
14f9c5c9 1786{
d2e4a39e 1787 struct type *r;
14f9c5c9
AS
1788
1789 type = desc_base_type (type);
1790
1791 if (type == NULL)
1792 return NULL;
1793 else if (is_thin_pntr (type))
1794 {
1795 type = thin_descriptor_type (type);
1796 if (type == NULL)
dda83cd7 1797 return NULL;
14f9c5c9
AS
1798 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1799 if (r != NULL)
dda83cd7 1800 return ada_check_typedef (r);
14f9c5c9 1801 }
78134374 1802 else if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9
AS
1803 {
1804 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1805 if (r != NULL)
27710edb 1806 return ada_check_typedef (ada_check_typedef (r)->target_type ());
14f9c5c9
AS
1807 }
1808 return NULL;
1809}
1810
1811/* If ARR is an array descriptor (fat or thin pointer), or pointer to
4c4b4cd2
PH
1812 one, a pointer to its bounds data. Otherwise NULL. */
1813
d2e4a39e
AS
1814static struct value *
1815desc_bounds (struct value *arr)
14f9c5c9 1816{
d0c97917 1817 struct type *type = ada_check_typedef (arr->type ());
5b4ee69b 1818
d2e4a39e 1819 if (is_thin_pntr (type))
14f9c5c9 1820 {
d2e4a39e 1821 struct type *bounds_type =
dda83cd7 1822 desc_bounds_type (thin_descriptor_type (type));
14f9c5c9
AS
1823 LONGEST addr;
1824
4cdfadb1 1825 if (bounds_type == NULL)
dda83cd7 1826 error (_("Bad GNAT array descriptor"));
14f9c5c9
AS
1827
1828 /* NOTE: The following calculation is not really kosher, but
dda83cd7
SM
1829 since desc_type is an XVE-encoded type (and shouldn't be),
1830 the correct calculation is a real pain. FIXME (and fix GCC). */
78134374 1831 if (type->code () == TYPE_CODE_PTR)
dda83cd7 1832 addr = value_as_long (arr);
d2e4a39e 1833 else
9feb2d07 1834 addr = arr->address ();
14f9c5c9 1835
d2e4a39e 1836 return
dda83cd7 1837 value_from_longest (lookup_pointer_type (bounds_type),
df86565b 1838 addr - bounds_type->length ());
14f9c5c9
AS
1839 }
1840
1841 else if (is_thick_pntr (type))
05e522ef 1842 {
158cc4fe 1843 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
05e522ef 1844 _("Bad GNAT array descriptor"));
d0c97917 1845 struct type *p_bounds_type = p_bounds->type ();
05e522ef
JB
1846
1847 if (p_bounds_type
78134374 1848 && p_bounds_type->code () == TYPE_CODE_PTR)
05e522ef 1849 {
27710edb 1850 struct type *target_type = p_bounds_type->target_type ();
05e522ef 1851
e46d3488 1852 if (target_type->is_stub ())
05e522ef
JB
1853 p_bounds = value_cast (lookup_pointer_type
1854 (ada_check_typedef (target_type)),
1855 p_bounds);
1856 }
1857 else
1858 error (_("Bad GNAT array descriptor"));
1859
1860 return p_bounds;
1861 }
14f9c5c9
AS
1862 else
1863 return NULL;
1864}
1865
4c4b4cd2
PH
1866/* If TYPE is the type of an array-descriptor (fat pointer), the bit
1867 position of the field containing the address of the bounds data. */
1868
14f9c5c9 1869static int
d2e4a39e 1870fat_pntr_bounds_bitpos (struct type *type)
14f9c5c9 1871{
b610c045 1872 return desc_base_type (type)->field (1).loc_bitpos ();
14f9c5c9
AS
1873}
1874
1875/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1876 size of the field containing the address of the bounds data. */
1877
14f9c5c9 1878static int
d2e4a39e 1879fat_pntr_bounds_bitsize (struct type *type)
14f9c5c9
AS
1880{
1881 type = desc_base_type (type);
1882
d2e4a39e 1883 if (TYPE_FIELD_BITSIZE (type, 1) > 0)
14f9c5c9
AS
1884 return TYPE_FIELD_BITSIZE (type, 1);
1885 else
df86565b 1886 return 8 * ada_check_typedef (type->field (1).type ())->length ();
14f9c5c9
AS
1887}
1888
4c4b4cd2 1889/* If TYPE is the type of an array descriptor (fat or thin pointer) or a
556bdfd4
UW
1890 pointer to one, the type of its array data (a array-with-no-bounds type);
1891 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1892 data. */
4c4b4cd2 1893
d2e4a39e 1894static struct type *
556bdfd4 1895desc_data_target_type (struct type *type)
14f9c5c9
AS
1896{
1897 type = desc_base_type (type);
1898
4c4b4cd2 1899 /* NOTE: The following is bogus; see comment in desc_bounds. */
14f9c5c9 1900 if (is_thin_pntr (type))
940da03e 1901 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
14f9c5c9 1902 else if (is_thick_pntr (type))
556bdfd4
UW
1903 {
1904 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1905
1906 if (data_type
78134374 1907 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
27710edb 1908 return ada_check_typedef (data_type->target_type ());
556bdfd4
UW
1909 }
1910
1911 return NULL;
14f9c5c9
AS
1912}
1913
1914/* If ARR is an array descriptor (fat or thin pointer), a pointer to
1915 its array data. */
4c4b4cd2 1916
d2e4a39e
AS
1917static struct value *
1918desc_data (struct value *arr)
14f9c5c9 1919{
d0c97917 1920 struct type *type = arr->type ();
5b4ee69b 1921
14f9c5c9
AS
1922 if (is_thin_pntr (type))
1923 return thin_data_pntr (arr);
1924 else if (is_thick_pntr (type))
158cc4fe 1925 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
dda83cd7 1926 _("Bad GNAT array descriptor"));
14f9c5c9
AS
1927 else
1928 return NULL;
1929}
1930
1931
1932/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1933 position of the field containing the address of the data. */
1934
14f9c5c9 1935static int
d2e4a39e 1936fat_pntr_data_bitpos (struct type *type)
14f9c5c9 1937{
b610c045 1938 return desc_base_type (type)->field (0).loc_bitpos ();
14f9c5c9
AS
1939}
1940
1941/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1942 size of the field containing the address of the data. */
1943
14f9c5c9 1944static int
d2e4a39e 1945fat_pntr_data_bitsize (struct type *type)
14f9c5c9
AS
1946{
1947 type = desc_base_type (type);
1948
1949 if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1950 return TYPE_FIELD_BITSIZE (type, 0);
d2e4a39e 1951 else
df86565b 1952 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
14f9c5c9
AS
1953}
1954
4c4b4cd2 1955/* If BOUNDS is an array-bounds structure (or pointer to one), return
14f9c5c9 1956 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1957 bound, if WHICH is 1. The first bound is I=1. */
1958
d2e4a39e
AS
1959static struct value *
1960desc_one_bound (struct value *bounds, int i, int which)
14f9c5c9 1961{
250106a7
TT
1962 char bound_name[20];
1963 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1964 which ? 'U' : 'L', i - 1);
158cc4fe 1965 return value_struct_elt (&bounds, {}, bound_name, NULL,
dda83cd7 1966 _("Bad GNAT array descriptor bounds"));
14f9c5c9
AS
1967}
1968
1969/* If BOUNDS is an array-bounds structure type, return the bit position
1970 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1971 bound, if WHICH is 1. The first bound is I=1. */
1972
14f9c5c9 1973static int
d2e4a39e 1974desc_bound_bitpos (struct type *type, int i, int which)
14f9c5c9 1975{
b610c045 1976 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
14f9c5c9
AS
1977}
1978
1979/* If BOUNDS is an array-bounds structure type, return the bit field size
1980 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1981 bound, if WHICH is 1. The first bound is I=1. */
1982
76a01679 1983static int
d2e4a39e 1984desc_bound_bitsize (struct type *type, int i, int which)
14f9c5c9
AS
1985{
1986 type = desc_base_type (type);
1987
d2e4a39e
AS
1988 if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1989 return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1990 else
df86565b 1991 return 8 * type->field (2 * i + which - 2).type ()->length ();
14f9c5c9
AS
1992}
1993
1994/* If TYPE is the type of an array-bounds structure, the type of its
4c4b4cd2
PH
1995 Ith bound (numbering from 1). Otherwise, NULL. */
1996
d2e4a39e
AS
1997static struct type *
1998desc_index_type (struct type *type, int i)
14f9c5c9
AS
1999{
2000 type = desc_base_type (type);
2001
78134374 2002 if (type->code () == TYPE_CODE_STRUCT)
250106a7
TT
2003 {
2004 char bound_name[20];
2005 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2006 return lookup_struct_elt_type (type, bound_name, 1);
2007 }
d2e4a39e 2008 else
14f9c5c9
AS
2009 return NULL;
2010}
2011
4c4b4cd2
PH
2012/* The number of index positions in the array-bounds type TYPE.
2013 Return 0 if TYPE is NULL. */
2014
14f9c5c9 2015static int
d2e4a39e 2016desc_arity (struct type *type)
14f9c5c9
AS
2017{
2018 type = desc_base_type (type);
2019
2020 if (type != NULL)
1f704f76 2021 return type->num_fields () / 2;
14f9c5c9
AS
2022 return 0;
2023}
2024
4c4b4cd2
PH
2025/* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2026 an array descriptor type (representing an unconstrained array
2027 type). */
2028
76a01679
JB
2029static int
2030ada_is_direct_array_type (struct type *type)
4c4b4cd2
PH
2031{
2032 if (type == NULL)
2033 return 0;
61ee279c 2034 type = ada_check_typedef (type);
78134374 2035 return (type->code () == TYPE_CODE_ARRAY
dda83cd7 2036 || ada_is_array_descriptor_type (type));
4c4b4cd2
PH
2037}
2038
52ce6436 2039/* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
0963b4bd 2040 * to one. */
52ce6436 2041
2c0b251b 2042static int
52ce6436
PH
2043ada_is_array_type (struct type *type)
2044{
78134374
SM
2045 while (type != NULL
2046 && (type->code () == TYPE_CODE_PTR
2047 || type->code () == TYPE_CODE_REF))
27710edb 2048 type = type->target_type ();
52ce6436
PH
2049 return ada_is_direct_array_type (type);
2050}
2051
4c4b4cd2 2052/* Non-zero iff TYPE is a simple array type or pointer to one. */
14f9c5c9 2053
14f9c5c9 2054int
4c4b4cd2 2055ada_is_simple_array_type (struct type *type)
14f9c5c9
AS
2056{
2057 if (type == NULL)
2058 return 0;
61ee279c 2059 type = ada_check_typedef (type);
78134374
SM
2060 return (type->code () == TYPE_CODE_ARRAY
2061 || (type->code () == TYPE_CODE_PTR
27710edb 2062 && (ada_check_typedef (type->target_type ())->code ()
78134374 2063 == TYPE_CODE_ARRAY)));
14f9c5c9
AS
2064}
2065
4c4b4cd2
PH
2066/* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2067
14f9c5c9 2068int
4c4b4cd2 2069ada_is_array_descriptor_type (struct type *type)
14f9c5c9 2070{
556bdfd4 2071 struct type *data_type = desc_data_target_type (type);
14f9c5c9
AS
2072
2073 if (type == NULL)
2074 return 0;
61ee279c 2075 type = ada_check_typedef (type);
556bdfd4 2076 return (data_type != NULL
78134374 2077 && data_type->code () == TYPE_CODE_ARRAY
556bdfd4 2078 && desc_arity (desc_bounds_type (type)) > 0);
14f9c5c9
AS
2079}
2080
2081/* Non-zero iff type is a partially mal-formed GNAT array
4c4b4cd2 2082 descriptor. FIXME: This is to compensate for some problems with
14f9c5c9 2083 debugging output from GNAT. Re-examine periodically to see if it
4c4b4cd2
PH
2084 is still needed. */
2085
14f9c5c9 2086int
ebf56fd3 2087ada_is_bogus_array_descriptor (struct type *type)
14f9c5c9 2088{
d2e4a39e 2089 return
14f9c5c9 2090 type != NULL
78134374 2091 && type->code () == TYPE_CODE_STRUCT
14f9c5c9 2092 && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
dda83cd7 2093 || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
4c4b4cd2 2094 && !ada_is_array_descriptor_type (type);
14f9c5c9
AS
2095}
2096
2097
4c4b4cd2 2098/* If ARR has a record type in the form of a standard GNAT array descriptor,
14f9c5c9 2099 (fat pointer) returns the type of the array data described---specifically,
4c4b4cd2 2100 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
14f9c5c9 2101 in from the descriptor; otherwise, they are left unspecified. If
4c4b4cd2
PH
2102 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2103 returns NULL. The result is simply the type of ARR if ARR is not
14f9c5c9 2104 a descriptor. */
de93309a
SM
2105
2106static struct type *
d2e4a39e 2107ada_type_of_array (struct value *arr, int bounds)
14f9c5c9 2108{
d0c97917
TT
2109 if (ada_is_constrained_packed_array_type (arr->type ()))
2110 return decode_constrained_packed_array_type (arr->type ());
14f9c5c9 2111
d0c97917
TT
2112 if (!ada_is_array_descriptor_type (arr->type ()))
2113 return arr->type ();
d2e4a39e
AS
2114
2115 if (!bounds)
ad82864c
JB
2116 {
2117 struct type *array_type =
d0c97917 2118 ada_check_typedef (desc_data_target_type (arr->type ()));
ad82864c 2119
d0c97917 2120 if (ada_is_unconstrained_packed_array_type (arr->type ()))
ad82864c 2121 TYPE_FIELD_BITSIZE (array_type, 0) =
d0c97917 2122 decode_packed_array_bitsize (arr->type ());
ad82864c
JB
2123
2124 return array_type;
2125 }
14f9c5c9
AS
2126 else
2127 {
d2e4a39e 2128 struct type *elt_type;
14f9c5c9 2129 int arity;
d2e4a39e 2130 struct value *descriptor;
14f9c5c9 2131
d0c97917
TT
2132 elt_type = ada_array_element_type (arr->type (), -1);
2133 arity = ada_array_arity (arr->type ());
14f9c5c9 2134
d2e4a39e 2135 if (elt_type == NULL || arity == 0)
d0c97917 2136 return ada_check_typedef (arr->type ());
14f9c5c9
AS
2137
2138 descriptor = desc_bounds (arr);
d2e4a39e 2139 if (value_as_long (descriptor) == 0)
dda83cd7 2140 return NULL;
d2e4a39e 2141 while (arity > 0)
dda83cd7 2142 {
9fa83a7a
TT
2143 type_allocator alloc (arr->type ());
2144 struct type *range_type = alloc.new_type ();
2145 struct type *array_type = alloc.new_type ();
dda83cd7
SM
2146 struct value *low = desc_one_bound (descriptor, arity, 0);
2147 struct value *high = desc_one_bound (descriptor, arity, 1);
2148
2149 arity -= 1;
d0c97917 2150 create_static_range_type (range_type, low->type (),
0c9c3474
SA
2151 longest_to_int (value_as_long (low)),
2152 longest_to_int (value_as_long (high)));
dda83cd7 2153 elt_type = create_array_type (array_type, elt_type, range_type);
ad82864c 2154
d0c97917 2155 if (ada_is_unconstrained_packed_array_type (arr->type ()))
e67ad678
JB
2156 {
2157 /* We need to store the element packed bitsize, as well as
dda83cd7 2158 recompute the array size, because it was previously
e67ad678
JB
2159 computed based on the unpacked element size. */
2160 LONGEST lo = value_as_long (low);
2161 LONGEST hi = value_as_long (high);
2162
2163 TYPE_FIELD_BITSIZE (elt_type, 0) =
d0c97917 2164 decode_packed_array_bitsize (arr->type ());
e67ad678 2165 /* If the array has no element, then the size is already
dda83cd7 2166 zero, and does not need to be recomputed. */
e67ad678
JB
2167 if (lo < hi)
2168 {
2169 int array_bitsize =
dda83cd7 2170 (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
e67ad678 2171
b6cdbc9a 2172 array_type->set_length ((array_bitsize + 7) / 8);
e67ad678
JB
2173 }
2174 }
dda83cd7 2175 }
14f9c5c9
AS
2176
2177 return lookup_pointer_type (elt_type);
2178 }
2179}
2180
2181/* If ARR does not represent an array, returns ARR unchanged.
4c4b4cd2
PH
2182 Otherwise, returns either a standard GDB array with bounds set
2183 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2184 GDB array. Returns NULL if ARR is a null fat pointer. */
2185
d2e4a39e
AS
2186struct value *
2187ada_coerce_to_simple_array_ptr (struct value *arr)
14f9c5c9 2188{
d0c97917 2189 if (ada_is_array_descriptor_type (arr->type ()))
14f9c5c9 2190 {
d2e4a39e 2191 struct type *arrType = ada_type_of_array (arr, 1);
5b4ee69b 2192
14f9c5c9 2193 if (arrType == NULL)
dda83cd7 2194 return NULL;
cda03344 2195 return value_cast (arrType, desc_data (arr)->copy ());
14f9c5c9 2196 }
d0c97917 2197 else if (ada_is_constrained_packed_array_type (arr->type ()))
ad82864c 2198 return decode_constrained_packed_array (arr);
14f9c5c9
AS
2199 else
2200 return arr;
2201}
2202
2203/* If ARR does not represent an array, returns ARR unchanged.
2204 Otherwise, returns a standard GDB array describing ARR (which may
4c4b4cd2
PH
2205 be ARR itself if it already is in the proper form). */
2206
720d1a40 2207struct value *
d2e4a39e 2208ada_coerce_to_simple_array (struct value *arr)
14f9c5c9 2209{
d0c97917 2210 if (ada_is_array_descriptor_type (arr->type ()))
14f9c5c9 2211 {
d2e4a39e 2212 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
5b4ee69b 2213
14f9c5c9 2214 if (arrVal == NULL)
dda83cd7 2215 error (_("Bounds unavailable for null array pointer."));
14f9c5c9
AS
2216 return value_ind (arrVal);
2217 }
d0c97917 2218 else if (ada_is_constrained_packed_array_type (arr->type ()))
ad82864c 2219 return decode_constrained_packed_array (arr);
d2e4a39e 2220 else
14f9c5c9
AS
2221 return arr;
2222}
2223
2224/* If TYPE represents a GNAT array type, return it translated to an
2225 ordinary GDB array type (possibly with BITSIZE fields indicating
4c4b4cd2
PH
2226 packing). For other types, is the identity. */
2227
d2e4a39e
AS
2228struct type *
2229ada_coerce_to_simple_array_type (struct type *type)
14f9c5c9 2230{
ad82864c
JB
2231 if (ada_is_constrained_packed_array_type (type))
2232 return decode_constrained_packed_array_type (type);
17280b9f
UW
2233
2234 if (ada_is_array_descriptor_type (type))
556bdfd4 2235 return ada_check_typedef (desc_data_target_type (type));
17280b9f
UW
2236
2237 return type;
14f9c5c9
AS
2238}
2239
4c4b4cd2
PH
2240/* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2241
ad82864c 2242static int
57567375 2243ada_is_gnat_encoded_packed_array_type (struct type *type)
14f9c5c9
AS
2244{
2245 if (type == NULL)
2246 return 0;
4c4b4cd2 2247 type = desc_base_type (type);
61ee279c 2248 type = ada_check_typedef (type);
d2e4a39e 2249 return
14f9c5c9
AS
2250 ada_type_name (type) != NULL
2251 && strstr (ada_type_name (type), "___XP") != NULL;
2252}
2253
ad82864c
JB
2254/* Non-zero iff TYPE represents a standard GNAT constrained
2255 packed-array type. */
2256
2257int
2258ada_is_constrained_packed_array_type (struct type *type)
2259{
57567375 2260 return ada_is_gnat_encoded_packed_array_type (type)
ad82864c
JB
2261 && !ada_is_array_descriptor_type (type);
2262}
2263
2264/* Non-zero iff TYPE represents an array descriptor for a
2265 unconstrained packed-array type. */
2266
2267static int
2268ada_is_unconstrained_packed_array_type (struct type *type)
2269{
57567375
TT
2270 if (!ada_is_array_descriptor_type (type))
2271 return 0;
2272
2273 if (ada_is_gnat_encoded_packed_array_type (type))
2274 return 1;
2275
2276 /* If we saw GNAT encodings, then the above code is sufficient.
2277 However, with minimal encodings, we will just have a thick
2278 pointer instead. */
2279 if (is_thick_pntr (type))
2280 {
2281 type = desc_base_type (type);
2282 /* The structure's first field is a pointer to an array, so this
2283 fetches the array type. */
27710edb 2284 type = type->field (0).type ()->target_type ();
af5300fe
TV
2285 if (type->code () == TYPE_CODE_TYPEDEF)
2286 type = ada_typedef_target_type (type);
57567375
TT
2287 /* Now we can see if the array elements are packed. */
2288 return TYPE_FIELD_BITSIZE (type, 0) > 0;
2289 }
2290
2291 return 0;
ad82864c
JB
2292}
2293
c9a28cbe
TT
2294/* Return true if TYPE is a (Gnat-encoded) constrained packed array
2295 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2296
2297static bool
2298ada_is_any_packed_array_type (struct type *type)
2299{
2300 return (ada_is_constrained_packed_array_type (type)
2301 || (type->code () == TYPE_CODE_ARRAY
2302 && TYPE_FIELD_BITSIZE (type, 0) % 8 != 0));
2303}
2304
ad82864c
JB
2305/* Given that TYPE encodes a packed array type (constrained or unconstrained),
2306 return the size of its elements in bits. */
2307
2308static long
2309decode_packed_array_bitsize (struct type *type)
2310{
0d5cff50
DE
2311 const char *raw_name;
2312 const char *tail;
ad82864c
JB
2313 long bits;
2314
720d1a40
JB
2315 /* Access to arrays implemented as fat pointers are encoded as a typedef
2316 of the fat pointer type. We need the name of the fat pointer type
2317 to do the decoding, so strip the typedef layer. */
78134374 2318 if (type->code () == TYPE_CODE_TYPEDEF)
720d1a40
JB
2319 type = ada_typedef_target_type (type);
2320
2321 raw_name = ada_type_name (ada_check_typedef (type));
ad82864c
JB
2322 if (!raw_name)
2323 raw_name = ada_type_name (desc_base_type (type));
2324
2325 if (!raw_name)
2326 return 0;
2327
2328 tail = strstr (raw_name, "___XP");
57567375
TT
2329 if (tail == nullptr)
2330 {
2331 gdb_assert (is_thick_pntr (type));
2332 /* The structure's first field is a pointer to an array, so this
2333 fetches the array type. */
27710edb 2334 type = type->field (0).type ()->target_type ();
57567375
TT
2335 /* Now we can see if the array elements are packed. */
2336 return TYPE_FIELD_BITSIZE (type, 0);
2337 }
ad82864c
JB
2338
2339 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2340 {
2341 lim_warning
2342 (_("could not understand bit size information on packed array"));
2343 return 0;
2344 }
2345
2346 return bits;
2347}
2348
14f9c5c9
AS
2349/* Given that TYPE is a standard GDB array type with all bounds filled
2350 in, and that the element size of its ultimate scalar constituents
2351 (that is, either its elements, or, if it is an array of arrays, its
2352 elements' elements, etc.) is *ELT_BITS, return an identical type,
2353 but with the bit sizes of its elements (and those of any
2354 constituent arrays) recorded in the BITSIZE components of its
4c4b4cd2 2355 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
4a46959e
JB
2356 in bits.
2357
2358 Note that, for arrays whose index type has an XA encoding where
2359 a bound references a record discriminant, getting that discriminant,
2360 and therefore the actual value of that bound, is not possible
2361 because none of the given parameters gives us access to the record.
2362 This function assumes that it is OK in the context where it is being
2363 used to return an array whose bounds are still dynamic and where
2364 the length is arbitrary. */
4c4b4cd2 2365
d2e4a39e 2366static struct type *
ad82864c 2367constrained_packed_array_type (struct type *type, long *elt_bits)
14f9c5c9 2368{
d2e4a39e
AS
2369 struct type *new_elt_type;
2370 struct type *new_type;
99b1c762
JB
2371 struct type *index_type_desc;
2372 struct type *index_type;
14f9c5c9
AS
2373 LONGEST low_bound, high_bound;
2374
61ee279c 2375 type = ada_check_typedef (type);
78134374 2376 if (type->code () != TYPE_CODE_ARRAY)
14f9c5c9
AS
2377 return type;
2378
99b1c762
JB
2379 index_type_desc = ada_find_parallel_type (type, "___XA");
2380 if (index_type_desc)
940da03e 2381 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
99b1c762
JB
2382 NULL);
2383 else
3d967001 2384 index_type = type->index_type ();
99b1c762 2385
9fa83a7a 2386 new_type = type_allocator (type).new_type ();
ad82864c 2387 new_elt_type =
27710edb 2388 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
ad82864c 2389 elt_bits);
99b1c762 2390 create_array_type (new_type, new_elt_type, index_type);
14f9c5c9 2391 TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
d0e39ea2 2392 new_type->set_name (ada_type_name (type));
14f9c5c9 2393
78134374 2394 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
4a46959e 2395 && is_dynamic_type (check_typedef (index_type)))
1f8d2881 2396 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
14f9c5c9
AS
2397 low_bound = high_bound = 0;
2398 if (high_bound < low_bound)
b6cdbc9a
SM
2399 {
2400 *elt_bits = 0;
2401 new_type->set_length (0);
2402 }
d2e4a39e 2403 else
14f9c5c9
AS
2404 {
2405 *elt_bits *= (high_bound - low_bound + 1);
b6cdbc9a 2406 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
14f9c5c9
AS
2407 }
2408
9cdd0d12 2409 new_type->set_is_fixed_instance (true);
14f9c5c9
AS
2410 return new_type;
2411}
2412
ad82864c
JB
2413/* The array type encoded by TYPE, where
2414 ada_is_constrained_packed_array_type (TYPE). */
4c4b4cd2 2415
d2e4a39e 2416static struct type *
ad82864c 2417decode_constrained_packed_array_type (struct type *type)
d2e4a39e 2418{
0d5cff50 2419 const char *raw_name = ada_type_name (ada_check_typedef (type));
727e3d2e 2420 char *name;
0d5cff50 2421 const char *tail;
d2e4a39e 2422 struct type *shadow_type;
14f9c5c9 2423 long bits;
14f9c5c9 2424
727e3d2e
JB
2425 if (!raw_name)
2426 raw_name = ada_type_name (desc_base_type (type));
2427
2428 if (!raw_name)
2429 return NULL;
2430
2431 name = (char *) alloca (strlen (raw_name) + 1);
2432 tail = strstr (raw_name, "___XP");
4c4b4cd2
PH
2433 type = desc_base_type (type);
2434
14f9c5c9
AS
2435 memcpy (name, raw_name, tail - raw_name);
2436 name[tail - raw_name] = '\000';
2437
b4ba55a1
JB
2438 shadow_type = ada_find_parallel_type_with_name (type, name);
2439
2440 if (shadow_type == NULL)
14f9c5c9 2441 {
323e0a4a 2442 lim_warning (_("could not find bounds information on packed array"));
14f9c5c9
AS
2443 return NULL;
2444 }
f168693b 2445 shadow_type = check_typedef (shadow_type);
14f9c5c9 2446
78134374 2447 if (shadow_type->code () != TYPE_CODE_ARRAY)
14f9c5c9 2448 {
0963b4bd
MS
2449 lim_warning (_("could not understand bounds "
2450 "information on packed array"));
14f9c5c9
AS
2451 return NULL;
2452 }
d2e4a39e 2453
ad82864c
JB
2454 bits = decode_packed_array_bitsize (type);
2455 return constrained_packed_array_type (shadow_type, &bits);
14f9c5c9
AS
2456}
2457
a7400e44
TT
2458/* Helper function for decode_constrained_packed_array. Set the field
2459 bitsize on a series of packed arrays. Returns the number of
2460 elements in TYPE. */
2461
2462static LONGEST
2463recursively_update_array_bitsize (struct type *type)
2464{
2465 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2466
2467 LONGEST low, high;
1f8d2881 2468 if (!get_discrete_bounds (type->index_type (), &low, &high)
a7400e44
TT
2469 || low > high)
2470 return 0;
2471 LONGEST our_len = high - low + 1;
2472
27710edb 2473 struct type *elt_type = type->target_type ();
a7400e44
TT
2474 if (elt_type->code () == TYPE_CODE_ARRAY)
2475 {
2476 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
2477 LONGEST elt_bitsize = elt_len * TYPE_FIELD_BITSIZE (elt_type, 0);
2478 TYPE_FIELD_BITSIZE (type, 0) = elt_bitsize;
2479
b6cdbc9a
SM
2480 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2481 / HOST_CHAR_BIT));
a7400e44
TT
2482 }
2483
2484 return our_len;
2485}
2486
ad82864c
JB
2487/* Given that ARR is a struct value *indicating a GNAT constrained packed
2488 array, returns a simple array that denotes that array. Its type is a
14f9c5c9
AS
2489 standard GDB array type except that the BITSIZEs of the array
2490 target types are set to the number of bits in each element, and the
4c4b4cd2 2491 type length is set appropriately. */
14f9c5c9 2492
d2e4a39e 2493static struct value *
ad82864c 2494decode_constrained_packed_array (struct value *arr)
14f9c5c9 2495{
4c4b4cd2 2496 struct type *type;
14f9c5c9 2497
11aa919a
PMR
2498 /* If our value is a pointer, then dereference it. Likewise if
2499 the value is a reference. Make sure that this operation does not
2500 cause the target type to be fixed, as this would indirectly cause
2501 this array to be decoded. The rest of the routine assumes that
2502 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2503 and "value_ind" routines to perform the dereferencing, as opposed
2504 to using "ada_coerce_ref" or "ada_value_ind". */
2505 arr = coerce_ref (arr);
d0c97917 2506 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
284614f0 2507 arr = value_ind (arr);
4c4b4cd2 2508
d0c97917 2509 type = decode_constrained_packed_array_type (arr->type ());
14f9c5c9
AS
2510 if (type == NULL)
2511 {
323e0a4a 2512 error (_("can't unpack array"));
14f9c5c9
AS
2513 return NULL;
2514 }
61ee279c 2515
a7400e44
TT
2516 /* Decoding the packed array type could not correctly set the field
2517 bitsizes for any dimension except the innermost, because the
2518 bounds may be variable and were not passed to that function. So,
2519 we further resolve the array bounds here and then update the
2520 sizes. */
efaf1ae0 2521 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
9feb2d07 2522 CORE_ADDR address = arr->address ();
a7400e44 2523 gdb::array_view<const gdb_byte> view
df86565b 2524 = gdb::make_array_view (valaddr, type->length ());
a7400e44
TT
2525 type = resolve_dynamic_type (type, view, address);
2526 recursively_update_array_bitsize (type);
2527
d0c97917
TT
2528 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2529 && ada_is_modular_type (arr->type ()))
61ee279c
PH
2530 {
2531 /* This is a (right-justified) modular type representing a packed
24b21115
SM
2532 array with no wrapper. In order to interpret the value through
2533 the (left-justified) packed array type we just built, we must
2534 first left-justify it. */
61ee279c
PH
2535 int bit_size, bit_pos;
2536 ULONGEST mod;
2537
d0c97917 2538 mod = ada_modulus (arr->type ()) - 1;
61ee279c
PH
2539 bit_size = 0;
2540 while (mod > 0)
2541 {
2542 bit_size += 1;
2543 mod >>= 1;
2544 }
d0c97917 2545 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
61ee279c
PH
2546 arr = ada_value_primitive_packed_val (arr, NULL,
2547 bit_pos / HOST_CHAR_BIT,
2548 bit_pos % HOST_CHAR_BIT,
2549 bit_size,
2550 type);
2551 }
2552
4c4b4cd2 2553 return coerce_unspec_val_to_type (arr, type);
14f9c5c9
AS
2554}
2555
2556
2557/* The value of the element of packed array ARR at the ARITY indices
4c4b4cd2 2558 given in IND. ARR must be a simple array. */
14f9c5c9 2559
d2e4a39e
AS
2560static struct value *
2561value_subscript_packed (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
2562{
2563 int i;
2564 int bits, elt_off, bit_off;
2565 long elt_total_bit_offset;
d2e4a39e
AS
2566 struct type *elt_type;
2567 struct value *v;
14f9c5c9
AS
2568
2569 bits = 0;
2570 elt_total_bit_offset = 0;
d0c97917 2571 elt_type = ada_check_typedef (arr->type ());
d2e4a39e 2572 for (i = 0; i < arity; i += 1)
14f9c5c9 2573 {
78134374 2574 if (elt_type->code () != TYPE_CODE_ARRAY
dda83cd7
SM
2575 || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2576 error
2577 (_("attempt to do packed indexing of "
0963b4bd 2578 "something other than a packed array"));
14f9c5c9 2579 else
dda83cd7
SM
2580 {
2581 struct type *range_type = elt_type->index_type ();
2582 LONGEST lowerbound, upperbound;
2583 LONGEST idx;
2584
1f8d2881 2585 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
dda83cd7
SM
2586 {
2587 lim_warning (_("don't know bounds of array"));
2588 lowerbound = upperbound = 0;
2589 }
2590
2591 idx = pos_atr (ind[i]);
2592 if (idx < lowerbound || idx > upperbound)
2593 lim_warning (_("packed array index %ld out of bounds"),
0963b4bd 2594 (long) idx);
dda83cd7
SM
2595 bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2596 elt_total_bit_offset += (idx - lowerbound) * bits;
27710edb 2597 elt_type = ada_check_typedef (elt_type->target_type ());
dda83cd7 2598 }
14f9c5c9
AS
2599 }
2600 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2601 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
d2e4a39e
AS
2602
2603 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
dda83cd7 2604 bits, elt_type);
14f9c5c9
AS
2605 return v;
2606}
2607
4c4b4cd2 2608/* Non-zero iff TYPE includes negative integer values. */
14f9c5c9
AS
2609
2610static int
d2e4a39e 2611has_negatives (struct type *type)
14f9c5c9 2612{
78134374 2613 switch (type->code ())
d2e4a39e
AS
2614 {
2615 default:
2616 return 0;
2617 case TYPE_CODE_INT:
c6d940a9 2618 return !type->is_unsigned ();
d2e4a39e 2619 case TYPE_CODE_RANGE:
5537ddd0 2620 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
d2e4a39e 2621 }
14f9c5c9 2622}
d2e4a39e 2623
f93fca70 2624/* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
5b639dea 2625 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
f93fca70 2626 the unpacked buffer.
14f9c5c9 2627
5b639dea
JB
2628 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2629 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2630
f93fca70
JB
2631 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2632 zero otherwise.
14f9c5c9 2633
f93fca70 2634 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
a1c95e6b 2635
f93fca70
JB
2636 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2637
2638static void
2639ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2640 gdb_byte *unpacked, int unpacked_len,
2641 int is_big_endian, int is_signed_type,
2642 int is_scalar)
2643{
a1c95e6b
JB
2644 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2645 int src_idx; /* Index into the source area */
2646 int src_bytes_left; /* Number of source bytes left to process. */
2647 int srcBitsLeft; /* Number of source bits left to move */
2648 int unusedLS; /* Number of bits in next significant
dda83cd7 2649 byte of source that are unused */
a1c95e6b 2650
a1c95e6b
JB
2651 int unpacked_idx; /* Index into the unpacked buffer */
2652 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2653
4c4b4cd2 2654 unsigned long accum; /* Staging area for bits being transferred */
a1c95e6b 2655 int accumSize; /* Number of meaningful bits in accum */
14f9c5c9 2656 unsigned char sign;
a1c95e6b 2657
4c4b4cd2
PH
2658 /* Transmit bytes from least to most significant; delta is the direction
2659 the indices move. */
f93fca70 2660 int delta = is_big_endian ? -1 : 1;
14f9c5c9 2661
5b639dea
JB
2662 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2663 bits from SRC. .*/
2664 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2665 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2666 bit_size, unpacked_len);
2667
14f9c5c9 2668 srcBitsLeft = bit_size;
086ca51f 2669 src_bytes_left = src_len;
f93fca70 2670 unpacked_bytes_left = unpacked_len;
14f9c5c9 2671 sign = 0;
f93fca70
JB
2672
2673 if (is_big_endian)
14f9c5c9 2674 {
086ca51f 2675 src_idx = src_len - 1;
f93fca70
JB
2676 if (is_signed_type
2677 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
dda83cd7 2678 sign = ~0;
d2e4a39e
AS
2679
2680 unusedLS =
dda83cd7
SM
2681 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2682 % HOST_CHAR_BIT;
14f9c5c9 2683
f93fca70
JB
2684 if (is_scalar)
2685 {
dda83cd7
SM
2686 accumSize = 0;
2687 unpacked_idx = unpacked_len - 1;
f93fca70
JB
2688 }
2689 else
2690 {
dda83cd7
SM
2691 /* Non-scalar values must be aligned at a byte boundary... */
2692 accumSize =
2693 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2694 /* ... And are placed at the beginning (most-significant) bytes
2695 of the target. */
2696 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2697 unpacked_bytes_left = unpacked_idx + 1;
f93fca70 2698 }
14f9c5c9 2699 }
d2e4a39e 2700 else
14f9c5c9
AS
2701 {
2702 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2703
086ca51f 2704 src_idx = unpacked_idx = 0;
14f9c5c9
AS
2705 unusedLS = bit_offset;
2706 accumSize = 0;
2707
f93fca70 2708 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
dda83cd7 2709 sign = ~0;
14f9c5c9 2710 }
d2e4a39e 2711
14f9c5c9 2712 accum = 0;
086ca51f 2713 while (src_bytes_left > 0)
14f9c5c9
AS
2714 {
2715 /* Mask for removing bits of the next source byte that are not
dda83cd7 2716 part of the value. */
d2e4a39e 2717 unsigned int unusedMSMask =
dda83cd7
SM
2718 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2719 1;
4c4b4cd2 2720 /* Sign-extend bits for this byte. */
14f9c5c9 2721 unsigned int signMask = sign & ~unusedMSMask;
5b4ee69b 2722
d2e4a39e 2723 accum |=
dda83cd7 2724 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
14f9c5c9 2725 accumSize += HOST_CHAR_BIT - unusedLS;
d2e4a39e 2726 if (accumSize >= HOST_CHAR_BIT)
dda83cd7
SM
2727 {
2728 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2729 accumSize -= HOST_CHAR_BIT;
2730 accum >>= HOST_CHAR_BIT;
2731 unpacked_bytes_left -= 1;
2732 unpacked_idx += delta;
2733 }
14f9c5c9
AS
2734 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2735 unusedLS = 0;
086ca51f
JB
2736 src_bytes_left -= 1;
2737 src_idx += delta;
14f9c5c9 2738 }
086ca51f 2739 while (unpacked_bytes_left > 0)
14f9c5c9
AS
2740 {
2741 accum |= sign << accumSize;
db297a65 2742 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
14f9c5c9 2743 accumSize -= HOST_CHAR_BIT;
9cd4d857
JB
2744 if (accumSize < 0)
2745 accumSize = 0;
14f9c5c9 2746 accum >>= HOST_CHAR_BIT;
086ca51f
JB
2747 unpacked_bytes_left -= 1;
2748 unpacked_idx += delta;
14f9c5c9 2749 }
f93fca70
JB
2750}
2751
2752/* Create a new value of type TYPE from the contents of OBJ starting
2753 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2754 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2755 assigning through the result will set the field fetched from.
2756 VALADDR is ignored unless OBJ is NULL, in which case,
2757 VALADDR+OFFSET must address the start of storage containing the
2758 packed value. The value returned in this case is never an lval.
2759 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2760
2761struct value *
2762ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2763 long offset, int bit_offset, int bit_size,
dda83cd7 2764 struct type *type)
f93fca70
JB
2765{
2766 struct value *v;
bfb1c796 2767 const gdb_byte *src; /* First byte containing data to unpack */
f93fca70 2768 gdb_byte *unpacked;
220475ed 2769 const int is_scalar = is_scalar_type (type);
d5a22e77 2770 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
d5722aa2 2771 gdb::byte_vector staging;
f93fca70
JB
2772
2773 type = ada_check_typedef (type);
2774
d0a9e810 2775 if (obj == NULL)
bfb1c796 2776 src = valaddr + offset;
d0a9e810 2777 else
efaf1ae0 2778 src = obj->contents ().data () + offset;
d0a9e810
JB
2779
2780 if (is_dynamic_type (type))
2781 {
2782 /* The length of TYPE might by dynamic, so we need to resolve
2783 TYPE in order to know its actual size, which we then use
2784 to create the contents buffer of the value we return.
2785 The difficulty is that the data containing our object is
2786 packed, and therefore maybe not at a byte boundary. So, what
2787 we do, is unpack the data into a byte-aligned buffer, and then
2788 use that buffer as our object's value for resolving the type. */
d5722aa2
PA
2789 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2790 staging.resize (staging_len);
d0a9e810
JB
2791
2792 ada_unpack_from_contents (src, bit_offset, bit_size,
dda83cd7 2793 staging.data (), staging.size (),
d0a9e810
JB
2794 is_big_endian, has_negatives (type),
2795 is_scalar);
b249d2c2 2796 type = resolve_dynamic_type (type, staging, 0);
df86565b 2797 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
0cafa88c
JB
2798 {
2799 /* This happens when the length of the object is dynamic,
2800 and is actually smaller than the space reserved for it.
2801 For instance, in an array of variant records, the bit_size
2802 we're given is the array stride, which is constant and
2803 normally equal to the maximum size of its element.
2804 But, in reality, each element only actually spans a portion
2805 of that stride. */
df86565b 2806 bit_size = type->length () * HOST_CHAR_BIT;
0cafa88c 2807 }
d0a9e810
JB
2808 }
2809
f93fca70
JB
2810 if (obj == NULL)
2811 {
317c3ed9 2812 v = value::allocate (type);
bfb1c796 2813 src = valaddr + offset;
f93fca70 2814 }
736355f2 2815 else if (obj->lval () == lval_memory && obj->lazy ())
f93fca70 2816 {
0cafa88c 2817 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
bfb1c796 2818 gdb_byte *buf;
0cafa88c 2819
9feb2d07 2820 v = value_at (type, obj->address () + offset);
bfb1c796 2821 buf = (gdb_byte *) alloca (src_len);
9feb2d07 2822 read_memory (v->address (), buf, src_len);
bfb1c796 2823 src = buf;
f93fca70
JB
2824 }
2825 else
2826 {
317c3ed9 2827 v = value::allocate (type);
efaf1ae0 2828 src = obj->contents ().data () + offset;
f93fca70
JB
2829 }
2830
2831 if (obj != NULL)
2832 {
2833 long new_offset = offset;
2834
8181b7b6 2835 v->set_component_location (obj);
5011c493 2836 v->set_bitpos (bit_offset + obj->bitpos ());
f49d5fa2 2837 v->set_bitsize (bit_size);
5011c493 2838 if (v->bitpos () >= HOST_CHAR_BIT)
dda83cd7 2839 {
f93fca70 2840 ++new_offset;
5011c493 2841 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
dda83cd7 2842 }
76675c4d 2843 v->set_offset (new_offset);
f93fca70
JB
2844
2845 /* Also set the parent value. This is needed when trying to
2846 assign a new value (in inferior memory). */
fac7bdaa 2847 v->set_parent (obj);
f93fca70
JB
2848 }
2849 else
f49d5fa2 2850 v->set_bitsize (bit_size);
bbe912ba 2851 unpacked = v->contents_writeable ().data ();
f93fca70
JB
2852
2853 if (bit_size == 0)
2854 {
df86565b 2855 memset (unpacked, 0, type->length ());
f93fca70
JB
2856 return v;
2857 }
2858
df86565b 2859 if (staging.size () == type->length ())
f93fca70 2860 {
d0a9e810
JB
2861 /* Small short-cut: If we've unpacked the data into a buffer
2862 of the same size as TYPE's length, then we can reuse that,
2863 instead of doing the unpacking again. */
d5722aa2 2864 memcpy (unpacked, staging.data (), staging.size ());
f93fca70 2865 }
d0a9e810
JB
2866 else
2867 ada_unpack_from_contents (src, bit_offset, bit_size,
df86565b 2868 unpacked, type->length (),
d0a9e810 2869 is_big_endian, has_negatives (type), is_scalar);
f93fca70 2870
14f9c5c9
AS
2871 return v;
2872}
d2e4a39e 2873
14f9c5c9
AS
2874/* Store the contents of FROMVAL into the location of TOVAL.
2875 Return a new value with the location of TOVAL and contents of
2876 FROMVAL. Handles assignment into packed fields that have
4c4b4cd2 2877 floating-point or non-scalar types. */
14f9c5c9 2878
d2e4a39e
AS
2879static struct value *
2880ada_value_assign (struct value *toval, struct value *fromval)
14f9c5c9 2881{
d0c97917 2882 struct type *type = toval->type ();
f49d5fa2 2883 int bits = toval->bitsize ();
14f9c5c9 2884
52ce6436
PH
2885 toval = ada_coerce_ref (toval);
2886 fromval = ada_coerce_ref (fromval);
2887
d0c97917 2888 if (ada_is_direct_array_type (toval->type ()))
52ce6436 2889 toval = ada_coerce_to_simple_array (toval);
d0c97917 2890 if (ada_is_direct_array_type (fromval->type ()))
52ce6436
PH
2891 fromval = ada_coerce_to_simple_array (fromval);
2892
4b53ca88 2893 if (!toval->deprecated_modifiable ())
323e0a4a 2894 error (_("Left operand of assignment is not a modifiable lvalue."));
14f9c5c9 2895
736355f2 2896 if (toval->lval () == lval_memory
14f9c5c9 2897 && bits > 0
78134374 2898 && (type->code () == TYPE_CODE_FLT
dda83cd7 2899 || type->code () == TYPE_CODE_STRUCT))
14f9c5c9 2900 {
5011c493 2901 int len = (toval->bitpos ()
df407dfe 2902 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
aced2898 2903 int from_size;
224c3ddb 2904 gdb_byte *buffer = (gdb_byte *) alloca (len);
d2e4a39e 2905 struct value *val;
9feb2d07 2906 CORE_ADDR to_addr = toval->address ();
14f9c5c9 2907
78134374 2908 if (type->code () == TYPE_CODE_FLT)
dda83cd7 2909 fromval = value_cast (type, fromval);
14f9c5c9 2910
52ce6436 2911 read_memory (to_addr, buffer, len);
f49d5fa2 2912 from_size = fromval->bitsize ();
aced2898 2913 if (from_size == 0)
d0c97917 2914 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
d48e62f4 2915
d5a22e77 2916 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
d48e62f4 2917 ULONGEST from_offset = 0;
d0c97917 2918 if (is_big_endian && is_scalar_type (fromval->type ()))
d48e62f4 2919 from_offset = from_size - bits;
5011c493 2920 copy_bitwise (buffer, toval->bitpos (),
efaf1ae0 2921 fromval->contents ().data (), from_offset,
d48e62f4 2922 bits, is_big_endian);
972daa01 2923 write_memory_with_notification (to_addr, buffer, len);
8cebebb9 2924
cda03344 2925 val = toval->copy ();
bbe912ba 2926 memcpy (val->contents_raw ().data (),
efaf1ae0 2927 fromval->contents ().data (),
df86565b 2928 type->length ());
81ae560c 2929 val->deprecated_set_type (type);
d2e4a39e 2930
14f9c5c9
AS
2931 return val;
2932 }
2933
2934 return value_assign (toval, fromval);
2935}
2936
2937
7c512744
JB
2938/* Given that COMPONENT is a memory lvalue that is part of the lvalue
2939 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2940 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2941 COMPONENT, and not the inferior's memory. The current contents
2942 of COMPONENT are ignored.
2943
2944 Although not part of the initial design, this function also works
2945 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2946 had a null address, and COMPONENT had an address which is equal to
2947 its offset inside CONTAINER. */
2948
52ce6436
PH
2949static void
2950value_assign_to_component (struct value *container, struct value *component,
2951 struct value *val)
2952{
2953 LONGEST offset_in_container =
9feb2d07 2954 (LONGEST) (component->address () - container->address ());
7c512744 2955 int bit_offset_in_container =
5011c493 2956 component->bitpos () - container->bitpos ();
52ce6436 2957 int bits;
7c512744 2958
d0c97917 2959 val = value_cast (component->type (), val);
52ce6436 2960
f49d5fa2 2961 if (component->bitsize () == 0)
d0c97917 2962 bits = TARGET_CHAR_BIT * component->type ()->length ();
52ce6436 2963 else
f49d5fa2 2964 bits = component->bitsize ();
52ce6436 2965
d0c97917 2966 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2a62dfa9
JB
2967 {
2968 int src_offset;
2969
d0c97917 2970 if (is_scalar_type (check_typedef (component->type ())))
dda83cd7 2971 src_offset
d0c97917 2972 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2a62dfa9
JB
2973 else
2974 src_offset = 0;
bbe912ba 2975 copy_bitwise ((container->contents_writeable ().data ()
50888e42 2976 + offset_in_container),
5011c493 2977 container->bitpos () + bit_offset_in_container,
efaf1ae0 2978 val->contents ().data (), src_offset, bits, 1);
2a62dfa9 2979 }
52ce6436 2980 else
bbe912ba 2981 copy_bitwise ((container->contents_writeable ().data ()
50888e42 2982 + offset_in_container),
5011c493 2983 container->bitpos () + bit_offset_in_container,
efaf1ae0 2984 val->contents ().data (), 0, bits, 0);
7c512744
JB
2985}
2986
736ade86
XR
2987/* Determine if TYPE is an access to an unconstrained array. */
2988
d91e9ea8 2989bool
736ade86
XR
2990ada_is_access_to_unconstrained_array (struct type *type)
2991{
78134374 2992 return (type->code () == TYPE_CODE_TYPEDEF
736ade86
XR
2993 && is_thick_pntr (ada_typedef_target_type (type)));
2994}
2995
4c4b4cd2
PH
2996/* The value of the element of array ARR at the ARITY indices given in IND.
2997 ARR may be either a simple array, GNAT array descriptor, or pointer
14f9c5c9
AS
2998 thereto. */
2999
d2e4a39e
AS
3000struct value *
3001ada_value_subscript (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
3002{
3003 int k;
d2e4a39e
AS
3004 struct value *elt;
3005 struct type *elt_type;
14f9c5c9
AS
3006
3007 elt = ada_coerce_to_simple_array (arr);
3008
d0c97917 3009 elt_type = ada_check_typedef (elt->type ());
78134374 3010 if (elt_type->code () == TYPE_CODE_ARRAY
14f9c5c9
AS
3011 && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
3012 return value_subscript_packed (elt, arity, ind);
3013
3014 for (k = 0; k < arity; k += 1)
3015 {
27710edb 3016 struct type *saved_elt_type = elt_type->target_type ();
b9c50e9a 3017
78134374 3018 if (elt_type->code () != TYPE_CODE_ARRAY)
dda83cd7 3019 error (_("too many subscripts (%d expected)"), k);
b9c50e9a 3020
2497b498 3021 elt = value_subscript (elt, pos_atr (ind[k]));
b9c50e9a
XR
3022
3023 if (ada_is_access_to_unconstrained_array (saved_elt_type)
d0c97917 3024 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
b9c50e9a
XR
3025 {
3026 /* The element is a typedef to an unconstrained array,
3027 except that the value_subscript call stripped the
3028 typedef layer. The typedef layer is GNAT's way to
3029 specify that the element is, at the source level, an
3030 access to the unconstrained array, rather than the
3031 unconstrained array. So, we need to restore that
3032 typedef layer, which we can do by forcing the element's
3033 type back to its original type. Otherwise, the returned
3034 value is going to be printed as the array, rather
3035 than as an access. Another symptom of the same issue
3036 would be that an expression trying to dereference the
3037 element would also be improperly rejected. */
81ae560c 3038 elt->deprecated_set_type (saved_elt_type);
b9c50e9a
XR
3039 }
3040
d0c97917 3041 elt_type = ada_check_typedef (elt->type ());
14f9c5c9 3042 }
b9c50e9a 3043
14f9c5c9
AS
3044 return elt;
3045}
3046
deede10c
JB
3047/* Assuming ARR is a pointer to a GDB array, the value of the element
3048 of *ARR at the ARITY indices given in IND.
919e6dbe
PMR
3049 Does not read the entire array into memory.
3050
3051 Note: Unlike what one would expect, this function is used instead of
3052 ada_value_subscript for basically all non-packed array types. The reason
3053 for this is that a side effect of doing our own pointer arithmetics instead
3054 of relying on value_subscript is that there is no implicit typedef peeling.
3055 This is important for arrays of array accesses, where it allows us to
3056 preserve the fact that the array's element is an array access, where the
3057 access part os encoded in a typedef layer. */
14f9c5c9 3058
2c0b251b 3059static struct value *
deede10c 3060ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
3061{
3062 int k;
919e6dbe 3063 struct value *array_ind = ada_value_ind (arr);
deede10c 3064 struct type *type
463b870d 3065 = check_typedef (array_ind->enclosing_type ());
919e6dbe 3066
78134374 3067 if (type->code () == TYPE_CODE_ARRAY
919e6dbe
PMR
3068 && TYPE_FIELD_BITSIZE (type, 0) > 0)
3069 return value_subscript_packed (array_ind, arity, ind);
14f9c5c9
AS
3070
3071 for (k = 0; k < arity; k += 1)
3072 {
3073 LONGEST lwb, upb;
14f9c5c9 3074
78134374 3075 if (type->code () != TYPE_CODE_ARRAY)
dda83cd7 3076 error (_("too many subscripts (%d expected)"), k);
27710edb 3077 arr = value_cast (lookup_pointer_type (type->target_type ()),
cda03344 3078 arr->copy ());
3d967001 3079 get_discrete_bounds (type->index_type (), &lwb, &upb);
53a47a3e 3080 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
27710edb 3081 type = type->target_type ();
14f9c5c9
AS
3082 }
3083
3084 return value_ind (arr);
3085}
3086
0b5d8877 3087/* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
aa715135
JG
3088 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3089 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3090 this array is LOW, as per Ada rules. */
0b5d8877 3091static struct value *
f5938064 3092ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
dda83cd7 3093 int low, int high)
0b5d8877 3094{
b0dd7688 3095 struct type *type0 = ada_check_typedef (type);
27710edb 3096 struct type *base_index_type = type0->index_type ()->target_type ();
0c9c3474 3097 struct type *index_type
aa715135 3098 = create_static_range_type (NULL, base_index_type, low, high);
9fe561ab 3099 struct type *slice_type = create_array_type_with_stride
27710edb 3100 (NULL, type0->target_type (), index_type,
24e99c6c 3101 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
9fe561ab 3102 TYPE_FIELD_BITSIZE (type0, 0));
3d967001 3103 int base_low = ada_discrete_type_low_bound (type0->index_type ());
6244c119 3104 gdb::optional<LONGEST> base_low_pos, low_pos;
aa715135
JG
3105 CORE_ADDR base;
3106
6244c119
SM
3107 low_pos = discrete_position (base_index_type, low);
3108 base_low_pos = discrete_position (base_index_type, base_low);
3109
3110 if (!low_pos.has_value () || !base_low_pos.has_value ())
aa715135
JG
3111 {
3112 warning (_("unable to get positions in slice, use bounds instead"));
3113 low_pos = low;
3114 base_low_pos = base_low;
3115 }
5b4ee69b 3116
7ff5b937
TT
3117 ULONGEST stride = TYPE_FIELD_BITSIZE (slice_type, 0) / 8;
3118 if (stride == 0)
df86565b 3119 stride = type0->target_type ()->length ();
7ff5b937 3120
6244c119 3121 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
f5938064 3122 return value_at_lazy (slice_type, base);
0b5d8877
PH
3123}
3124
3125
3126static struct value *
3127ada_value_slice (struct value *array, int low, int high)
3128{
d0c97917 3129 struct type *type = ada_check_typedef (array->type ());
27710edb 3130 struct type *base_index_type = type->index_type ()->target_type ();
0c9c3474 3131 struct type *index_type
3d967001 3132 = create_static_range_type (NULL, type->index_type (), low, high);
9fe561ab 3133 struct type *slice_type = create_array_type_with_stride
27710edb 3134 (NULL, type->target_type (), index_type,
24e99c6c 3135 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
9fe561ab 3136 TYPE_FIELD_BITSIZE (type, 0));
6244c119
SM
3137 gdb::optional<LONGEST> low_pos, high_pos;
3138
5b4ee69b 3139
6244c119
SM
3140 low_pos = discrete_position (base_index_type, low);
3141 high_pos = discrete_position (base_index_type, high);
3142
3143 if (!low_pos.has_value () || !high_pos.has_value ())
aa715135
JG
3144 {
3145 warning (_("unable to get positions in slice, use bounds instead"));
3146 low_pos = low;
3147 high_pos = high;
3148 }
3149
3150 return value_cast (slice_type,
6244c119 3151 value_slice (array, low, *high_pos - *low_pos + 1));
0b5d8877
PH
3152}
3153
14f9c5c9
AS
3154/* If type is a record type in the form of a standard GNAT array
3155 descriptor, returns the number of dimensions for type. If arr is a
3156 simple array, returns the number of "array of"s that prefix its
4c4b4cd2 3157 type designation. Otherwise, returns 0. */
14f9c5c9
AS
3158
3159int
d2e4a39e 3160ada_array_arity (struct type *type)
14f9c5c9
AS
3161{
3162 int arity;
3163
3164 if (type == NULL)
3165 return 0;
3166
3167 type = desc_base_type (type);
3168
3169 arity = 0;
78134374 3170 if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9 3171 return desc_arity (desc_bounds_type (type));
d2e4a39e 3172 else
78134374 3173 while (type->code () == TYPE_CODE_ARRAY)
14f9c5c9 3174 {
dda83cd7 3175 arity += 1;
27710edb 3176 type = ada_check_typedef (type->target_type ());
14f9c5c9 3177 }
d2e4a39e 3178
14f9c5c9
AS
3179 return arity;
3180}
3181
3182/* If TYPE is a record type in the form of a standard GNAT array
3183 descriptor or a simple array type, returns the element type for
3184 TYPE after indexing by NINDICES indices, or by all indices if
4c4b4cd2 3185 NINDICES is -1. Otherwise, returns NULL. */
14f9c5c9 3186
d2e4a39e
AS
3187struct type *
3188ada_array_element_type (struct type *type, int nindices)
14f9c5c9
AS
3189{
3190 type = desc_base_type (type);
3191
78134374 3192 if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9
AS
3193 {
3194 int k;
d2e4a39e 3195 struct type *p_array_type;
14f9c5c9 3196
556bdfd4 3197 p_array_type = desc_data_target_type (type);
14f9c5c9
AS
3198
3199 k = ada_array_arity (type);
3200 if (k == 0)
dda83cd7 3201 return NULL;
d2e4a39e 3202
4c4b4cd2 3203 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
14f9c5c9 3204 if (nindices >= 0 && k > nindices)
dda83cd7 3205 k = nindices;
d2e4a39e 3206 while (k > 0 && p_array_type != NULL)
dda83cd7 3207 {
27710edb 3208 p_array_type = ada_check_typedef (p_array_type->target_type ());
dda83cd7
SM
3209 k -= 1;
3210 }
14f9c5c9
AS
3211 return p_array_type;
3212 }
78134374 3213 else if (type->code () == TYPE_CODE_ARRAY)
14f9c5c9 3214 {
78134374 3215 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
dda83cd7 3216 {
27710edb 3217 type = type->target_type ();
6a40c6e4
TT
3218 /* A multi-dimensional array is represented using a sequence
3219 of array types. If one of these types has a name, then
3220 it is not another dimension of the outer array, but
3221 rather the element type of the outermost array. */
3222 if (type->name () != nullptr)
3223 break;
dda83cd7
SM
3224 nindices -= 1;
3225 }
14f9c5c9
AS
3226 return type;
3227 }
3228
3229 return NULL;
3230}
3231
08a057e6 3232/* See ada-lang.h. */
14f9c5c9 3233
08a057e6 3234struct type *
1eea4ebd 3235ada_index_type (struct type *type, int n, const char *name)
14f9c5c9 3236{
4c4b4cd2
PH
3237 struct type *result_type;
3238
14f9c5c9
AS
3239 type = desc_base_type (type);
3240
1eea4ebd
UW
3241 if (n < 0 || n > ada_array_arity (type))
3242 error (_("invalid dimension number to '%s"), name);
14f9c5c9 3243
4c4b4cd2 3244 if (ada_is_simple_array_type (type))
14f9c5c9
AS
3245 {
3246 int i;
3247
3248 for (i = 1; i < n; i += 1)
2869ac4b
TT
3249 {
3250 type = ada_check_typedef (type);
27710edb 3251 type = type->target_type ();
2869ac4b 3252 }
27710edb 3253 result_type = ada_check_typedef (type)->index_type ()->target_type ();
4c4b4cd2 3254 /* FIXME: The stabs type r(0,0);bound;bound in an array type
dda83cd7
SM
3255 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3256 perhaps stabsread.c would make more sense. */
78134374 3257 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
dda83cd7 3258 result_type = NULL;
14f9c5c9 3259 }
d2e4a39e 3260 else
1eea4ebd
UW
3261 {
3262 result_type = desc_index_type (desc_bounds_type (type), n);
3263 if (result_type == NULL)
3264 error (_("attempt to take bound of something that is not an array"));
3265 }
3266
3267 return result_type;
14f9c5c9
AS
3268}
3269
3270/* Given that arr is an array type, returns the lower bound of the
3271 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
4c4b4cd2 3272 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
1eea4ebd
UW
3273 array-descriptor type. It works for other arrays with bounds supplied
3274 by run-time quantities other than discriminants. */
14f9c5c9 3275
abb68b3e 3276static LONGEST
fb5e3d5c 3277ada_array_bound_from_type (struct type *arr_type, int n, int which)
14f9c5c9 3278{
8a48ac95 3279 struct type *type, *index_type_desc, *index_type;
1ce677a4 3280 int i;
262452ec
JK
3281
3282 gdb_assert (which == 0 || which == 1);
14f9c5c9 3283
ad82864c
JB
3284 if (ada_is_constrained_packed_array_type (arr_type))
3285 arr_type = decode_constrained_packed_array_type (arr_type);
14f9c5c9 3286
4c4b4cd2 3287 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
1eea4ebd 3288 return (LONGEST) - which;
14f9c5c9 3289
78134374 3290 if (arr_type->code () == TYPE_CODE_PTR)
27710edb 3291 type = arr_type->target_type ();
14f9c5c9
AS
3292 else
3293 type = arr_type;
3294
22c4c60c 3295 if (type->is_fixed_instance ())
bafffb51
JB
3296 {
3297 /* The array has already been fixed, so we do not need to
3298 check the parallel ___XA type again. That encoding has
3299 already been applied, so ignore it now. */
3300 index_type_desc = NULL;
3301 }
3302 else
3303 {
3304 index_type_desc = ada_find_parallel_type (type, "___XA");
3305 ada_fixup_array_indexes_type (index_type_desc);
3306 }
3307
262452ec 3308 if (index_type_desc != NULL)
940da03e 3309 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
28c85d6c 3310 NULL);
262452ec 3311 else
8a48ac95
JB
3312 {
3313 struct type *elt_type = check_typedef (type);
3314
3315 for (i = 1; i < n; i++)
27710edb 3316 elt_type = check_typedef (elt_type->target_type ());
8a48ac95 3317
3d967001 3318 index_type = elt_type->index_type ();
8a48ac95 3319 }
262452ec 3320
43bbcdc2
PH
3321 return
3322 (LONGEST) (which == 0
dda83cd7
SM
3323 ? ada_discrete_type_low_bound (index_type)
3324 : ada_discrete_type_high_bound (index_type));
14f9c5c9
AS
3325}
3326
3327/* Given that arr is an array value, returns the lower bound of the
abb68b3e
JB
3328 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3329 WHICH is 1. This routine will also work for arrays with bounds
4c4b4cd2 3330 supplied by run-time quantities other than discriminants. */
14f9c5c9 3331
1eea4ebd 3332static LONGEST
4dc81987 3333ada_array_bound (struct value *arr, int n, int which)
14f9c5c9 3334{
eb479039
JB
3335 struct type *arr_type;
3336
d0c97917 3337 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
eb479039 3338 arr = value_ind (arr);
463b870d 3339 arr_type = arr->enclosing_type ();
14f9c5c9 3340
ad82864c
JB
3341 if (ada_is_constrained_packed_array_type (arr_type))
3342 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
4c4b4cd2 3343 else if (ada_is_simple_array_type (arr_type))
1eea4ebd 3344 return ada_array_bound_from_type (arr_type, n, which);
14f9c5c9 3345 else
1eea4ebd 3346 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
14f9c5c9
AS
3347}
3348
3349/* Given that arr is an array value, returns the length of the
3350 nth index. This routine will also work for arrays with bounds
4c4b4cd2
PH
3351 supplied by run-time quantities other than discriminants.
3352 Does not work for arrays indexed by enumeration types with representation
3353 clauses at the moment. */
14f9c5c9 3354
1eea4ebd 3355static LONGEST
d2e4a39e 3356ada_array_length (struct value *arr, int n)
14f9c5c9 3357{
aa715135
JG
3358 struct type *arr_type, *index_type;
3359 int low, high;
eb479039 3360
d0c97917 3361 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
eb479039 3362 arr = value_ind (arr);
463b870d 3363 arr_type = arr->enclosing_type ();
14f9c5c9 3364
ad82864c
JB
3365 if (ada_is_constrained_packed_array_type (arr_type))
3366 return ada_array_length (decode_constrained_packed_array (arr), n);
14f9c5c9 3367
4c4b4cd2 3368 if (ada_is_simple_array_type (arr_type))
aa715135
JG
3369 {
3370 low = ada_array_bound_from_type (arr_type, n, 0);
3371 high = ada_array_bound_from_type (arr_type, n, 1);
3372 }
14f9c5c9 3373 else
aa715135
JG
3374 {
3375 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3376 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3377 }
3378
f168693b 3379 arr_type = check_typedef (arr_type);
7150d33c 3380 index_type = ada_index_type (arr_type, n, "length");
aa715135
JG
3381 if (index_type != NULL)
3382 {
3383 struct type *base_type;
78134374 3384 if (index_type->code () == TYPE_CODE_RANGE)
27710edb 3385 base_type = index_type->target_type ();
aa715135
JG
3386 else
3387 base_type = index_type;
3388
3389 low = pos_atr (value_from_longest (base_type, low));
3390 high = pos_atr (value_from_longest (base_type, high));
3391 }
3392 return high - low + 1;
4c4b4cd2
PH
3393}
3394
bff8c71f
TT
3395/* An array whose type is that of ARR_TYPE (an array type), with
3396 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3397 less than LOW, then LOW-1 is used. */
4c4b4cd2
PH
3398
3399static struct value *
bff8c71f 3400empty_array (struct type *arr_type, int low, int high)
4c4b4cd2 3401{
b0dd7688 3402 struct type *arr_type0 = ada_check_typedef (arr_type);
0c9c3474
SA
3403 struct type *index_type
3404 = create_static_range_type
27710edb 3405 (NULL, arr_type0->index_type ()->target_type (), low,
bff8c71f 3406 high < low ? low - 1 : high);
b0dd7688 3407 struct type *elt_type = ada_array_element_type (arr_type0, 1);
5b4ee69b 3408
317c3ed9 3409 return value::allocate (create_array_type (NULL, elt_type, index_type));
14f9c5c9 3410}
14f9c5c9 3411\f
d2e4a39e 3412
dda83cd7 3413 /* Name resolution */
14f9c5c9 3414
4c4b4cd2
PH
3415/* The "decoded" name for the user-definable Ada operator corresponding
3416 to OP. */
14f9c5c9 3417
d2e4a39e 3418static const char *
4c4b4cd2 3419ada_decoded_op_name (enum exp_opcode op)
14f9c5c9
AS
3420{
3421 int i;
3422
4c4b4cd2 3423 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
14f9c5c9
AS
3424 {
3425 if (ada_opname_table[i].op == op)
dda83cd7 3426 return ada_opname_table[i].decoded;
14f9c5c9 3427 }
323e0a4a 3428 error (_("Could not find operator name for opcode"));
14f9c5c9
AS
3429}
3430
de93309a
SM
3431/* Returns true (non-zero) iff decoded name N0 should appear before N1
3432 in a listing of choices during disambiguation (see sort_choices, below).
3433 The idea is that overloadings of a subprogram name from the
3434 same package should sort in their source order. We settle for ordering
3435 such symbols by their trailing number (__N or $N). */
14f9c5c9 3436
de93309a
SM
3437static int
3438encoded_ordered_before (const char *N0, const char *N1)
14f9c5c9 3439{
de93309a
SM
3440 if (N1 == NULL)
3441 return 0;
3442 else if (N0 == NULL)
3443 return 1;
3444 else
3445 {
3446 int k0, k1;
30b15541 3447
de93309a 3448 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
dda83cd7 3449 ;
de93309a 3450 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
dda83cd7 3451 ;
de93309a 3452 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
dda83cd7
SM
3453 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3454 {
3455 int n0, n1;
3456
3457 n0 = k0;
3458 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3459 n0 -= 1;
3460 n1 = k1;
3461 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3462 n1 -= 1;
3463 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3464 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3465 }
de93309a
SM
3466 return (strcmp (N0, N1) < 0);
3467 }
14f9c5c9
AS
3468}
3469
de93309a
SM
3470/* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3471 encoded names. */
14f9c5c9 3472
de93309a
SM
3473static void
3474sort_choices (struct block_symbol syms[], int nsyms)
14f9c5c9 3475{
14f9c5c9 3476 int i;
14f9c5c9 3477
de93309a 3478 for (i = 1; i < nsyms; i += 1)
14f9c5c9 3479 {
de93309a
SM
3480 struct block_symbol sym = syms[i];
3481 int j;
3482
3483 for (j = i - 1; j >= 0; j -= 1)
dda83cd7
SM
3484 {
3485 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3486 sym.symbol->linkage_name ()))
3487 break;
3488 syms[j + 1] = syms[j];
3489 }
de93309a
SM
3490 syms[j + 1] = sym;
3491 }
3492}
14f9c5c9 3493
de93309a
SM
3494/* Whether GDB should display formals and return types for functions in the
3495 overloads selection menu. */
3496static bool print_signatures = true;
4c4b4cd2 3497
de93309a
SM
3498/* Print the signature for SYM on STREAM according to the FLAGS options. For
3499 all but functions, the signature is just the name of the symbol. For
3500 functions, this is the name of the function, the list of types for formals
3501 and the return type (if any). */
4c4b4cd2 3502
de93309a
SM
3503static void
3504ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3505 const struct type_print_options *flags)
3506{
5f9c5a63 3507 struct type *type = sym->type ();
14f9c5c9 3508
6cb06a8c 3509 gdb_printf (stream, "%s", sym->print_name ());
de93309a
SM
3510 if (!print_signatures
3511 || type == NULL
78134374 3512 || type->code () != TYPE_CODE_FUNC)
de93309a 3513 return;
4c4b4cd2 3514
1f704f76 3515 if (type->num_fields () > 0)
de93309a
SM
3516 {
3517 int i;
14f9c5c9 3518
6cb06a8c 3519 gdb_printf (stream, " (");
1f704f76 3520 for (i = 0; i < type->num_fields (); ++i)
de93309a
SM
3521 {
3522 if (i > 0)
6cb06a8c 3523 gdb_printf (stream, "; ");
940da03e 3524 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
de93309a
SM
3525 flags);
3526 }
6cb06a8c 3527 gdb_printf (stream, ")");
de93309a 3528 }
27710edb
SM
3529 if (type->target_type () != NULL
3530 && type->target_type ()->code () != TYPE_CODE_VOID)
de93309a 3531 {
6cb06a8c 3532 gdb_printf (stream, " return ");
27710edb 3533 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
de93309a
SM
3534 }
3535}
14f9c5c9 3536
de93309a
SM
3537/* Read and validate a set of numeric choices from the user in the
3538 range 0 .. N_CHOICES-1. Place the results in increasing
3539 order in CHOICES[0 .. N-1], and return N.
14f9c5c9 3540
de93309a
SM
3541 The user types choices as a sequence of numbers on one line
3542 separated by blanks, encoding them as follows:
14f9c5c9 3543
de93309a
SM
3544 + A choice of 0 means to cancel the selection, throwing an error.
3545 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3546 + The user chooses k by typing k+IS_ALL_CHOICE+1.
14f9c5c9 3547
de93309a 3548 The user is not allowed to choose more than MAX_RESULTS values.
14f9c5c9 3549
de93309a
SM
3550 ANNOTATION_SUFFIX, if present, is used to annotate the input
3551 prompts (for use with the -f switch). */
14f9c5c9 3552
de93309a
SM
3553static int
3554get_selections (int *choices, int n_choices, int max_results,
dda83cd7 3555 int is_all_choice, const char *annotation_suffix)
de93309a 3556{
992a7040 3557 const char *args;
de93309a
SM
3558 const char *prompt;
3559 int n_chosen;
3560 int first_choice = is_all_choice ? 2 : 1;
14f9c5c9 3561
de93309a
SM
3562 prompt = getenv ("PS2");
3563 if (prompt == NULL)
3564 prompt = "> ";
4c4b4cd2 3565
f8631e5e
SM
3566 std::string buffer;
3567 args = command_line_input (buffer, prompt, annotation_suffix);
4c4b4cd2 3568
de93309a
SM
3569 if (args == NULL)
3570 error_no_arg (_("one or more choice numbers"));
14f9c5c9 3571
de93309a 3572 n_chosen = 0;
4c4b4cd2 3573
de93309a
SM
3574 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3575 order, as given in args. Choices are validated. */
3576 while (1)
14f9c5c9 3577 {
de93309a
SM
3578 char *args2;
3579 int choice, j;
76a01679 3580
de93309a
SM
3581 args = skip_spaces (args);
3582 if (*args == '\0' && n_chosen == 0)
dda83cd7 3583 error_no_arg (_("one or more choice numbers"));
de93309a 3584 else if (*args == '\0')
dda83cd7 3585 break;
76a01679 3586
de93309a
SM
3587 choice = strtol (args, &args2, 10);
3588 if (args == args2 || choice < 0
dda83cd7
SM
3589 || choice > n_choices + first_choice - 1)
3590 error (_("Argument must be choice number"));
de93309a 3591 args = args2;
76a01679 3592
de93309a 3593 if (choice == 0)
dda83cd7 3594 error (_("cancelled"));
76a01679 3595
de93309a 3596 if (choice < first_choice)
dda83cd7
SM
3597 {
3598 n_chosen = n_choices;
3599 for (j = 0; j < n_choices; j += 1)
3600 choices[j] = j;
3601 break;
3602 }
de93309a 3603 choice -= first_choice;
76a01679 3604
de93309a 3605 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
dda83cd7
SM
3606 {
3607 }
4c4b4cd2 3608
de93309a 3609 if (j < 0 || choice != choices[j])
dda83cd7
SM
3610 {
3611 int k;
4c4b4cd2 3612
dda83cd7
SM
3613 for (k = n_chosen - 1; k > j; k -= 1)
3614 choices[k + 1] = choices[k];
3615 choices[j + 1] = choice;
3616 n_chosen += 1;
3617 }
14f9c5c9
AS
3618 }
3619
de93309a
SM
3620 if (n_chosen > max_results)
3621 error (_("Select no more than %d of the above"), max_results);
3622
3623 return n_chosen;
14f9c5c9
AS
3624}
3625
de93309a
SM
3626/* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3627 by asking the user (if necessary), returning the number selected,
3628 and setting the first elements of SYMS items. Error if no symbols
3629 selected. */
3630
3631/* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3632 to be re-integrated one of these days. */
14f9c5c9
AS
3633
3634static int
de93309a 3635user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
14f9c5c9 3636{
de93309a
SM
3637 int i;
3638 int *chosen = XALLOCAVEC (int , nsyms);
3639 int n_chosen;
3640 int first_choice = (max_results == 1) ? 1 : 2;
3641 const char *select_mode = multiple_symbols_select_mode ();
14f9c5c9 3642
de93309a
SM
3643 if (max_results < 1)
3644 error (_("Request to select 0 symbols!"));
3645 if (nsyms <= 1)
3646 return nsyms;
14f9c5c9 3647
de93309a
SM
3648 if (select_mode == multiple_symbols_cancel)
3649 error (_("\
3650canceled because the command is ambiguous\n\
3651See set/show multiple-symbol."));
14f9c5c9 3652
de93309a
SM
3653 /* If select_mode is "all", then return all possible symbols.
3654 Only do that if more than one symbol can be selected, of course.
3655 Otherwise, display the menu as usual. */
3656 if (select_mode == multiple_symbols_all && max_results > 1)
3657 return nsyms;
14f9c5c9 3658
6cb06a8c 3659 gdb_printf (_("[0] cancel\n"));
de93309a 3660 if (max_results > 1)
6cb06a8c 3661 gdb_printf (_("[1] all\n"));
14f9c5c9 3662
de93309a 3663 sort_choices (syms, nsyms);
14f9c5c9 3664
de93309a
SM
3665 for (i = 0; i < nsyms; i += 1)
3666 {
3667 if (syms[i].symbol == NULL)
dda83cd7 3668 continue;
14f9c5c9 3669
66d7f48f 3670 if (syms[i].symbol->aclass () == LOC_BLOCK)
dda83cd7
SM
3671 {
3672 struct symtab_and_line sal =
3673 find_function_start_sal (syms[i].symbol, 1);
14f9c5c9 3674
6cb06a8c 3675 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3676 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3677 &type_print_raw_options);
3678 if (sal.symtab == NULL)
6cb06a8c
TT
3679 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3680 metadata_style.style ().ptr (), nullptr, sal.line);
de93309a 3681 else
6cb06a8c 3682 gdb_printf
de93309a
SM
3683 (_(" at %ps:%d\n"),
3684 styled_string (file_name_style.style (),
3685 symtab_to_filename_for_display (sal.symtab)),
3686 sal.line);
dda83cd7
SM
3687 continue;
3688 }
76a01679 3689 else
dda83cd7
SM
3690 {
3691 int is_enumeral =
66d7f48f 3692 (syms[i].symbol->aclass () == LOC_CONST
5f9c5a63
SM
3693 && syms[i].symbol->type () != NULL
3694 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
de93309a 3695 struct symtab *symtab = NULL;
4c4b4cd2 3696
7b3ecc75 3697 if (syms[i].symbol->is_objfile_owned ())
4206d69e 3698 symtab = syms[i].symbol->symtab ();
de93309a 3699
5d0027b9 3700 if (syms[i].symbol->line () != 0 && symtab != NULL)
de93309a 3701 {
6cb06a8c 3702 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3703 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3704 &type_print_raw_options);
6cb06a8c
TT
3705 gdb_printf (_(" at %s:%d\n"),
3706 symtab_to_filename_for_display (symtab),
3707 syms[i].symbol->line ());
de93309a 3708 }
dda83cd7 3709 else if (is_enumeral
5f9c5a63 3710 && syms[i].symbol->type ()->name () != NULL)
dda83cd7 3711 {
6cb06a8c 3712 gdb_printf (("[%d] "), i + first_choice);
5f9c5a63 3713 ada_print_type (syms[i].symbol->type (), NULL,
dda83cd7 3714 gdb_stdout, -1, 0, &type_print_raw_options);
6cb06a8c
TT
3715 gdb_printf (_("'(%s) (enumeral)\n"),
3716 syms[i].symbol->print_name ());
dda83cd7 3717 }
de93309a
SM
3718 else
3719 {
6cb06a8c 3720 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3721 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3722 &type_print_raw_options);
3723
3724 if (symtab != NULL)
6cb06a8c
TT
3725 gdb_printf (is_enumeral
3726 ? _(" in %s (enumeral)\n")
3727 : _(" at %s:?\n"),
3728 symtab_to_filename_for_display (symtab));
de93309a 3729 else
6cb06a8c
TT
3730 gdb_printf (is_enumeral
3731 ? _(" (enumeral)\n")
3732 : _(" at ?\n"));
de93309a 3733 }
dda83cd7 3734 }
14f9c5c9 3735 }
14f9c5c9 3736
de93309a 3737 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
dda83cd7 3738 "overload-choice");
14f9c5c9 3739
de93309a
SM
3740 for (i = 0; i < n_chosen; i += 1)
3741 syms[i] = syms[chosen[i]];
14f9c5c9 3742
de93309a
SM
3743 return n_chosen;
3744}
14f9c5c9 3745
cd9a3148
TT
3746/* See ada-lang.h. */
3747
3748block_symbol
7056f312 3749ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
cd9a3148
TT
3750 int nargs, value *argvec[])
3751{
3752 if (possible_user_operator_p (op, argvec))
3753 {
3754 std::vector<struct block_symbol> candidates
3755 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3756 NULL, VAR_DOMAIN);
3757
3758 int i = ada_resolve_function (candidates, argvec,
3759 nargs, ada_decoded_op_name (op), NULL,
3760 parse_completion);
3761 if (i >= 0)
3762 return candidates[i];
3763 }
3764 return {};
3765}
3766
3767/* See ada-lang.h. */
3768
3769block_symbol
3770ada_resolve_funcall (struct symbol *sym, const struct block *block,
3771 struct type *context_type,
7056f312 3772 bool parse_completion,
cd9a3148
TT
3773 int nargs, value *argvec[],
3774 innermost_block_tracker *tracker)
3775{
3776 std::vector<struct block_symbol> candidates
3777 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3778
3779 int i;
3780 if (candidates.size () == 1)
3781 i = 0;
3782 else
3783 {
3784 i = ada_resolve_function
3785 (candidates,
3786 argvec, nargs,
3787 sym->linkage_name (),
3788 context_type, parse_completion);
3789 if (i < 0)
3790 error (_("Could not find a match for %s"), sym->print_name ());
3791 }
3792
3793 tracker->update (candidates[i]);
3794 return candidates[i];
3795}
3796
ba8694b6
TT
3797/* Resolve a mention of a name where the context type is an
3798 enumeration type. */
3799
3800static int
3801ada_resolve_enum (std::vector<struct block_symbol> &syms,
3802 const char *name, struct type *context_type,
3803 bool parse_completion)
3804{
3805 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3806 context_type = ada_check_typedef (context_type);
3807
3808 for (int i = 0; i < syms.size (); ++i)
3809 {
3810 /* We already know the name matches, so we're just looking for
3811 an element of the correct enum type. */
5f9c5a63 3812 if (ada_check_typedef (syms[i].symbol->type ()) == context_type)
ba8694b6
TT
3813 return i;
3814 }
3815
3816 error (_("No name '%s' in enumeration type '%s'"), name,
3817 ada_type_name (context_type));
3818}
3819
cd9a3148
TT
3820/* See ada-lang.h. */
3821
3822block_symbol
3823ada_resolve_variable (struct symbol *sym, const struct block *block,
3824 struct type *context_type,
7056f312 3825 bool parse_completion,
cd9a3148
TT
3826 int deprocedure_p,
3827 innermost_block_tracker *tracker)
3828{
3829 std::vector<struct block_symbol> candidates
3830 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3831
3832 if (std::any_of (candidates.begin (),
3833 candidates.end (),
3834 [] (block_symbol &bsym)
3835 {
66d7f48f 3836 switch (bsym.symbol->aclass ())
cd9a3148
TT
3837 {
3838 case LOC_REGISTER:
3839 case LOC_ARG:
3840 case LOC_REF_ARG:
3841 case LOC_REGPARM_ADDR:
3842 case LOC_LOCAL:
3843 case LOC_COMPUTED:
3844 return true;
3845 default:
3846 return false;
3847 }
3848 }))
3849 {
3850 /* Types tend to get re-introduced locally, so if there
3851 are any local symbols that are not types, first filter
3852 out all types. */
3853 candidates.erase
3854 (std::remove_if
3855 (candidates.begin (),
3856 candidates.end (),
3857 [] (block_symbol &bsym)
3858 {
66d7f48f 3859 return bsym.symbol->aclass () == LOC_TYPEDEF;
cd9a3148
TT
3860 }),
3861 candidates.end ());
3862 }
3863
2c71f639
TV
3864 /* Filter out artificial symbols. */
3865 candidates.erase
3866 (std::remove_if
3867 (candidates.begin (),
3868 candidates.end (),
3869 [] (block_symbol &bsym)
3870 {
496feb16 3871 return bsym.symbol->is_artificial ();
2c71f639
TV
3872 }),
3873 candidates.end ());
3874
cd9a3148
TT
3875 int i;
3876 if (candidates.empty ())
3877 error (_("No definition found for %s"), sym->print_name ());
3878 else if (candidates.size () == 1)
3879 i = 0;
ba8694b6
TT
3880 else if (context_type != nullptr
3881 && context_type->code () == TYPE_CODE_ENUM)
3882 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3883 parse_completion);
cd9a3148
TT
3884 else if (deprocedure_p && !is_nonfunction (candidates))
3885 {
3886 i = ada_resolve_function
3887 (candidates, NULL, 0,
3888 sym->linkage_name (),
3889 context_type, parse_completion);
3890 if (i < 0)
3891 error (_("Could not find a match for %s"), sym->print_name ());
3892 }
3893 else
3894 {
6cb06a8c 3895 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
cd9a3148
TT
3896 user_select_syms (candidates.data (), candidates.size (), 1);
3897 i = 0;
3898 }
3899
3900 tracker->update (candidates[i]);
3901 return candidates[i];
3902}
3903
db2534b7 3904/* Return non-zero if formal type FTYPE matches actual type ATYPE. */
de93309a
SM
3905/* The term "match" here is rather loose. The match is heuristic and
3906 liberal. */
14f9c5c9 3907
de93309a 3908static int
db2534b7 3909ada_type_match (struct type *ftype, struct type *atype)
14f9c5c9 3910{
de93309a
SM
3911 ftype = ada_check_typedef (ftype);
3912 atype = ada_check_typedef (atype);
14f9c5c9 3913
78134374 3914 if (ftype->code () == TYPE_CODE_REF)
27710edb 3915 ftype = ftype->target_type ();
78134374 3916 if (atype->code () == TYPE_CODE_REF)
27710edb 3917 atype = atype->target_type ();
14f9c5c9 3918
78134374 3919 switch (ftype->code ())
14f9c5c9 3920 {
de93309a 3921 default:
78134374 3922 return ftype->code () == atype->code ();
de93309a 3923 case TYPE_CODE_PTR:
db2534b7
TT
3924 if (atype->code () != TYPE_CODE_PTR)
3925 return 0;
27710edb 3926 atype = atype->target_type ();
db2534b7 3927 /* This can only happen if the actual argument is 'null'. */
df86565b 3928 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
db2534b7 3929 return 1;
27710edb 3930 return ada_type_match (ftype->target_type (), atype);
de93309a
SM
3931 case TYPE_CODE_INT:
3932 case TYPE_CODE_ENUM:
3933 case TYPE_CODE_RANGE:
78134374 3934 switch (atype->code ())
dda83cd7
SM
3935 {
3936 case TYPE_CODE_INT:
3937 case TYPE_CODE_ENUM:
3938 case TYPE_CODE_RANGE:
3939 return 1;
3940 default:
3941 return 0;
3942 }
d2e4a39e 3943
de93309a 3944 case TYPE_CODE_ARRAY:
78134374 3945 return (atype->code () == TYPE_CODE_ARRAY
dda83cd7 3946 || ada_is_array_descriptor_type (atype));
14f9c5c9 3947
de93309a
SM
3948 case TYPE_CODE_STRUCT:
3949 if (ada_is_array_descriptor_type (ftype))
dda83cd7
SM
3950 return (atype->code () == TYPE_CODE_ARRAY
3951 || ada_is_array_descriptor_type (atype));
de93309a 3952 else
dda83cd7
SM
3953 return (atype->code () == TYPE_CODE_STRUCT
3954 && !ada_is_array_descriptor_type (atype));
14f9c5c9 3955
de93309a
SM
3956 case TYPE_CODE_UNION:
3957 case TYPE_CODE_FLT:
78134374 3958 return (atype->code () == ftype->code ());
de93309a 3959 }
14f9c5c9
AS
3960}
3961
de93309a
SM
3962/* Return non-zero if the formals of FUNC "sufficiently match" the
3963 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3964 may also be an enumeral, in which case it is treated as a 0-
3965 argument function. */
14f9c5c9 3966
de93309a
SM
3967static int
3968ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3969{
3970 int i;
5f9c5a63 3971 struct type *func_type = func->type ();
14f9c5c9 3972
66d7f48f 3973 if (func->aclass () == LOC_CONST
78134374 3974 && func_type->code () == TYPE_CODE_ENUM)
de93309a 3975 return (n_actuals == 0);
78134374 3976 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
de93309a 3977 return 0;
14f9c5c9 3978
1f704f76 3979 if (func_type->num_fields () != n_actuals)
de93309a 3980 return 0;
14f9c5c9 3981
de93309a
SM
3982 for (i = 0; i < n_actuals; i += 1)
3983 {
3984 if (actuals[i] == NULL)
dda83cd7 3985 return 0;
de93309a 3986 else
dda83cd7
SM
3987 {
3988 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
d0c97917 3989 struct type *atype = ada_check_typedef (actuals[i]->type ());
14f9c5c9 3990
db2534b7 3991 if (!ada_type_match (ftype, atype))
dda83cd7
SM
3992 return 0;
3993 }
de93309a
SM
3994 }
3995 return 1;
3996}
d2e4a39e 3997
de93309a
SM
3998/* False iff function type FUNC_TYPE definitely does not produce a value
3999 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4000 FUNC_TYPE is not a valid function type with a non-null return type
4001 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
14f9c5c9 4002
de93309a
SM
4003static int
4004return_match (struct type *func_type, struct type *context_type)
4005{
4006 struct type *return_type;
d2e4a39e 4007
de93309a
SM
4008 if (func_type == NULL)
4009 return 1;
14f9c5c9 4010
78134374 4011 if (func_type->code () == TYPE_CODE_FUNC)
27710edb 4012 return_type = get_base_type (func_type->target_type ());
de93309a
SM
4013 else
4014 return_type = get_base_type (func_type);
4015 if (return_type == NULL)
4016 return 1;
76a01679 4017
de93309a 4018 context_type = get_base_type (context_type);
14f9c5c9 4019
78134374 4020 if (return_type->code () == TYPE_CODE_ENUM)
de93309a
SM
4021 return context_type == NULL || return_type == context_type;
4022 else if (context_type == NULL)
78134374 4023 return return_type->code () != TYPE_CODE_VOID;
de93309a 4024 else
78134374 4025 return return_type->code () == context_type->code ();
de93309a 4026}
14f9c5c9 4027
14f9c5c9 4028
1bfa81ac 4029/* Returns the index in SYMS that contains the symbol for the
de93309a
SM
4030 function (if any) that matches the types of the NARGS arguments in
4031 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4032 that returns that type, then eliminate matches that don't. If
4033 CONTEXT_TYPE is void and there is at least one match that does not
4034 return void, eliminate all matches that do.
14f9c5c9 4035
de93309a
SM
4036 Asks the user if there is more than one match remaining. Returns -1
4037 if there is no such symbol or none is selected. NAME is used
4038 solely for messages. May re-arrange and modify SYMS in
4039 the process; the index returned is for the modified vector. */
14f9c5c9 4040
de93309a 4041static int
d1183b06
TT
4042ada_resolve_function (std::vector<struct block_symbol> &syms,
4043 struct value **args, int nargs,
dda83cd7 4044 const char *name, struct type *context_type,
7056f312 4045 bool parse_completion)
de93309a
SM
4046{
4047 int fallback;
4048 int k;
4049 int m; /* Number of hits */
14f9c5c9 4050
de93309a
SM
4051 m = 0;
4052 /* In the first pass of the loop, we only accept functions matching
4053 context_type. If none are found, we add a second pass of the loop
4054 where every function is accepted. */
4055 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4056 {
d1183b06 4057 for (k = 0; k < syms.size (); k += 1)
dda83cd7 4058 {
5f9c5a63 4059 struct type *type = ada_check_typedef (syms[k].symbol->type ());
5b4ee69b 4060
dda83cd7
SM
4061 if (ada_args_match (syms[k].symbol, args, nargs)
4062 && (fallback || return_match (type, context_type)))
4063 {
4064 syms[m] = syms[k];
4065 m += 1;
4066 }
4067 }
14f9c5c9
AS
4068 }
4069
de93309a
SM
4070 /* If we got multiple matches, ask the user which one to use. Don't do this
4071 interactive thing during completion, though, as the purpose of the
4072 completion is providing a list of all possible matches. Prompting the
4073 user to filter it down would be completely unexpected in this case. */
4074 if (m == 0)
4075 return -1;
4076 else if (m > 1 && !parse_completion)
4077 {
6cb06a8c 4078 gdb_printf (_("Multiple matches for %s\n"), name);
d1183b06 4079 user_select_syms (syms.data (), m, 1);
de93309a
SM
4080 return 0;
4081 }
4082 return 0;
14f9c5c9
AS
4083}
4084
14f9c5c9
AS
4085/* Type-class predicates */
4086
4c4b4cd2
PH
4087/* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4088 or FLOAT). */
14f9c5c9
AS
4089
4090static int
d2e4a39e 4091numeric_type_p (struct type *type)
14f9c5c9
AS
4092{
4093 if (type == NULL)
4094 return 0;
d2e4a39e
AS
4095 else
4096 {
78134374 4097 switch (type->code ())
dda83cd7
SM
4098 {
4099 case TYPE_CODE_INT:
4100 case TYPE_CODE_FLT:
c04da66c 4101 case TYPE_CODE_FIXED_POINT:
dda83cd7
SM
4102 return 1;
4103 case TYPE_CODE_RANGE:
27710edb
SM
4104 return (type == type->target_type ()
4105 || numeric_type_p (type->target_type ()));
dda83cd7
SM
4106 default:
4107 return 0;
4108 }
d2e4a39e 4109 }
14f9c5c9
AS
4110}
4111
4c4b4cd2 4112/* True iff TYPE is integral (an INT or RANGE of INTs). */
14f9c5c9
AS
4113
4114static int
d2e4a39e 4115integer_type_p (struct type *type)
14f9c5c9
AS
4116{
4117 if (type == NULL)
4118 return 0;
d2e4a39e
AS
4119 else
4120 {
78134374 4121 switch (type->code ())
dda83cd7
SM
4122 {
4123 case TYPE_CODE_INT:
4124 return 1;
4125 case TYPE_CODE_RANGE:
27710edb
SM
4126 return (type == type->target_type ()
4127 || integer_type_p (type->target_type ()));
dda83cd7
SM
4128 default:
4129 return 0;
4130 }
d2e4a39e 4131 }
14f9c5c9
AS
4132}
4133
4c4b4cd2 4134/* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
14f9c5c9
AS
4135
4136static int
d2e4a39e 4137scalar_type_p (struct type *type)
14f9c5c9
AS
4138{
4139 if (type == NULL)
4140 return 0;
d2e4a39e
AS
4141 else
4142 {
78134374 4143 switch (type->code ())
dda83cd7
SM
4144 {
4145 case TYPE_CODE_INT:
4146 case TYPE_CODE_RANGE:
4147 case TYPE_CODE_ENUM:
4148 case TYPE_CODE_FLT:
c04da66c 4149 case TYPE_CODE_FIXED_POINT:
dda83cd7
SM
4150 return 1;
4151 default:
4152 return 0;
4153 }
d2e4a39e 4154 }
14f9c5c9
AS
4155}
4156
98847c1e
TT
4157/* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4158 This essentially means one of (INT, RANGE, ENUM) -- but note that
4159 "enum" includes character and boolean as well. */
14f9c5c9
AS
4160
4161static int
d2e4a39e 4162discrete_type_p (struct type *type)
14f9c5c9
AS
4163{
4164 if (type == NULL)
4165 return 0;
d2e4a39e
AS
4166 else
4167 {
78134374 4168 switch (type->code ())
dda83cd7
SM
4169 {
4170 case TYPE_CODE_INT:
4171 case TYPE_CODE_RANGE:
4172 case TYPE_CODE_ENUM:
4173 case TYPE_CODE_BOOL:
98847c1e 4174 case TYPE_CODE_CHAR:
dda83cd7
SM
4175 return 1;
4176 default:
4177 return 0;
4178 }
d2e4a39e 4179 }
14f9c5c9
AS
4180}
4181
4c4b4cd2
PH
4182/* Returns non-zero if OP with operands in the vector ARGS could be
4183 a user-defined function. Errs on the side of pre-defined operators
4184 (i.e., result 0). */
14f9c5c9
AS
4185
4186static int
d2e4a39e 4187possible_user_operator_p (enum exp_opcode op, struct value *args[])
14f9c5c9 4188{
76a01679 4189 struct type *type0 =
d0c97917 4190 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
d2e4a39e 4191 struct type *type1 =
d0c97917 4192 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
d2e4a39e 4193
4c4b4cd2
PH
4194 if (type0 == NULL)
4195 return 0;
4196
14f9c5c9
AS
4197 switch (op)
4198 {
4199 default:
4200 return 0;
4201
4202 case BINOP_ADD:
4203 case BINOP_SUB:
4204 case BINOP_MUL:
4205 case BINOP_DIV:
d2e4a39e 4206 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
14f9c5c9
AS
4207
4208 case BINOP_REM:
4209 case BINOP_MOD:
4210 case BINOP_BITWISE_AND:
4211 case BINOP_BITWISE_IOR:
4212 case BINOP_BITWISE_XOR:
d2e4a39e 4213 return (!(integer_type_p (type0) && integer_type_p (type1)));
14f9c5c9
AS
4214
4215 case BINOP_EQUAL:
4216 case BINOP_NOTEQUAL:
4217 case BINOP_LESS:
4218 case BINOP_GTR:
4219 case BINOP_LEQ:
4220 case BINOP_GEQ:
d2e4a39e 4221 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
14f9c5c9
AS
4222
4223 case BINOP_CONCAT:
ee90b9ab 4224 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
14f9c5c9
AS
4225
4226 case BINOP_EXP:
d2e4a39e 4227 return (!(numeric_type_p (type0) && integer_type_p (type1)));
14f9c5c9
AS
4228
4229 case UNOP_NEG:
4230 case UNOP_PLUS:
4231 case UNOP_LOGICAL_NOT:
d2e4a39e
AS
4232 case UNOP_ABS:
4233 return (!numeric_type_p (type0));
14f9c5c9
AS
4234
4235 }
4236}
4237\f
dda83cd7 4238 /* Renaming */
14f9c5c9 4239
aeb5907d
JB
4240/* NOTES:
4241
4242 1. In the following, we assume that a renaming type's name may
4243 have an ___XD suffix. It would be nice if this went away at some
4244 point.
4245 2. We handle both the (old) purely type-based representation of
4246 renamings and the (new) variable-based encoding. At some point,
4247 it is devoutly to be hoped that the former goes away
4248 (FIXME: hilfinger-2007-07-09).
4249 3. Subprogram renamings are not implemented, although the XRS
4250 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4251
4252/* If SYM encodes a renaming,
4253
4254 <renaming> renames <renamed entity>,
4255
4256 sets *LEN to the length of the renamed entity's name,
4257 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4258 the string describing the subcomponent selected from the renamed
0963b4bd 4259 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
aeb5907d
JB
4260 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4261 are undefined). Otherwise, returns a value indicating the category
4262 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4263 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4264 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4265 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4266 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4267 may be NULL, in which case they are not assigned.
4268
4269 [Currently, however, GCC does not generate subprogram renamings.] */
4270
4271enum ada_renaming_category
4272ada_parse_renaming (struct symbol *sym,
4273 const char **renamed_entity, int *len,
4274 const char **renaming_expr)
4275{
4276 enum ada_renaming_category kind;
4277 const char *info;
4278 const char *suffix;
4279
4280 if (sym == NULL)
4281 return ADA_NOT_RENAMING;
66d7f48f 4282 switch (sym->aclass ())
14f9c5c9 4283 {
aeb5907d
JB
4284 default:
4285 return ADA_NOT_RENAMING;
aeb5907d
JB
4286 case LOC_LOCAL:
4287 case LOC_STATIC:
4288 case LOC_COMPUTED:
4289 case LOC_OPTIMIZED_OUT:
987012b8 4290 info = strstr (sym->linkage_name (), "___XR");
aeb5907d
JB
4291 if (info == NULL)
4292 return ADA_NOT_RENAMING;
4293 switch (info[5])
4294 {
4295 case '_':
4296 kind = ADA_OBJECT_RENAMING;
4297 info += 6;
4298 break;
4299 case 'E':
4300 kind = ADA_EXCEPTION_RENAMING;
4301 info += 7;
4302 break;
4303 case 'P':
4304 kind = ADA_PACKAGE_RENAMING;
4305 info += 7;
4306 break;
4307 case 'S':
4308 kind = ADA_SUBPROGRAM_RENAMING;
4309 info += 7;
4310 break;
4311 default:
4312 return ADA_NOT_RENAMING;
4313 }
14f9c5c9 4314 }
4c4b4cd2 4315
de93309a
SM
4316 if (renamed_entity != NULL)
4317 *renamed_entity = info;
4318 suffix = strstr (info, "___XE");
4319 if (suffix == NULL || suffix == info)
4320 return ADA_NOT_RENAMING;
4321 if (len != NULL)
4322 *len = strlen (info) - strlen (suffix);
4323 suffix += 5;
4324 if (renaming_expr != NULL)
4325 *renaming_expr = suffix;
4326 return kind;
4327}
4328
4329/* Compute the value of the given RENAMING_SYM, which is expected to
4330 be a symbol encoding a renaming expression. BLOCK is the block
4331 used to evaluate the renaming. */
4332
4333static struct value *
4334ada_read_renaming_var_value (struct symbol *renaming_sym,
4335 const struct block *block)
4336{
4337 const char *sym_name;
4338
987012b8 4339 sym_name = renaming_sym->linkage_name ();
de93309a
SM
4340 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4341 return evaluate_expression (expr.get ());
4342}
4343\f
4344
dda83cd7 4345 /* Evaluation: Function Calls */
de93309a
SM
4346
4347/* Return an lvalue containing the value VAL. This is the identity on
4348 lvalues, and otherwise has the side-effect of allocating memory
4349 in the inferior where a copy of the value contents is copied. */
4350
4351static struct value *
4352ensure_lval (struct value *val)
4353{
736355f2
TT
4354 if (val->lval () == not_lval
4355 || val->lval () == lval_internalvar)
de93309a 4356 {
d0c97917 4357 int len = ada_check_typedef (val->type ())->length ();
de93309a 4358 const CORE_ADDR addr =
dda83cd7 4359 value_as_long (value_allocate_space_in_inferior (len));
de93309a 4360
6f9c9d71 4361 val->set_lval (lval_memory);
9feb2d07 4362 val->set_address (addr);
efaf1ae0 4363 write_memory (addr, val->contents ().data (), len);
de93309a
SM
4364 }
4365
4366 return val;
4367}
4368
4369/* Given ARG, a value of type (pointer or reference to a)*
4370 structure/union, extract the component named NAME from the ultimate
4371 target structure/union and return it as a value with its
4372 appropriate type.
4373
4374 The routine searches for NAME among all members of the structure itself
4375 and (recursively) among all members of any wrapper members
4376 (e.g., '_parent').
4377
4378 If NO_ERR, then simply return NULL in case of error, rather than
4379 calling error. */
4380
4381static struct value *
4382ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4383{
4384 struct type *t, *t1;
4385 struct value *v;
4386 int check_tag;
4387
4388 v = NULL;
d0c97917 4389 t1 = t = ada_check_typedef (arg->type ());
78134374 4390 if (t->code () == TYPE_CODE_REF)
de93309a 4391 {
27710edb 4392 t1 = t->target_type ();
de93309a
SM
4393 if (t1 == NULL)
4394 goto BadValue;
4395 t1 = ada_check_typedef (t1);
78134374 4396 if (t1->code () == TYPE_CODE_PTR)
dda83cd7
SM
4397 {
4398 arg = coerce_ref (arg);
4399 t = t1;
4400 }
de93309a
SM
4401 }
4402
78134374 4403 while (t->code () == TYPE_CODE_PTR)
de93309a 4404 {
27710edb 4405 t1 = t->target_type ();
de93309a
SM
4406 if (t1 == NULL)
4407 goto BadValue;
4408 t1 = ada_check_typedef (t1);
78134374 4409 if (t1->code () == TYPE_CODE_PTR)
dda83cd7
SM
4410 {
4411 arg = value_ind (arg);
4412 t = t1;
4413 }
de93309a 4414 else
dda83cd7 4415 break;
de93309a 4416 }
aeb5907d 4417
78134374 4418 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
de93309a 4419 goto BadValue;
52ce6436 4420
de93309a
SM
4421 if (t1 == t)
4422 v = ada_search_struct_field (name, arg, 0, t);
4423 else
4424 {
4425 int bit_offset, bit_size, byte_offset;
4426 struct type *field_type;
4427 CORE_ADDR address;
a5ee536b 4428
78134374 4429 if (t->code () == TYPE_CODE_PTR)
9feb2d07 4430 address = ada_value_ind (arg)->address ();
de93309a 4431 else
9feb2d07 4432 address = ada_coerce_ref (arg)->address ();
d2e4a39e 4433
de93309a 4434 /* Check to see if this is a tagged type. We also need to handle
dda83cd7
SM
4435 the case where the type is a reference to a tagged type, but
4436 we have to be careful to exclude pointers to tagged types.
4437 The latter should be shown as usual (as a pointer), whereas
4438 a reference should mostly be transparent to the user. */
14f9c5c9 4439
de93309a 4440 if (ada_is_tagged_type (t1, 0)
dda83cd7 4441 || (t1->code () == TYPE_CODE_REF
27710edb 4442 && ada_is_tagged_type (t1->target_type (), 0)))
dda83cd7
SM
4443 {
4444 /* We first try to find the searched field in the current type.
de93309a 4445 If not found then let's look in the fixed type. */
14f9c5c9 4446
dda83cd7 4447 if (!find_struct_field (name, t1, 0,
4d1795ac
TT
4448 nullptr, nullptr, nullptr,
4449 nullptr, nullptr))
de93309a
SM
4450 check_tag = 1;
4451 else
4452 check_tag = 0;
dda83cd7 4453 }
de93309a
SM
4454 else
4455 check_tag = 0;
c3e5cd34 4456
de93309a
SM
4457 /* Convert to fixed type in all cases, so that we have proper
4458 offsets to each field in unconstrained record types. */
4459 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4460 address, NULL, check_tag);
4461
24aa1b02
TT
4462 /* Resolve the dynamic type as well. */
4463 arg = value_from_contents_and_address (t1, nullptr, address);
d0c97917 4464 t1 = arg->type ();
24aa1b02 4465
de93309a 4466 if (find_struct_field (name, t1, 0,
dda83cd7
SM
4467 &field_type, &byte_offset, &bit_offset,
4468 &bit_size, NULL))
4469 {
4470 if (bit_size != 0)
4471 {
4472 if (t->code () == TYPE_CODE_REF)
4473 arg = ada_coerce_ref (arg);
4474 else
4475 arg = ada_value_ind (arg);
4476 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4477 bit_offset, bit_size,
4478 field_type);
4479 }
4480 else
4481 v = value_at_lazy (field_type, address + byte_offset);
4482 }
c3e5cd34 4483 }
14f9c5c9 4484
de93309a
SM
4485 if (v != NULL || no_err)
4486 return v;
4487 else
4488 error (_("There is no member named %s."), name);
4489
4490 BadValue:
4491 if (no_err)
4492 return NULL;
4493 else
4494 error (_("Attempt to extract a component of "
4495 "a value that is not a record."));
14f9c5c9
AS
4496}
4497
4498/* Return the value ACTUAL, converted to be an appropriate value for a
4499 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4500 allocating any necessary descriptors (fat pointers), or copies of
4c4b4cd2 4501 values not residing in memory, updating it as needed. */
14f9c5c9 4502
a93c0eb6 4503struct value *
40bc484c 4504ada_convert_actual (struct value *actual, struct type *formal_type0)
14f9c5c9 4505{
d0c97917 4506 struct type *actual_type = ada_check_typedef (actual->type ());
61ee279c 4507 struct type *formal_type = ada_check_typedef (formal_type0);
d2e4a39e 4508 struct type *formal_target =
78134374 4509 formal_type->code () == TYPE_CODE_PTR
27710edb 4510 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
d2e4a39e 4511 struct type *actual_target =
78134374 4512 actual_type->code () == TYPE_CODE_PTR
27710edb 4513 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
14f9c5c9 4514
4c4b4cd2 4515 if (ada_is_array_descriptor_type (formal_target)
78134374 4516 && actual_target->code () == TYPE_CODE_ARRAY)
40bc484c 4517 return make_array_descriptor (formal_type, actual);
78134374
SM
4518 else if (formal_type->code () == TYPE_CODE_PTR
4519 || formal_type->code () == TYPE_CODE_REF)
14f9c5c9 4520 {
a84a8a0d 4521 struct value *result;
5b4ee69b 4522
78134374 4523 if (formal_target->code () == TYPE_CODE_ARRAY
dda83cd7 4524 && ada_is_array_descriptor_type (actual_target))
a84a8a0d 4525 result = desc_data (actual);
78134374 4526 else if (formal_type->code () != TYPE_CODE_PTR)
dda83cd7 4527 {
736355f2 4528 if (actual->lval () != lval_memory)
dda83cd7
SM
4529 {
4530 struct value *val;
4531
d0c97917 4532 actual_type = ada_check_typedef (actual->type ());
317c3ed9 4533 val = value::allocate (actual_type);
efaf1ae0 4534 copy (actual->contents (), val->contents_raw ());
dda83cd7
SM
4535 actual = ensure_lval (val);
4536 }
4537 result = value_addr (actual);
4538 }
a84a8a0d
JB
4539 else
4540 return actual;
b1af9e97 4541 return value_cast_pointers (formal_type, result, 0);
14f9c5c9 4542 }
78134374 4543 else if (actual_type->code () == TYPE_CODE_PTR)
14f9c5c9 4544 return ada_value_ind (actual);
8344af1e
JB
4545 else if (ada_is_aligner_type (formal_type))
4546 {
4547 /* We need to turn this parameter into an aligner type
4548 as well. */
317c3ed9 4549 struct value *aligner = value::allocate (formal_type);
8344af1e
JB
4550 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4551
4552 value_assign_to_component (aligner, component, actual);
4553 return aligner;
4554 }
14f9c5c9
AS
4555
4556 return actual;
4557}
4558
438c98a1
JB
4559/* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4560 type TYPE. This is usually an inefficient no-op except on some targets
4561 (such as AVR) where the representation of a pointer and an address
4562 differs. */
4563
4564static CORE_ADDR
4565value_pointer (struct value *value, struct type *type)
4566{
df86565b 4567 unsigned len = type->length ();
224c3ddb 4568 gdb_byte *buf = (gdb_byte *) alloca (len);
438c98a1
JB
4569 CORE_ADDR addr;
4570
9feb2d07 4571 addr = value->address ();
8ee511af 4572 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
34877895 4573 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
438c98a1
JB
4574 return addr;
4575}
4576
14f9c5c9 4577
4c4b4cd2
PH
4578/* Push a descriptor of type TYPE for array value ARR on the stack at
4579 *SP, updating *SP to reflect the new descriptor. Return either
14f9c5c9 4580 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4c4b4cd2
PH
4581 to-descriptor type rather than a descriptor type), a struct value *
4582 representing a pointer to this descriptor. */
14f9c5c9 4583
d2e4a39e 4584static struct value *
40bc484c 4585make_array_descriptor (struct type *type, struct value *arr)
14f9c5c9 4586{
d2e4a39e
AS
4587 struct type *bounds_type = desc_bounds_type (type);
4588 struct type *desc_type = desc_base_type (type);
317c3ed9
TT
4589 struct value *descriptor = value::allocate (desc_type);
4590 struct value *bounds = value::allocate (bounds_type);
14f9c5c9 4591 int i;
d2e4a39e 4592
d0c97917 4593 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
0963b4bd 4594 i > 0; i -= 1)
14f9c5c9 4595 {
d0c97917 4596 modify_field (bounds->type (),
bbe912ba 4597 bounds->contents_writeable ().data (),
19f220c3
JK
4598 ada_array_bound (arr, i, 0),
4599 desc_bound_bitpos (bounds_type, i, 0),
4600 desc_bound_bitsize (bounds_type, i, 0));
d0c97917 4601 modify_field (bounds->type (),
bbe912ba 4602 bounds->contents_writeable ().data (),
19f220c3
JK
4603 ada_array_bound (arr, i, 1),
4604 desc_bound_bitpos (bounds_type, i, 1),
4605 desc_bound_bitsize (bounds_type, i, 1));
14f9c5c9 4606 }
d2e4a39e 4607
40bc484c 4608 bounds = ensure_lval (bounds);
d2e4a39e 4609
d0c97917 4610 modify_field (descriptor->type (),
bbe912ba 4611 descriptor->contents_writeable ().data (),
19f220c3 4612 value_pointer (ensure_lval (arr),
940da03e 4613 desc_type->field (0).type ()),
19f220c3
JK
4614 fat_pntr_data_bitpos (desc_type),
4615 fat_pntr_data_bitsize (desc_type));
4616
d0c97917 4617 modify_field (descriptor->type (),
bbe912ba 4618 descriptor->contents_writeable ().data (),
19f220c3 4619 value_pointer (bounds,
940da03e 4620 desc_type->field (1).type ()),
19f220c3
JK
4621 fat_pntr_bounds_bitpos (desc_type),
4622 fat_pntr_bounds_bitsize (desc_type));
14f9c5c9 4623
40bc484c 4624 descriptor = ensure_lval (descriptor);
14f9c5c9 4625
78134374 4626 if (type->code () == TYPE_CODE_PTR)
14f9c5c9
AS
4627 return value_addr (descriptor);
4628 else
4629 return descriptor;
4630}
14f9c5c9 4631\f
dda83cd7 4632 /* Symbol Cache Module */
3d9434b5 4633
3d9434b5 4634/* Performance measurements made as of 2010-01-15 indicate that
ee01b665 4635 this cache does bring some noticeable improvements. Depending
3d9434b5
JB
4636 on the type of entity being printed, the cache can make it as much
4637 as an order of magnitude faster than without it.
4638
4639 The descriptive type DWARF extension has significantly reduced
4640 the need for this cache, at least when DWARF is being used. However,
4641 even in this case, some expensive name-based symbol searches are still
4642 sometimes necessary - to find an XVZ variable, mostly. */
4643
ee01b665
JB
4644/* Return the symbol cache associated to the given program space PSPACE.
4645 If not allocated for this PSPACE yet, allocate and initialize one. */
3d9434b5 4646
ee01b665
JB
4647static struct ada_symbol_cache *
4648ada_get_symbol_cache (struct program_space *pspace)
4649{
4650 struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
ee01b665 4651
bdcccc56
TT
4652 if (pspace_data->sym_cache == nullptr)
4653 pspace_data->sym_cache.reset (new ada_symbol_cache);
ee01b665 4654
bdcccc56 4655 return pspace_data->sym_cache.get ();
ee01b665 4656}
3d9434b5
JB
4657
4658/* Clear all entries from the symbol cache. */
4659
4660static void
bdcccc56 4661ada_clear_symbol_cache ()
3d9434b5 4662{
bdcccc56
TT
4663 struct ada_pspace_data *pspace_data
4664 = get_ada_pspace_data (current_program_space);
ee01b665 4665
bdcccc56
TT
4666 if (pspace_data->sym_cache != nullptr)
4667 pspace_data->sym_cache.reset ();
3d9434b5
JB
4668}
4669
fe978cb0 4670/* Search our cache for an entry matching NAME and DOMAIN.
3d9434b5
JB
4671 Return it if found, or NULL otherwise. */
4672
4673static struct cache_entry **
fe978cb0 4674find_entry (const char *name, domain_enum domain)
3d9434b5 4675{
ee01b665
JB
4676 struct ada_symbol_cache *sym_cache
4677 = ada_get_symbol_cache (current_program_space);
3d9434b5
JB
4678 int h = msymbol_hash (name) % HASH_SIZE;
4679 struct cache_entry **e;
4680
ee01b665 4681 for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
3d9434b5 4682 {
fe978cb0 4683 if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
dda83cd7 4684 return e;
3d9434b5
JB
4685 }
4686 return NULL;
4687}
4688
fe978cb0 4689/* Search the symbol cache for an entry matching NAME and DOMAIN.
3d9434b5
JB
4690 Return 1 if found, 0 otherwise.
4691
4692 If an entry was found and SYM is not NULL, set *SYM to the entry's
4693 SYM. Same principle for BLOCK if not NULL. */
96d887e8 4694
96d887e8 4695static int
fe978cb0 4696lookup_cached_symbol (const char *name, domain_enum domain,
dda83cd7 4697 struct symbol **sym, const struct block **block)
96d887e8 4698{
fe978cb0 4699 struct cache_entry **e = find_entry (name, domain);
3d9434b5
JB
4700
4701 if (e == NULL)
4702 return 0;
4703 if (sym != NULL)
4704 *sym = (*e)->sym;
4705 if (block != NULL)
4706 *block = (*e)->block;
4707 return 1;
96d887e8
PH
4708}
4709
3d9434b5 4710/* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
fe978cb0 4711 in domain DOMAIN, save this result in our symbol cache. */
3d9434b5 4712
96d887e8 4713static void
fe978cb0 4714cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
dda83cd7 4715 const struct block *block)
96d887e8 4716{
ee01b665
JB
4717 struct ada_symbol_cache *sym_cache
4718 = ada_get_symbol_cache (current_program_space);
3d9434b5 4719 int h;
3d9434b5
JB
4720 struct cache_entry *e;
4721
1994afbf
DE
4722 /* Symbols for builtin types don't have a block.
4723 For now don't cache such symbols. */
7b3ecc75 4724 if (sym != NULL && !sym->is_objfile_owned ())
1994afbf
DE
4725 return;
4726
3d9434b5
JB
4727 /* If the symbol is a local symbol, then do not cache it, as a search
4728 for that symbol depends on the context. To determine whether
4729 the symbol is local or not, we check the block where we found it
4730 against the global and static blocks of its associated symtab. */
63d609de
SM
4731 if (sym != nullptr)
4732 {
4733 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4734
4735 if (bv.global_block () != block && bv.static_block () != block)
4736 return;
4737 }
3d9434b5
JB
4738
4739 h = msymbol_hash (name) % HASH_SIZE;
e39db4db 4740 e = XOBNEW (&sym_cache->cache_space, cache_entry);
ee01b665
JB
4741 e->next = sym_cache->root[h];
4742 sym_cache->root[h] = e;
2ef5453b 4743 e->name = obstack_strdup (&sym_cache->cache_space, name);
3d9434b5 4744 e->sym = sym;
fe978cb0 4745 e->domain = domain;
3d9434b5 4746 e->block = block;
96d887e8 4747}
4c4b4cd2 4748\f
dda83cd7 4749 /* Symbol Lookup */
4c4b4cd2 4750
b5ec771e
PA
4751/* Return the symbol name match type that should be used used when
4752 searching for all symbols matching LOOKUP_NAME.
c0431670
JB
4753
4754 LOOKUP_NAME is expected to be a symbol name after transformation
f98b2e33 4755 for Ada lookups. */
c0431670 4756
b5ec771e
PA
4757static symbol_name_match_type
4758name_match_type_from_name (const char *lookup_name)
c0431670 4759{
b5ec771e
PA
4760 return (strstr (lookup_name, "__") == NULL
4761 ? symbol_name_match_type::WILD
4762 : symbol_name_match_type::FULL);
c0431670
JB
4763}
4764
4c4b4cd2
PH
4765/* Return the result of a standard (literal, C-like) lookup of NAME in
4766 given DOMAIN, visible from lexical block BLOCK. */
4767
4768static struct symbol *
4769standard_lookup (const char *name, const struct block *block,
dda83cd7 4770 domain_enum domain)
4c4b4cd2 4771{
acbd605d 4772 /* Initialize it just to avoid a GCC false warning. */
6640a367 4773 struct block_symbol sym = {};
4c4b4cd2 4774
d12307c1
PMR
4775 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4776 return sym.symbol;
a2cd4f14 4777 ada_lookup_encoded_symbol (name, block, domain, &sym);
d12307c1
PMR
4778 cache_symbol (name, domain, sym.symbol, sym.block);
4779 return sym.symbol;
4c4b4cd2
PH
4780}
4781
4782
4783/* Non-zero iff there is at least one non-function/non-enumeral symbol
1bfa81ac 4784 in the symbol fields of SYMS. We treat enumerals as functions,
4c4b4cd2
PH
4785 since they contend in overloading in the same way. */
4786static int
d1183b06 4787is_nonfunction (const std::vector<struct block_symbol> &syms)
4c4b4cd2 4788{
d1183b06 4789 for (const block_symbol &sym : syms)
5f9c5a63
SM
4790 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4791 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
66d7f48f 4792 || sym.symbol->aclass () != LOC_CONST))
14f9c5c9
AS
4793 return 1;
4794
4795 return 0;
4796}
4797
4798/* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4c4b4cd2 4799 struct types. Otherwise, they may not. */
14f9c5c9
AS
4800
4801static int
d2e4a39e 4802equiv_types (struct type *type0, struct type *type1)
14f9c5c9 4803{
d2e4a39e 4804 if (type0 == type1)
14f9c5c9 4805 return 1;
d2e4a39e 4806 if (type0 == NULL || type1 == NULL
78134374 4807 || type0->code () != type1->code ())
14f9c5c9 4808 return 0;
78134374
SM
4809 if ((type0->code () == TYPE_CODE_STRUCT
4810 || type0->code () == TYPE_CODE_ENUM)
14f9c5c9 4811 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4c4b4cd2 4812 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
14f9c5c9 4813 return 1;
d2e4a39e 4814
14f9c5c9
AS
4815 return 0;
4816}
4817
4818/* True iff SYM0 represents the same entity as SYM1, or one that is
4c4b4cd2 4819 no more defined than that of SYM1. */
14f9c5c9
AS
4820
4821static int
d2e4a39e 4822lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
14f9c5c9
AS
4823{
4824 if (sym0 == sym1)
4825 return 1;
6c9c307c 4826 if (sym0->domain () != sym1->domain ()
66d7f48f 4827 || sym0->aclass () != sym1->aclass ())
14f9c5c9
AS
4828 return 0;
4829
66d7f48f 4830 switch (sym0->aclass ())
14f9c5c9
AS
4831 {
4832 case LOC_UNDEF:
4833 return 1;
4834 case LOC_TYPEDEF:
4835 {
5f9c5a63
SM
4836 struct type *type0 = sym0->type ();
4837 struct type *type1 = sym1->type ();
dda83cd7
SM
4838 const char *name0 = sym0->linkage_name ();
4839 const char *name1 = sym1->linkage_name ();
4840 int len0 = strlen (name0);
4841
4842 return
4843 type0->code () == type1->code ()
4844 && (equiv_types (type0, type1)
4845 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4846 && startswith (name1 + len0, "___XV")));
14f9c5c9
AS
4847 }
4848 case LOC_CONST:
4aeddc50 4849 return sym0->value_longest () == sym1->value_longest ()
5f9c5a63 4850 && equiv_types (sym0->type (), sym1->type ());
4b610737
TT
4851
4852 case LOC_STATIC:
4853 {
dda83cd7
SM
4854 const char *name0 = sym0->linkage_name ();
4855 const char *name1 = sym1->linkage_name ();
4856 return (strcmp (name0, name1) == 0
4aeddc50 4857 && sym0->value_address () == sym1->value_address ());
4b610737
TT
4858 }
4859
d2e4a39e
AS
4860 default:
4861 return 0;
14f9c5c9
AS
4862 }
4863}
4864
d1183b06
TT
4865/* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4866 records in RESULT. Do nothing if SYM is a duplicate. */
14f9c5c9
AS
4867
4868static void
d1183b06 4869add_defn_to_vec (std::vector<struct block_symbol> &result,
dda83cd7
SM
4870 struct symbol *sym,
4871 const struct block *block)
14f9c5c9 4872{
529cad9c
PH
4873 /* Do not try to complete stub types, as the debugger is probably
4874 already scanning all symbols matching a certain name at the
4875 time when this function is called. Trying to replace the stub
4876 type by its associated full type will cause us to restart a scan
4877 which may lead to an infinite recursion. Instead, the client
4878 collecting the matching symbols will end up collecting several
4879 matches, with at least one of them complete. It can then filter
4880 out the stub ones if needed. */
4881
d1183b06 4882 for (int i = result.size () - 1; i >= 0; i -= 1)
4c4b4cd2 4883 {
d1183b06 4884 if (lesseq_defined_than (sym, result[i].symbol))
dda83cd7 4885 return;
d1183b06 4886 else if (lesseq_defined_than (result[i].symbol, sym))
dda83cd7 4887 {
d1183b06
TT
4888 result[i].symbol = sym;
4889 result[i].block = block;
dda83cd7
SM
4890 return;
4891 }
4c4b4cd2
PH
4892 }
4893
d1183b06
TT
4894 struct block_symbol info;
4895 info.symbol = sym;
4896 info.block = block;
4897 result.push_back (info);
4c4b4cd2
PH
4898}
4899
7c7b6655
TT
4900/* Return a bound minimal symbol matching NAME according to Ada
4901 decoding rules. Returns an invalid symbol if there is no such
4902 minimal symbol. Names prefixed with "standard__" are handled
4903 specially: "standard__" is first stripped off, and only static and
4904 global symbols are searched. */
4c4b4cd2 4905
7c7b6655 4906struct bound_minimal_symbol
06a670e2 4907ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4c4b4cd2 4908{
7c7b6655 4909 struct bound_minimal_symbol result;
4c4b4cd2 4910
b5ec771e
PA
4911 symbol_name_match_type match_type = name_match_type_from_name (name);
4912 lookup_name_info lookup_name (name, match_type);
4913
4914 symbol_name_matcher_ftype *match_name
4915 = ada_get_symbol_name_matcher (lookup_name);
4c4b4cd2 4916
06a670e2
MM
4917 gdbarch_iterate_over_objfiles_in_search_order
4918 (objfile != NULL ? objfile->arch () : target_gdbarch (),
4919 [&result, lookup_name, match_name] (struct objfile *obj)
4920 {
4921 for (minimal_symbol *msymbol : obj->msymbols ())
4922 {
4923 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4924 && msymbol->type () != mst_solib_trampoline)
4925 {
4926 result.minsym = msymbol;
4927 result.objfile = obj;
4928 return 1;
4929 }
4930 }
4931
4932 return 0;
4933 }, objfile);
4c4b4cd2 4934
7c7b6655 4935 return result;
96d887e8 4936}
4c4b4cd2 4937
96d887e8
PH
4938/* True if TYPE is definitely an artificial type supplied to a symbol
4939 for which no debugging information was given in the symbol file. */
14f9c5c9 4940
96d887e8
PH
4941static int
4942is_nondebugging_type (struct type *type)
4943{
0d5cff50 4944 const char *name = ada_type_name (type);
5b4ee69b 4945
96d887e8
PH
4946 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4947}
4c4b4cd2 4948
8f17729f
JB
4949/* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4950 that are deemed "identical" for practical purposes.
4951
4952 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4953 types and that their number of enumerals is identical (in other
1f704f76 4954 words, type1->num_fields () == type2->num_fields ()). */
8f17729f
JB
4955
4956static int
4957ada_identical_enum_types_p (struct type *type1, struct type *type2)
4958{
4959 int i;
4960
4961 /* The heuristic we use here is fairly conservative. We consider
4962 that 2 enumerate types are identical if they have the same
4963 number of enumerals and that all enumerals have the same
4964 underlying value and name. */
4965
4966 /* All enums in the type should have an identical underlying value. */
1f704f76 4967 for (i = 0; i < type1->num_fields (); i++)
970db518 4968 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
8f17729f
JB
4969 return 0;
4970
4971 /* All enumerals should also have the same name (modulo any numerical
4972 suffix). */
1f704f76 4973 for (i = 0; i < type1->num_fields (); i++)
8f17729f 4974 {
33d16dd9
SM
4975 const char *name_1 = type1->field (i).name ();
4976 const char *name_2 = type2->field (i).name ();
8f17729f
JB
4977 int len_1 = strlen (name_1);
4978 int len_2 = strlen (name_2);
4979
33d16dd9
SM
4980 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4981 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
8f17729f 4982 if (len_1 != len_2
33d16dd9
SM
4983 || strncmp (type1->field (i).name (),
4984 type2->field (i).name (),
8f17729f
JB
4985 len_1) != 0)
4986 return 0;
4987 }
4988
4989 return 1;
4990}
4991
4992/* Return nonzero if all the symbols in SYMS are all enumeral symbols
4993 that are deemed "identical" for practical purposes. Sometimes,
4994 enumerals are not strictly identical, but their types are so similar
4995 that they can be considered identical.
4996
4997 For instance, consider the following code:
4998
4999 type Color is (Black, Red, Green, Blue, White);
5000 type RGB_Color is new Color range Red .. Blue;
5001
5002 Type RGB_Color is a subrange of an implicit type which is a copy
5003 of type Color. If we call that implicit type RGB_ColorB ("B" is
5004 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5005 As a result, when an expression references any of the enumeral
5006 by name (Eg. "print green"), the expression is technically
5007 ambiguous and the user should be asked to disambiguate. But
5008 doing so would only hinder the user, since it wouldn't matter
5009 what choice he makes, the outcome would always be the same.
5010 So, for practical purposes, we consider them as the same. */
5011
5012static int
54d343a2 5013symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
8f17729f
JB
5014{
5015 int i;
5016
5017 /* Before performing a thorough comparison check of each type,
5018 we perform a series of inexpensive checks. We expect that these
5019 checks will quickly fail in the vast majority of cases, and thus
5020 help prevent the unnecessary use of a more expensive comparison.
5021 Said comparison also expects us to make some of these checks
5022 (see ada_identical_enum_types_p). */
5023
5024 /* Quick check: All symbols should have an enum type. */
54d343a2 5025 for (i = 0; i < syms.size (); i++)
5f9c5a63 5026 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
8f17729f
JB
5027 return 0;
5028
5029 /* Quick check: They should all have the same value. */
54d343a2 5030 for (i = 1; i < syms.size (); i++)
4aeddc50 5031 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
8f17729f
JB
5032 return 0;
5033
5034 /* Quick check: They should all have the same number of enumerals. */
54d343a2 5035 for (i = 1; i < syms.size (); i++)
5f9c5a63
SM
5036 if (syms[i].symbol->type ()->num_fields ()
5037 != syms[0].symbol->type ()->num_fields ())
8f17729f
JB
5038 return 0;
5039
5040 /* All the sanity checks passed, so we might have a set of
5041 identical enumeration types. Perform a more complete
5042 comparison of the type of each symbol. */
54d343a2 5043 for (i = 1; i < syms.size (); i++)
5f9c5a63
SM
5044 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5045 syms[0].symbol->type ()))
8f17729f
JB
5046 return 0;
5047
5048 return 1;
5049}
5050
54d343a2 5051/* Remove any non-debugging symbols in SYMS that definitely
96d887e8
PH
5052 duplicate other symbols in the list (The only case I know of where
5053 this happens is when object files containing stabs-in-ecoff are
5054 linked with files containing ordinary ecoff debugging symbols (or no
1bfa81ac 5055 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
4c4b4cd2 5056
d1183b06 5057static void
54d343a2 5058remove_extra_symbols (std::vector<struct block_symbol> *syms)
96d887e8
PH
5059{
5060 int i, j;
4c4b4cd2 5061
8f17729f
JB
5062 /* We should never be called with less than 2 symbols, as there
5063 cannot be any extra symbol in that case. But it's easy to
5064 handle, since we have nothing to do in that case. */
54d343a2 5065 if (syms->size () < 2)
d1183b06 5066 return;
8f17729f 5067
96d887e8 5068 i = 0;
54d343a2 5069 while (i < syms->size ())
96d887e8 5070 {
a35ddb44 5071 int remove_p = 0;
339c13b6
JB
5072
5073 /* If two symbols have the same name and one of them is a stub type,
dda83cd7 5074 the get rid of the stub. */
339c13b6 5075
5f9c5a63 5076 if ((*syms)[i].symbol->type ()->is_stub ()
dda83cd7
SM
5077 && (*syms)[i].symbol->linkage_name () != NULL)
5078 {
5079 for (j = 0; j < syms->size (); j++)
5080 {
5081 if (j != i
5f9c5a63 5082 && !(*syms)[j].symbol->type ()->is_stub ()
dda83cd7
SM
5083 && (*syms)[j].symbol->linkage_name () != NULL
5084 && strcmp ((*syms)[i].symbol->linkage_name (),
5085 (*syms)[j].symbol->linkage_name ()) == 0)
5086 remove_p = 1;
5087 }
5088 }
339c13b6
JB
5089
5090 /* Two symbols with the same name, same class and same address
dda83cd7 5091 should be identical. */
339c13b6 5092
987012b8 5093 else if ((*syms)[i].symbol->linkage_name () != NULL
66d7f48f 5094 && (*syms)[i].symbol->aclass () == LOC_STATIC
5f9c5a63 5095 && is_nondebugging_type ((*syms)[i].symbol->type ()))
dda83cd7
SM
5096 {
5097 for (j = 0; j < syms->size (); j += 1)
5098 {
5099 if (i != j
5100 && (*syms)[j].symbol->linkage_name () != NULL
5101 && strcmp ((*syms)[i].symbol->linkage_name (),
5102 (*syms)[j].symbol->linkage_name ()) == 0
66d7f48f
SM
5103 && ((*syms)[i].symbol->aclass ()
5104 == (*syms)[j].symbol->aclass ())
4aeddc50
SM
5105 && (*syms)[i].symbol->value_address ()
5106 == (*syms)[j].symbol->value_address ())
dda83cd7
SM
5107 remove_p = 1;
5108 }
5109 }
339c13b6 5110
a35ddb44 5111 if (remove_p)
54d343a2 5112 syms->erase (syms->begin () + i);
1b788fb6
TT
5113 else
5114 i += 1;
14f9c5c9 5115 }
8f17729f
JB
5116
5117 /* If all the remaining symbols are identical enumerals, then
5118 just keep the first one and discard the rest.
5119
5120 Unlike what we did previously, we do not discard any entry
5121 unless they are ALL identical. This is because the symbol
5122 comparison is not a strict comparison, but rather a practical
5123 comparison. If all symbols are considered identical, then
5124 we can just go ahead and use the first one and discard the rest.
5125 But if we cannot reduce the list to a single element, we have
5126 to ask the user to disambiguate anyways. And if we have to
5127 present a multiple-choice menu, it's less confusing if the list
5128 isn't missing some choices that were identical and yet distinct. */
54d343a2
TT
5129 if (symbols_are_identical_enums (*syms))
5130 syms->resize (1);
14f9c5c9
AS
5131}
5132
96d887e8
PH
5133/* Given a type that corresponds to a renaming entity, use the type name
5134 to extract the scope (package name or function name, fully qualified,
5135 and following the GNAT encoding convention) where this renaming has been
49d83361 5136 defined. */
4c4b4cd2 5137
49d83361 5138static std::string
96d887e8 5139xget_renaming_scope (struct type *renaming_type)
14f9c5c9 5140{
96d887e8 5141 /* The renaming types adhere to the following convention:
0963b4bd 5142 <scope>__<rename>___<XR extension>.
96d887e8
PH
5143 So, to extract the scope, we search for the "___XR" extension,
5144 and then backtrack until we find the first "__". */
76a01679 5145
7d93a1e0 5146 const char *name = renaming_type->name ();
108d56a4
SM
5147 const char *suffix = strstr (name, "___XR");
5148 const char *last;
14f9c5c9 5149
96d887e8
PH
5150 /* Now, backtrack a bit until we find the first "__". Start looking
5151 at suffix - 3, as the <rename> part is at least one character long. */
14f9c5c9 5152
96d887e8
PH
5153 for (last = suffix - 3; last > name; last--)
5154 if (last[0] == '_' && last[1] == '_')
5155 break;
76a01679 5156
96d887e8 5157 /* Make a copy of scope and return it. */
49d83361 5158 return std::string (name, last);
4c4b4cd2
PH
5159}
5160
96d887e8 5161/* Return nonzero if NAME corresponds to a package name. */
4c4b4cd2 5162
96d887e8
PH
5163static int
5164is_package_name (const char *name)
4c4b4cd2 5165{
96d887e8
PH
5166 /* Here, We take advantage of the fact that no symbols are generated
5167 for packages, while symbols are generated for each function.
5168 So the condition for NAME represent a package becomes equivalent
5169 to NAME not existing in our list of symbols. There is only one
5170 small complication with library-level functions (see below). */
4c4b4cd2 5171
96d887e8
PH
5172 /* If it is a function that has not been defined at library level,
5173 then we should be able to look it up in the symbols. */
5174 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5175 return 0;
14f9c5c9 5176
96d887e8
PH
5177 /* Library-level function names start with "_ada_". See if function
5178 "_ada_" followed by NAME can be found. */
14f9c5c9 5179
96d887e8 5180 /* Do a quick check that NAME does not contain "__", since library-level
e1d5a0d2 5181 functions names cannot contain "__" in them. */
96d887e8
PH
5182 if (strstr (name, "__") != NULL)
5183 return 0;
4c4b4cd2 5184
528e1572 5185 std::string fun_name = string_printf ("_ada_%s", name);
14f9c5c9 5186
528e1572 5187 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
96d887e8 5188}
14f9c5c9 5189
96d887e8 5190/* Return nonzero if SYM corresponds to a renaming entity that is
aeb5907d 5191 not visible from FUNCTION_NAME. */
14f9c5c9 5192
96d887e8 5193static int
0d5cff50 5194old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
96d887e8 5195{
66d7f48f 5196 if (sym->aclass () != LOC_TYPEDEF)
aeb5907d
JB
5197 return 0;
5198
5f9c5a63 5199 std::string scope = xget_renaming_scope (sym->type ());
14f9c5c9 5200
96d887e8 5201 /* If the rename has been defined in a package, then it is visible. */
49d83361
TT
5202 if (is_package_name (scope.c_str ()))
5203 return 0;
14f9c5c9 5204
96d887e8
PH
5205 /* Check that the rename is in the current function scope by checking
5206 that its name starts with SCOPE. */
76a01679 5207
96d887e8
PH
5208 /* If the function name starts with "_ada_", it means that it is
5209 a library-level function. Strip this prefix before doing the
5210 comparison, as the encoding for the renaming does not contain
5211 this prefix. */
61012eef 5212 if (startswith (function_name, "_ada_"))
96d887e8 5213 function_name += 5;
f26caa11 5214
49d83361 5215 return !startswith (function_name, scope.c_str ());
f26caa11
PH
5216}
5217
aeb5907d
JB
5218/* Remove entries from SYMS that corresponds to a renaming entity that
5219 is not visible from the function associated with CURRENT_BLOCK or
5220 that is superfluous due to the presence of more specific renaming
5221 information. Places surviving symbols in the initial entries of
d1183b06
TT
5222 SYMS.
5223
96d887e8 5224 Rationale:
aeb5907d
JB
5225 First, in cases where an object renaming is implemented as a
5226 reference variable, GNAT may produce both the actual reference
5227 variable and the renaming encoding. In this case, we discard the
5228 latter.
5229
5230 Second, GNAT emits a type following a specified encoding for each renaming
96d887e8
PH
5231 entity. Unfortunately, STABS currently does not support the definition
5232 of types that are local to a given lexical block, so all renamings types
5233 are emitted at library level. As a consequence, if an application
5234 contains two renaming entities using the same name, and a user tries to
5235 print the value of one of these entities, the result of the ada symbol
5236 lookup will also contain the wrong renaming type.
f26caa11 5237
96d887e8
PH
5238 This function partially covers for this limitation by attempting to
5239 remove from the SYMS list renaming symbols that should be visible
5240 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5241 method with the current information available. The implementation
5242 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5243
5244 - When the user tries to print a rename in a function while there
dda83cd7
SM
5245 is another rename entity defined in a package: Normally, the
5246 rename in the function has precedence over the rename in the
5247 package, so the latter should be removed from the list. This is
5248 currently not the case.
5249
96d887e8 5250 - This function will incorrectly remove valid renames if
dda83cd7
SM
5251 the CURRENT_BLOCK corresponds to a function which symbol name
5252 has been changed by an "Export" pragma. As a consequence,
5253 the user will be unable to print such rename entities. */
4c4b4cd2 5254
d1183b06 5255static void
54d343a2
TT
5256remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5257 const struct block *current_block)
4c4b4cd2
PH
5258{
5259 struct symbol *current_function;
0d5cff50 5260 const char *current_function_name;
4c4b4cd2 5261 int i;
aeb5907d
JB
5262 int is_new_style_renaming;
5263
5264 /* If there is both a renaming foo___XR... encoded as a variable and
5265 a simple variable foo in the same block, discard the latter.
0963b4bd 5266 First, zero out such symbols, then compress. */
aeb5907d 5267 is_new_style_renaming = 0;
54d343a2 5268 for (i = 0; i < syms->size (); i += 1)
aeb5907d 5269 {
54d343a2
TT
5270 struct symbol *sym = (*syms)[i].symbol;
5271 const struct block *block = (*syms)[i].block;
aeb5907d
JB
5272 const char *name;
5273 const char *suffix;
5274
66d7f48f 5275 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
aeb5907d 5276 continue;
987012b8 5277 name = sym->linkage_name ();
aeb5907d
JB
5278 suffix = strstr (name, "___XR");
5279
5280 if (suffix != NULL)
5281 {
5282 int name_len = suffix - name;
5283 int j;
5b4ee69b 5284
aeb5907d 5285 is_new_style_renaming = 1;
54d343a2
TT
5286 for (j = 0; j < syms->size (); j += 1)
5287 if (i != j && (*syms)[j].symbol != NULL
987012b8 5288 && strncmp (name, (*syms)[j].symbol->linkage_name (),
aeb5907d 5289 name_len) == 0
54d343a2
TT
5290 && block == (*syms)[j].block)
5291 (*syms)[j].symbol = NULL;
aeb5907d
JB
5292 }
5293 }
5294 if (is_new_style_renaming)
5295 {
5296 int j, k;
5297
54d343a2
TT
5298 for (j = k = 0; j < syms->size (); j += 1)
5299 if ((*syms)[j].symbol != NULL)
aeb5907d 5300 {
54d343a2 5301 (*syms)[k] = (*syms)[j];
aeb5907d
JB
5302 k += 1;
5303 }
d1183b06
TT
5304 syms->resize (k);
5305 return;
aeb5907d 5306 }
4c4b4cd2
PH
5307
5308 /* Extract the function name associated to CURRENT_BLOCK.
5309 Abort if unable to do so. */
76a01679 5310
4c4b4cd2 5311 if (current_block == NULL)
d1183b06 5312 return;
76a01679 5313
3c9d0506 5314 current_function = current_block->linkage_function ();
4c4b4cd2 5315 if (current_function == NULL)
d1183b06 5316 return;
4c4b4cd2 5317
987012b8 5318 current_function_name = current_function->linkage_name ();
4c4b4cd2 5319 if (current_function_name == NULL)
d1183b06 5320 return;
4c4b4cd2
PH
5321
5322 /* Check each of the symbols, and remove it from the list if it is
5323 a type corresponding to a renaming that is out of the scope of
5324 the current block. */
5325
5326 i = 0;
54d343a2 5327 while (i < syms->size ())
4c4b4cd2 5328 {
54d343a2 5329 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
dda83cd7
SM
5330 == ADA_OBJECT_RENAMING
5331 && old_renaming_is_invisible ((*syms)[i].symbol,
54d343a2
TT
5332 current_function_name))
5333 syms->erase (syms->begin () + i);
4c4b4cd2 5334 else
dda83cd7 5335 i += 1;
4c4b4cd2 5336 }
4c4b4cd2
PH
5337}
5338
d1183b06 5339/* Add to RESULT all symbols from BLOCK (and its super-blocks)
cd458349 5340 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
339c13b6 5341
cd458349 5342 Note: This function assumes that RESULT is empty. */
339c13b6
JB
5343
5344static void
d1183b06 5345ada_add_local_symbols (std::vector<struct block_symbol> &result,
b5ec771e
PA
5346 const lookup_name_info &lookup_name,
5347 const struct block *block, domain_enum domain)
339c13b6 5348{
339c13b6
JB
5349 while (block != NULL)
5350 {
d1183b06 5351 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
339c13b6 5352
ba8694b6
TT
5353 /* If we found a non-function match, assume that's the one. We
5354 only check this when finding a function boundary, so that we
5355 can accumulate all results from intervening blocks first. */
6c00f721 5356 if (block->function () != nullptr && is_nonfunction (result))
dda83cd7 5357 return;
339c13b6 5358
f135fe72 5359 block = block->superblock ();
339c13b6 5360 }
339c13b6
JB
5361}
5362
2315bb2d 5363/* An object of this type is used as the callback argument when
40658b94 5364 calling the map_matching_symbols method. */
ccefe4c4 5365
40658b94 5366struct match_data
ccefe4c4 5367{
1bfa81ac
TT
5368 explicit match_data (std::vector<struct block_symbol> *rp)
5369 : resultp (rp)
5370 {
5371 }
5372 DISABLE_COPY_AND_ASSIGN (match_data);
5373
2315bb2d
TT
5374 bool operator() (struct block_symbol *bsym);
5375
1bfa81ac 5376 struct objfile *objfile = nullptr;
d1183b06 5377 std::vector<struct block_symbol> *resultp;
1bfa81ac 5378 struct symbol *arg_sym = nullptr;
1178743e 5379 bool found_sym = false;
ccefe4c4
TT
5380};
5381
2315bb2d
TT
5382/* A callback for add_nonlocal_symbols that adds symbol, found in
5383 BSYM, to a list of symbols. */
ccefe4c4 5384
2315bb2d
TT
5385bool
5386match_data::operator() (struct block_symbol *bsym)
ccefe4c4 5387{
199b4314
TT
5388 const struct block *block = bsym->block;
5389 struct symbol *sym = bsym->symbol;
5390
40658b94
PH
5391 if (sym == NULL)
5392 {
2315bb2d 5393 if (!found_sym && arg_sym != NULL)
dae58e04 5394 add_defn_to_vec (*resultp, arg_sym, block);
2315bb2d
TT
5395 found_sym = false;
5396 arg_sym = NULL;
40658b94
PH
5397 }
5398 else
5399 {
66d7f48f 5400 if (sym->aclass () == LOC_UNRESOLVED)
199b4314 5401 return true;
d9743061 5402 else if (sym->is_argument ())
2315bb2d 5403 arg_sym = sym;
40658b94
PH
5404 else
5405 {
2315bb2d 5406 found_sym = true;
dae58e04 5407 add_defn_to_vec (*resultp, sym, block);
40658b94
PH
5408 }
5409 }
199b4314 5410 return true;
40658b94
PH
5411}
5412
b5ec771e
PA
5413/* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5414 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
1bfa81ac 5415 symbols to RESULT. Return whether we found such symbols. */
22cee43f
PMR
5416
5417static int
d1183b06 5418ada_add_block_renamings (std::vector<struct block_symbol> &result,
22cee43f 5419 const struct block *block,
b5ec771e
PA
5420 const lookup_name_info &lookup_name,
5421 domain_enum domain)
22cee43f
PMR
5422{
5423 struct using_direct *renaming;
d1183b06 5424 int defns_mark = result.size ();
22cee43f 5425
b5ec771e
PA
5426 symbol_name_matcher_ftype *name_match
5427 = ada_get_symbol_name_matcher (lookup_name);
5428
3c45e9f9 5429 for (renaming = block->get_using ();
22cee43f
PMR
5430 renaming != NULL;
5431 renaming = renaming->next)
5432 {
5433 const char *r_name;
22cee43f
PMR
5434
5435 /* Avoid infinite recursions: skip this renaming if we are actually
5436 already traversing it.
5437
5438 Currently, symbol lookup in Ada don't use the namespace machinery from
5439 C++/Fortran support: skip namespace imports that use them. */
5440 if (renaming->searched
5441 || (renaming->import_src != NULL
5442 && renaming->import_src[0] != '\0')
5443 || (renaming->import_dest != NULL
5444 && renaming->import_dest[0] != '\0'))
5445 continue;
5446 renaming->searched = 1;
5447
5448 /* TODO: here, we perform another name-based symbol lookup, which can
5449 pull its own multiple overloads. In theory, we should be able to do
5450 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5451 not a simple name. But in order to do this, we would need to enhance
5452 the DWARF reader to associate a symbol to this renaming, instead of a
5453 name. So, for now, we do something simpler: re-use the C++/Fortran
5454 namespace machinery. */
5455 r_name = (renaming->alias != NULL
5456 ? renaming->alias
5457 : renaming->declaration);
b5ec771e
PA
5458 if (name_match (r_name, lookup_name, NULL))
5459 {
5460 lookup_name_info decl_lookup_name (renaming->declaration,
5461 lookup_name.match_type ());
d1183b06 5462 ada_add_all_symbols (result, block, decl_lookup_name, domain,
b5ec771e
PA
5463 1, NULL);
5464 }
22cee43f
PMR
5465 renaming->searched = 0;
5466 }
d1183b06 5467 return result.size () != defns_mark;
22cee43f
PMR
5468}
5469
db230ce3
JB
5470/* Implements compare_names, but only applying the comparision using
5471 the given CASING. */
5b4ee69b 5472
40658b94 5473static int
db230ce3
JB
5474compare_names_with_case (const char *string1, const char *string2,
5475 enum case_sensitivity casing)
40658b94
PH
5476{
5477 while (*string1 != '\0' && *string2 != '\0')
5478 {
db230ce3
JB
5479 char c1, c2;
5480
40658b94
PH
5481 if (isspace (*string1) || isspace (*string2))
5482 return strcmp_iw_ordered (string1, string2);
db230ce3
JB
5483
5484 if (casing == case_sensitive_off)
5485 {
5486 c1 = tolower (*string1);
5487 c2 = tolower (*string2);
5488 }
5489 else
5490 {
5491 c1 = *string1;
5492 c2 = *string2;
5493 }
5494 if (c1 != c2)
40658b94 5495 break;
db230ce3 5496
40658b94
PH
5497 string1 += 1;
5498 string2 += 1;
5499 }
db230ce3 5500
40658b94
PH
5501 switch (*string1)
5502 {
5503 case '(':
5504 return strcmp_iw_ordered (string1, string2);
5505 case '_':
5506 if (*string2 == '\0')
5507 {
052874e8 5508 if (is_name_suffix (string1))
40658b94
PH
5509 return 0;
5510 else
1a1d5513 5511 return 1;
40658b94 5512 }
dbb8534f 5513 /* FALLTHROUGH */
40658b94
PH
5514 default:
5515 if (*string2 == '(')
5516 return strcmp_iw_ordered (string1, string2);
5517 else
db230ce3
JB
5518 {
5519 if (casing == case_sensitive_off)
5520 return tolower (*string1) - tolower (*string2);
5521 else
5522 return *string1 - *string2;
5523 }
40658b94 5524 }
ccefe4c4
TT
5525}
5526
db230ce3
JB
5527/* Compare STRING1 to STRING2, with results as for strcmp.
5528 Compatible with strcmp_iw_ordered in that...
5529
5530 strcmp_iw_ordered (STRING1, STRING2) <= 0
5531
5532 ... implies...
5533
5534 compare_names (STRING1, STRING2) <= 0
5535
5536 (they may differ as to what symbols compare equal). */
5537
5538static int
5539compare_names (const char *string1, const char *string2)
5540{
5541 int result;
5542
5543 /* Similar to what strcmp_iw_ordered does, we need to perform
5544 a case-insensitive comparison first, and only resort to
5545 a second, case-sensitive, comparison if the first one was
5546 not sufficient to differentiate the two strings. */
5547
5548 result = compare_names_with_case (string1, string2, case_sensitive_off);
5549 if (result == 0)
5550 result = compare_names_with_case (string1, string2, case_sensitive_on);
5551
5552 return result;
5553}
5554
b5ec771e
PA
5555/* Convenience function to get at the Ada encoded lookup name for
5556 LOOKUP_NAME, as a C string. */
5557
5558static const char *
5559ada_lookup_name (const lookup_name_info &lookup_name)
5560{
5561 return lookup_name.ada ().lookup_name ().c_str ();
5562}
5563
0b7b2c2a
TT
5564/* A helper for add_nonlocal_symbols. Call expand_matching_symbols
5565 for OBJFILE, then walk the objfile's symtabs and update the
5566 results. */
5567
5568static void
5569map_matching_symbols (struct objfile *objfile,
5570 const lookup_name_info &lookup_name,
5571 bool is_wild_match,
5572 domain_enum domain,
5573 int global,
5574 match_data &data)
5575{
5576 data.objfile = objfile;
5577 objfile->expand_matching_symbols (lookup_name, domain, global,
5578 is_wild_match ? nullptr : compare_names);
5579
5580 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5581 for (compunit_symtab *symtab : objfile->compunits ())
5582 {
5583 const struct block *block
63d609de 5584 = symtab->blockvector ()->block (block_kind);
0b7b2c2a
TT
5585 if (!iterate_over_symbols_terminated (block, lookup_name,
5586 domain, data))
5587 break;
5588 }
5589}
5590
1bfa81ac 5591/* Add to RESULT all non-local symbols whose name and domain match
b5ec771e
PA
5592 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5593 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5594 symbols otherwise. */
339c13b6
JB
5595
5596static void
d1183b06 5597add_nonlocal_symbols (std::vector<struct block_symbol> &result,
b5ec771e
PA
5598 const lookup_name_info &lookup_name,
5599 domain_enum domain, int global)
339c13b6 5600{
1bfa81ac 5601 struct match_data data (&result);
339c13b6 5602
b5ec771e
PA
5603 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5604
2030c079 5605 for (objfile *objfile : current_program_space->objfiles ())
40658b94 5606 {
0b7b2c2a
TT
5607 map_matching_symbols (objfile, lookup_name, is_wild_match, domain,
5608 global, data);
22cee43f 5609
b669c953 5610 for (compunit_symtab *cu : objfile->compunits ())
22cee43f
PMR
5611 {
5612 const struct block *global_block
63d609de 5613 = cu->blockvector ()->global_block ();
22cee43f 5614
d1183b06 5615 if (ada_add_block_renamings (result, global_block, lookup_name,
b5ec771e 5616 domain))
1178743e 5617 data.found_sym = true;
22cee43f 5618 }
40658b94
PH
5619 }
5620
d1183b06 5621 if (result.empty () && global && !is_wild_match)
40658b94 5622 {
b5ec771e 5623 const char *name = ada_lookup_name (lookup_name);
e0802d59
TT
5624 std::string bracket_name = std::string ("<_ada_") + name + '>';
5625 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
b5ec771e 5626
2030c079 5627 for (objfile *objfile : current_program_space->objfiles ())
0b7b2c2a
TT
5628 map_matching_symbols (objfile, name1, false, domain, global, data);
5629 }
339c13b6
JB
5630}
5631
b5ec771e
PA
5632/* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5633 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
1bfa81ac 5634 returning the number of matches. Add these to RESULT.
4eeaa230 5635
22cee43f
PMR
5636 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5637 symbol match within the nest of blocks whose innermost member is BLOCK,
4c4b4cd2 5638 is the one match returned (no other matches in that or
d9680e73 5639 enclosing blocks is returned). If there are any matches in or
22cee43f 5640 surrounding BLOCK, then these alone are returned.
4eeaa230 5641
b5ec771e
PA
5642 Names prefixed with "standard__" are handled specially:
5643 "standard__" is first stripped off (by the lookup_name
5644 constructor), and only static and global symbols are searched.
14f9c5c9 5645
22cee43f
PMR
5646 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5647 to lookup global symbols. */
5648
5649static void
d1183b06 5650ada_add_all_symbols (std::vector<struct block_symbol> &result,
22cee43f 5651 const struct block *block,
b5ec771e 5652 const lookup_name_info &lookup_name,
22cee43f
PMR
5653 domain_enum domain,
5654 int full_search,
5655 int *made_global_lookup_p)
14f9c5c9
AS
5656{
5657 struct symbol *sym;
14f9c5c9 5658
22cee43f
PMR
5659 if (made_global_lookup_p)
5660 *made_global_lookup_p = 0;
339c13b6
JB
5661
5662 /* Special case: If the user specifies a symbol name inside package
5663 Standard, do a non-wild matching of the symbol name without
5664 the "standard__" prefix. This was primarily introduced in order
5665 to allow the user to specifically access the standard exceptions
5666 using, for instance, Standard.Constraint_Error when Constraint_Error
5667 is ambiguous (due to the user defining its own Constraint_Error
5668 entity inside its program). */
b5ec771e
PA
5669 if (lookup_name.ada ().standard_p ())
5670 block = NULL;
4c4b4cd2 5671
339c13b6 5672 /* Check the non-global symbols. If we have ANY match, then we're done. */
14f9c5c9 5673
4eeaa230
DE
5674 if (block != NULL)
5675 {
5676 if (full_search)
d1183b06 5677 ada_add_local_symbols (result, lookup_name, block, domain);
4eeaa230
DE
5678 else
5679 {
5680 /* In the !full_search case we're are being called by
4009ee92 5681 iterate_over_symbols, and we don't want to search
4eeaa230 5682 superblocks. */
d1183b06 5683 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
4eeaa230 5684 }
d1183b06 5685 if (!result.empty () || !full_search)
22cee43f 5686 return;
4eeaa230 5687 }
d2e4a39e 5688
339c13b6
JB
5689 /* No non-global symbols found. Check our cache to see if we have
5690 already performed this search before. If we have, then return
5691 the same result. */
5692
b5ec771e
PA
5693 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5694 domain, &sym, &block))
4c4b4cd2
PH
5695 {
5696 if (sym != NULL)
d1183b06 5697 add_defn_to_vec (result, sym, block);
22cee43f 5698 return;
4c4b4cd2 5699 }
14f9c5c9 5700
22cee43f
PMR
5701 if (made_global_lookup_p)
5702 *made_global_lookup_p = 1;
b1eedac9 5703
339c13b6
JB
5704 /* Search symbols from all global blocks. */
5705
d1183b06 5706 add_nonlocal_symbols (result, lookup_name, domain, 1);
d2e4a39e 5707
4c4b4cd2 5708 /* Now add symbols from all per-file blocks if we've gotten no hits
339c13b6 5709 (not strictly correct, but perhaps better than an error). */
d2e4a39e 5710
d1183b06
TT
5711 if (result.empty ())
5712 add_nonlocal_symbols (result, lookup_name, domain, 0);
22cee43f
PMR
5713}
5714
b5ec771e 5715/* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
d1183b06
TT
5716 is non-zero, enclosing scope and in global scopes.
5717
5718 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5719 blocks and symbol tables (if any) in which they were found.
22cee43f
PMR
5720
5721 When full_search is non-zero, any non-function/non-enumeral
5722 symbol match within the nest of blocks whose innermost member is BLOCK,
5723 is the one match returned (no other matches in that or
5724 enclosing blocks is returned). If there are any matches in or
5725 surrounding BLOCK, then these alone are returned.
5726
5727 Names prefixed with "standard__" are handled specially: "standard__"
5728 is first stripped off, and only static and global symbols are searched. */
5729
d1183b06 5730static std::vector<struct block_symbol>
b5ec771e
PA
5731ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5732 const struct block *block,
22cee43f 5733 domain_enum domain,
22cee43f
PMR
5734 int full_search)
5735{
22cee43f 5736 int syms_from_global_search;
d1183b06 5737 std::vector<struct block_symbol> results;
22cee43f 5738
d1183b06 5739 ada_add_all_symbols (results, block, lookup_name,
b5ec771e 5740 domain, full_search, &syms_from_global_search);
14f9c5c9 5741
d1183b06 5742 remove_extra_symbols (&results);
4c4b4cd2 5743
d1183b06 5744 if (results.empty () && full_search && syms_from_global_search)
b5ec771e 5745 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
14f9c5c9 5746
d1183b06 5747 if (results.size () == 1 && full_search && syms_from_global_search)
b5ec771e 5748 cache_symbol (ada_lookup_name (lookup_name), domain,
d1183b06 5749 results[0].symbol, results[0].block);
ec6a20c2 5750
d1183b06
TT
5751 remove_irrelevant_renamings (&results, block);
5752 return results;
14f9c5c9
AS
5753}
5754
b5ec771e 5755/* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
d1183b06 5756 in global scopes, returning (SYM,BLOCK) tuples.
ec6a20c2 5757
4eeaa230
DE
5758 See ada_lookup_symbol_list_worker for further details. */
5759
d1183b06 5760std::vector<struct block_symbol>
b5ec771e 5761ada_lookup_symbol_list (const char *name, const struct block *block,
d1183b06 5762 domain_enum domain)
4eeaa230 5763{
b5ec771e
PA
5764 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5765 lookup_name_info lookup_name (name, name_match_type);
5766
d1183b06 5767 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
4eeaa230
DE
5768}
5769
4e5c77fe
JB
5770/* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5771 to 1, but choosing the first symbol found if there are multiple
5772 choices.
5773
5e2336be
JB
5774 The result is stored in *INFO, which must be non-NULL.
5775 If no match is found, INFO->SYM is set to NULL. */
4e5c77fe
JB
5776
5777void
5778ada_lookup_encoded_symbol (const char *name, const struct block *block,
fe978cb0 5779 domain_enum domain,
d12307c1 5780 struct block_symbol *info)
14f9c5c9 5781{
b5ec771e
PA
5782 /* Since we already have an encoded name, wrap it in '<>' to force a
5783 verbatim match. Otherwise, if the name happens to not look like
5784 an encoded name (because it doesn't include a "__"),
5785 ada_lookup_name_info would re-encode/fold it again, and that
5786 would e.g., incorrectly lowercase object renaming names like
5787 "R28b" -> "r28b". */
12932e2c 5788 std::string verbatim = add_angle_brackets (name);
b5ec771e 5789
5e2336be 5790 gdb_assert (info != NULL);
65392b3e 5791 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
4e5c77fe 5792}
aeb5907d
JB
5793
5794/* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5795 scope and in global scopes, or NULL if none. NAME is folded and
5796 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
65392b3e 5797 choosing the first symbol if there are multiple choices. */
4e5c77fe 5798
d12307c1 5799struct block_symbol
aeb5907d 5800ada_lookup_symbol (const char *name, const struct block *block0,
dda83cd7 5801 domain_enum domain)
aeb5907d 5802{
d1183b06
TT
5803 std::vector<struct block_symbol> candidates
5804 = ada_lookup_symbol_list (name, block0, domain);
f98fc17b 5805
d1183b06 5806 if (candidates.empty ())
54d343a2 5807 return {};
f98fc17b 5808
dae58e04 5809 return candidates[0];
4c4b4cd2 5810}
14f9c5c9 5811
14f9c5c9 5812
4c4b4cd2
PH
5813/* True iff STR is a possible encoded suffix of a normal Ada name
5814 that is to be ignored for matching purposes. Suffixes of parallel
5815 names (e.g., XVE) are not included here. Currently, the possible suffixes
5823c3ef 5816 are given by any of the regular expressions:
4c4b4cd2 5817
babe1480
JB
5818 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5819 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
9ac7f98e 5820 TKB [subprogram suffix for task bodies]
babe1480 5821 _E[0-9]+[bs]$ [protected object entry suffixes]
61ee279c 5822 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
babe1480
JB
5823
5824 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5825 match is performed. This sequence is used to differentiate homonyms,
5826 is an optional part of a valid name suffix. */
4c4b4cd2 5827
14f9c5c9 5828static int
d2e4a39e 5829is_name_suffix (const char *str)
14f9c5c9
AS
5830{
5831 int k;
4c4b4cd2
PH
5832 const char *matching;
5833 const int len = strlen (str);
5834
babe1480
JB
5835 /* Skip optional leading __[0-9]+. */
5836
4c4b4cd2
PH
5837 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5838 {
babe1480
JB
5839 str += 3;
5840 while (isdigit (str[0]))
dda83cd7 5841 str += 1;
4c4b4cd2 5842 }
babe1480
JB
5843
5844 /* [.$][0-9]+ */
4c4b4cd2 5845
babe1480 5846 if (str[0] == '.' || str[0] == '$')
4c4b4cd2 5847 {
babe1480 5848 matching = str + 1;
4c4b4cd2 5849 while (isdigit (matching[0]))
dda83cd7 5850 matching += 1;
4c4b4cd2 5851 if (matching[0] == '\0')
dda83cd7 5852 return 1;
4c4b4cd2
PH
5853 }
5854
5855 /* ___[0-9]+ */
babe1480 5856
4c4b4cd2
PH
5857 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5858 {
5859 matching = str + 3;
5860 while (isdigit (matching[0]))
dda83cd7 5861 matching += 1;
4c4b4cd2 5862 if (matching[0] == '\0')
dda83cd7 5863 return 1;
4c4b4cd2
PH
5864 }
5865
9ac7f98e
JB
5866 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5867
5868 if (strcmp (str, "TKB") == 0)
5869 return 1;
5870
529cad9c
PH
5871#if 0
5872 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
0963b4bd
MS
5873 with a N at the end. Unfortunately, the compiler uses the same
5874 convention for other internal types it creates. So treating
529cad9c 5875 all entity names that end with an "N" as a name suffix causes
0963b4bd
MS
5876 some regressions. For instance, consider the case of an enumerated
5877 type. To support the 'Image attribute, it creates an array whose
529cad9c
PH
5878 name ends with N.
5879 Having a single character like this as a suffix carrying some
0963b4bd 5880 information is a bit risky. Perhaps we should change the encoding
529cad9c
PH
5881 to be something like "_N" instead. In the meantime, do not do
5882 the following check. */
5883 /* Protected Object Subprograms */
5884 if (len == 1 && str [0] == 'N')
5885 return 1;
5886#endif
5887
5888 /* _E[0-9]+[bs]$ */
5889 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5890 {
5891 matching = str + 3;
5892 while (isdigit (matching[0]))
dda83cd7 5893 matching += 1;
529cad9c 5894 if ((matching[0] == 'b' || matching[0] == 's')
dda83cd7
SM
5895 && matching [1] == '\0')
5896 return 1;
529cad9c
PH
5897 }
5898
4c4b4cd2
PH
5899 /* ??? We should not modify STR directly, as we are doing below. This
5900 is fine in this case, but may become problematic later if we find
5901 that this alternative did not work, and want to try matching
5902 another one from the begining of STR. Since we modified it, we
5903 won't be able to find the begining of the string anymore! */
14f9c5c9
AS
5904 if (str[0] == 'X')
5905 {
5906 str += 1;
d2e4a39e 5907 while (str[0] != '_' && str[0] != '\0')
dda83cd7
SM
5908 {
5909 if (str[0] != 'n' && str[0] != 'b')
5910 return 0;
5911 str += 1;
5912 }
14f9c5c9 5913 }
babe1480 5914
14f9c5c9
AS
5915 if (str[0] == '\000')
5916 return 1;
babe1480 5917
d2e4a39e 5918 if (str[0] == '_')
14f9c5c9
AS
5919 {
5920 if (str[1] != '_' || str[2] == '\000')
dda83cd7 5921 return 0;
d2e4a39e 5922 if (str[2] == '_')
dda83cd7
SM
5923 {
5924 if (strcmp (str + 3, "JM") == 0)
5925 return 1;
5926 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5927 the LJM suffix in favor of the JM one. But we will
5928 still accept LJM as a valid suffix for a reasonable
5929 amount of time, just to allow ourselves to debug programs
5930 compiled using an older version of GNAT. */
5931 if (strcmp (str + 3, "LJM") == 0)
5932 return 1;
5933 if (str[3] != 'X')
5934 return 0;
5935 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5936 || str[4] == 'U' || str[4] == 'P')
5937 return 1;
5938 if (str[4] == 'R' && str[5] != 'T')
5939 return 1;
5940 return 0;
5941 }
4c4b4cd2 5942 if (!isdigit (str[2]))
dda83cd7 5943 return 0;
4c4b4cd2 5944 for (k = 3; str[k] != '\0'; k += 1)
dda83cd7
SM
5945 if (!isdigit (str[k]) && str[k] != '_')
5946 return 0;
14f9c5c9
AS
5947 return 1;
5948 }
4c4b4cd2 5949 if (str[0] == '$' && isdigit (str[1]))
14f9c5c9 5950 {
4c4b4cd2 5951 for (k = 2; str[k] != '\0'; k += 1)
dda83cd7
SM
5952 if (!isdigit (str[k]) && str[k] != '_')
5953 return 0;
14f9c5c9
AS
5954 return 1;
5955 }
5956 return 0;
5957}
d2e4a39e 5958
aeb5907d
JB
5959/* Return non-zero if the string starting at NAME and ending before
5960 NAME_END contains no capital letters. */
529cad9c
PH
5961
5962static int
5963is_valid_name_for_wild_match (const char *name0)
5964{
f945dedf 5965 std::string decoded_name = ada_decode (name0);
529cad9c
PH
5966 int i;
5967
5823c3ef
JB
5968 /* If the decoded name starts with an angle bracket, it means that
5969 NAME0 does not follow the GNAT encoding format. It should then
5970 not be allowed as a possible wild match. */
5971 if (decoded_name[0] == '<')
5972 return 0;
5973
529cad9c
PH
5974 for (i=0; decoded_name[i] != '\0'; i++)
5975 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5976 return 0;
5977
5978 return 1;
5979}
5980
59c8a30b
JB
5981/* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5982 character which could start a simple name. Assumes that *NAMEP points
5983 somewhere inside the string beginning at NAME0. */
4c4b4cd2 5984
14f9c5c9 5985static int
59c8a30b 5986advance_wild_match (const char **namep, const char *name0, char target0)
14f9c5c9 5987{
73589123 5988 const char *name = *namep;
5b4ee69b 5989
5823c3ef 5990 while (1)
14f9c5c9 5991 {
59c8a30b 5992 char t0, t1;
73589123
PH
5993
5994 t0 = *name;
5995 if (t0 == '_')
5996 {
5997 t1 = name[1];
5998 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5999 {
6000 name += 1;
61012eef 6001 if (name == name0 + 5 && startswith (name0, "_ada"))
73589123
PH
6002 break;
6003 else
6004 name += 1;
6005 }
aa27d0b3
JB
6006 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
6007 || name[2] == target0))
73589123
PH
6008 {
6009 name += 2;
6010 break;
6011 }
86b44259
TT
6012 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
6013 {
6014 /* Names like "pkg__B_N__name", where N is a number, are
6015 block-local. We can handle these by simply skipping
6016 the "B_" here. */
6017 name += 4;
6018 }
73589123
PH
6019 else
6020 return 0;
6021 }
6022 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
6023 name += 1;
6024 else
5823c3ef 6025 return 0;
73589123
PH
6026 }
6027
6028 *namep = name;
6029 return 1;
6030}
6031
b5ec771e
PA
6032/* Return true iff NAME encodes a name of the form prefix.PATN.
6033 Ignores any informational suffixes of NAME (i.e., for which
6034 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6035 simple name. */
73589123 6036
b5ec771e 6037static bool
73589123
PH
6038wild_match (const char *name, const char *patn)
6039{
22e048c9 6040 const char *p;
73589123
PH
6041 const char *name0 = name;
6042
81eaa506
TT
6043 if (startswith (name, "___ghost_"))
6044 name += 9;
6045
73589123
PH
6046 while (1)
6047 {
6048 const char *match = name;
6049
6050 if (*name == *patn)
6051 {
6052 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6053 if (*p != *name)
6054 break;
6055 if (*p == '\0' && is_name_suffix (name))
b5ec771e 6056 return match == name0 || is_valid_name_for_wild_match (name0);
73589123
PH
6057
6058 if (name[-1] == '_')
6059 name -= 1;
6060 }
6061 if (!advance_wild_match (&name, name0, *patn))
b5ec771e 6062 return false;
96d887e8 6063 }
96d887e8
PH
6064}
6065
d1183b06 6066/* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
b5ec771e 6067 necessary). OBJFILE is the section containing BLOCK. */
96d887e8
PH
6068
6069static void
d1183b06 6070ada_add_block_symbols (std::vector<struct block_symbol> &result,
b5ec771e
PA
6071 const struct block *block,
6072 const lookup_name_info &lookup_name,
6073 domain_enum domain, struct objfile *objfile)
96d887e8 6074{
96d887e8
PH
6075 /* A matching argument symbol, if any. */
6076 struct symbol *arg_sym;
6077 /* Set true when we find a matching non-argument symbol. */
1178743e 6078 bool found_sym;
96d887e8
PH
6079
6080 arg_sym = NULL;
1178743e 6081 found_sym = false;
1c49bb45 6082 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
96d887e8 6083 {
6c9c307c 6084 if (symbol_matches_domain (sym->language (), sym->domain (), domain))
b5ec771e 6085 {
66d7f48f 6086 if (sym->aclass () != LOC_UNRESOLVED)
b5ec771e 6087 {
d9743061 6088 if (sym->is_argument ())
b5ec771e
PA
6089 arg_sym = sym;
6090 else
6091 {
1178743e 6092 found_sym = true;
dae58e04 6093 add_defn_to_vec (result, sym, block);
b5ec771e
PA
6094 }
6095 }
6096 }
96d887e8
PH
6097 }
6098
22cee43f
PMR
6099 /* Handle renamings. */
6100
d1183b06 6101 if (ada_add_block_renamings (result, block, lookup_name, domain))
1178743e 6102 found_sym = true;
22cee43f 6103
96d887e8
PH
6104 if (!found_sym && arg_sym != NULL)
6105 {
dae58e04 6106 add_defn_to_vec (result, arg_sym, block);
96d887e8
PH
6107 }
6108
b5ec771e 6109 if (!lookup_name.ada ().wild_match_p ())
96d887e8
PH
6110 {
6111 arg_sym = NULL;
1178743e 6112 found_sym = false;
b5ec771e
PA
6113 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6114 const char *name = ada_lookup_name.c_str ();
6115 size_t name_len = ada_lookup_name.size ();
96d887e8 6116
548a89df 6117 for (struct symbol *sym : block_iterator_range (block))
76a01679 6118 {
dda83cd7 6119 if (symbol_matches_domain (sym->language (),
6c9c307c 6120 sym->domain (), domain))
dda83cd7
SM
6121 {
6122 int cmp;
6123
6124 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6125 if (cmp == 0)
6126 {
6127 cmp = !startswith (sym->linkage_name (), "_ada_");
6128 if (cmp == 0)
6129 cmp = strncmp (name, sym->linkage_name () + 5,
6130 name_len);
6131 }
6132
6133 if (cmp == 0
6134 && is_name_suffix (sym->linkage_name () + name_len + 5))
6135 {
66d7f48f 6136 if (sym->aclass () != LOC_UNRESOLVED)
2a2d4dc3 6137 {
d9743061 6138 if (sym->is_argument ())
2a2d4dc3
AS
6139 arg_sym = sym;
6140 else
6141 {
1178743e 6142 found_sym = true;
dae58e04 6143 add_defn_to_vec (result, sym, block);
2a2d4dc3
AS
6144 }
6145 }
dda83cd7
SM
6146 }
6147 }
76a01679 6148 }
96d887e8
PH
6149
6150 /* NOTE: This really shouldn't be needed for _ada_ symbols.
dda83cd7 6151 They aren't parameters, right? */
96d887e8 6152 if (!found_sym && arg_sym != NULL)
dda83cd7 6153 {
dae58e04 6154 add_defn_to_vec (result, arg_sym, block);
dda83cd7 6155 }
96d887e8
PH
6156 }
6157}
6158\f
41d27058 6159
dda83cd7 6160 /* Symbol Completion */
41d27058 6161
b5ec771e 6162/* See symtab.h. */
41d27058 6163
b5ec771e
PA
6164bool
6165ada_lookup_name_info::matches
6166 (const char *sym_name,
6167 symbol_name_match_type match_type,
a207cff2 6168 completion_match_result *comp_match_res) const
41d27058 6169{
b5ec771e
PA
6170 bool match = false;
6171 const char *text = m_encoded_name.c_str ();
6172 size_t text_len = m_encoded_name.size ();
41d27058
JB
6173
6174 /* First, test against the fully qualified name of the symbol. */
6175
6176 if (strncmp (sym_name, text, text_len) == 0)
b5ec771e 6177 match = true;
41d27058 6178
f945dedf 6179 std::string decoded_name = ada_decode (sym_name);
b5ec771e 6180 if (match && !m_encoded_p)
41d27058
JB
6181 {
6182 /* One needed check before declaring a positive match is to verify
dda83cd7
SM
6183 that iff we are doing a verbatim match, the decoded version
6184 of the symbol name starts with '<'. Otherwise, this symbol name
6185 is not a suitable completion. */
41d27058 6186
f945dedf 6187 bool has_angle_bracket = (decoded_name[0] == '<');
b5ec771e 6188 match = (has_angle_bracket == m_verbatim_p);
41d27058
JB
6189 }
6190
b5ec771e 6191 if (match && !m_verbatim_p)
41d27058
JB
6192 {
6193 /* When doing non-verbatim match, another check that needs to
dda83cd7
SM
6194 be done is to verify that the potentially matching symbol name
6195 does not include capital letters, because the ada-mode would
6196 not be able to understand these symbol names without the
6197 angle bracket notation. */
41d27058
JB
6198 const char *tmp;
6199
6200 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6201 if (*tmp != '\0')
b5ec771e 6202 match = false;
41d27058
JB
6203 }
6204
6205 /* Second: Try wild matching... */
6206
b5ec771e 6207 if (!match && m_wild_match_p)
41d27058
JB
6208 {
6209 /* Since we are doing wild matching, this means that TEXT
dda83cd7
SM
6210 may represent an unqualified symbol name. We therefore must
6211 also compare TEXT against the unqualified name of the symbol. */
f945dedf 6212 sym_name = ada_unqualified_name (decoded_name.c_str ());
41d27058
JB
6213
6214 if (strncmp (sym_name, text, text_len) == 0)
b5ec771e 6215 match = true;
41d27058
JB
6216 }
6217
b5ec771e 6218 /* Finally: If we found a match, prepare the result to return. */
41d27058
JB
6219
6220 if (!match)
b5ec771e 6221 return false;
41d27058 6222
a207cff2 6223 if (comp_match_res != NULL)
b5ec771e 6224 {
a207cff2 6225 std::string &match_str = comp_match_res->match.storage ();
41d27058 6226
b5ec771e 6227 if (!m_encoded_p)
a207cff2 6228 match_str = ada_decode (sym_name);
b5ec771e
PA
6229 else
6230 {
6231 if (m_verbatim_p)
6232 match_str = add_angle_brackets (sym_name);
6233 else
6234 match_str = sym_name;
41d27058 6235
b5ec771e 6236 }
a207cff2
PA
6237
6238 comp_match_res->set_match (match_str.c_str ());
41d27058
JB
6239 }
6240
b5ec771e 6241 return true;
41d27058
JB
6242}
6243
dda83cd7 6244 /* Field Access */
96d887e8 6245
73fb9985
JB
6246/* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6247 for tagged types. */
6248
6249static int
6250ada_is_dispatch_table_ptr_type (struct type *type)
6251{
0d5cff50 6252 const char *name;
73fb9985 6253
78134374 6254 if (type->code () != TYPE_CODE_PTR)
73fb9985
JB
6255 return 0;
6256
27710edb 6257 name = type->target_type ()->name ();
73fb9985
JB
6258 if (name == NULL)
6259 return 0;
6260
6261 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6262}
6263
ac4a2da4
JG
6264/* Return non-zero if TYPE is an interface tag. */
6265
6266static int
6267ada_is_interface_tag (struct type *type)
6268{
7d93a1e0 6269 const char *name = type->name ();
ac4a2da4
JG
6270
6271 if (name == NULL)
6272 return 0;
6273
6274 return (strcmp (name, "ada__tags__interface_tag") == 0);
6275}
6276
963a6417
PH
6277/* True if field number FIELD_NUM in struct or union type TYPE is supposed
6278 to be invisible to users. */
96d887e8 6279
963a6417
PH
6280int
6281ada_is_ignored_field (struct type *type, int field_num)
96d887e8 6282{
1f704f76 6283 if (field_num < 0 || field_num > type->num_fields ())
963a6417 6284 return 1;
ffde82bf 6285
73fb9985
JB
6286 /* Check the name of that field. */
6287 {
33d16dd9 6288 const char *name = type->field (field_num).name ();
73fb9985
JB
6289
6290 /* Anonymous field names should not be printed.
6291 brobecker/2007-02-20: I don't think this can actually happen
30baf67b 6292 but we don't want to print the value of anonymous fields anyway. */
73fb9985
JB
6293 if (name == NULL)
6294 return 1;
6295
ffde82bf
JB
6296 /* Normally, fields whose name start with an underscore ("_")
6297 are fields that have been internally generated by the compiler,
6298 and thus should not be printed. The "_parent" field is special,
6299 however: This is a field internally generated by the compiler
6300 for tagged types, and it contains the components inherited from
6301 the parent type. This field should not be printed as is, but
6302 should not be ignored either. */
61012eef 6303 if (name[0] == '_' && !startswith (name, "_parent"))
73fb9985 6304 return 1;
d537777d
TT
6305
6306 /* The compiler doesn't document this, but sometimes it emits
6307 a field whose name starts with a capital letter, like 'V148s'.
6308 These aren't marked as artificial in any way, but we know they
6309 should be ignored. However, wrapper fields should not be
6310 ignored. */
6311 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6312 {
6313 /* Wrapper field. */
6314 }
6315 else if (isupper (name[0]))
6316 return 1;
73fb9985
JB
6317 }
6318
ac4a2da4
JG
6319 /* If this is the dispatch table of a tagged type or an interface tag,
6320 then ignore. */
73fb9985 6321 if (ada_is_tagged_type (type, 1)
940da03e
SM
6322 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6323 || ada_is_interface_tag (type->field (field_num).type ())))
73fb9985
JB
6324 return 1;
6325
6326 /* Not a special field, so it should not be ignored. */
6327 return 0;
963a6417 6328}
96d887e8 6329
963a6417 6330/* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
0963b4bd 6331 pointer or reference type whose ultimate target has a tag field. */
96d887e8 6332
963a6417
PH
6333int
6334ada_is_tagged_type (struct type *type, int refok)
6335{
988f6b3d 6336 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
963a6417 6337}
96d887e8 6338
963a6417 6339/* True iff TYPE represents the type of X'Tag */
96d887e8 6340
963a6417
PH
6341int
6342ada_is_tag_type (struct type *type)
6343{
460efde1
JB
6344 type = ada_check_typedef (type);
6345
78134374 6346 if (type == NULL || type->code () != TYPE_CODE_PTR)
963a6417
PH
6347 return 0;
6348 else
96d887e8 6349 {
27710edb 6350 const char *name = ada_type_name (type->target_type ());
5b4ee69b 6351
963a6417 6352 return (name != NULL
dda83cd7 6353 && strcmp (name, "ada__tags__dispatch_table") == 0);
96d887e8 6354 }
96d887e8
PH
6355}
6356
963a6417 6357/* The type of the tag on VAL. */
76a01679 6358
de93309a 6359static struct type *
963a6417 6360ada_tag_type (struct value *val)
96d887e8 6361{
d0c97917 6362 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
963a6417 6363}
96d887e8 6364
b50d69b5
JG
6365/* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6366 retired at Ada 05). */
6367
6368static int
6369is_ada95_tag (struct value *tag)
6370{
6371 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6372}
6373
963a6417 6374/* The value of the tag on VAL. */
96d887e8 6375
de93309a 6376static struct value *
963a6417
PH
6377ada_value_tag (struct value *val)
6378{
03ee6b2e 6379 return ada_value_struct_elt (val, "_tag", 0);
96d887e8
PH
6380}
6381
963a6417
PH
6382/* The value of the tag on the object of type TYPE whose contents are
6383 saved at VALADDR, if it is non-null, or is at memory address
0963b4bd 6384 ADDRESS. */
96d887e8 6385
963a6417 6386static struct value *
10a2c479 6387value_tag_from_contents_and_address (struct type *type,
fc1a4b47 6388 const gdb_byte *valaddr,
dda83cd7 6389 CORE_ADDR address)
96d887e8 6390{
b5385fc0 6391 int tag_byte_offset;
963a6417 6392 struct type *tag_type;
5b4ee69b 6393
4d1795ac
TT
6394 gdb::array_view<const gdb_byte> contents;
6395 if (valaddr != nullptr)
df86565b 6396 contents = gdb::make_array_view (valaddr, type->length ());
4d1795ac
TT
6397 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6398 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
dda83cd7 6399 NULL, NULL, NULL))
96d887e8 6400 {
fc1a4b47 6401 const gdb_byte *valaddr1 = ((valaddr == NULL)
10a2c479
AC
6402 ? NULL
6403 : valaddr + tag_byte_offset);
963a6417 6404 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
96d887e8 6405
963a6417 6406 return value_from_contents_and_address (tag_type, valaddr1, address1);
96d887e8 6407 }
963a6417
PH
6408 return NULL;
6409}
96d887e8 6410
963a6417
PH
6411static struct type *
6412type_from_tag (struct value *tag)
6413{
f5272a3b 6414 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
5b4ee69b 6415
963a6417 6416 if (type_name != NULL)
5c4258f4 6417 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
963a6417
PH
6418 return NULL;
6419}
96d887e8 6420
b50d69b5
JG
6421/* Given a value OBJ of a tagged type, return a value of this
6422 type at the base address of the object. The base address, as
6423 defined in Ada.Tags, it is the address of the primary tag of
6424 the object, and therefore where the field values of its full
6425 view can be fetched. */
6426
6427struct value *
6428ada_tag_value_at_base_address (struct value *obj)
6429{
b50d69b5
JG
6430 struct value *val;
6431 LONGEST offset_to_top = 0;
6432 struct type *ptr_type, *obj_type;
6433 struct value *tag;
6434 CORE_ADDR base_address;
6435
d0c97917 6436 obj_type = obj->type ();
b50d69b5
JG
6437
6438 /* It is the responsability of the caller to deref pointers. */
6439
78134374 6440 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
b50d69b5
JG
6441 return obj;
6442
6443 tag = ada_value_tag (obj);
6444 if (!tag)
6445 return obj;
6446
6447 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6448
6449 if (is_ada95_tag (tag))
6450 return obj;
6451
d537777d
TT
6452 struct type *offset_type
6453 = language_lookup_primitive_type (language_def (language_ada),
6454 target_gdbarch(), "storage_offset");
6455 ptr_type = lookup_pointer_type (offset_type);
b50d69b5
JG
6456 val = value_cast (ptr_type, tag);
6457 if (!val)
6458 return obj;
6459
6460 /* It is perfectly possible that an exception be raised while
6461 trying to determine the base address, just like for the tag;
6462 see ada_tag_name for more details. We do not print the error
6463 message for the same reason. */
6464
a70b8144 6465 try
b50d69b5
JG
6466 {
6467 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6468 }
6469
230d2906 6470 catch (const gdb_exception_error &e)
492d29ea
PA
6471 {
6472 return obj;
6473 }
b50d69b5
JG
6474
6475 /* If offset is null, nothing to do. */
6476
6477 if (offset_to_top == 0)
6478 return obj;
6479
6480 /* -1 is a special case in Ada.Tags; however, what should be done
6481 is not quite clear from the documentation. So do nothing for
6482 now. */
6483
6484 if (offset_to_top == -1)
6485 return obj;
6486
d537777d
TT
6487 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6488 top is used. In this situation the offset is stored just after
6489 the tag, in the object itself. */
df86565b 6490 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
d537777d
TT
6491 if (offset_to_top == last)
6492 {
6493 struct value *tem = value_addr (tag);
6494 tem = value_ptradd (tem, 1);
6495 tem = value_cast (ptr_type, tem);
6496 offset_to_top = value_as_long (value_ind (tem));
6497 }
05527d8c
TV
6498
6499 if (offset_to_top > 0)
d537777d
TT
6500 {
6501 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6502 from the base address. This was however incompatible with
6503 C++ dispatch table: C++ uses a *negative* value to *add*
6504 to the base address. Ada's convention has therefore been
6505 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6506 use the same convention. Here, we support both cases by
6507 checking the sign of OFFSET_TO_TOP. */
6508 offset_to_top = -offset_to_top;
6509 }
08f49010 6510
9feb2d07 6511 base_address = obj->address () + offset_to_top;
b50d69b5
JG
6512 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6513
6514 /* Make sure that we have a proper tag at the new address.
6515 Otherwise, offset_to_top is bogus (which can happen when
6516 the object is not initialized yet). */
6517
6518 if (!tag)
6519 return obj;
6520
6521 obj_type = type_from_tag (tag);
6522
6523 if (!obj_type)
6524 return obj;
6525
6526 return value_from_contents_and_address (obj_type, NULL, base_address);
6527}
6528
1b611343
JB
6529/* Return the "ada__tags__type_specific_data" type. */
6530
6531static struct type *
6532ada_get_tsd_type (struct inferior *inf)
963a6417 6533{
1b611343 6534 struct ada_inferior_data *data = get_ada_inferior_data (inf);
4c4b4cd2 6535
1b611343
JB
6536 if (data->tsd_type == 0)
6537 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6538 return data->tsd_type;
6539}
529cad9c 6540
1b611343
JB
6541/* Return the TSD (type-specific data) associated to the given TAG.
6542 TAG is assumed to be the tag of a tagged-type entity.
529cad9c 6543
1b611343 6544 May return NULL if we are unable to get the TSD. */
4c4b4cd2 6545
1b611343
JB
6546static struct value *
6547ada_get_tsd_from_tag (struct value *tag)
4c4b4cd2 6548{
4c4b4cd2 6549 struct value *val;
1b611343 6550 struct type *type;
5b4ee69b 6551
1b611343
JB
6552 /* First option: The TSD is simply stored as a field of our TAG.
6553 Only older versions of GNAT would use this format, but we have
6554 to test it first, because there are no visible markers for
6555 the current approach except the absence of that field. */
529cad9c 6556
1b611343
JB
6557 val = ada_value_struct_elt (tag, "tsd", 1);
6558 if (val)
6559 return val;
e802dbe0 6560
1b611343
JB
6561 /* Try the second representation for the dispatch table (in which
6562 there is no explicit 'tsd' field in the referent of the tag pointer,
6563 and instead the tsd pointer is stored just before the dispatch
6564 table. */
e802dbe0 6565
1b611343
JB
6566 type = ada_get_tsd_type (current_inferior());
6567 if (type == NULL)
6568 return NULL;
6569 type = lookup_pointer_type (lookup_pointer_type (type));
6570 val = value_cast (type, tag);
6571 if (val == NULL)
6572 return NULL;
6573 return value_ind (value_ptradd (val, -1));
e802dbe0
JB
6574}
6575
1b611343
JB
6576/* Given the TSD of a tag (type-specific data), return a string
6577 containing the name of the associated type.
6578
f5272a3b 6579 May return NULL if we are unable to determine the tag name. */
1b611343 6580
f5272a3b 6581static gdb::unique_xmalloc_ptr<char>
1b611343 6582ada_tag_name_from_tsd (struct value *tsd)
529cad9c 6583{
1b611343 6584 struct value *val;
529cad9c 6585
1b611343 6586 val = ada_value_struct_elt (tsd, "expanded_name", 1);
4c4b4cd2 6587 if (val == NULL)
1b611343 6588 return NULL;
66920317
TT
6589 gdb::unique_xmalloc_ptr<char> buffer
6590 = target_read_string (value_as_address (val), INT_MAX);
6591 if (buffer == nullptr)
f5272a3b
TT
6592 return nullptr;
6593
315e4ebb 6594 try
f5272a3b 6595 {
315e4ebb
TT
6596 /* Let this throw an exception on error. If the data is
6597 uninitialized, we'd rather not have the user see a
6598 warning. */
6599 const char *folded = ada_fold_name (buffer.get (), true);
6600 return make_unique_xstrdup (folded);
6601 }
6602 catch (const gdb_exception &)
6603 {
6604 return nullptr;
f5272a3b 6605 }
4c4b4cd2
PH
6606}
6607
6608/* The type name of the dynamic type denoted by the 'tag value TAG, as
1b611343
JB
6609 a C string.
6610
6611 Return NULL if the TAG is not an Ada tag, or if we were unable to
f5272a3b 6612 determine the name of that tag. */
4c4b4cd2 6613
f5272a3b 6614gdb::unique_xmalloc_ptr<char>
4c4b4cd2
PH
6615ada_tag_name (struct value *tag)
6616{
f5272a3b 6617 gdb::unique_xmalloc_ptr<char> name;
5b4ee69b 6618
d0c97917 6619 if (!ada_is_tag_type (tag->type ()))
4c4b4cd2 6620 return NULL;
1b611343
JB
6621
6622 /* It is perfectly possible that an exception be raised while trying
6623 to determine the TAG's name, even under normal circumstances:
6624 The associated variable may be uninitialized or corrupted, for
6625 instance. We do not let any exception propagate past this point.
6626 instead we return NULL.
6627
6628 We also do not print the error message either (which often is very
6629 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6630 the caller print a more meaningful message if necessary. */
a70b8144 6631 try
1b611343
JB
6632 {
6633 struct value *tsd = ada_get_tsd_from_tag (tag);
6634
6635 if (tsd != NULL)
6636 name = ada_tag_name_from_tsd (tsd);
6637 }
230d2906 6638 catch (const gdb_exception_error &e)
492d29ea
PA
6639 {
6640 }
1b611343
JB
6641
6642 return name;
4c4b4cd2
PH
6643}
6644
6645/* The parent type of TYPE, or NULL if none. */
14f9c5c9 6646
d2e4a39e 6647struct type *
ebf56fd3 6648ada_parent_type (struct type *type)
14f9c5c9
AS
6649{
6650 int i;
6651
61ee279c 6652 type = ada_check_typedef (type);
14f9c5c9 6653
78134374 6654 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
14f9c5c9
AS
6655 return NULL;
6656
1f704f76 6657 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 6658 if (ada_is_parent_field (type, i))
0c1f74cf 6659 {
dda83cd7 6660 struct type *parent_type = type->field (i).type ();
0c1f74cf 6661
dda83cd7
SM
6662 /* If the _parent field is a pointer, then dereference it. */
6663 if (parent_type->code () == TYPE_CODE_PTR)
27710edb 6664 parent_type = parent_type->target_type ();
dda83cd7
SM
6665 /* If there is a parallel XVS type, get the actual base type. */
6666 parent_type = ada_get_base_type (parent_type);
0c1f74cf 6667
dda83cd7 6668 return ada_check_typedef (parent_type);
0c1f74cf 6669 }
14f9c5c9
AS
6670
6671 return NULL;
6672}
6673
4c4b4cd2
PH
6674/* True iff field number FIELD_NUM of structure type TYPE contains the
6675 parent-type (inherited) fields of a derived type. Assumes TYPE is
6676 a structure type with at least FIELD_NUM+1 fields. */
14f9c5c9
AS
6677
6678int
ebf56fd3 6679ada_is_parent_field (struct type *type, int field_num)
14f9c5c9 6680{
33d16dd9 6681 const char *name = ada_check_typedef (type)->field (field_num).name ();
5b4ee69b 6682
4c4b4cd2 6683 return (name != NULL
dda83cd7
SM
6684 && (startswith (name, "PARENT")
6685 || startswith (name, "_parent")));
14f9c5c9
AS
6686}
6687
4c4b4cd2 6688/* True iff field number FIELD_NUM of structure type TYPE is a
14f9c5c9 6689 transparent wrapper field (which should be silently traversed when doing
4c4b4cd2 6690 field selection and flattened when printing). Assumes TYPE is a
14f9c5c9 6691 structure type with at least FIELD_NUM+1 fields. Such fields are always
4c4b4cd2 6692 structures. */
14f9c5c9
AS
6693
6694int
ebf56fd3 6695ada_is_wrapper_field (struct type *type, int field_num)
14f9c5c9 6696{
33d16dd9 6697 const char *name = type->field (field_num).name ();
5b4ee69b 6698
dddc0e16
JB
6699 if (name != NULL && strcmp (name, "RETVAL") == 0)
6700 {
6701 /* This happens in functions with "out" or "in out" parameters
6702 which are passed by copy. For such functions, GNAT describes
6703 the function's return type as being a struct where the return
6704 value is in a field called RETVAL, and where the other "out"
6705 or "in out" parameters are fields of that struct. This is not
6706 a wrapper. */
6707 return 0;
6708 }
6709
d2e4a39e 6710 return (name != NULL
dda83cd7
SM
6711 && (startswith (name, "PARENT")
6712 || strcmp (name, "REP") == 0
6713 || startswith (name, "_parent")
6714 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
14f9c5c9
AS
6715}
6716
4c4b4cd2
PH
6717/* True iff field number FIELD_NUM of structure or union type TYPE
6718 is a variant wrapper. Assumes TYPE is a structure type with at least
6719 FIELD_NUM+1 fields. */
14f9c5c9
AS
6720
6721int
ebf56fd3 6722ada_is_variant_part (struct type *type, int field_num)
14f9c5c9 6723{
8ecb59f8
TT
6724 /* Only Ada types are eligible. */
6725 if (!ADA_TYPE_P (type))
6726 return 0;
6727
940da03e 6728 struct type *field_type = type->field (field_num).type ();
5b4ee69b 6729
78134374
SM
6730 return (field_type->code () == TYPE_CODE_UNION
6731 || (is_dynamic_field (type, field_num)
27710edb 6732 && (field_type->target_type ()->code ()
c3e5cd34 6733 == TYPE_CODE_UNION)));
14f9c5c9
AS
6734}
6735
6736/* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
4c4b4cd2 6737 whose discriminants are contained in the record type OUTER_TYPE,
7c964f07
UW
6738 returns the type of the controlling discriminant for the variant.
6739 May return NULL if the type could not be found. */
14f9c5c9 6740
d2e4a39e 6741struct type *
ebf56fd3 6742ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
14f9c5c9 6743{
a121b7c1 6744 const char *name = ada_variant_discrim_name (var_type);
5b4ee69b 6745
988f6b3d 6746 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
14f9c5c9
AS
6747}
6748
4c4b4cd2 6749/* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
14f9c5c9 6750 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
4c4b4cd2 6751 represents a 'when others' clause; otherwise 0. */
14f9c5c9 6752
de93309a 6753static int
ebf56fd3 6754ada_is_others_clause (struct type *type, int field_num)
14f9c5c9 6755{
33d16dd9 6756 const char *name = type->field (field_num).name ();
5b4ee69b 6757
14f9c5c9
AS
6758 return (name != NULL && name[0] == 'O');
6759}
6760
6761/* Assuming that TYPE0 is the type of the variant part of a record,
4c4b4cd2
PH
6762 returns the name of the discriminant controlling the variant.
6763 The value is valid until the next call to ada_variant_discrim_name. */
14f9c5c9 6764
a121b7c1 6765const char *
ebf56fd3 6766ada_variant_discrim_name (struct type *type0)
14f9c5c9 6767{
5f9febe0 6768 static std::string result;
d2e4a39e
AS
6769 struct type *type;
6770 const char *name;
6771 const char *discrim_end;
6772 const char *discrim_start;
14f9c5c9 6773
78134374 6774 if (type0->code () == TYPE_CODE_PTR)
27710edb 6775 type = type0->target_type ();
14f9c5c9
AS
6776 else
6777 type = type0;
6778
6779 name = ada_type_name (type);
6780
6781 if (name == NULL || name[0] == '\000')
6782 return "";
6783
6784 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6785 discrim_end -= 1)
6786 {
61012eef 6787 if (startswith (discrim_end, "___XVN"))
dda83cd7 6788 break;
14f9c5c9
AS
6789 }
6790 if (discrim_end == name)
6791 return "";
6792
d2e4a39e 6793 for (discrim_start = discrim_end; discrim_start != name + 3;
14f9c5c9
AS
6794 discrim_start -= 1)
6795 {
d2e4a39e 6796 if (discrim_start == name + 1)
dda83cd7 6797 return "";
76a01679 6798 if ((discrim_start > name + 3
dda83cd7
SM
6799 && startswith (discrim_start - 3, "___"))
6800 || discrim_start[-1] == '.')
6801 break;
14f9c5c9
AS
6802 }
6803
5f9febe0
TT
6804 result = std::string (discrim_start, discrim_end - discrim_start);
6805 return result.c_str ();
14f9c5c9
AS
6806}
6807
4c4b4cd2
PH
6808/* Scan STR for a subtype-encoded number, beginning at position K.
6809 Put the position of the character just past the number scanned in
6810 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6811 Return 1 if there was a valid number at the given position, and 0
6812 otherwise. A "subtype-encoded" number consists of the absolute value
6813 in decimal, followed by the letter 'm' to indicate a negative number.
6814 Assumes 0m does not occur. */
14f9c5c9
AS
6815
6816int
d2e4a39e 6817ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
14f9c5c9
AS
6818{
6819 ULONGEST RU;
6820
d2e4a39e 6821 if (!isdigit (str[k]))
14f9c5c9
AS
6822 return 0;
6823
4c4b4cd2 6824 /* Do it the hard way so as not to make any assumption about
14f9c5c9 6825 the relationship of unsigned long (%lu scan format code) and
4c4b4cd2 6826 LONGEST. */
14f9c5c9
AS
6827 RU = 0;
6828 while (isdigit (str[k]))
6829 {
d2e4a39e 6830 RU = RU * 10 + (str[k] - '0');
14f9c5c9
AS
6831 k += 1;
6832 }
6833
d2e4a39e 6834 if (str[k] == 'm')
14f9c5c9
AS
6835 {
6836 if (R != NULL)
dda83cd7 6837 *R = (-(LONGEST) (RU - 1)) - 1;
14f9c5c9
AS
6838 k += 1;
6839 }
6840 else if (R != NULL)
6841 *R = (LONGEST) RU;
6842
4c4b4cd2 6843 /* NOTE on the above: Technically, C does not say what the results of
14f9c5c9
AS
6844 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6845 number representable as a LONGEST (although either would probably work
6846 in most implementations). When RU>0, the locution in the then branch
4c4b4cd2 6847 above is always equivalent to the negative of RU. */
14f9c5c9
AS
6848
6849 if (new_k != NULL)
6850 *new_k = k;
6851 return 1;
6852}
6853
4c4b4cd2
PH
6854/* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6855 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6856 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
14f9c5c9 6857
de93309a 6858static int
ebf56fd3 6859ada_in_variant (LONGEST val, struct type *type, int field_num)
14f9c5c9 6860{
33d16dd9 6861 const char *name = type->field (field_num).name ();
14f9c5c9
AS
6862 int p;
6863
6864 p = 0;
6865 while (1)
6866 {
d2e4a39e 6867 switch (name[p])
dda83cd7
SM
6868 {
6869 case '\0':
6870 return 0;
6871 case 'S':
6872 {
6873 LONGEST W;
6874
6875 if (!ada_scan_number (name, p + 1, &W, &p))
6876 return 0;
6877 if (val == W)
6878 return 1;
6879 break;
6880 }
6881 case 'R':
6882 {
6883 LONGEST L, U;
6884
6885 if (!ada_scan_number (name, p + 1, &L, &p)
6886 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6887 return 0;
6888 if (val >= L && val <= U)
6889 return 1;
6890 break;
6891 }
6892 case 'O':
6893 return 1;
6894 default:
6895 return 0;
6896 }
4c4b4cd2
PH
6897 }
6898}
6899
0963b4bd 6900/* FIXME: Lots of redundancy below. Try to consolidate. */
4c4b4cd2
PH
6901
6902/* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6903 ARG_TYPE, extract and return the value of one of its (non-static)
6904 fields. FIELDNO says which field. Differs from value_primitive_field
6905 only in that it can handle packed values of arbitrary type. */
14f9c5c9 6906
5eb68a39 6907struct value *
d2e4a39e 6908ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
dda83cd7 6909 struct type *arg_type)
14f9c5c9 6910{
14f9c5c9
AS
6911 struct type *type;
6912
61ee279c 6913 arg_type = ada_check_typedef (arg_type);
940da03e 6914 type = arg_type->field (fieldno).type ();
14f9c5c9 6915
4504bbde
TT
6916 /* Handle packed fields. It might be that the field is not packed
6917 relative to its containing structure, but the structure itself is
6918 packed; in this case we must take the bit-field path. */
5011c493 6919 if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0 || arg1->bitpos () != 0)
14f9c5c9 6920 {
b610c045 6921 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
14f9c5c9 6922 int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
d2e4a39e 6923
50888e42 6924 return ada_value_primitive_packed_val (arg1,
efaf1ae0 6925 arg1->contents ().data (),
dda83cd7
SM
6926 offset + bit_pos / 8,
6927 bit_pos % 8, bit_size, type);
14f9c5c9
AS
6928 }
6929 else
6c49729e 6930 return arg1->primitive_field (offset, fieldno, arg_type);
14f9c5c9
AS
6931}
6932
52ce6436
PH
6933/* Find field with name NAME in object of type TYPE. If found,
6934 set the following for each argument that is non-null:
6935 - *FIELD_TYPE_P to the field's type;
6936 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6937 an object of that type;
6938 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6939 - *BIT_SIZE_P to its size in bits if the field is packed, and
6940 0 otherwise;
6941 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6942 fields up to but not including the desired field, or by the total
6943 number of fields if not found. A NULL value of NAME never
6944 matches; the function just counts visible fields in this case.
6945
828d5846
XR
6946 Notice that we need to handle when a tagged record hierarchy
6947 has some components with the same name, like in this scenario:
6948
6949 type Top_T is tagged record
dda83cd7
SM
6950 N : Integer := 1;
6951 U : Integer := 974;
6952 A : Integer := 48;
828d5846
XR
6953 end record;
6954
6955 type Middle_T is new Top.Top_T with record
dda83cd7
SM
6956 N : Character := 'a';
6957 C : Integer := 3;
828d5846
XR
6958 end record;
6959
6960 type Bottom_T is new Middle.Middle_T with record
dda83cd7
SM
6961 N : Float := 4.0;
6962 C : Character := '5';
6963 X : Integer := 6;
6964 A : Character := 'J';
828d5846
XR
6965 end record;
6966
6967 Let's say we now have a variable declared and initialized as follow:
6968
6969 TC : Top_A := new Bottom_T;
6970
6971 And then we use this variable to call this function
6972
6973 procedure Assign (Obj: in out Top_T; TV : Integer);
6974
6975 as follow:
6976
6977 Assign (Top_T (B), 12);
6978
6979 Now, we're in the debugger, and we're inside that procedure
6980 then and we want to print the value of obj.c:
6981
6982 Usually, the tagged record or one of the parent type owns the
6983 component to print and there's no issue but in this particular
6984 case, what does it mean to ask for Obj.C? Since the actual
6985 type for object is type Bottom_T, it could mean two things: type
6986 component C from the Middle_T view, but also component C from
6987 Bottom_T. So in that "undefined" case, when the component is
6988 not found in the non-resolved type (which includes all the
6989 components of the parent type), then resolve it and see if we
6990 get better luck once expanded.
6991
6992 In the case of homonyms in the derived tagged type, we don't
6993 guaranty anything, and pick the one that's easiest for us
6994 to program.
6995
0963b4bd 6996 Returns 1 if found, 0 otherwise. */
52ce6436 6997
4c4b4cd2 6998static int
0d5cff50 6999find_struct_field (const char *name, struct type *type, int offset,
dda83cd7
SM
7000 struct type **field_type_p,
7001 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
52ce6436 7002 int *index_p)
4c4b4cd2
PH
7003{
7004 int i;
828d5846 7005 int parent_offset = -1;
4c4b4cd2 7006
61ee279c 7007 type = ada_check_typedef (type);
76a01679 7008
52ce6436
PH
7009 if (field_type_p != NULL)
7010 *field_type_p = NULL;
7011 if (byte_offset_p != NULL)
d5d6fca5 7012 *byte_offset_p = 0;
52ce6436
PH
7013 if (bit_offset_p != NULL)
7014 *bit_offset_p = 0;
7015 if (bit_size_p != NULL)
7016 *bit_size_p = 0;
7017
1f704f76 7018 for (i = 0; i < type->num_fields (); i += 1)
4c4b4cd2 7019 {
4d1795ac
TT
7020 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
7021 type. However, we only need the values to be correct when
7022 the caller asks for them. */
7023 int bit_pos = 0, fld_offset = 0;
7024 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7025 {
b610c045 7026 bit_pos = type->field (i).loc_bitpos ();
4d1795ac
TT
7027 fld_offset = offset + bit_pos / 8;
7028 }
7029
33d16dd9 7030 const char *t_field_name = type->field (i).name ();
76a01679 7031
4c4b4cd2 7032 if (t_field_name == NULL)
dda83cd7 7033 continue;
4c4b4cd2 7034
828d5846 7035 else if (ada_is_parent_field (type, i))
dda83cd7 7036 {
828d5846
XR
7037 /* This is a field pointing us to the parent type of a tagged
7038 type. As hinted in this function's documentation, we give
7039 preference to fields in the current record first, so what
7040 we do here is just record the index of this field before
7041 we skip it. If it turns out we couldn't find our field
7042 in the current record, then we'll get back to it and search
7043 inside it whether the field might exist in the parent. */
7044
dda83cd7
SM
7045 parent_offset = i;
7046 continue;
7047 }
828d5846 7048
52ce6436 7049 else if (name != NULL && field_name_match (t_field_name, name))
dda83cd7
SM
7050 {
7051 int bit_size = TYPE_FIELD_BITSIZE (type, i);
5b4ee69b 7052
52ce6436 7053 if (field_type_p != NULL)
940da03e 7054 *field_type_p = type->field (i).type ();
52ce6436
PH
7055 if (byte_offset_p != NULL)
7056 *byte_offset_p = fld_offset;
7057 if (bit_offset_p != NULL)
7058 *bit_offset_p = bit_pos % 8;
7059 if (bit_size_p != NULL)
7060 *bit_size_p = bit_size;
dda83cd7
SM
7061 return 1;
7062 }
4c4b4cd2 7063 else if (ada_is_wrapper_field (type, i))
dda83cd7 7064 {
940da03e 7065 if (find_struct_field (name, type->field (i).type (), fld_offset,
52ce6436
PH
7066 field_type_p, byte_offset_p, bit_offset_p,
7067 bit_size_p, index_p))
dda83cd7
SM
7068 return 1;
7069 }
4c4b4cd2 7070 else if (ada_is_variant_part (type, i))
dda83cd7 7071 {
52ce6436
PH
7072 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7073 fixed type?? */
dda83cd7
SM
7074 int j;
7075 struct type *field_type
940da03e 7076 = ada_check_typedef (type->field (i).type ());
4c4b4cd2 7077
dda83cd7
SM
7078 for (j = 0; j < field_type->num_fields (); j += 1)
7079 {
7080 if (find_struct_field (name, field_type->field (j).type (),
7081 fld_offset
b610c045 7082 + field_type->field (j).loc_bitpos () / 8,
dda83cd7
SM
7083 field_type_p, byte_offset_p,
7084 bit_offset_p, bit_size_p, index_p))
7085 return 1;
7086 }
7087 }
52ce6436
PH
7088 else if (index_p != NULL)
7089 *index_p += 1;
4c4b4cd2 7090 }
828d5846
XR
7091
7092 /* Field not found so far. If this is a tagged type which
7093 has a parent, try finding that field in the parent now. */
7094
7095 if (parent_offset != -1)
7096 {
4d1795ac
TT
7097 /* As above, only compute the offset when truly needed. */
7098 int fld_offset = offset;
7099 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7100 {
b610c045 7101 int bit_pos = type->field (parent_offset).loc_bitpos ();
4d1795ac
TT
7102 fld_offset += bit_pos / 8;
7103 }
828d5846 7104
940da03e 7105 if (find_struct_field (name, type->field (parent_offset).type (),
dda83cd7
SM
7106 fld_offset, field_type_p, byte_offset_p,
7107 bit_offset_p, bit_size_p, index_p))
7108 return 1;
828d5846
XR
7109 }
7110
4c4b4cd2
PH
7111 return 0;
7112}
7113
0963b4bd 7114/* Number of user-visible fields in record type TYPE. */
4c4b4cd2 7115
52ce6436
PH
7116static int
7117num_visible_fields (struct type *type)
7118{
7119 int n;
5b4ee69b 7120
52ce6436
PH
7121 n = 0;
7122 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7123 return n;
7124}
14f9c5c9 7125
4c4b4cd2 7126/* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
14f9c5c9
AS
7127 and search in it assuming it has (class) type TYPE.
7128 If found, return value, else return NULL.
7129
828d5846
XR
7130 Searches recursively through wrapper fields (e.g., '_parent').
7131
7132 In the case of homonyms in the tagged types, please refer to the
7133 long explanation in find_struct_field's function documentation. */
14f9c5c9 7134
4c4b4cd2 7135static struct value *
108d56a4 7136ada_search_struct_field (const char *name, struct value *arg, int offset,
dda83cd7 7137 struct type *type)
14f9c5c9
AS
7138{
7139 int i;
828d5846 7140 int parent_offset = -1;
14f9c5c9 7141
5b4ee69b 7142 type = ada_check_typedef (type);
1f704f76 7143 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 7144 {
33d16dd9 7145 const char *t_field_name = type->field (i).name ();
14f9c5c9
AS
7146
7147 if (t_field_name == NULL)
dda83cd7 7148 continue;
14f9c5c9 7149
828d5846 7150 else if (ada_is_parent_field (type, i))
dda83cd7 7151 {
828d5846
XR
7152 /* This is a field pointing us to the parent type of a tagged
7153 type. As hinted in this function's documentation, we give
7154 preference to fields in the current record first, so what
7155 we do here is just record the index of this field before
7156 we skip it. If it turns out we couldn't find our field
7157 in the current record, then we'll get back to it and search
7158 inside it whether the field might exist in the parent. */
7159
dda83cd7
SM
7160 parent_offset = i;
7161 continue;
7162 }
828d5846 7163
14f9c5c9 7164 else if (field_name_match (t_field_name, name))
dda83cd7 7165 return ada_value_primitive_field (arg, offset, i, type);
14f9c5c9
AS
7166
7167 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7168 {
7169 struct value *v = /* Do not let indent join lines here. */
7170 ada_search_struct_field (name, arg,
b610c045 7171 offset + type->field (i).loc_bitpos () / 8,
dda83cd7 7172 type->field (i).type ());
5b4ee69b 7173
dda83cd7
SM
7174 if (v != NULL)
7175 return v;
7176 }
14f9c5c9
AS
7177
7178 else if (ada_is_variant_part (type, i))
dda83cd7 7179 {
0963b4bd 7180 /* PNH: Do we ever get here? See find_struct_field. */
dda83cd7
SM
7181 int j;
7182 struct type *field_type = ada_check_typedef (type->field (i).type ());
b610c045 7183 int var_offset = offset + type->field (i).loc_bitpos () / 8;
4c4b4cd2 7184
dda83cd7
SM
7185 for (j = 0; j < field_type->num_fields (); j += 1)
7186 {
7187 struct value *v = ada_search_struct_field /* Force line
0963b4bd 7188 break. */
dda83cd7 7189 (name, arg,
b610c045 7190 var_offset + field_type->field (j).loc_bitpos () / 8,
dda83cd7 7191 field_type->field (j).type ());
5b4ee69b 7192
dda83cd7
SM
7193 if (v != NULL)
7194 return v;
7195 }
7196 }
14f9c5c9 7197 }
828d5846
XR
7198
7199 /* Field not found so far. If this is a tagged type which
7200 has a parent, try finding that field in the parent now. */
7201
7202 if (parent_offset != -1)
7203 {
7204 struct value *v = ada_search_struct_field (
b610c045 7205 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
940da03e 7206 type->field (parent_offset).type ());
828d5846
XR
7207
7208 if (v != NULL)
dda83cd7 7209 return v;
828d5846
XR
7210 }
7211
14f9c5c9
AS
7212 return NULL;
7213}
d2e4a39e 7214
52ce6436
PH
7215static struct value *ada_index_struct_field_1 (int *, struct value *,
7216 int, struct type *);
7217
7218
7219/* Return field #INDEX in ARG, where the index is that returned by
7220 * find_struct_field through its INDEX_P argument. Adjust the address
7221 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
0963b4bd 7222 * If found, return value, else return NULL. */
52ce6436
PH
7223
7224static struct value *
7225ada_index_struct_field (int index, struct value *arg, int offset,
7226 struct type *type)
7227{
7228 return ada_index_struct_field_1 (&index, arg, offset, type);
7229}
7230
7231
7232/* Auxiliary function for ada_index_struct_field. Like
7233 * ada_index_struct_field, but takes index from *INDEX_P and modifies
0963b4bd 7234 * *INDEX_P. */
52ce6436
PH
7235
7236static struct value *
7237ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7238 struct type *type)
7239{
7240 int i;
7241 type = ada_check_typedef (type);
7242
1f704f76 7243 for (i = 0; i < type->num_fields (); i += 1)
52ce6436 7244 {
33d16dd9 7245 if (type->field (i).name () == NULL)
dda83cd7 7246 continue;
52ce6436 7247 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7248 {
7249 struct value *v = /* Do not let indent join lines here. */
7250 ada_index_struct_field_1 (index_p, arg,
b610c045 7251 offset + type->field (i).loc_bitpos () / 8,
940da03e 7252 type->field (i).type ());
5b4ee69b 7253
dda83cd7
SM
7254 if (v != NULL)
7255 return v;
7256 }
52ce6436
PH
7257
7258 else if (ada_is_variant_part (type, i))
dda83cd7 7259 {
52ce6436 7260 /* PNH: Do we ever get here? See ada_search_struct_field,
0963b4bd 7261 find_struct_field. */
52ce6436 7262 error (_("Cannot assign this kind of variant record"));
dda83cd7 7263 }
52ce6436 7264 else if (*index_p == 0)
dda83cd7 7265 return ada_value_primitive_field (arg, offset, i, type);
52ce6436
PH
7266 else
7267 *index_p -= 1;
7268 }
7269 return NULL;
7270}
7271
3b4de39c 7272/* Return a string representation of type TYPE. */
99bbb428 7273
3b4de39c 7274static std::string
99bbb428
PA
7275type_as_string (struct type *type)
7276{
d7e74731 7277 string_file tmp_stream;
99bbb428 7278
d7e74731 7279 type_print (type, "", &tmp_stream, -1);
99bbb428 7280
5d10a204 7281 return tmp_stream.release ();
99bbb428
PA
7282}
7283
14f9c5c9 7284/* Given a type TYPE, look up the type of the component of type named NAME.
4c4b4cd2
PH
7285 If DISPP is non-null, add its byte displacement from the beginning of a
7286 structure (pointed to by a value) of type TYPE to *DISPP (does not
14f9c5c9
AS
7287 work for packed fields).
7288
7289 Matches any field whose name has NAME as a prefix, possibly
4c4b4cd2 7290 followed by "___".
14f9c5c9 7291
0963b4bd 7292 TYPE can be either a struct or union. If REFOK, TYPE may also
4c4b4cd2
PH
7293 be a (pointer or reference)+ to a struct or union, and the
7294 ultimate target type will be searched.
14f9c5c9
AS
7295
7296 Looks recursively into variant clauses and parent types.
7297
828d5846
XR
7298 In the case of homonyms in the tagged types, please refer to the
7299 long explanation in find_struct_field's function documentation.
7300
4c4b4cd2
PH
7301 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7302 TYPE is not a type of the right kind. */
14f9c5c9 7303
4c4b4cd2 7304static struct type *
a121b7c1 7305ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
dda83cd7 7306 int noerr)
14f9c5c9
AS
7307{
7308 int i;
828d5846 7309 int parent_offset = -1;
14f9c5c9
AS
7310
7311 if (name == NULL)
7312 goto BadName;
7313
76a01679 7314 if (refok && type != NULL)
4c4b4cd2
PH
7315 while (1)
7316 {
dda83cd7
SM
7317 type = ada_check_typedef (type);
7318 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7319 break;
27710edb 7320 type = type->target_type ();
4c4b4cd2 7321 }
14f9c5c9 7322
76a01679 7323 if (type == NULL
78134374
SM
7324 || (type->code () != TYPE_CODE_STRUCT
7325 && type->code () != TYPE_CODE_UNION))
14f9c5c9 7326 {
4c4b4cd2 7327 if (noerr)
dda83cd7 7328 return NULL;
99bbb428 7329
3b4de39c
PA
7330 error (_("Type %s is not a structure or union type"),
7331 type != NULL ? type_as_string (type).c_str () : _("(null)"));
14f9c5c9
AS
7332 }
7333
7334 type = to_static_fixed_type (type);
7335
1f704f76 7336 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 7337 {
33d16dd9 7338 const char *t_field_name = type->field (i).name ();
14f9c5c9 7339 struct type *t;
d2e4a39e 7340
14f9c5c9 7341 if (t_field_name == NULL)
dda83cd7 7342 continue;
14f9c5c9 7343
828d5846 7344 else if (ada_is_parent_field (type, i))
dda83cd7 7345 {
828d5846
XR
7346 /* This is a field pointing us to the parent type of a tagged
7347 type. As hinted in this function's documentation, we give
7348 preference to fields in the current record first, so what
7349 we do here is just record the index of this field before
7350 we skip it. If it turns out we couldn't find our field
7351 in the current record, then we'll get back to it and search
7352 inside it whether the field might exist in the parent. */
7353
dda83cd7
SM
7354 parent_offset = i;
7355 continue;
7356 }
828d5846 7357
14f9c5c9 7358 else if (field_name_match (t_field_name, name))
940da03e 7359 return type->field (i).type ();
14f9c5c9
AS
7360
7361 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7362 {
7363 t = ada_lookup_struct_elt_type (type->field (i).type (), name,
7364 0, 1);
7365 if (t != NULL)
988f6b3d 7366 return t;
dda83cd7 7367 }
14f9c5c9
AS
7368
7369 else if (ada_is_variant_part (type, i))
dda83cd7
SM
7370 {
7371 int j;
7372 struct type *field_type = ada_check_typedef (type->field (i).type ());
4c4b4cd2 7373
dda83cd7
SM
7374 for (j = field_type->num_fields () - 1; j >= 0; j -= 1)
7375 {
b1f33ddd 7376 /* FIXME pnh 2008/01/26: We check for a field that is
dda83cd7 7377 NOT wrapped in a struct, since the compiler sometimes
b1f33ddd 7378 generates these for unchecked variant types. Revisit
dda83cd7 7379 if the compiler changes this practice. */
33d16dd9 7380 const char *v_field_name = field_type->field (j).name ();
988f6b3d 7381
b1f33ddd
JB
7382 if (v_field_name != NULL
7383 && field_name_match (v_field_name, name))
940da03e 7384 t = field_type->field (j).type ();
b1f33ddd 7385 else
940da03e 7386 t = ada_lookup_struct_elt_type (field_type->field (j).type (),
988f6b3d 7387 name, 0, 1);
b1f33ddd 7388
dda83cd7 7389 if (t != NULL)
988f6b3d 7390 return t;
dda83cd7
SM
7391 }
7392 }
14f9c5c9
AS
7393
7394 }
7395
828d5846
XR
7396 /* Field not found so far. If this is a tagged type which
7397 has a parent, try finding that field in the parent now. */
7398
7399 if (parent_offset != -1)
7400 {
dda83cd7 7401 struct type *t;
828d5846 7402
dda83cd7
SM
7403 t = ada_lookup_struct_elt_type (type->field (parent_offset).type (),
7404 name, 0, 1);
7405 if (t != NULL)
828d5846
XR
7406 return t;
7407 }
7408
14f9c5c9 7409BadName:
d2e4a39e 7410 if (!noerr)
14f9c5c9 7411 {
2b2798cc 7412 const char *name_str = name != NULL ? name : _("<null>");
99bbb428
PA
7413
7414 error (_("Type %s has no component named %s"),
3b4de39c 7415 type_as_string (type).c_str (), name_str);
14f9c5c9
AS
7416 }
7417
7418 return NULL;
7419}
7420
b1f33ddd
JB
7421/* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7422 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7423 represents an unchecked union (that is, the variant part of a
0963b4bd 7424 record that is named in an Unchecked_Union pragma). */
b1f33ddd
JB
7425
7426static int
7427is_unchecked_variant (struct type *var_type, struct type *outer_type)
7428{
a121b7c1 7429 const char *discrim_name = ada_variant_discrim_name (var_type);
5b4ee69b 7430
988f6b3d 7431 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
b1f33ddd
JB
7432}
7433
7434
14f9c5c9 7435/* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
d8af9068 7436 within OUTER, determine which variant clause (field number in VAR_TYPE,
4c4b4cd2 7437 numbering from 0) is applicable. Returns -1 if none are. */
14f9c5c9 7438
d2e4a39e 7439int
d8af9068 7440ada_which_variant_applies (struct type *var_type, struct value *outer)
14f9c5c9
AS
7441{
7442 int others_clause;
7443 int i;
a121b7c1 7444 const char *discrim_name = ada_variant_discrim_name (var_type);
0c281816 7445 struct value *discrim;
14f9c5c9
AS
7446 LONGEST discrim_val;
7447
012370f6
TT
7448 /* Using plain value_from_contents_and_address here causes problems
7449 because we will end up trying to resolve a type that is currently
7450 being constructed. */
0c281816
JB
7451 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7452 if (discrim == NULL)
14f9c5c9 7453 return -1;
0c281816 7454 discrim_val = value_as_long (discrim);
14f9c5c9
AS
7455
7456 others_clause = -1;
1f704f76 7457 for (i = 0; i < var_type->num_fields (); i += 1)
14f9c5c9
AS
7458 {
7459 if (ada_is_others_clause (var_type, i))
dda83cd7 7460 others_clause = i;
14f9c5c9 7461 else if (ada_in_variant (discrim_val, var_type, i))
dda83cd7 7462 return i;
14f9c5c9
AS
7463 }
7464
7465 return others_clause;
7466}
d2e4a39e 7467\f
14f9c5c9
AS
7468
7469
dda83cd7 7470 /* Dynamic-Sized Records */
14f9c5c9
AS
7471
7472/* Strategy: The type ostensibly attached to a value with dynamic size
7473 (i.e., a size that is not statically recorded in the debugging
7474 data) does not accurately reflect the size or layout of the value.
7475 Our strategy is to convert these values to values with accurate,
4c4b4cd2 7476 conventional types that are constructed on the fly. */
14f9c5c9
AS
7477
7478/* There is a subtle and tricky problem here. In general, we cannot
7479 determine the size of dynamic records without its data. However,
7480 the 'struct value' data structure, which GDB uses to represent
7481 quantities in the inferior process (the target), requires the size
7482 of the type at the time of its allocation in order to reserve space
7483 for GDB's internal copy of the data. That's why the
7484 'to_fixed_xxx_type' routines take (target) addresses as parameters,
4c4b4cd2 7485 rather than struct value*s.
14f9c5c9
AS
7486
7487 However, GDB's internal history variables ($1, $2, etc.) are
7488 struct value*s containing internal copies of the data that are not, in
7489 general, the same as the data at their corresponding addresses in
7490 the target. Fortunately, the types we give to these values are all
7491 conventional, fixed-size types (as per the strategy described
7492 above), so that we don't usually have to perform the
7493 'to_fixed_xxx_type' conversions to look at their values.
7494 Unfortunately, there is one exception: if one of the internal
7495 history variables is an array whose elements are unconstrained
7496 records, then we will need to create distinct fixed types for each
7497 element selected. */
7498
7499/* The upshot of all of this is that many routines take a (type, host
7500 address, target address) triple as arguments to represent a value.
7501 The host address, if non-null, is supposed to contain an internal
7502 copy of the relevant data; otherwise, the program is to consult the
4c4b4cd2 7503 target at the target address. */
14f9c5c9
AS
7504
7505/* Assuming that VAL0 represents a pointer value, the result of
7506 dereferencing it. Differs from value_ind in its treatment of
4c4b4cd2 7507 dynamic-sized types. */
14f9c5c9 7508
d2e4a39e
AS
7509struct value *
7510ada_value_ind (struct value *val0)
14f9c5c9 7511{
c48db5ca 7512 struct value *val = value_ind (val0);
5b4ee69b 7513
d0c97917 7514 if (ada_is_tagged_type (val->type (), 0))
b50d69b5
JG
7515 val = ada_tag_value_at_base_address (val);
7516
4c4b4cd2 7517 return ada_to_fixed_value (val);
14f9c5c9
AS
7518}
7519
7520/* The value resulting from dereferencing any "reference to"
4c4b4cd2
PH
7521 qualifiers on VAL0. */
7522
d2e4a39e
AS
7523static struct value *
7524ada_coerce_ref (struct value *val0)
7525{
d0c97917 7526 if (val0->type ()->code () == TYPE_CODE_REF)
d2e4a39e
AS
7527 {
7528 struct value *val = val0;
5b4ee69b 7529
994b9211 7530 val = coerce_ref (val);
b50d69b5 7531
d0c97917 7532 if (ada_is_tagged_type (val->type (), 0))
b50d69b5
JG
7533 val = ada_tag_value_at_base_address (val);
7534
4c4b4cd2 7535 return ada_to_fixed_value (val);
d2e4a39e
AS
7536 }
7537 else
14f9c5c9
AS
7538 return val0;
7539}
7540
4c4b4cd2 7541/* Return the bit alignment required for field #F of template type TYPE. */
14f9c5c9
AS
7542
7543static unsigned int
ebf56fd3 7544field_alignment (struct type *type, int f)
14f9c5c9 7545{
33d16dd9 7546 const char *name = type->field (f).name ();
64a1bf19 7547 int len;
14f9c5c9
AS
7548 int align_offset;
7549
64a1bf19
JB
7550 /* The field name should never be null, unless the debugging information
7551 is somehow malformed. In this case, we assume the field does not
7552 require any alignment. */
7553 if (name == NULL)
7554 return 1;
7555
7556 len = strlen (name);
7557
4c4b4cd2
PH
7558 if (!isdigit (name[len - 1]))
7559 return 1;
14f9c5c9 7560
d2e4a39e 7561 if (isdigit (name[len - 2]))
14f9c5c9
AS
7562 align_offset = len - 2;
7563 else
7564 align_offset = len - 1;
7565
61012eef 7566 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
14f9c5c9
AS
7567 return TARGET_CHAR_BIT;
7568
4c4b4cd2
PH
7569 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7570}
7571
852dff6c 7572/* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
4c4b4cd2 7573
852dff6c
JB
7574static struct symbol *
7575ada_find_any_type_symbol (const char *name)
4c4b4cd2
PH
7576{
7577 struct symbol *sym;
7578
7579 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
66d7f48f 7580 if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
4c4b4cd2
PH
7581 return sym;
7582
4186eb54
KS
7583 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7584 return sym;
14f9c5c9
AS
7585}
7586
dddfab26
UW
7587/* Find a type named NAME. Ignores ambiguity. This routine will look
7588 solely for types defined by debug info, it will not search the GDB
7589 primitive types. */
4c4b4cd2 7590
852dff6c 7591static struct type *
ebf56fd3 7592ada_find_any_type (const char *name)
14f9c5c9 7593{
852dff6c 7594 struct symbol *sym = ada_find_any_type_symbol (name);
14f9c5c9 7595
14f9c5c9 7596 if (sym != NULL)
5f9c5a63 7597 return sym->type ();
14f9c5c9 7598
dddfab26 7599 return NULL;
14f9c5c9
AS
7600}
7601
739593e0
JB
7602/* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7603 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7604 symbol, in which case it is returned. Otherwise, this looks for
7605 symbols whose name is that of NAME_SYM suffixed with "___XR".
7606 Return symbol if found, and NULL otherwise. */
4c4b4cd2 7607
c0e70c62
TT
7608static bool
7609ada_is_renaming_symbol (struct symbol *name_sym)
aeb5907d 7610{
987012b8 7611 const char *name = name_sym->linkage_name ();
c0e70c62 7612 return strstr (name, "___XR") != NULL;
4c4b4cd2
PH
7613}
7614
14f9c5c9 7615/* Because of GNAT encoding conventions, several GDB symbols may match a
4c4b4cd2 7616 given type name. If the type denoted by TYPE0 is to be preferred to
14f9c5c9 7617 that of TYPE1 for purposes of type printing, return non-zero;
4c4b4cd2
PH
7618 otherwise return 0. */
7619
14f9c5c9 7620int
d2e4a39e 7621ada_prefer_type (struct type *type0, struct type *type1)
14f9c5c9
AS
7622{
7623 if (type1 == NULL)
7624 return 1;
7625 else if (type0 == NULL)
7626 return 0;
78134374 7627 else if (type1->code () == TYPE_CODE_VOID)
14f9c5c9 7628 return 1;
78134374 7629 else if (type0->code () == TYPE_CODE_VOID)
14f9c5c9 7630 return 0;
7d93a1e0 7631 else if (type1->name () == NULL && type0->name () != NULL)
4c4b4cd2 7632 return 1;
ad82864c 7633 else if (ada_is_constrained_packed_array_type (type0))
14f9c5c9 7634 return 1;
4c4b4cd2 7635 else if (ada_is_array_descriptor_type (type0)
dda83cd7 7636 && !ada_is_array_descriptor_type (type1))
14f9c5c9 7637 return 1;
aeb5907d
JB
7638 else
7639 {
7d93a1e0
SM
7640 const char *type0_name = type0->name ();
7641 const char *type1_name = type1->name ();
aeb5907d
JB
7642
7643 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7644 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7645 return 1;
7646 }
14f9c5c9
AS
7647 return 0;
7648}
7649
e86ca25f
TT
7650/* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7651 null. */
4c4b4cd2 7652
0d5cff50 7653const char *
d2e4a39e 7654ada_type_name (struct type *type)
14f9c5c9 7655{
d2e4a39e 7656 if (type == NULL)
14f9c5c9 7657 return NULL;
7d93a1e0 7658 return type->name ();
14f9c5c9
AS
7659}
7660
b4ba55a1
JB
7661/* Search the list of "descriptive" types associated to TYPE for a type
7662 whose name is NAME. */
7663
7664static struct type *
7665find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7666{
931e5bc3 7667 struct type *result, *tmp;
b4ba55a1 7668
c6044dd1
JB
7669 if (ada_ignore_descriptive_types_p)
7670 return NULL;
7671
b4ba55a1
JB
7672 /* If there no descriptive-type info, then there is no parallel type
7673 to be found. */
7674 if (!HAVE_GNAT_AUX_INFO (type))
7675 return NULL;
7676
7677 result = TYPE_DESCRIPTIVE_TYPE (type);
7678 while (result != NULL)
7679 {
0d5cff50 7680 const char *result_name = ada_type_name (result);
b4ba55a1
JB
7681
7682 if (result_name == NULL)
dda83cd7
SM
7683 {
7684 warning (_("unexpected null name on descriptive type"));
7685 return NULL;
7686 }
b4ba55a1
JB
7687
7688 /* If the names match, stop. */
7689 if (strcmp (result_name, name) == 0)
7690 break;
7691
7692 /* Otherwise, look at the next item on the list, if any. */
7693 if (HAVE_GNAT_AUX_INFO (result))
931e5bc3
JG
7694 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7695 else
7696 tmp = NULL;
7697
7698 /* If not found either, try after having resolved the typedef. */
7699 if (tmp != NULL)
7700 result = tmp;
b4ba55a1 7701 else
931e5bc3 7702 {
f168693b 7703 result = check_typedef (result);
931e5bc3
JG
7704 if (HAVE_GNAT_AUX_INFO (result))
7705 result = TYPE_DESCRIPTIVE_TYPE (result);
7706 else
7707 result = NULL;
7708 }
b4ba55a1
JB
7709 }
7710
7711 /* If we didn't find a match, see whether this is a packed array. With
7712 older compilers, the descriptive type information is either absent or
7713 irrelevant when it comes to packed arrays so the above lookup fails.
7714 Fall back to using a parallel lookup by name in this case. */
12ab9e09 7715 if (result == NULL && ada_is_constrained_packed_array_type (type))
b4ba55a1
JB
7716 return ada_find_any_type (name);
7717
7718 return result;
7719}
7720
7721/* Find a parallel type to TYPE with the specified NAME, using the
7722 descriptive type taken from the debugging information, if available,
7723 and otherwise using the (slower) name-based method. */
7724
7725static struct type *
7726ada_find_parallel_type_with_name (struct type *type, const char *name)
7727{
7728 struct type *result = NULL;
7729
7730 if (HAVE_GNAT_AUX_INFO (type))
7731 result = find_parallel_type_by_descriptive_type (type, name);
7732 else
7733 result = ada_find_any_type (name);
7734
7735 return result;
7736}
7737
7738/* Same as above, but specify the name of the parallel type by appending
4c4b4cd2 7739 SUFFIX to the name of TYPE. */
14f9c5c9 7740
d2e4a39e 7741struct type *
ebf56fd3 7742ada_find_parallel_type (struct type *type, const char *suffix)
14f9c5c9 7743{
0d5cff50 7744 char *name;
fe978cb0 7745 const char *type_name = ada_type_name (type);
14f9c5c9 7746 int len;
d2e4a39e 7747
fe978cb0 7748 if (type_name == NULL)
14f9c5c9
AS
7749 return NULL;
7750
fe978cb0 7751 len = strlen (type_name);
14f9c5c9 7752
b4ba55a1 7753 name = (char *) alloca (len + strlen (suffix) + 1);
14f9c5c9 7754
fe978cb0 7755 strcpy (name, type_name);
14f9c5c9
AS
7756 strcpy (name + len, suffix);
7757
b4ba55a1 7758 return ada_find_parallel_type_with_name (type, name);
14f9c5c9
AS
7759}
7760
14f9c5c9 7761/* If TYPE is a variable-size record type, return the corresponding template
4c4b4cd2 7762 type describing its fields. Otherwise, return NULL. */
14f9c5c9 7763
d2e4a39e
AS
7764static struct type *
7765dynamic_template_type (struct type *type)
14f9c5c9 7766{
61ee279c 7767 type = ada_check_typedef (type);
14f9c5c9 7768
78134374 7769 if (type == NULL || type->code () != TYPE_CODE_STRUCT
d2e4a39e 7770 || ada_type_name (type) == NULL)
14f9c5c9 7771 return NULL;
d2e4a39e 7772 else
14f9c5c9
AS
7773 {
7774 int len = strlen (ada_type_name (type));
5b4ee69b 7775
4c4b4cd2 7776 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
dda83cd7 7777 return type;
14f9c5c9 7778 else
dda83cd7 7779 return ada_find_parallel_type (type, "___XVE");
14f9c5c9
AS
7780 }
7781}
7782
7783/* Assuming that TEMPL_TYPE is a union or struct type, returns
4c4b4cd2 7784 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
14f9c5c9 7785
d2e4a39e
AS
7786static int
7787is_dynamic_field (struct type *templ_type, int field_num)
14f9c5c9 7788{
33d16dd9 7789 const char *name = templ_type->field (field_num).name ();
5b4ee69b 7790
d2e4a39e 7791 return name != NULL
940da03e 7792 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
14f9c5c9
AS
7793 && strstr (name, "___XVL") != NULL;
7794}
7795
4c4b4cd2
PH
7796/* The index of the variant field of TYPE, or -1 if TYPE does not
7797 represent a variant record type. */
14f9c5c9 7798
d2e4a39e 7799static int
4c4b4cd2 7800variant_field_index (struct type *type)
14f9c5c9
AS
7801{
7802 int f;
7803
78134374 7804 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
4c4b4cd2
PH
7805 return -1;
7806
1f704f76 7807 for (f = 0; f < type->num_fields (); f += 1)
4c4b4cd2
PH
7808 {
7809 if (ada_is_variant_part (type, f))
dda83cd7 7810 return f;
4c4b4cd2
PH
7811 }
7812 return -1;
14f9c5c9
AS
7813}
7814
4c4b4cd2
PH
7815/* A record type with no fields. */
7816
d2e4a39e 7817static struct type *
fe978cb0 7818empty_record (struct type *templ)
14f9c5c9 7819{
9fa83a7a 7820 struct type *type = type_allocator (templ).new_type ();
5b4ee69b 7821
67607e24 7822 type->set_code (TYPE_CODE_STRUCT);
8ecb59f8 7823 INIT_NONE_SPECIFIC (type);
d0e39ea2 7824 type->set_name ("<empty>");
b6cdbc9a 7825 type->set_length (0);
14f9c5c9
AS
7826 return type;
7827}
7828
7829/* An ordinary record type (with fixed-length fields) that describes
4c4b4cd2
PH
7830 the value of type TYPE at VALADDR or ADDRESS (see comments at
7831 the beginning of this section) VAL according to GNAT conventions.
7832 DVAL0 should describe the (portion of a) record that contains any
d0c97917 7833 necessary discriminants. It should be NULL if VAL->type () is
14f9c5c9
AS
7834 an outer-level type (i.e., as opposed to a branch of a variant.) A
7835 variant field (unless unchecked) is replaced by a particular branch
4c4b4cd2 7836 of the variant.
14f9c5c9 7837
4c4b4cd2
PH
7838 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7839 length are not statically known are discarded. As a consequence,
7840 VALADDR, ADDRESS and DVAL0 are ignored.
7841
7842 NOTE: Limitations: For now, we assume that dynamic fields and
7843 variants occupy whole numbers of bytes. However, they need not be
7844 byte-aligned. */
7845
7846struct type *
10a2c479 7847ada_template_to_fixed_record_type_1 (struct type *type,
fc1a4b47 7848 const gdb_byte *valaddr,
dda83cd7
SM
7849 CORE_ADDR address, struct value *dval0,
7850 int keep_dynamic_fields)
14f9c5c9 7851{
d2e4a39e
AS
7852 struct value *dval;
7853 struct type *rtype;
14f9c5c9 7854 int nfields, bit_len;
4c4b4cd2 7855 int variant_field;
14f9c5c9 7856 long off;
d94e4f4f 7857 int fld_bit_len;
14f9c5c9
AS
7858 int f;
7859
65558ca5
TT
7860 scoped_value_mark mark;
7861
4c4b4cd2
PH
7862 /* Compute the number of fields in this record type that are going
7863 to be processed: unless keep_dynamic_fields, this includes only
7864 fields whose position and length are static will be processed. */
7865 if (keep_dynamic_fields)
1f704f76 7866 nfields = type->num_fields ();
4c4b4cd2
PH
7867 else
7868 {
7869 nfields = 0;
1f704f76 7870 while (nfields < type->num_fields ()
dda83cd7
SM
7871 && !ada_is_variant_part (type, nfields)
7872 && !is_dynamic_field (type, nfields))
7873 nfields++;
4c4b4cd2
PH
7874 }
7875
9fa83a7a 7876 rtype = type_allocator (type).new_type ();
67607e24 7877 rtype->set_code (TYPE_CODE_STRUCT);
8ecb59f8 7878 INIT_NONE_SPECIFIC (rtype);
5e33d5f4 7879 rtype->set_num_fields (nfields);
3cabb6b0
SM
7880 rtype->set_fields
7881 ((struct field *) TYPE_ZALLOC (rtype, nfields * sizeof (struct field)));
d0e39ea2 7882 rtype->set_name (ada_type_name (type));
9cdd0d12 7883 rtype->set_is_fixed_instance (true);
14f9c5c9 7884
d2e4a39e
AS
7885 off = 0;
7886 bit_len = 0;
4c4b4cd2
PH
7887 variant_field = -1;
7888
14f9c5c9
AS
7889 for (f = 0; f < nfields; f += 1)
7890 {
a89febbd 7891 off = align_up (off, field_alignment (type, f))
b610c045 7892 + type->field (f).loc_bitpos ();
cd3f655c 7893 rtype->field (f).set_loc_bitpos (off);
d2e4a39e 7894 TYPE_FIELD_BITSIZE (rtype, f) = 0;
14f9c5c9 7895
d2e4a39e 7896 if (ada_is_variant_part (type, f))
dda83cd7
SM
7897 {
7898 variant_field = f;
7899 fld_bit_len = 0;
7900 }
14f9c5c9 7901 else if (is_dynamic_field (type, f))
dda83cd7 7902 {
284614f0
JB
7903 const gdb_byte *field_valaddr = valaddr;
7904 CORE_ADDR field_address = address;
27710edb 7905 struct type *field_type = type->field (f).type ()->target_type ();
284614f0 7906
dda83cd7 7907 if (dval0 == NULL)
b5304971 7908 {
012370f6
TT
7909 /* Using plain value_from_contents_and_address here
7910 causes problems because we will end up trying to
7911 resolve a type that is currently being
7912 constructed. */
7913 dval = value_from_contents_and_address_unresolved (rtype,
7914 valaddr,
7915 address);
d0c97917 7916 rtype = dval->type ();
b5304971 7917 }
dda83cd7
SM
7918 else
7919 dval = dval0;
4c4b4cd2 7920
284614f0
JB
7921 /* If the type referenced by this field is an aligner type, we need
7922 to unwrap that aligner type, because its size might not be set.
7923 Keeping the aligner type would cause us to compute the wrong
7924 size for this field, impacting the offset of the all the fields
7925 that follow this one. */
7926 if (ada_is_aligner_type (field_type))
7927 {
b610c045 7928 long field_offset = type->field (f).loc_bitpos ();
284614f0
JB
7929
7930 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7931 field_address = cond_offset_target (field_address, field_offset);
7932 field_type = ada_aligned_type (field_type);
7933 }
7934
7935 field_valaddr = cond_offset_host (field_valaddr,
7936 off / TARGET_CHAR_BIT);
7937 field_address = cond_offset_target (field_address,
7938 off / TARGET_CHAR_BIT);
7939
7940 /* Get the fixed type of the field. Note that, in this case,
7941 we do not want to get the real type out of the tag: if
7942 the current field is the parent part of a tagged record,
7943 we will get the tag of the object. Clearly wrong: the real
7944 type of the parent is not the real type of the child. We
7945 would end up in an infinite loop. */
7946 field_type = ada_get_base_type (field_type);
7947 field_type = ada_to_fixed_type (field_type, field_valaddr,
7948 field_address, dval, 0);
7949
5d14b6e5 7950 rtype->field (f).set_type (field_type);
33d16dd9 7951 rtype->field (f).set_name (type->field (f).name ());
27f2a97b
JB
7952 /* The multiplication can potentially overflow. But because
7953 the field length has been size-checked just above, and
7954 assuming that the maximum size is a reasonable value,
7955 an overflow should not happen in practice. So rather than
7956 adding overflow recovery code to this already complex code,
7957 we just assume that it's not going to happen. */
df86565b 7958 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
dda83cd7 7959 }
14f9c5c9 7960 else
dda83cd7 7961 {
5ded5331
JB
7962 /* Note: If this field's type is a typedef, it is important
7963 to preserve the typedef layer.
7964
7965 Otherwise, we might be transforming a typedef to a fat
7966 pointer (encoding a pointer to an unconstrained array),
7967 into a basic fat pointer (encoding an unconstrained
7968 array). As both types are implemented using the same
7969 structure, the typedef is the only clue which allows us
7970 to distinguish between the two options. Stripping it
7971 would prevent us from printing this field appropriately. */
dda83cd7 7972 rtype->field (f).set_type (type->field (f).type ());
33d16dd9 7973 rtype->field (f).set_name (type->field (f).name ());
dda83cd7
SM
7974 if (TYPE_FIELD_BITSIZE (type, f) > 0)
7975 fld_bit_len =
7976 TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
7977 else
5ded5331 7978 {
940da03e 7979 struct type *field_type = type->field (f).type ();
5ded5331
JB
7980
7981 /* We need to be careful of typedefs when computing
7982 the length of our field. If this is a typedef,
7983 get the length of the target type, not the length
7984 of the typedef. */
78134374 7985 if (field_type->code () == TYPE_CODE_TYPEDEF)
5ded5331
JB
7986 field_type = ada_typedef_target_type (field_type);
7987
dda83cd7 7988 fld_bit_len =
df86565b 7989 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
5ded5331 7990 }
dda83cd7 7991 }
14f9c5c9 7992 if (off + fld_bit_len > bit_len)
dda83cd7 7993 bit_len = off + fld_bit_len;
d94e4f4f 7994 off += fld_bit_len;
b6cdbc9a 7995 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
14f9c5c9 7996 }
4c4b4cd2
PH
7997
7998 /* We handle the variant part, if any, at the end because of certain
b1f33ddd 7999 odd cases in which it is re-ordered so as NOT to be the last field of
4c4b4cd2
PH
8000 the record. This can happen in the presence of representation
8001 clauses. */
8002 if (variant_field >= 0)
8003 {
8004 struct type *branch_type;
8005
b610c045 8006 off = rtype->field (variant_field).loc_bitpos ();
4c4b4cd2
PH
8007
8008 if (dval0 == NULL)
9f1f738a 8009 {
012370f6
TT
8010 /* Using plain value_from_contents_and_address here causes
8011 problems because we will end up trying to resolve a type
8012 that is currently being constructed. */
8013 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
8014 address);
d0c97917 8015 rtype = dval->type ();
9f1f738a 8016 }
4c4b4cd2 8017 else
dda83cd7 8018 dval = dval0;
4c4b4cd2
PH
8019
8020 branch_type =
dda83cd7
SM
8021 to_fixed_variant_branch_type
8022 (type->field (variant_field).type (),
8023 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
8024 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
4c4b4cd2 8025 if (branch_type == NULL)
dda83cd7
SM
8026 {
8027 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
8028 rtype->field (f - 1) = rtype->field (f);
5e33d5f4 8029 rtype->set_num_fields (rtype->num_fields () - 1);
dda83cd7 8030 }
4c4b4cd2 8031 else
dda83cd7
SM
8032 {
8033 rtype->field (variant_field).set_type (branch_type);
d3fd12df 8034 rtype->field (variant_field).set_name ("S");
dda83cd7 8035 fld_bit_len =
df86565b 8036 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
dda83cd7
SM
8037 if (off + fld_bit_len > bit_len)
8038 bit_len = off + fld_bit_len;
b6cdbc9a
SM
8039
8040 rtype->set_length
8041 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
dda83cd7 8042 }
4c4b4cd2
PH
8043 }
8044
714e53ab
PH
8045 /* According to exp_dbug.ads, the size of TYPE for variable-size records
8046 should contain the alignment of that record, which should be a strictly
8047 positive value. If null or negative, then something is wrong, most
8048 probably in the debug info. In that case, we don't round up the size
0963b4bd 8049 of the resulting type. If this record is not part of another structure,
714e53ab 8050 the current RTYPE length might be good enough for our purposes. */
df86565b 8051 if (type->length () <= 0)
714e53ab 8052 {
7d93a1e0 8053 if (rtype->name ())
cc1defb1 8054 warning (_("Invalid type size for `%s' detected: %s."),
df86565b 8055 rtype->name (), pulongest (type->length ()));
323e0a4a 8056 else
cc1defb1 8057 warning (_("Invalid type size for <unnamed> detected: %s."),
df86565b 8058 pulongest (type->length ()));
714e53ab
PH
8059 }
8060 else
df86565b 8061 rtype->set_length (align_up (rtype->length (), type->length ()));
14f9c5c9 8062
14f9c5c9
AS
8063 return rtype;
8064}
8065
4c4b4cd2
PH
8066/* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
8067 of 1. */
14f9c5c9 8068
d2e4a39e 8069static struct type *
fc1a4b47 8070template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
dda83cd7 8071 CORE_ADDR address, struct value *dval0)
4c4b4cd2
PH
8072{
8073 return ada_template_to_fixed_record_type_1 (type, valaddr,
dda83cd7 8074 address, dval0, 1);
4c4b4cd2
PH
8075}
8076
8077/* An ordinary record type in which ___XVL-convention fields and
8078 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8079 static approximations, containing all possible fields. Uses
8080 no runtime values. Useless for use in values, but that's OK,
8081 since the results are used only for type determinations. Works on both
8082 structs and unions. Representation note: to save space, we memorize
27710edb 8083 the result of this function in the type::target_type of the
4c4b4cd2
PH
8084 template type. */
8085
8086static struct type *
8087template_to_static_fixed_type (struct type *type0)
14f9c5c9
AS
8088{
8089 struct type *type;
8090 int nfields;
8091 int f;
8092
9e195661 8093 /* No need no do anything if the input type is already fixed. */
22c4c60c 8094 if (type0->is_fixed_instance ())
9e195661
PMR
8095 return type0;
8096
8097 /* Likewise if we already have computed the static approximation. */
27710edb
SM
8098 if (type0->target_type () != NULL)
8099 return type0->target_type ();
4c4b4cd2 8100
9e195661 8101 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
4c4b4cd2 8102 type = type0;
1f704f76 8103 nfields = type0->num_fields ();
9e195661
PMR
8104
8105 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8106 recompute all over next time. */
8a50fdce 8107 type0->set_target_type (type);
14f9c5c9
AS
8108
8109 for (f = 0; f < nfields; f += 1)
8110 {
940da03e 8111 struct type *field_type = type0->field (f).type ();
4c4b4cd2 8112 struct type *new_type;
14f9c5c9 8113
4c4b4cd2 8114 if (is_dynamic_field (type0, f))
460efde1
JB
8115 {
8116 field_type = ada_check_typedef (field_type);
27710edb 8117 new_type = to_static_fixed_type (field_type->target_type ());
460efde1 8118 }
14f9c5c9 8119 else
dda83cd7 8120 new_type = static_unwrap_type (field_type);
9e195661
PMR
8121
8122 if (new_type != field_type)
8123 {
8124 /* Clone TYPE0 only the first time we get a new field type. */
8125 if (type == type0)
8126 {
9fa83a7a 8127 type = type_allocator (type0).new_type ();
8a50fdce 8128 type0->set_target_type (type);
78134374 8129 type->set_code (type0->code ());
8ecb59f8 8130 INIT_NONE_SPECIFIC (type);
5e33d5f4 8131 type->set_num_fields (nfields);
3cabb6b0
SM
8132
8133 field *fields =
8134 ((struct field *)
8135 TYPE_ALLOC (type, nfields * sizeof (struct field)));
80fc5e77 8136 memcpy (fields, type0->fields (),
9e195661 8137 sizeof (struct field) * nfields);
3cabb6b0
SM
8138 type->set_fields (fields);
8139
d0e39ea2 8140 type->set_name (ada_type_name (type0));
9cdd0d12 8141 type->set_is_fixed_instance (true);
b6cdbc9a 8142 type->set_length (0);
9e195661 8143 }
5d14b6e5 8144 type->field (f).set_type (new_type);
33d16dd9 8145 type->field (f).set_name (type0->field (f).name ());
9e195661 8146 }
14f9c5c9 8147 }
9e195661 8148
14f9c5c9
AS
8149 return type;
8150}
8151
4c4b4cd2 8152/* Given an object of type TYPE whose contents are at VALADDR and
5823c3ef
JB
8153 whose address in memory is ADDRESS, returns a revision of TYPE,
8154 which should be a non-dynamic-sized record, in which the variant
8155 part, if any, is replaced with the appropriate branch. Looks
4c4b4cd2
PH
8156 for discriminant values in DVAL0, which can be NULL if the record
8157 contains the necessary discriminant values. */
8158
d2e4a39e 8159static struct type *
fc1a4b47 8160to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
dda83cd7 8161 CORE_ADDR address, struct value *dval0)
14f9c5c9 8162{
4c4b4cd2 8163 struct value *dval;
d2e4a39e 8164 struct type *rtype;
14f9c5c9 8165 struct type *branch_type;
1f704f76 8166 int nfields = type->num_fields ();
4c4b4cd2 8167 int variant_field = variant_field_index (type);
14f9c5c9 8168
4c4b4cd2 8169 if (variant_field == -1)
14f9c5c9
AS
8170 return type;
8171
65558ca5 8172 scoped_value_mark mark;
4c4b4cd2 8173 if (dval0 == NULL)
9f1f738a
SA
8174 {
8175 dval = value_from_contents_and_address (type, valaddr, address);
d0c97917 8176 type = dval->type ();
9f1f738a 8177 }
4c4b4cd2
PH
8178 else
8179 dval = dval0;
8180
9fa83a7a 8181 rtype = type_allocator (type).new_type ();
67607e24 8182 rtype->set_code (TYPE_CODE_STRUCT);
8ecb59f8 8183 INIT_NONE_SPECIFIC (rtype);
5e33d5f4 8184 rtype->set_num_fields (nfields);
3cabb6b0
SM
8185
8186 field *fields =
d2e4a39e 8187 (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
80fc5e77 8188 memcpy (fields, type->fields (), sizeof (struct field) * nfields);
3cabb6b0
SM
8189 rtype->set_fields (fields);
8190
d0e39ea2 8191 rtype->set_name (ada_type_name (type));
9cdd0d12 8192 rtype->set_is_fixed_instance (true);
df86565b 8193 rtype->set_length (type->length ());
14f9c5c9 8194
4c4b4cd2 8195 branch_type = to_fixed_variant_branch_type
940da03e 8196 (type->field (variant_field).type (),
d2e4a39e 8197 cond_offset_host (valaddr,
b610c045 8198 type->field (variant_field).loc_bitpos ()
dda83cd7 8199 / TARGET_CHAR_BIT),
d2e4a39e 8200 cond_offset_target (address,
b610c045 8201 type->field (variant_field).loc_bitpos ()
dda83cd7 8202 / TARGET_CHAR_BIT), dval);
d2e4a39e 8203 if (branch_type == NULL)
14f9c5c9 8204 {
4c4b4cd2 8205 int f;
5b4ee69b 8206
4c4b4cd2 8207 for (f = variant_field + 1; f < nfields; f += 1)
dda83cd7 8208 rtype->field (f - 1) = rtype->field (f);
5e33d5f4 8209 rtype->set_num_fields (rtype->num_fields () - 1);
14f9c5c9
AS
8210 }
8211 else
8212 {
5d14b6e5 8213 rtype->field (variant_field).set_type (branch_type);
d3fd12df 8214 rtype->field (variant_field).set_name ("S");
4c4b4cd2 8215 TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
df86565b 8216 rtype->set_length (rtype->length () + branch_type->length ());
14f9c5c9 8217 }
b6cdbc9a 8218
df86565b
SM
8219 rtype->set_length (rtype->length ()
8220 - type->field (variant_field).type ()->length ());
d2e4a39e 8221
14f9c5c9
AS
8222 return rtype;
8223}
8224
8225/* An ordinary record type (with fixed-length fields) that describes
8226 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8227 beginning of this section]. Any necessary discriminants' values
4c4b4cd2
PH
8228 should be in DVAL, a record value; it may be NULL if the object
8229 at ADDR itself contains any necessary discriminant values.
8230 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8231 values from the record are needed. Except in the case that DVAL,
8232 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8233 unchecked) is replaced by a particular branch of the variant.
8234
8235 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8236 is questionable and may be removed. It can arise during the
8237 processing of an unconstrained-array-of-record type where all the
8238 variant branches have exactly the same size. This is because in
8239 such cases, the compiler does not bother to use the XVS convention
8240 when encoding the record. I am currently dubious of this
8241 shortcut and suspect the compiler should be altered. FIXME. */
14f9c5c9 8242
d2e4a39e 8243static struct type *
fc1a4b47 8244to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
dda83cd7 8245 CORE_ADDR address, struct value *dval)
14f9c5c9 8246{
d2e4a39e 8247 struct type *templ_type;
14f9c5c9 8248
22c4c60c 8249 if (type0->is_fixed_instance ())
4c4b4cd2
PH
8250 return type0;
8251
d2e4a39e 8252 templ_type = dynamic_template_type (type0);
14f9c5c9
AS
8253
8254 if (templ_type != NULL)
8255 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
4c4b4cd2
PH
8256 else if (variant_field_index (type0) >= 0)
8257 {
8258 if (dval == NULL && valaddr == NULL && address == 0)
dda83cd7 8259 return type0;
4c4b4cd2 8260 return to_record_with_fixed_variant_part (type0, valaddr, address,
dda83cd7 8261 dval);
4c4b4cd2 8262 }
14f9c5c9
AS
8263 else
8264 {
9cdd0d12 8265 type0->set_is_fixed_instance (true);
14f9c5c9
AS
8266 return type0;
8267 }
8268
8269}
8270
8271/* An ordinary record type (with fixed-length fields) that describes
8272 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8273 union type. Any necessary discriminants' values should be in DVAL,
8274 a record value. That is, this routine selects the appropriate
8275 branch of the union at ADDR according to the discriminant value
b1f33ddd 8276 indicated in the union's type name. Returns VAR_TYPE0 itself if
0963b4bd 8277 it represents a variant subject to a pragma Unchecked_Union. */
14f9c5c9 8278
d2e4a39e 8279static struct type *
fc1a4b47 8280to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
dda83cd7 8281 CORE_ADDR address, struct value *dval)
14f9c5c9
AS
8282{
8283 int which;
d2e4a39e
AS
8284 struct type *templ_type;
8285 struct type *var_type;
14f9c5c9 8286
78134374 8287 if (var_type0->code () == TYPE_CODE_PTR)
27710edb 8288 var_type = var_type0->target_type ();
d2e4a39e 8289 else
14f9c5c9
AS
8290 var_type = var_type0;
8291
8292 templ_type = ada_find_parallel_type (var_type, "___XVU");
8293
8294 if (templ_type != NULL)
8295 var_type = templ_type;
8296
d0c97917 8297 if (is_unchecked_variant (var_type, dval->type ()))
b1f33ddd 8298 return var_type0;
d8af9068 8299 which = ada_which_variant_applies (var_type, dval);
14f9c5c9
AS
8300
8301 if (which < 0)
e9bb382b 8302 return empty_record (var_type);
14f9c5c9 8303 else if (is_dynamic_field (var_type, which))
4c4b4cd2 8304 return to_fixed_record_type
27710edb 8305 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
940da03e 8306 else if (variant_field_index (var_type->field (which).type ()) >= 0)
d2e4a39e
AS
8307 return
8308 to_fixed_record_type
940da03e 8309 (var_type->field (which).type (), valaddr, address, dval);
14f9c5c9 8310 else
940da03e 8311 return var_type->field (which).type ();
14f9c5c9
AS
8312}
8313
8908fca5
JB
8314/* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8315 ENCODING_TYPE, a type following the GNAT conventions for discrete
8316 type encodings, only carries redundant information. */
8317
8318static int
8319ada_is_redundant_range_encoding (struct type *range_type,
8320 struct type *encoding_type)
8321{
108d56a4 8322 const char *bounds_str;
8908fca5
JB
8323 int n;
8324 LONGEST lo, hi;
8325
78134374 8326 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8908fca5 8327
78134374
SM
8328 if (get_base_type (range_type)->code ()
8329 != get_base_type (encoding_type)->code ())
005e2509
JB
8330 {
8331 /* The compiler probably used a simple base type to describe
8332 the range type instead of the range's actual base type,
8333 expecting us to get the real base type from the encoding
8334 anyway. In this situation, the encoding cannot be ignored
8335 as redundant. */
8336 return 0;
8337 }
8338
8908fca5
JB
8339 if (is_dynamic_type (range_type))
8340 return 0;
8341
7d93a1e0 8342 if (encoding_type->name () == NULL)
8908fca5
JB
8343 return 0;
8344
7d93a1e0 8345 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8908fca5
JB
8346 if (bounds_str == NULL)
8347 return 0;
8348
8349 n = 8; /* Skip "___XDLU_". */
8350 if (!ada_scan_number (bounds_str, n, &lo, &n))
8351 return 0;
5537ddd0 8352 if (range_type->bounds ()->low.const_val () != lo)
8908fca5
JB
8353 return 0;
8354
8355 n += 2; /* Skip the "__" separator between the two bounds. */
8356 if (!ada_scan_number (bounds_str, n, &hi, &n))
8357 return 0;
5537ddd0 8358 if (range_type->bounds ()->high.const_val () != hi)
8908fca5
JB
8359 return 0;
8360
8361 return 1;
8362}
8363
8364/* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8365 a type following the GNAT encoding for describing array type
8366 indices, only carries redundant information. */
8367
8368static int
8369ada_is_redundant_index_type_desc (struct type *array_type,
8370 struct type *desc_type)
8371{
8372 struct type *this_layer = check_typedef (array_type);
8373 int i;
8374
1f704f76 8375 for (i = 0; i < desc_type->num_fields (); i++)
8908fca5 8376 {
3d967001 8377 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
940da03e 8378 desc_type->field (i).type ()))
8908fca5 8379 return 0;
27710edb 8380 this_layer = check_typedef (this_layer->target_type ());
8908fca5
JB
8381 }
8382
8383 return 1;
8384}
8385
14f9c5c9
AS
8386/* Assuming that TYPE0 is an array type describing the type of a value
8387 at ADDR, and that DVAL describes a record containing any
8388 discriminants used in TYPE0, returns a type for the value that
8389 contains no dynamic components (that is, no components whose sizes
8390 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8391 true, gives an error message if the resulting type's size is over
4c4b4cd2 8392 varsize_limit. */
14f9c5c9 8393
d2e4a39e
AS
8394static struct type *
8395to_fixed_array_type (struct type *type0, struct value *dval,
dda83cd7 8396 int ignore_too_big)
14f9c5c9 8397{
d2e4a39e
AS
8398 struct type *index_type_desc;
8399 struct type *result;
ad82864c 8400 int constrained_packed_array_p;
931e5bc3 8401 static const char *xa_suffix = "___XA";
14f9c5c9 8402
b0dd7688 8403 type0 = ada_check_typedef (type0);
22c4c60c 8404 if (type0->is_fixed_instance ())
4c4b4cd2 8405 return type0;
14f9c5c9 8406
ad82864c
JB
8407 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8408 if (constrained_packed_array_p)
75fd6a26
TT
8409 {
8410 type0 = decode_constrained_packed_array_type (type0);
8411 if (type0 == nullptr)
8412 error (_("could not decode constrained packed array type"));
8413 }
284614f0 8414
931e5bc3
JG
8415 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8416
8417 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8418 encoding suffixed with 'P' may still be generated. If so,
8419 it should be used to find the XA type. */
8420
8421 if (index_type_desc == NULL)
8422 {
1da0522e 8423 const char *type_name = ada_type_name (type0);
931e5bc3 8424
1da0522e 8425 if (type_name != NULL)
931e5bc3 8426 {
1da0522e 8427 const int len = strlen (type_name);
931e5bc3
JG
8428 char *name = (char *) alloca (len + strlen (xa_suffix));
8429
1da0522e 8430 if (type_name[len - 1] == 'P')
931e5bc3 8431 {
1da0522e 8432 strcpy (name, type_name);
931e5bc3
JG
8433 strcpy (name + len - 1, xa_suffix);
8434 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8435 }
8436 }
8437 }
8438
28c85d6c 8439 ada_fixup_array_indexes_type (index_type_desc);
8908fca5
JB
8440 if (index_type_desc != NULL
8441 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8442 {
8443 /* Ignore this ___XA parallel type, as it does not bring any
8444 useful information. This allows us to avoid creating fixed
8445 versions of the array's index types, which would be identical
8446 to the original ones. This, in turn, can also help avoid
8447 the creation of fixed versions of the array itself. */
8448 index_type_desc = NULL;
8449 }
8450
14f9c5c9
AS
8451 if (index_type_desc == NULL)
8452 {
27710edb 8453 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
5b4ee69b 8454
14f9c5c9 8455 /* NOTE: elt_type---the fixed version of elt_type0---should never
dda83cd7
SM
8456 depend on the contents of the array in properly constructed
8457 debugging data. */
529cad9c 8458 /* Create a fixed version of the array element type.
dda83cd7
SM
8459 We're not providing the address of an element here,
8460 and thus the actual object value cannot be inspected to do
8461 the conversion. This should not be a problem, since arrays of
8462 unconstrained objects are not allowed. In particular, all
8463 the elements of an array of a tagged type should all be of
8464 the same type specified in the debugging info. No need to
8465 consult the object tag. */
1ed6ede0 8466 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
14f9c5c9 8467
284614f0
JB
8468 /* Make sure we always create a new array type when dealing with
8469 packed array types, since we're going to fix-up the array
8470 type length and element bitsize a little further down. */
ad82864c 8471 if (elt_type0 == elt_type && !constrained_packed_array_p)
dda83cd7 8472 result = type0;
14f9c5c9 8473 else
9fa83a7a 8474 result = create_array_type (type_allocator (type0).new_type (),
dda83cd7 8475 elt_type, type0->index_type ());
14f9c5c9
AS
8476 }
8477 else
8478 {
8479 int i;
8480 struct type *elt_type0;
8481
8482 elt_type0 = type0;
1f704f76 8483 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
27710edb 8484 elt_type0 = elt_type0->target_type ();
14f9c5c9
AS
8485
8486 /* NOTE: result---the fixed version of elt_type0---should never
dda83cd7
SM
8487 depend on the contents of the array in properly constructed
8488 debugging data. */
529cad9c 8489 /* Create a fixed version of the array element type.
dda83cd7
SM
8490 We're not providing the address of an element here,
8491 and thus the actual object value cannot be inspected to do
8492 the conversion. This should not be a problem, since arrays of
8493 unconstrained objects are not allowed. In particular, all
8494 the elements of an array of a tagged type should all be of
8495 the same type specified in the debugging info. No need to
8496 consult the object tag. */
1ed6ede0 8497 result =
dda83cd7 8498 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
1ce677a4
UW
8499
8500 elt_type0 = type0;
1f704f76 8501 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
dda83cd7
SM
8502 {
8503 struct type *range_type =
8504 to_fixed_range_type (index_type_desc->field (i).type (), dval);
5b4ee69b 8505
9fa83a7a 8506 result = create_array_type (type_allocator (elt_type0).new_type (),
dda83cd7 8507 result, range_type);
27710edb 8508 elt_type0 = elt_type0->target_type ();
dda83cd7 8509 }
14f9c5c9
AS
8510 }
8511
2e6fda7d
JB
8512 /* We want to preserve the type name. This can be useful when
8513 trying to get the type name of a value that has already been
8514 printed (for instance, if the user did "print VAR; whatis $". */
7d93a1e0 8515 result->set_name (type0->name ());
2e6fda7d 8516
ad82864c 8517 if (constrained_packed_array_p)
284614f0
JB
8518 {
8519 /* So far, the resulting type has been created as if the original
8520 type was a regular (non-packed) array type. As a result, the
8521 bitsize of the array elements needs to be set again, and the array
8522 length needs to be recomputed based on that bitsize. */
df86565b 8523 int len = result->length () / result->target_type ()->length ();
284614f0
JB
8524 int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8525
8526 TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
b6cdbc9a 8527 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
df86565b
SM
8528 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8529 result->set_length (result->length () + 1);
284614f0
JB
8530 }
8531
9cdd0d12 8532 result->set_is_fixed_instance (true);
14f9c5c9 8533 return result;
d2e4a39e 8534}
14f9c5c9
AS
8535
8536
8537/* A standard type (containing no dynamically sized components)
8538 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8539 DVAL describes a record containing any discriminants used in TYPE0,
4c4b4cd2 8540 and may be NULL if there are none, or if the object of type TYPE at
529cad9c
PH
8541 ADDRESS or in VALADDR contains these discriminants.
8542
1ed6ede0
JB
8543 If CHECK_TAG is not null, in the case of tagged types, this function
8544 attempts to locate the object's tag and use it to compute the actual
8545 type. However, when ADDRESS is null, we cannot use it to determine the
8546 location of the tag, and therefore compute the tagged type's actual type.
8547 So we return the tagged type without consulting the tag. */
529cad9c 8548
f192137b
JB
8549static struct type *
8550ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
dda83cd7 8551 CORE_ADDR address, struct value *dval, int check_tag)
14f9c5c9 8552{
61ee279c 8553 type = ada_check_typedef (type);
8ecb59f8
TT
8554
8555 /* Only un-fixed types need to be handled here. */
8556 if (!HAVE_GNAT_AUX_INFO (type))
8557 return type;
8558
78134374 8559 switch (type->code ())
d2e4a39e
AS
8560 {
8561 default:
14f9c5c9 8562 return type;
d2e4a39e 8563 case TYPE_CODE_STRUCT:
4c4b4cd2 8564 {
dda83cd7
SM
8565 struct type *static_type = to_static_fixed_type (type);
8566 struct type *fixed_record_type =
8567 to_fixed_record_type (type, valaddr, address, NULL);
8568
8569 /* If STATIC_TYPE is a tagged type and we know the object's address,
8570 then we can determine its tag, and compute the object's actual
8571 type from there. Note that we have to use the fixed record
8572 type (the parent part of the record may have dynamic fields
8573 and the way the location of _tag is expressed may depend on
8574 them). */
8575
8576 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8577 {
b50d69b5
JG
8578 struct value *tag =
8579 value_tag_from_contents_and_address
8580 (fixed_record_type,
8581 valaddr,
8582 address);
8583 struct type *real_type = type_from_tag (tag);
8584 struct value *obj =
8585 value_from_contents_and_address (fixed_record_type,
8586 valaddr,
8587 address);
d0c97917 8588 fixed_record_type = obj->type ();
dda83cd7
SM
8589 if (real_type != NULL)
8590 return to_fixed_record_type
b50d69b5 8591 (real_type, NULL,
9feb2d07 8592 ada_tag_value_at_base_address (obj)->address (), NULL);
dda83cd7
SM
8593 }
8594
8595 /* Check to see if there is a parallel ___XVZ variable.
8596 If there is, then it provides the actual size of our type. */
8597 else if (ada_type_name (fixed_record_type) != NULL)
8598 {
8599 const char *name = ada_type_name (fixed_record_type);
8600 char *xvz_name
224c3ddb 8601 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
eccab96d 8602 bool xvz_found = false;
dda83cd7 8603 LONGEST size;
4af88198 8604
dda83cd7 8605 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
a70b8144 8606 try
eccab96d
JB
8607 {
8608 xvz_found = get_int_var_value (xvz_name, size);
8609 }
230d2906 8610 catch (const gdb_exception_error &except)
eccab96d
JB
8611 {
8612 /* We found the variable, but somehow failed to read
8613 its value. Rethrow the same error, but with a little
8614 bit more information, to help the user understand
8615 what went wrong (Eg: the variable might have been
8616 optimized out). */
8617 throw_error (except.error,
8618 _("unable to read value of %s (%s)"),
3d6e9d23 8619 xvz_name, except.what ());
eccab96d 8620 }
eccab96d 8621
df86565b 8622 if (xvz_found && fixed_record_type->length () != size)
dda83cd7
SM
8623 {
8624 fixed_record_type = copy_type (fixed_record_type);
b6cdbc9a 8625 fixed_record_type->set_length (size);
dda83cd7
SM
8626
8627 /* The FIXED_RECORD_TYPE may have be a stub. We have
8628 observed this when the debugging info is STABS, and
8629 apparently it is something that is hard to fix.
8630
8631 In practice, we don't need the actual type definition
8632 at all, because the presence of the XVZ variable allows us
8633 to assume that there must be a XVS type as well, which we
8634 should be able to use later, when we need the actual type
8635 definition.
8636
8637 In the meantime, pretend that the "fixed" type we are
8638 returning is NOT a stub, because this can cause trouble
8639 when using this type to create new types targeting it.
8640 Indeed, the associated creation routines often check
8641 whether the target type is a stub and will try to replace
8642 it, thus using a type with the wrong size. This, in turn,
8643 might cause the new type to have the wrong size too.
8644 Consider the case of an array, for instance, where the size
8645 of the array is computed from the number of elements in
8646 our array multiplied by the size of its element. */
b4b73759 8647 fixed_record_type->set_is_stub (false);
dda83cd7
SM
8648 }
8649 }
8650 return fixed_record_type;
4c4b4cd2 8651 }
d2e4a39e 8652 case TYPE_CODE_ARRAY:
4c4b4cd2 8653 return to_fixed_array_type (type, dval, 1);
d2e4a39e
AS
8654 case TYPE_CODE_UNION:
8655 if (dval == NULL)
dda83cd7 8656 return type;
d2e4a39e 8657 else
dda83cd7 8658 return to_fixed_variant_branch_type (type, valaddr, address, dval);
d2e4a39e 8659 }
14f9c5c9
AS
8660}
8661
f192137b
JB
8662/* The same as ada_to_fixed_type_1, except that it preserves the type
8663 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
96dbd2c1
JB
8664
8665 The typedef layer needs be preserved in order to differentiate between
8666 arrays and array pointers when both types are implemented using the same
8667 fat pointer. In the array pointer case, the pointer is encoded as
8668 a typedef of the pointer type. For instance, considering:
8669
8670 type String_Access is access String;
8671 S1 : String_Access := null;
8672
8673 To the debugger, S1 is defined as a typedef of type String. But
8674 to the user, it is a pointer. So if the user tries to print S1,
8675 we should not dereference the array, but print the array address
8676 instead.
8677
8678 If we didn't preserve the typedef layer, we would lose the fact that
8679 the type is to be presented as a pointer (needs de-reference before
8680 being printed). And we would also use the source-level type name. */
f192137b
JB
8681
8682struct type *
8683ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
dda83cd7 8684 CORE_ADDR address, struct value *dval, int check_tag)
f192137b
JB
8685
8686{
8687 struct type *fixed_type =
8688 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8689
96dbd2c1
JB
8690 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8691 then preserve the typedef layer.
8692
8693 Implementation note: We can only check the main-type portion of
8694 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8695 from TYPE now returns a type that has the same instance flags
8696 as TYPE. For instance, if TYPE is a "typedef const", and its
8697 target type is a "struct", then the typedef elimination will return
8698 a "const" version of the target type. See check_typedef for more
8699 details about how the typedef layer elimination is done.
8700
8701 brobecker/2010-11-19: It seems to me that the only case where it is
8702 useful to preserve the typedef layer is when dealing with fat pointers.
8703 Perhaps, we could add a check for that and preserve the typedef layer
85102364 8704 only in that situation. But this seems unnecessary so far, probably
96dbd2c1
JB
8705 because we call check_typedef/ada_check_typedef pretty much everywhere.
8706 */
78134374 8707 if (type->code () == TYPE_CODE_TYPEDEF
720d1a40 8708 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
96dbd2c1 8709 == TYPE_MAIN_TYPE (fixed_type)))
f192137b
JB
8710 return type;
8711
8712 return fixed_type;
8713}
8714
14f9c5c9 8715/* A standard (static-sized) type corresponding as well as possible to
4c4b4cd2 8716 TYPE0, but based on no runtime data. */
14f9c5c9 8717
d2e4a39e
AS
8718static struct type *
8719to_static_fixed_type (struct type *type0)
14f9c5c9 8720{
d2e4a39e 8721 struct type *type;
14f9c5c9
AS
8722
8723 if (type0 == NULL)
8724 return NULL;
8725
22c4c60c 8726 if (type0->is_fixed_instance ())
4c4b4cd2
PH
8727 return type0;
8728
61ee279c 8729 type0 = ada_check_typedef (type0);
d2e4a39e 8730
78134374 8731 switch (type0->code ())
14f9c5c9
AS
8732 {
8733 default:
8734 return type0;
8735 case TYPE_CODE_STRUCT:
8736 type = dynamic_template_type (type0);
d2e4a39e 8737 if (type != NULL)
dda83cd7 8738 return template_to_static_fixed_type (type);
4c4b4cd2 8739 else
dda83cd7 8740 return template_to_static_fixed_type (type0);
14f9c5c9
AS
8741 case TYPE_CODE_UNION:
8742 type = ada_find_parallel_type (type0, "___XVU");
8743 if (type != NULL)
dda83cd7 8744 return template_to_static_fixed_type (type);
4c4b4cd2 8745 else
dda83cd7 8746 return template_to_static_fixed_type (type0);
14f9c5c9
AS
8747 }
8748}
8749
4c4b4cd2
PH
8750/* A static approximation of TYPE with all type wrappers removed. */
8751
d2e4a39e
AS
8752static struct type *
8753static_unwrap_type (struct type *type)
14f9c5c9
AS
8754{
8755 if (ada_is_aligner_type (type))
8756 {
940da03e 8757 struct type *type1 = ada_check_typedef (type)->field (0).type ();
14f9c5c9 8758 if (ada_type_name (type1) == NULL)
d0e39ea2 8759 type1->set_name (ada_type_name (type));
14f9c5c9
AS
8760
8761 return static_unwrap_type (type1);
8762 }
d2e4a39e 8763 else
14f9c5c9 8764 {
d2e4a39e 8765 struct type *raw_real_type = ada_get_base_type (type);
5b4ee69b 8766
d2e4a39e 8767 if (raw_real_type == type)
dda83cd7 8768 return type;
14f9c5c9 8769 else
dda83cd7 8770 return to_static_fixed_type (raw_real_type);
14f9c5c9
AS
8771 }
8772}
8773
8774/* In some cases, incomplete and private types require
4c4b4cd2 8775 cross-references that are not resolved as records (for example,
14f9c5c9
AS
8776 type Foo;
8777 type FooP is access Foo;
8778 V: FooP;
8779 type Foo is array ...;
4c4b4cd2 8780 ). In these cases, since there is no mechanism for producing
14f9c5c9
AS
8781 cross-references to such types, we instead substitute for FooP a
8782 stub enumeration type that is nowhere resolved, and whose tag is
4c4b4cd2 8783 the name of the actual type. Call these types "non-record stubs". */
14f9c5c9
AS
8784
8785/* A type equivalent to TYPE that is not a non-record stub, if one
4c4b4cd2
PH
8786 exists, otherwise TYPE. */
8787
d2e4a39e 8788struct type *
61ee279c 8789ada_check_typedef (struct type *type)
14f9c5c9 8790{
727e3d2e
JB
8791 if (type == NULL)
8792 return NULL;
8793
736ade86
XR
8794 /* If our type is an access to an unconstrained array, which is encoded
8795 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
720d1a40
JB
8796 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8797 what allows us to distinguish between fat pointers that represent
8798 array types, and fat pointers that represent array access types
8799 (in both cases, the compiler implements them as fat pointers). */
736ade86 8800 if (ada_is_access_to_unconstrained_array (type))
720d1a40
JB
8801 return type;
8802
f168693b 8803 type = check_typedef (type);
78134374 8804 if (type == NULL || type->code () != TYPE_CODE_ENUM
e46d3488 8805 || !type->is_stub ()
7d93a1e0 8806 || type->name () == NULL)
14f9c5c9 8807 return type;
d2e4a39e 8808 else
14f9c5c9 8809 {
7d93a1e0 8810 const char *name = type->name ();
d2e4a39e 8811 struct type *type1 = ada_find_any_type (name);
5b4ee69b 8812
05e522ef 8813 if (type1 == NULL)
dda83cd7 8814 return type;
05e522ef
JB
8815
8816 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8817 stubs pointing to arrays, as we don't create symbols for array
3a867c22
JB
8818 types, only for the typedef-to-array types). If that's the case,
8819 strip the typedef layer. */
78134374 8820 if (type1->code () == TYPE_CODE_TYPEDEF)
3a867c22
JB
8821 type1 = ada_check_typedef (type1);
8822
8823 return type1;
14f9c5c9
AS
8824 }
8825}
8826
8827/* A value representing the data at VALADDR/ADDRESS as described by
8828 type TYPE0, but with a standard (static-sized) type that correctly
8829 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8830 type, then return VAL0 [this feature is simply to avoid redundant
4c4b4cd2 8831 creation of struct values]. */
14f9c5c9 8832
4c4b4cd2
PH
8833static struct value *
8834ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
dda83cd7 8835 struct value *val0)
14f9c5c9 8836{
1ed6ede0 8837 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
5b4ee69b 8838
14f9c5c9
AS
8839 if (type == type0 && val0 != NULL)
8840 return val0;
cc0e770c 8841
736355f2 8842 if (val0->lval () != lval_memory)
cc0e770c
JB
8843 {
8844 /* Our value does not live in memory; it could be a convenience
8845 variable, for instance. Create a not_lval value using val0's
8846 contents. */
efaf1ae0 8847 return value_from_contents (type, val0->contents ().data ());
cc0e770c
JB
8848 }
8849
8850 return value_from_contents_and_address (type, 0, address);
4c4b4cd2
PH
8851}
8852
8853/* A value representing VAL, but with a standard (static-sized) type
8854 that correctly describes it. Does not necessarily create a new
8855 value. */
8856
0c3acc09 8857struct value *
4c4b4cd2
PH
8858ada_to_fixed_value (struct value *val)
8859{
c48db5ca 8860 val = unwrap_value (val);
9feb2d07 8861 val = ada_to_fixed_value_create (val->type (), val->address (), val);
c48db5ca 8862 return val;
14f9c5c9 8863}
d2e4a39e 8864\f
14f9c5c9 8865
14f9c5c9
AS
8866/* Attributes */
8867
4c4b4cd2
PH
8868/* Table mapping attribute numbers to names.
8869 NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h. */
14f9c5c9 8870
27087b7f 8871static const char * const attribute_names[] = {
14f9c5c9
AS
8872 "<?>",
8873
d2e4a39e 8874 "first",
14f9c5c9
AS
8875 "last",
8876 "length",
8877 "image",
14f9c5c9
AS
8878 "max",
8879 "min",
4c4b4cd2
PH
8880 "modulus",
8881 "pos",
8882 "size",
8883 "tag",
14f9c5c9 8884 "val",
14f9c5c9
AS
8885 0
8886};
8887
de93309a 8888static const char *
4c4b4cd2 8889ada_attribute_name (enum exp_opcode n)
14f9c5c9 8890{
4c4b4cd2
PH
8891 if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
8892 return attribute_names[n - OP_ATR_FIRST + 1];
14f9c5c9
AS
8893 else
8894 return attribute_names[0];
8895}
8896
4c4b4cd2 8897/* Evaluate the 'POS attribute applied to ARG. */
14f9c5c9 8898
4c4b4cd2
PH
8899static LONGEST
8900pos_atr (struct value *arg)
14f9c5c9 8901{
24209737 8902 struct value *val = coerce_ref (arg);
d0c97917 8903 struct type *type = val->type ();
14f9c5c9 8904
d2e4a39e 8905 if (!discrete_type_p (type))
323e0a4a 8906 error (_("'POS only defined on discrete types"));
14f9c5c9 8907
6244c119
SM
8908 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8909 if (!result.has_value ())
aa715135 8910 error (_("enumeration value is invalid: can't find 'POS"));
14f9c5c9 8911
6244c119 8912 return *result;
4c4b4cd2
PH
8913}
8914
7631cf6c 8915struct value *
7992accc
TT
8916ada_pos_atr (struct type *expect_type,
8917 struct expression *exp,
8918 enum noside noside, enum exp_opcode op,
8919 struct value *arg)
4c4b4cd2 8920{
7992accc
TT
8921 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8922 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 8923 return value::zero (type, not_lval);
3cb382c9 8924 return value_from_longest (type, pos_atr (arg));
14f9c5c9
AS
8925}
8926
4c4b4cd2 8927/* Evaluate the TYPE'VAL attribute applied to ARG. */
14f9c5c9 8928
d2e4a39e 8929static struct value *
53a47a3e 8930val_atr (struct type *type, LONGEST val)
14f9c5c9 8931{
53a47a3e 8932 gdb_assert (discrete_type_p (type));
0bc2354b 8933 if (type->code () == TYPE_CODE_RANGE)
27710edb 8934 type = type->target_type ();
78134374 8935 if (type->code () == TYPE_CODE_ENUM)
14f9c5c9 8936 {
53a47a3e 8937 if (val < 0 || val >= type->num_fields ())
dda83cd7 8938 error (_("argument to 'VAL out of range"));
970db518 8939 val = type->field (val).loc_enumval ();
14f9c5c9 8940 }
53a47a3e
TT
8941 return value_from_longest (type, val);
8942}
8943
9e99f48f 8944struct value *
3848abd6 8945ada_val_atr (enum noside noside, struct type *type, struct value *arg)
53a47a3e 8946{
3848abd6 8947 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 8948 return value::zero (type, not_lval);
3848abd6 8949
53a47a3e
TT
8950 if (!discrete_type_p (type))
8951 error (_("'VAL only defined on discrete types"));
d0c97917 8952 if (!integer_type_p (arg->type ()))
53a47a3e
TT
8953 error (_("'VAL requires integral argument"));
8954
8955 return val_atr (type, value_as_long (arg));
14f9c5c9 8956}
14f9c5c9 8957\f
d2e4a39e 8958
dda83cd7 8959 /* Evaluation */
14f9c5c9 8960
4c4b4cd2
PH
8961/* True if TYPE appears to be an Ada character type.
8962 [At the moment, this is true only for Character and Wide_Character;
8963 It is a heuristic test that could stand improvement]. */
14f9c5c9 8964
fc913e53 8965bool
d2e4a39e 8966ada_is_character_type (struct type *type)
14f9c5c9 8967{
7b9f71f2
JB
8968 const char *name;
8969
8970 /* If the type code says it's a character, then assume it really is,
8971 and don't check any further. */
78134374 8972 if (type->code () == TYPE_CODE_CHAR)
fc913e53 8973 return true;
7b9f71f2
JB
8974
8975 /* Otherwise, assume it's a character type iff it is a discrete type
8976 with a known character type name. */
8977 name = ada_type_name (type);
8978 return (name != NULL
dda83cd7
SM
8979 && (type->code () == TYPE_CODE_INT
8980 || type->code () == TYPE_CODE_RANGE)
8981 && (strcmp (name, "character") == 0
8982 || strcmp (name, "wide_character") == 0
8983 || strcmp (name, "wide_wide_character") == 0
8984 || strcmp (name, "unsigned char") == 0));
14f9c5c9
AS
8985}
8986
4c4b4cd2 8987/* True if TYPE appears to be an Ada string type. */
14f9c5c9 8988
fc913e53 8989bool
ebf56fd3 8990ada_is_string_type (struct type *type)
14f9c5c9 8991{
61ee279c 8992 type = ada_check_typedef (type);
d2e4a39e 8993 if (type != NULL
78134374 8994 && type->code () != TYPE_CODE_PTR
76a01679 8995 && (ada_is_simple_array_type (type)
dda83cd7 8996 || ada_is_array_descriptor_type (type))
14f9c5c9
AS
8997 && ada_array_arity (type) == 1)
8998 {
8999 struct type *elttype = ada_array_element_type (type, 1);
9000
9001 return ada_is_character_type (elttype);
9002 }
d2e4a39e 9003 else
fc913e53 9004 return false;
14f9c5c9
AS
9005}
9006
5bf03f13
JB
9007/* The compiler sometimes provides a parallel XVS type for a given
9008 PAD type. Normally, it is safe to follow the PAD type directly,
9009 but older versions of the compiler have a bug that causes the offset
9010 of its "F" field to be wrong. Following that field in that case
9011 would lead to incorrect results, but this can be worked around
9012 by ignoring the PAD type and using the associated XVS type instead.
9013
9014 Set to True if the debugger should trust the contents of PAD types.
9015 Otherwise, ignore the PAD type if there is a parallel XVS type. */
491144b5 9016static bool trust_pad_over_xvs = true;
14f9c5c9
AS
9017
9018/* True if TYPE is a struct type introduced by the compiler to force the
9019 alignment of a value. Such types have a single field with a
4c4b4cd2 9020 distinctive name. */
14f9c5c9
AS
9021
9022int
ebf56fd3 9023ada_is_aligner_type (struct type *type)
14f9c5c9 9024{
61ee279c 9025 type = ada_check_typedef (type);
714e53ab 9026
5bf03f13 9027 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
714e53ab
PH
9028 return 0;
9029
78134374 9030 return (type->code () == TYPE_CODE_STRUCT
dda83cd7 9031 && type->num_fields () == 1
33d16dd9 9032 && strcmp (type->field (0).name (), "F") == 0);
14f9c5c9
AS
9033}
9034
9035/* If there is an ___XVS-convention type parallel to SUBTYPE, return
4c4b4cd2 9036 the parallel type. */
14f9c5c9 9037
d2e4a39e
AS
9038struct type *
9039ada_get_base_type (struct type *raw_type)
14f9c5c9 9040{
d2e4a39e
AS
9041 struct type *real_type_namer;
9042 struct type *raw_real_type;
14f9c5c9 9043
78134374 9044 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
14f9c5c9
AS
9045 return raw_type;
9046
284614f0
JB
9047 if (ada_is_aligner_type (raw_type))
9048 /* The encoding specifies that we should always use the aligner type.
9049 So, even if this aligner type has an associated XVS type, we should
9050 simply ignore it.
9051
9052 According to the compiler gurus, an XVS type parallel to an aligner
9053 type may exist because of a stabs limitation. In stabs, aligner
9054 types are empty because the field has a variable-sized type, and
9055 thus cannot actually be used as an aligner type. As a result,
9056 we need the associated parallel XVS type to decode the type.
9057 Since the policy in the compiler is to not change the internal
9058 representation based on the debugging info format, we sometimes
9059 end up having a redundant XVS type parallel to the aligner type. */
9060 return raw_type;
9061
14f9c5c9 9062 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
d2e4a39e 9063 if (real_type_namer == NULL
78134374 9064 || real_type_namer->code () != TYPE_CODE_STRUCT
1f704f76 9065 || real_type_namer->num_fields () != 1)
14f9c5c9
AS
9066 return raw_type;
9067
940da03e 9068 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
f80d3ff2
JB
9069 {
9070 /* This is an older encoding form where the base type needs to be
85102364 9071 looked up by name. We prefer the newer encoding because it is
f80d3ff2 9072 more efficient. */
33d16dd9 9073 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
f80d3ff2
JB
9074 if (raw_real_type == NULL)
9075 return raw_type;
9076 else
9077 return raw_real_type;
9078 }
9079
9080 /* The field in our XVS type is a reference to the base type. */
27710edb 9081 return real_type_namer->field (0).type ()->target_type ();
d2e4a39e 9082}
14f9c5c9 9083
4c4b4cd2 9084/* The type of value designated by TYPE, with all aligners removed. */
14f9c5c9 9085
d2e4a39e
AS
9086struct type *
9087ada_aligned_type (struct type *type)
14f9c5c9
AS
9088{
9089 if (ada_is_aligner_type (type))
940da03e 9090 return ada_aligned_type (type->field (0).type ());
14f9c5c9
AS
9091 else
9092 return ada_get_base_type (type);
9093}
9094
9095
9096/* The address of the aligned value in an object at address VALADDR
4c4b4cd2 9097 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
14f9c5c9 9098
fc1a4b47
AC
9099const gdb_byte *
9100ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
14f9c5c9 9101{
d2e4a39e 9102 if (ada_is_aligner_type (type))
b610c045
SM
9103 return ada_aligned_value_addr
9104 (type->field (0).type (),
9105 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
14f9c5c9
AS
9106 else
9107 return valaddr;
9108}
9109
4c4b4cd2
PH
9110
9111
14f9c5c9 9112/* The printed representation of an enumeration literal with encoded
4c4b4cd2 9113 name NAME. The value is good to the next call of ada_enum_name. */
d2e4a39e
AS
9114const char *
9115ada_enum_name (const char *name)
14f9c5c9 9116{
5f9febe0 9117 static std::string storage;
e6a959d6 9118 const char *tmp;
14f9c5c9 9119
4c4b4cd2
PH
9120 /* First, unqualify the enumeration name:
9121 1. Search for the last '.' character. If we find one, then skip
177b42fe 9122 all the preceding characters, the unqualified name starts
76a01679 9123 right after that dot.
4c4b4cd2 9124 2. Otherwise, we may be debugging on a target where the compiler
76a01679
JB
9125 translates dots into "__". Search forward for double underscores,
9126 but stop searching when we hit an overloading suffix, which is
9127 of the form "__" followed by digits. */
4c4b4cd2 9128
c3e5cd34
PH
9129 tmp = strrchr (name, '.');
9130 if (tmp != NULL)
4c4b4cd2
PH
9131 name = tmp + 1;
9132 else
14f9c5c9 9133 {
4c4b4cd2 9134 while ((tmp = strstr (name, "__")) != NULL)
dda83cd7
SM
9135 {
9136 if (isdigit (tmp[2]))
9137 break;
9138 else
9139 name = tmp + 2;
9140 }
14f9c5c9
AS
9141 }
9142
9143 if (name[0] == 'Q')
9144 {
14f9c5c9 9145 int v;
5b4ee69b 9146
14f9c5c9 9147 if (name[1] == 'U' || name[1] == 'W')
dda83cd7 9148 {
a7041de8
TT
9149 int offset = 2;
9150 if (name[1] == 'W' && name[2] == 'W')
9151 {
9152 /* Also handle the QWW case. */
9153 ++offset;
9154 }
9155 if (sscanf (name + offset, "%x", &v) != 1)
dda83cd7
SM
9156 return name;
9157 }
272560b5
TT
9158 else if (((name[1] >= '0' && name[1] <= '9')
9159 || (name[1] >= 'a' && name[1] <= 'z'))
9160 && name[2] == '\0')
9161 {
5f9febe0
TT
9162 storage = string_printf ("'%c'", name[1]);
9163 return storage.c_str ();
272560b5 9164 }
14f9c5c9 9165 else
dda83cd7 9166 return name;
14f9c5c9
AS
9167
9168 if (isascii (v) && isprint (v))
5f9febe0 9169 storage = string_printf ("'%c'", v);
14f9c5c9 9170 else if (name[1] == 'U')
a7041de8
TT
9171 storage = string_printf ("'[\"%02x\"]'", v);
9172 else if (name[2] != 'W')
9173 storage = string_printf ("'[\"%04x\"]'", v);
14f9c5c9 9174 else
a7041de8 9175 storage = string_printf ("'[\"%06x\"]'", v);
14f9c5c9 9176
5f9febe0 9177 return storage.c_str ();
14f9c5c9 9178 }
d2e4a39e 9179 else
4c4b4cd2 9180 {
c3e5cd34
PH
9181 tmp = strstr (name, "__");
9182 if (tmp == NULL)
9183 tmp = strstr (name, "$");
9184 if (tmp != NULL)
dda83cd7 9185 {
5f9febe0
TT
9186 storage = std::string (name, tmp - name);
9187 return storage.c_str ();
dda83cd7 9188 }
4c4b4cd2
PH
9189
9190 return name;
9191 }
14f9c5c9
AS
9192}
9193
013a623f
TT
9194/* If TYPE is a dynamic type, return the base type. Otherwise, if
9195 there is no parallel type, return nullptr. */
9196
9197static struct type *
9198find_base_type (struct type *type)
9199{
9200 struct type *raw_real_type
9201 = ada_check_typedef (ada_get_base_type (type));
9202
9203 /* No parallel XVS or XVE type. */
9204 if (type == raw_real_type
9205 && ada_find_parallel_type (type, "___XVE") == nullptr)
9206 return nullptr;
9207
9208 return raw_real_type;
9209}
9210
14f9c5c9 9211/* If VAL is wrapped in an aligner or subtype wrapper, return the
4c4b4cd2 9212 value it wraps. */
14f9c5c9 9213
d2e4a39e
AS
9214static struct value *
9215unwrap_value (struct value *val)
14f9c5c9 9216{
d0c97917 9217 struct type *type = ada_check_typedef (val->type ());
5b4ee69b 9218
14f9c5c9
AS
9219 if (ada_is_aligner_type (type))
9220 {
de4d072f 9221 struct value *v = ada_value_struct_elt (val, "F", 0);
d0c97917 9222 struct type *val_type = ada_check_typedef (v->type ());
5b4ee69b 9223
14f9c5c9 9224 if (ada_type_name (val_type) == NULL)
d0e39ea2 9225 val_type->set_name (ada_type_name (type));
14f9c5c9
AS
9226
9227 return unwrap_value (v);
9228 }
d2e4a39e 9229 else
14f9c5c9 9230 {
013a623f
TT
9231 struct type *raw_real_type = find_base_type (type);
9232 if (raw_real_type == nullptr)
5bf03f13 9233 return val;
14f9c5c9 9234
d2e4a39e 9235 return
dda83cd7
SM
9236 coerce_unspec_val_to_type
9237 (val, ada_to_fixed_type (raw_real_type, 0,
9feb2d07 9238 val->address (),
dda83cd7 9239 NULL, 1));
14f9c5c9
AS
9240 }
9241}
d2e4a39e 9242
d99dcf51
JB
9243/* Given two array types T1 and T2, return nonzero iff both arrays
9244 contain the same number of elements. */
9245
9246static int
9247ada_same_array_size_p (struct type *t1, struct type *t2)
9248{
9249 LONGEST lo1, hi1, lo2, hi2;
9250
9251 /* Get the array bounds in order to verify that the size of
9252 the two arrays match. */
9253 if (!get_array_bounds (t1, &lo1, &hi1)
9254 || !get_array_bounds (t2, &lo2, &hi2))
9255 error (_("unable to determine array bounds"));
9256
9257 /* To make things easier for size comparison, normalize a bit
9258 the case of empty arrays by making sure that the difference
9259 between upper bound and lower bound is always -1. */
9260 if (lo1 > hi1)
9261 hi1 = lo1 - 1;
9262 if (lo2 > hi2)
9263 hi2 = lo2 - 1;
9264
9265 return (hi1 - lo1 == hi2 - lo2);
9266}
9267
9268/* Assuming that VAL is an array of integrals, and TYPE represents
9269 an array with the same number of elements, but with wider integral
9270 elements, return an array "casted" to TYPE. In practice, this
9271 means that the returned array is built by casting each element
9272 of the original array into TYPE's (wider) element type. */
9273
9274static struct value *
9275ada_promote_array_of_integrals (struct type *type, struct value *val)
9276{
27710edb 9277 struct type *elt_type = type->target_type ();
d99dcf51 9278 LONGEST lo, hi;
d99dcf51
JB
9279 LONGEST i;
9280
9281 /* Verify that both val and type are arrays of scalars, and
9282 that the size of val's elements is smaller than the size
9283 of type's element. */
78134374 9284 gdb_assert (type->code () == TYPE_CODE_ARRAY);
27710edb 9285 gdb_assert (is_integral_type (type->target_type ()));
d0c97917
TT
9286 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9287 gdb_assert (is_integral_type (val->type ()->target_type ()));
df86565b 9288 gdb_assert (type->target_type ()->length ()
d0c97917 9289 > val->type ()->target_type ()->length ());
d99dcf51
JB
9290
9291 if (!get_array_bounds (type, &lo, &hi))
9292 error (_("unable to determine array bounds"));
9293
317c3ed9 9294 value *res = value::allocate (type);
bbe912ba 9295 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
d99dcf51
JB
9296
9297 /* Promote each array element. */
9298 for (i = 0; i < hi - lo + 1; i++)
9299 {
9300 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
df86565b 9301 int elt_len = elt_type->length ();
d99dcf51 9302
efaf1ae0 9303 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
d99dcf51
JB
9304 }
9305
9306 return res;
9307}
9308
4c4b4cd2
PH
9309/* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9310 return the converted value. */
9311
d2e4a39e
AS
9312static struct value *
9313coerce_for_assign (struct type *type, struct value *val)
14f9c5c9 9314{
d0c97917 9315 struct type *type2 = val->type ();
5b4ee69b 9316
14f9c5c9
AS
9317 if (type == type2)
9318 return val;
9319
61ee279c
PH
9320 type2 = ada_check_typedef (type2);
9321 type = ada_check_typedef (type);
14f9c5c9 9322
78134374
SM
9323 if (type2->code () == TYPE_CODE_PTR
9324 && type->code () == TYPE_CODE_ARRAY)
14f9c5c9
AS
9325 {
9326 val = ada_value_ind (val);
d0c97917 9327 type2 = val->type ();
14f9c5c9
AS
9328 }
9329
78134374
SM
9330 if (type2->code () == TYPE_CODE_ARRAY
9331 && type->code () == TYPE_CODE_ARRAY)
14f9c5c9 9332 {
d99dcf51
JB
9333 if (!ada_same_array_size_p (type, type2))
9334 error (_("cannot assign arrays of different length"));
9335
27710edb
SM
9336 if (is_integral_type (type->target_type ())
9337 && is_integral_type (type2->target_type ())
df86565b 9338 && type2->target_type ()->length () < type->target_type ()->length ())
d99dcf51
JB
9339 {
9340 /* Allow implicit promotion of the array elements to
9341 a wider type. */
9342 return ada_promote_array_of_integrals (type, val);
9343 }
9344
df86565b 9345 if (type2->target_type ()->length () != type->target_type ()->length ())
dda83cd7 9346 error (_("Incompatible types in assignment"));
81ae560c 9347 val->deprecated_set_type (type);
14f9c5c9 9348 }
d2e4a39e 9349 return val;
14f9c5c9
AS
9350}
9351
4c4b4cd2
PH
9352static struct value *
9353ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9354{
9355 struct value *val;
9356 struct type *type1, *type2;
9357 LONGEST v, v1, v2;
9358
994b9211
AC
9359 arg1 = coerce_ref (arg1);
9360 arg2 = coerce_ref (arg2);
d0c97917
TT
9361 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9362 type2 = get_base_type (ada_check_typedef (arg2->type ()));
4c4b4cd2 9363
78134374
SM
9364 if (type1->code () != TYPE_CODE_INT
9365 || type2->code () != TYPE_CODE_INT)
4c4b4cd2
PH
9366 return value_binop (arg1, arg2, op);
9367
76a01679 9368 switch (op)
4c4b4cd2
PH
9369 {
9370 case BINOP_MOD:
9371 case BINOP_DIV:
9372 case BINOP_REM:
9373 break;
9374 default:
9375 return value_binop (arg1, arg2, op);
9376 }
9377
9378 v2 = value_as_long (arg2);
9379 if (v2 == 0)
b0f9164c
TT
9380 {
9381 const char *name;
9382 if (op == BINOP_MOD)
9383 name = "mod";
9384 else if (op == BINOP_DIV)
9385 name = "/";
9386 else
9387 {
9388 gdb_assert (op == BINOP_REM);
9389 name = "rem";
9390 }
9391
9392 error (_("second operand of %s must not be zero."), name);
9393 }
4c4b4cd2 9394
c6d940a9 9395 if (type1->is_unsigned () || op == BINOP_MOD)
4c4b4cd2
PH
9396 return value_binop (arg1, arg2, op);
9397
9398 v1 = value_as_long (arg1);
9399 switch (op)
9400 {
9401 case BINOP_DIV:
9402 v = v1 / v2;
76a01679 9403 if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
dda83cd7 9404 v += v > 0 ? -1 : 1;
4c4b4cd2
PH
9405 break;
9406 case BINOP_REM:
9407 v = v1 % v2;
76a01679 9408 if (v * v1 < 0)
dda83cd7 9409 v -= v2;
4c4b4cd2
PH
9410 break;
9411 default:
9412 /* Should not reach this point. */
9413 v = 0;
9414 }
9415
317c3ed9 9416 val = value::allocate (type1);
bbe912ba 9417 store_unsigned_integer (val->contents_raw ().data (),
d0c97917 9418 val->type ()->length (),
34877895 9419 type_byte_order (type1), v);
4c4b4cd2
PH
9420 return val;
9421}
9422
9423static int
9424ada_value_equal (struct value *arg1, struct value *arg2)
9425{
d0c97917
TT
9426 if (ada_is_direct_array_type (arg1->type ())
9427 || ada_is_direct_array_type (arg2->type ()))
4c4b4cd2 9428 {
79e8fcaa
JB
9429 struct type *arg1_type, *arg2_type;
9430
f58b38bf 9431 /* Automatically dereference any array reference before
dda83cd7 9432 we attempt to perform the comparison. */
f58b38bf
JB
9433 arg1 = ada_coerce_ref (arg1);
9434 arg2 = ada_coerce_ref (arg2);
79e8fcaa 9435
4c4b4cd2
PH
9436 arg1 = ada_coerce_to_simple_array (arg1);
9437 arg2 = ada_coerce_to_simple_array (arg2);
79e8fcaa 9438
d0c97917
TT
9439 arg1_type = ada_check_typedef (arg1->type ());
9440 arg2_type = ada_check_typedef (arg2->type ());
79e8fcaa 9441
78134374 9442 if (arg1_type->code () != TYPE_CODE_ARRAY
dda83cd7
SM
9443 || arg2_type->code () != TYPE_CODE_ARRAY)
9444 error (_("Attempt to compare array with non-array"));
4c4b4cd2 9445 /* FIXME: The following works only for types whose
dda83cd7
SM
9446 representations use all bits (no padding or undefined bits)
9447 and do not have user-defined equality. */
df86565b 9448 return (arg1_type->length () == arg2_type->length ()
efaf1ae0
TT
9449 && memcmp (arg1->contents ().data (),
9450 arg2->contents ().data (),
df86565b 9451 arg1_type->length ()) == 0);
4c4b4cd2
PH
9452 }
9453 return value_equal (arg1, arg2);
9454}
9455
d3c54a1c
TT
9456namespace expr
9457{
9458
9459bool
9460check_objfile (const std::unique_ptr<ada_component> &comp,
9461 struct objfile *objfile)
9462{
9463 return comp->uses_objfile (objfile);
9464}
9465
9466/* Assign the result of evaluating ARG starting at *POS to the INDEXth
9467 component of LHS (a simple array or a record). Does not modify the
9468 inferior's memory, nor does it modify LHS (unless LHS ==
9469 CONTAINER). */
52ce6436
PH
9470
9471static void
9472assign_component (struct value *container, struct value *lhs, LONGEST index,
d3c54a1c 9473 struct expression *exp, operation_up &arg)
52ce6436 9474{
d3c54a1c
TT
9475 scoped_value_mark mark;
9476
52ce6436 9477 struct value *elt;
d0c97917 9478 struct type *lhs_type = check_typedef (lhs->type ());
5b4ee69b 9479
78134374 9480 if (lhs_type->code () == TYPE_CODE_ARRAY)
52ce6436 9481 {
22601c15
UW
9482 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9483 struct value *index_val = value_from_longest (index_type, index);
5b4ee69b 9484
52ce6436
PH
9485 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9486 }
9487 else
9488 {
d0c97917 9489 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
c48db5ca 9490 elt = ada_to_fixed_value (elt);
52ce6436
PH
9491 }
9492
d3c54a1c
TT
9493 ada_aggregate_operation *ag_op
9494 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9495 if (ag_op != nullptr)
9496 ag_op->assign_aggregate (container, elt, exp);
52ce6436 9497 else
d3c54a1c
TT
9498 value_assign_to_component (container, elt,
9499 arg->evaluate (nullptr, exp,
9500 EVAL_NORMAL));
9501}
52ce6436 9502
d3c54a1c
TT
9503bool
9504ada_aggregate_component::uses_objfile (struct objfile *objfile)
9505{
9506 for (const auto &item : m_components)
9507 if (item->uses_objfile (objfile))
9508 return true;
9509 return false;
9510}
9511
9512void
9513ada_aggregate_component::dump (ui_file *stream, int depth)
9514{
6cb06a8c 9515 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
d3c54a1c
TT
9516 for (const auto &item : m_components)
9517 item->dump (stream, depth + 1);
9518}
9519
9520void
9521ada_aggregate_component::assign (struct value *container,
9522 struct value *lhs, struct expression *exp,
9523 std::vector<LONGEST> &indices,
9524 LONGEST low, LONGEST high)
9525{
9526 for (auto &item : m_components)
9527 item->assign (container, lhs, exp, indices, low, high);
52ce6436
PH
9528}
9529
207582c0 9530/* See ada-exp.h. */
52ce6436 9531
207582c0 9532value *
d3c54a1c
TT
9533ada_aggregate_operation::assign_aggregate (struct value *container,
9534 struct value *lhs,
9535 struct expression *exp)
52ce6436
PH
9536{
9537 struct type *lhs_type;
52ce6436 9538 LONGEST low_index, high_index;
52ce6436
PH
9539
9540 container = ada_coerce_ref (container);
d0c97917 9541 if (ada_is_direct_array_type (container->type ()))
52ce6436
PH
9542 container = ada_coerce_to_simple_array (container);
9543 lhs = ada_coerce_ref (lhs);
4b53ca88 9544 if (!lhs->deprecated_modifiable ())
52ce6436
PH
9545 error (_("Left operand of assignment is not a modifiable lvalue."));
9546
d0c97917 9547 lhs_type = check_typedef (lhs->type ());
52ce6436
PH
9548 if (ada_is_direct_array_type (lhs_type))
9549 {
9550 lhs = ada_coerce_to_simple_array (lhs);
d0c97917 9551 lhs_type = check_typedef (lhs->type ());
cf88be68
SM
9552 low_index = lhs_type->bounds ()->low.const_val ();
9553 high_index = lhs_type->bounds ()->high.const_val ();
52ce6436 9554 }
78134374 9555 else if (lhs_type->code () == TYPE_CODE_STRUCT)
52ce6436
PH
9556 {
9557 low_index = 0;
9558 high_index = num_visible_fields (lhs_type) - 1;
52ce6436
PH
9559 }
9560 else
9561 error (_("Left-hand side must be array or record."));
9562
cf608cc4 9563 std::vector<LONGEST> indices (4);
52ce6436
PH
9564 indices[0] = indices[1] = low_index - 1;
9565 indices[2] = indices[3] = high_index + 1;
52ce6436 9566
d3c54a1c
TT
9567 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9568 low_index, high_index);
207582c0
TT
9569
9570 return container;
d3c54a1c
TT
9571}
9572
9573bool
9574ada_positional_component::uses_objfile (struct objfile *objfile)
9575{
9576 return m_op->uses_objfile (objfile);
9577}
52ce6436 9578
d3c54a1c
TT
9579void
9580ada_positional_component::dump (ui_file *stream, int depth)
9581{
6cb06a8c
TT
9582 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9583 depth, "", m_index);
d3c54a1c 9584 m_op->dump (stream, depth + 1);
52ce6436 9585}
d3c54a1c 9586
52ce6436 9587/* Assign into the component of LHS indexed by the OP_POSITIONAL
d3c54a1c
TT
9588 construct, given that the positions are relative to lower bound
9589 LOW, where HIGH is the upper bound. Record the position in
9590 INDICES. CONTAINER is as for assign_aggregate. */
9591void
9592ada_positional_component::assign (struct value *container,
9593 struct value *lhs, struct expression *exp,
9594 std::vector<LONGEST> &indices,
9595 LONGEST low, LONGEST high)
52ce6436 9596{
d3c54a1c
TT
9597 LONGEST ind = m_index + low;
9598
52ce6436 9599 if (ind - 1 == high)
e1d5a0d2 9600 warning (_("Extra components in aggregate ignored."));
52ce6436
PH
9601 if (ind <= high)
9602 {
cf608cc4 9603 add_component_interval (ind, ind, indices);
d3c54a1c 9604 assign_component (container, lhs, ind, exp, m_op);
52ce6436 9605 }
52ce6436
PH
9606}
9607
d3c54a1c
TT
9608bool
9609ada_discrete_range_association::uses_objfile (struct objfile *objfile)
a88c4354
TT
9610{
9611 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9612}
9613
9614void
9615ada_discrete_range_association::dump (ui_file *stream, int depth)
9616{
6cb06a8c 9617 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
a88c4354
TT
9618 m_low->dump (stream, depth + 1);
9619 m_high->dump (stream, depth + 1);
9620}
9621
9622void
9623ada_discrete_range_association::assign (struct value *container,
9624 struct value *lhs,
9625 struct expression *exp,
9626 std::vector<LONGEST> &indices,
9627 LONGEST low, LONGEST high,
9628 operation_up &op)
9629{
9630 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9631 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9632
9633 if (lower <= upper && (lower < low || upper > high))
9634 error (_("Index in component association out of bounds."));
9635
9636 add_component_interval (lower, upper, indices);
9637 while (lower <= upper)
9638 {
9639 assign_component (container, lhs, lower, exp, op);
9640 lower += 1;
9641 }
9642}
9643
9644bool
9645ada_name_association::uses_objfile (struct objfile *objfile)
9646{
9647 return m_val->uses_objfile (objfile);
9648}
9649
9650void
9651ada_name_association::dump (ui_file *stream, int depth)
9652{
6cb06a8c 9653 gdb_printf (stream, _("%*sName:\n"), depth, "");
a88c4354
TT
9654 m_val->dump (stream, depth + 1);
9655}
9656
9657void
9658ada_name_association::assign (struct value *container,
9659 struct value *lhs,
9660 struct expression *exp,
9661 std::vector<LONGEST> &indices,
9662 LONGEST low, LONGEST high,
9663 operation_up &op)
9664{
9665 int index;
9666
d0c97917 9667 if (ada_is_direct_array_type (lhs->type ()))
a88c4354
TT
9668 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9669 EVAL_NORMAL)));
9670 else
9671 {
9672 ada_string_operation *strop
9673 = dynamic_cast<ada_string_operation *> (m_val.get ());
9674
9675 const char *name;
9676 if (strop != nullptr)
9677 name = strop->get_name ();
9678 else
9679 {
9680 ada_var_value_operation *vvo
9681 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
9682 if (vvo != nullptr)
9683 error (_("Invalid record component association."));
9684 name = vvo->get_symbol ()->natural_name ();
9685 }
9686
9687 index = 0;
d0c97917 9688 if (! find_struct_field (name, lhs->type (), 0,
a88c4354
TT
9689 NULL, NULL, NULL, NULL, &index))
9690 error (_("Unknown component name: %s."), name);
9691 }
9692
9693 add_component_interval (index, index, indices);
9694 assign_component (container, lhs, index, exp, op);
9695}
9696
9697bool
9698ada_choices_component::uses_objfile (struct objfile *objfile)
9699{
9700 if (m_op->uses_objfile (objfile))
9701 return true;
9702 for (const auto &item : m_assocs)
9703 if (item->uses_objfile (objfile))
9704 return true;
9705 return false;
9706}
9707
9708void
9709ada_choices_component::dump (ui_file *stream, int depth)
9710{
6cb06a8c 9711 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
a88c4354
TT
9712 m_op->dump (stream, depth + 1);
9713 for (const auto &item : m_assocs)
9714 item->dump (stream, depth + 1);
9715}
9716
9717/* Assign into the components of LHS indexed by the OP_CHOICES
9718 construct at *POS, updating *POS past the construct, given that
9719 the allowable indices are LOW..HIGH. Record the indices assigned
9720 to in INDICES. CONTAINER is as for assign_aggregate. */
9721void
9722ada_choices_component::assign (struct value *container,
9723 struct value *lhs, struct expression *exp,
9724 std::vector<LONGEST> &indices,
9725 LONGEST low, LONGEST high)
9726{
9727 for (auto &item : m_assocs)
9728 item->assign (container, lhs, exp, indices, low, high, m_op);
9729}
9730
9731bool
9732ada_others_component::uses_objfile (struct objfile *objfile)
9733{
9734 return m_op->uses_objfile (objfile);
9735}
9736
9737void
9738ada_others_component::dump (ui_file *stream, int depth)
9739{
6cb06a8c 9740 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
a88c4354
TT
9741 m_op->dump (stream, depth + 1);
9742}
9743
9744/* Assign the value of the expression in the OP_OTHERS construct in
9745 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9746 have not been previously assigned. The index intervals already assigned
9747 are in INDICES. CONTAINER is as for assign_aggregate. */
9748void
9749ada_others_component::assign (struct value *container,
9750 struct value *lhs, struct expression *exp,
9751 std::vector<LONGEST> &indices,
9752 LONGEST low, LONGEST high)
9753{
9754 int num_indices = indices.size ();
9755 for (int i = 0; i < num_indices - 2; i += 2)
9756 {
9757 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9758 assign_component (container, lhs, ind, exp, m_op);
9759 }
9760}
9761
9762struct value *
9763ada_assign_operation::evaluate (struct type *expect_type,
9764 struct expression *exp,
9765 enum noside noside)
9766{
9767 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
9768
9769 ada_aggregate_operation *ag_op
9770 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9771 if (ag_op != nullptr)
9772 {
9773 if (noside != EVAL_NORMAL)
9774 return arg1;
9775
207582c0 9776 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
a88c4354
TT
9777 return ada_value_assign (arg1, arg1);
9778 }
9779 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9780 except if the lhs of our assignment is a convenience variable.
9781 In the case of assigning to a convenience variable, the lhs
9782 should be exactly the result of the evaluation of the rhs. */
d0c97917 9783 struct type *type = arg1->type ();
736355f2 9784 if (arg1->lval () == lval_internalvar)
a88c4354
TT
9785 type = NULL;
9786 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
0b2b0b82 9787 if (noside == EVAL_AVOID_SIDE_EFFECTS)
a88c4354 9788 return arg1;
736355f2 9789 if (arg1->lval () == lval_internalvar)
a88c4354
TT
9790 {
9791 /* Nothing. */
9792 }
9793 else
d0c97917 9794 arg2 = coerce_for_assign (arg1->type (), arg2);
a88c4354
TT
9795 return ada_value_assign (arg1, arg2);
9796}
9797
9798} /* namespace expr */
9799
cf608cc4
TT
9800/* Add the interval [LOW .. HIGH] to the sorted set of intervals
9801 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9802 overlap. */
52ce6436
PH
9803static void
9804add_component_interval (LONGEST low, LONGEST high,
cf608cc4 9805 std::vector<LONGEST> &indices)
52ce6436
PH
9806{
9807 int i, j;
5b4ee69b 9808
cf608cc4
TT
9809 int size = indices.size ();
9810 for (i = 0; i < size; i += 2) {
52ce6436
PH
9811 if (high >= indices[i] && low <= indices[i + 1])
9812 {
9813 int kh;
5b4ee69b 9814
cf608cc4 9815 for (kh = i + 2; kh < size; kh += 2)
52ce6436
PH
9816 if (high < indices[kh])
9817 break;
9818 if (low < indices[i])
9819 indices[i] = low;
9820 indices[i + 1] = indices[kh - 1];
9821 if (high > indices[i + 1])
9822 indices[i + 1] = high;
cf608cc4
TT
9823 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9824 indices.resize (kh - i - 2);
52ce6436
PH
9825 return;
9826 }
9827 else if (high < indices[i])
9828 break;
9829 }
9830
cf608cc4 9831 indices.resize (indices.size () + 2);
d4813f10 9832 for (j = indices.size () - 1; j >= i + 2; j -= 1)
52ce6436
PH
9833 indices[j] = indices[j - 2];
9834 indices[i] = low;
9835 indices[i + 1] = high;
9836}
9837
6e48bd2c
JB
9838/* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9839 is different. */
9840
9841static struct value *
b7e22850 9842ada_value_cast (struct type *type, struct value *arg2)
6e48bd2c 9843{
d0c97917 9844 if (type == ada_check_typedef (arg2->type ()))
6e48bd2c
JB
9845 return arg2;
9846
6e48bd2c
JB
9847 return value_cast (type, arg2);
9848}
9849
284614f0
JB
9850/* Evaluating Ada expressions, and printing their result.
9851 ------------------------------------------------------
9852
21649b50
JB
9853 1. Introduction:
9854 ----------------
9855
284614f0
JB
9856 We usually evaluate an Ada expression in order to print its value.
9857 We also evaluate an expression in order to print its type, which
9858 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9859 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9860 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9861 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9862 similar.
9863
9864 Evaluating expressions is a little more complicated for Ada entities
9865 than it is for entities in languages such as C. The main reason for
9866 this is that Ada provides types whose definition might be dynamic.
9867 One example of such types is variant records. Or another example
9868 would be an array whose bounds can only be known at run time.
9869
9870 The following description is a general guide as to what should be
9871 done (and what should NOT be done) in order to evaluate an expression
9872 involving such types, and when. This does not cover how the semantic
9873 information is encoded by GNAT as this is covered separatly. For the
9874 document used as the reference for the GNAT encoding, see exp_dbug.ads
9875 in the GNAT sources.
9876
9877 Ideally, we should embed each part of this description next to its
9878 associated code. Unfortunately, the amount of code is so vast right
9879 now that it's hard to see whether the code handling a particular
9880 situation might be duplicated or not. One day, when the code is
9881 cleaned up, this guide might become redundant with the comments
9882 inserted in the code, and we might want to remove it.
9883
21649b50
JB
9884 2. ``Fixing'' an Entity, the Simple Case:
9885 -----------------------------------------
9886
284614f0
JB
9887 When evaluating Ada expressions, the tricky issue is that they may
9888 reference entities whose type contents and size are not statically
9889 known. Consider for instance a variant record:
9890
9891 type Rec (Empty : Boolean := True) is record
dda83cd7
SM
9892 case Empty is
9893 when True => null;
9894 when False => Value : Integer;
9895 end case;
284614f0
JB
9896 end record;
9897 Yes : Rec := (Empty => False, Value => 1);
9898 No : Rec := (empty => True);
9899
9900 The size and contents of that record depends on the value of the
9901 descriminant (Rec.Empty). At this point, neither the debugging
9902 information nor the associated type structure in GDB are able to
9903 express such dynamic types. So what the debugger does is to create
9904 "fixed" versions of the type that applies to the specific object.
30baf67b 9905 We also informally refer to this operation as "fixing" an object,
284614f0
JB
9906 which means creating its associated fixed type.
9907
9908 Example: when printing the value of variable "Yes" above, its fixed
9909 type would look like this:
9910
9911 type Rec is record
dda83cd7
SM
9912 Empty : Boolean;
9913 Value : Integer;
284614f0
JB
9914 end record;
9915
9916 On the other hand, if we printed the value of "No", its fixed type
9917 would become:
9918
9919 type Rec is record
dda83cd7 9920 Empty : Boolean;
284614f0
JB
9921 end record;
9922
9923 Things become a little more complicated when trying to fix an entity
9924 with a dynamic type that directly contains another dynamic type,
9925 such as an array of variant records, for instance. There are
9926 two possible cases: Arrays, and records.
9927
21649b50
JB
9928 3. ``Fixing'' Arrays:
9929 ---------------------
9930
9931 The type structure in GDB describes an array in terms of its bounds,
9932 and the type of its elements. By design, all elements in the array
9933 have the same type and we cannot represent an array of variant elements
9934 using the current type structure in GDB. When fixing an array,
9935 we cannot fix the array element, as we would potentially need one
9936 fixed type per element of the array. As a result, the best we can do
9937 when fixing an array is to produce an array whose bounds and size
9938 are correct (allowing us to read it from memory), but without having
9939 touched its element type. Fixing each element will be done later,
9940 when (if) necessary.
9941
9942 Arrays are a little simpler to handle than records, because the same
9943 amount of memory is allocated for each element of the array, even if
1b536f04 9944 the amount of space actually used by each element differs from element
21649b50 9945 to element. Consider for instance the following array of type Rec:
284614f0
JB
9946
9947 type Rec_Array is array (1 .. 2) of Rec;
9948
1b536f04
JB
9949 The actual amount of memory occupied by each element might be different
9950 from element to element, depending on the value of their discriminant.
21649b50 9951 But the amount of space reserved for each element in the array remains
1b536f04 9952 fixed regardless. So we simply need to compute that size using
21649b50
JB
9953 the debugging information available, from which we can then determine
9954 the array size (we multiply the number of elements of the array by
9955 the size of each element).
9956
9957 The simplest case is when we have an array of a constrained element
9958 type. For instance, consider the following type declarations:
9959
dda83cd7
SM
9960 type Bounded_String (Max_Size : Integer) is
9961 Length : Integer;
9962 Buffer : String (1 .. Max_Size);
9963 end record;
9964 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
21649b50
JB
9965
9966 In this case, the compiler describes the array as an array of
9967 variable-size elements (identified by its XVS suffix) for which
9968 the size can be read in the parallel XVZ variable.
9969
9970 In the case of an array of an unconstrained element type, the compiler
9971 wraps the array element inside a private PAD type. This type should not
9972 be shown to the user, and must be "unwrap"'ed before printing. Note
284614f0
JB
9973 that we also use the adjective "aligner" in our code to designate
9974 these wrapper types.
9975
1b536f04 9976 In some cases, the size allocated for each element is statically
21649b50
JB
9977 known. In that case, the PAD type already has the correct size,
9978 and the array element should remain unfixed.
9979
9980 But there are cases when this size is not statically known.
9981 For instance, assuming that "Five" is an integer variable:
284614f0 9982
dda83cd7
SM
9983 type Dynamic is array (1 .. Five) of Integer;
9984 type Wrapper (Has_Length : Boolean := False) is record
9985 Data : Dynamic;
9986 case Has_Length is
9987 when True => Length : Integer;
9988 when False => null;
9989 end case;
9990 end record;
9991 type Wrapper_Array is array (1 .. 2) of Wrapper;
284614f0 9992
dda83cd7
SM
9993 Hello : Wrapper_Array := (others => (Has_Length => True,
9994 Data => (others => 17),
9995 Length => 1));
284614f0
JB
9996
9997
9998 The debugging info would describe variable Hello as being an
9999 array of a PAD type. The size of that PAD type is not statically
10000 known, but can be determined using a parallel XVZ variable.
10001 In that case, a copy of the PAD type with the correct size should
10002 be used for the fixed array.
10003
21649b50
JB
10004 3. ``Fixing'' record type objects:
10005 ----------------------------------
10006
10007 Things are slightly different from arrays in the case of dynamic
284614f0
JB
10008 record types. In this case, in order to compute the associated
10009 fixed type, we need to determine the size and offset of each of
10010 its components. This, in turn, requires us to compute the fixed
10011 type of each of these components.
10012
10013 Consider for instance the example:
10014
dda83cd7
SM
10015 type Bounded_String (Max_Size : Natural) is record
10016 Str : String (1 .. Max_Size);
10017 Length : Natural;
10018 end record;
10019 My_String : Bounded_String (Max_Size => 10);
284614f0
JB
10020
10021 In that case, the position of field "Length" depends on the size
10022 of field Str, which itself depends on the value of the Max_Size
21649b50 10023 discriminant. In order to fix the type of variable My_String,
284614f0
JB
10024 we need to fix the type of field Str. Therefore, fixing a variant
10025 record requires us to fix each of its components.
10026
10027 However, if a component does not have a dynamic size, the component
10028 should not be fixed. In particular, fields that use a PAD type
10029 should not fixed. Here is an example where this might happen
10030 (assuming type Rec above):
10031
10032 type Container (Big : Boolean) is record
dda83cd7
SM
10033 First : Rec;
10034 After : Integer;
10035 case Big is
10036 when True => Another : Integer;
10037 when False => null;
10038 end case;
284614f0
JB
10039 end record;
10040 My_Container : Container := (Big => False,
dda83cd7
SM
10041 First => (Empty => True),
10042 After => 42);
284614f0
JB
10043
10044 In that example, the compiler creates a PAD type for component First,
10045 whose size is constant, and then positions the component After just
10046 right after it. The offset of component After is therefore constant
10047 in this case.
10048
10049 The debugger computes the position of each field based on an algorithm
10050 that uses, among other things, the actual position and size of the field
21649b50
JB
10051 preceding it. Let's now imagine that the user is trying to print
10052 the value of My_Container. If the type fixing was recursive, we would
284614f0
JB
10053 end up computing the offset of field After based on the size of the
10054 fixed version of field First. And since in our example First has
10055 only one actual field, the size of the fixed type is actually smaller
10056 than the amount of space allocated to that field, and thus we would
10057 compute the wrong offset of field After.
10058
21649b50
JB
10059 To make things more complicated, we need to watch out for dynamic
10060 components of variant records (identified by the ___XVL suffix in
10061 the component name). Even if the target type is a PAD type, the size
10062 of that type might not be statically known. So the PAD type needs
10063 to be unwrapped and the resulting type needs to be fixed. Otherwise,
10064 we might end up with the wrong size for our component. This can be
10065 observed with the following type declarations:
284614f0 10066
dda83cd7
SM
10067 type Octal is new Integer range 0 .. 7;
10068 type Octal_Array is array (Positive range <>) of Octal;
10069 pragma Pack (Octal_Array);
284614f0 10070
dda83cd7
SM
10071 type Octal_Buffer (Size : Positive) is record
10072 Buffer : Octal_Array (1 .. Size);
10073 Length : Integer;
10074 end record;
284614f0
JB
10075
10076 In that case, Buffer is a PAD type whose size is unset and needs
10077 to be computed by fixing the unwrapped type.
10078
21649b50
JB
10079 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10080 ----------------------------------------------------------
10081
10082 Lastly, when should the sub-elements of an entity that remained unfixed
284614f0
JB
10083 thus far, be actually fixed?
10084
10085 The answer is: Only when referencing that element. For instance
10086 when selecting one component of a record, this specific component
10087 should be fixed at that point in time. Or when printing the value
10088 of a record, each component should be fixed before its value gets
10089 printed. Similarly for arrays, the element of the array should be
10090 fixed when printing each element of the array, or when extracting
10091 one element out of that array. On the other hand, fixing should
10092 not be performed on the elements when taking a slice of an array!
10093
31432a67 10094 Note that one of the side effects of miscomputing the offset and
284614f0
JB
10095 size of each field is that we end up also miscomputing the size
10096 of the containing type. This can have adverse results when computing
10097 the value of an entity. GDB fetches the value of an entity based
10098 on the size of its type, and thus a wrong size causes GDB to fetch
10099 the wrong amount of memory. In the case where the computed size is
10100 too small, GDB fetches too little data to print the value of our
31432a67 10101 entity. Results in this case are unpredictable, as we usually read
284614f0
JB
10102 past the buffer containing the data =:-o. */
10103
62d4bd94
TT
10104/* A helper function for TERNOP_IN_RANGE. */
10105
10106static value *
10107eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10108 enum noside noside,
10109 value *arg1, value *arg2, value *arg3)
10110{
62d4bd94
TT
10111 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10112 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10113 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10114 return
10115 value_from_longest (type,
10116 (value_less (arg1, arg3)
10117 || value_equal (arg1, arg3))
10118 && (value_less (arg2, arg1)
10119 || value_equal (arg2, arg1)));
10120}
10121
82390ab8
TT
10122/* A helper function for UNOP_NEG. */
10123
7c15d377 10124value *
82390ab8
TT
10125ada_unop_neg (struct type *expect_type,
10126 struct expression *exp,
10127 enum noside noside, enum exp_opcode op,
10128 struct value *arg1)
10129{
82390ab8
TT
10130 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10131 return value_neg (arg1);
10132}
10133
7efc87ff
TT
10134/* A helper function for UNOP_IN_RANGE. */
10135
95d49dfb 10136value *
7efc87ff
TT
10137ada_unop_in_range (struct type *expect_type,
10138 struct expression *exp,
10139 enum noside noside, enum exp_opcode op,
10140 struct value *arg1, struct type *type)
10141{
7efc87ff
TT
10142 struct value *arg2, *arg3;
10143 switch (type->code ())
10144 {
10145 default:
10146 lim_warning (_("Membership test incompletely implemented; "
10147 "always returns true"));
10148 type = language_bool_type (exp->language_defn, exp->gdbarch);
10149 return value_from_longest (type, (LONGEST) 1);
10150
10151 case TYPE_CODE_RANGE:
10152 arg2 = value_from_longest (type,
10153 type->bounds ()->low.const_val ());
10154 arg3 = value_from_longest (type,
10155 type->bounds ()->high.const_val ());
10156 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10157 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10158 type = language_bool_type (exp->language_defn, exp->gdbarch);
10159 return
10160 value_from_longest (type,
10161 (value_less (arg1, arg3)
10162 || value_equal (arg1, arg3))
10163 && (value_less (arg2, arg1)
10164 || value_equal (arg2, arg1)));
10165 }
10166}
10167
020dbabe
TT
10168/* A helper function for OP_ATR_TAG. */
10169
7c15d377 10170value *
020dbabe
TT
10171ada_atr_tag (struct type *expect_type,
10172 struct expression *exp,
10173 enum noside noside, enum exp_opcode op,
10174 struct value *arg1)
10175{
10176 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10177 return value::zero (ada_tag_type (arg1), not_lval);
020dbabe
TT
10178
10179 return ada_value_tag (arg1);
10180}
10181
68c75735
TT
10182/* A helper function for OP_ATR_SIZE. */
10183
7c15d377 10184value *
68c75735
TT
10185ada_atr_size (struct type *expect_type,
10186 struct expression *exp,
10187 enum noside noside, enum exp_opcode op,
10188 struct value *arg1)
10189{
d0c97917 10190 struct type *type = arg1->type ();
68c75735
TT
10191
10192 /* If the argument is a reference, then dereference its type, since
10193 the user is really asking for the size of the actual object,
10194 not the size of the pointer. */
10195 if (type->code () == TYPE_CODE_REF)
27710edb 10196 type = type->target_type ();
68c75735 10197
0b2b0b82 10198 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10199 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
68c75735
TT
10200 else
10201 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
df86565b 10202 TARGET_CHAR_BIT * type->length ());
68c75735
TT
10203}
10204
d05e24e6
TT
10205/* A helper function for UNOP_ABS. */
10206
7c15d377 10207value *
d05e24e6
TT
10208ada_abs (struct type *expect_type,
10209 struct expression *exp,
10210 enum noside noside, enum exp_opcode op,
10211 struct value *arg1)
10212{
10213 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
ee7bb294 10214 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
d05e24e6
TT
10215 return value_neg (arg1);
10216 else
10217 return arg1;
10218}
10219
faa1dfd7
TT
10220/* A helper function for BINOP_MUL. */
10221
d9e7db06 10222value *
faa1dfd7
TT
10223ada_mult_binop (struct type *expect_type,
10224 struct expression *exp,
10225 enum noside noside, enum exp_opcode op,
10226 struct value *arg1, struct value *arg2)
10227{
10228 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10229 {
10230 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
ee7bb294 10231 return value::zero (arg1->type (), not_lval);
faa1dfd7
TT
10232 }
10233 else
10234 {
10235 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10236 return ada_value_binop (arg1, arg2, op);
10237 }
10238}
10239
214b13ac
TT
10240/* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10241
6e8fb7b7 10242value *
214b13ac
TT
10243ada_equal_binop (struct type *expect_type,
10244 struct expression *exp,
10245 enum noside noside, enum exp_opcode op,
10246 struct value *arg1, struct value *arg2)
10247{
10248 int tem;
10249 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10250 tem = 0;
10251 else
10252 {
10253 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10254 tem = ada_value_equal (arg1, arg2);
10255 }
10256 if (op == BINOP_NOTEQUAL)
10257 tem = !tem;
10258 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10259 return value_from_longest (type, (LONGEST) tem);
10260}
10261
5ce19db8
TT
10262/* A helper function for TERNOP_SLICE. */
10263
1b1ebfab 10264value *
5ce19db8
TT
10265ada_ternop_slice (struct expression *exp,
10266 enum noside noside,
10267 struct value *array, struct value *low_bound_val,
10268 struct value *high_bound_val)
10269{
10270 LONGEST low_bound;
10271 LONGEST high_bound;
10272
10273 low_bound_val = coerce_ref (low_bound_val);
10274 high_bound_val = coerce_ref (high_bound_val);
10275 low_bound = value_as_long (low_bound_val);
10276 high_bound = value_as_long (high_bound_val);
10277
10278 /* If this is a reference to an aligner type, then remove all
10279 the aligners. */
d0c97917
TT
10280 if (array->type ()->code () == TYPE_CODE_REF
10281 && ada_is_aligner_type (array->type ()->target_type ()))
10282 array->type ()->set_target_type
10283 (ada_aligned_type (array->type ()->target_type ()));
5ce19db8 10284
d0c97917 10285 if (ada_is_any_packed_array_type (array->type ()))
5ce19db8
TT
10286 error (_("cannot slice a packed array"));
10287
10288 /* If this is a reference to an array or an array lvalue,
10289 convert to a pointer. */
d0c97917
TT
10290 if (array->type ()->code () == TYPE_CODE_REF
10291 || (array->type ()->code () == TYPE_CODE_ARRAY
736355f2 10292 && array->lval () == lval_memory))
5ce19db8
TT
10293 array = value_addr (array);
10294
10295 if (noside == EVAL_AVOID_SIDE_EFFECTS
10296 && ada_is_array_descriptor_type (ada_check_typedef
d0c97917 10297 (array->type ())))
5ce19db8
TT
10298 return empty_array (ada_type_of_array (array, 0), low_bound,
10299 high_bound);
10300
10301 array = ada_coerce_to_simple_array_ptr (array);
10302
10303 /* If we have more than one level of pointer indirection,
10304 dereference the value until we get only one level. */
d0c97917
TT
10305 while (array->type ()->code () == TYPE_CODE_PTR
10306 && (array->type ()->target_type ()->code ()
5ce19db8
TT
10307 == TYPE_CODE_PTR))
10308 array = value_ind (array);
10309
10310 /* Make sure we really do have an array type before going further,
10311 to avoid a SEGV when trying to get the index type or the target
10312 type later down the road if the debug info generated by
10313 the compiler is incorrect or incomplete. */
d0c97917 10314 if (!ada_is_simple_array_type (array->type ()))
5ce19db8
TT
10315 error (_("cannot take slice of non-array"));
10316
d0c97917 10317 if (ada_check_typedef (array->type ())->code ()
5ce19db8
TT
10318 == TYPE_CODE_PTR)
10319 {
d0c97917 10320 struct type *type0 = ada_check_typedef (array->type ());
5ce19db8
TT
10321
10322 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
27710edb 10323 return empty_array (type0->target_type (), low_bound, high_bound);
5ce19db8
TT
10324 else
10325 {
10326 struct type *arr_type0 =
27710edb 10327 to_fixed_array_type (type0->target_type (), NULL, 1);
5ce19db8
TT
10328
10329 return ada_value_slice_from_ptr (array, arr_type0,
10330 longest_to_int (low_bound),
10331 longest_to_int (high_bound));
10332 }
10333 }
10334 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10335 return array;
10336 else if (high_bound < low_bound)
d0c97917 10337 return empty_array (array->type (), low_bound, high_bound);
5ce19db8
TT
10338 else
10339 return ada_value_slice (array, longest_to_int (low_bound),
10340 longest_to_int (high_bound));
10341}
10342
b467efaa
TT
10343/* A helper function for BINOP_IN_BOUNDS. */
10344
82c3886e 10345value *
b467efaa
TT
10346ada_binop_in_bounds (struct expression *exp, enum noside noside,
10347 struct value *arg1, struct value *arg2, int n)
10348{
10349 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10350 {
10351 struct type *type = language_bool_type (exp->language_defn,
10352 exp->gdbarch);
ee7bb294 10353 return value::zero (type, not_lval);
b467efaa
TT
10354 }
10355
d0c97917 10356 struct type *type = ada_index_type (arg2->type (), n, "range");
b467efaa 10357 if (!type)
d0c97917 10358 type = arg1->type ();
b467efaa
TT
10359
10360 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10361 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10362
10363 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10364 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10365 type = language_bool_type (exp->language_defn, exp->gdbarch);
10366 return value_from_longest (type,
10367 (value_less (arg1, arg3)
10368 || value_equal (arg1, arg3))
10369 && (value_less (arg2, arg1)
10370 || value_equal (arg2, arg1)));
10371}
10372
b84564fc
TT
10373/* A helper function for some attribute operations. */
10374
10375static value *
10376ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10377 struct value *arg1, struct type *type_arg, int tem)
10378{
10379 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10380 {
10381 if (type_arg == NULL)
d0c97917 10382 type_arg = arg1->type ();
b84564fc
TT
10383
10384 if (ada_is_constrained_packed_array_type (type_arg))
10385 type_arg = decode_constrained_packed_array_type (type_arg);
10386
10387 if (!discrete_type_p (type_arg))
10388 {
10389 switch (op)
10390 {
10391 default: /* Should never happen. */
10392 error (_("unexpected attribute encountered"));
10393 case OP_ATR_FIRST:
10394 case OP_ATR_LAST:
10395 type_arg = ada_index_type (type_arg, tem,
10396 ada_attribute_name (op));
10397 break;
10398 case OP_ATR_LENGTH:
10399 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10400 break;
10401 }
10402 }
10403
ee7bb294 10404 return value::zero (type_arg, not_lval);
b84564fc
TT
10405 }
10406 else if (type_arg == NULL)
10407 {
10408 arg1 = ada_coerce_ref (arg1);
10409
d0c97917 10410 if (ada_is_constrained_packed_array_type (arg1->type ()))
b84564fc
TT
10411 arg1 = ada_coerce_to_simple_array (arg1);
10412
10413 struct type *type;
10414 if (op == OP_ATR_LENGTH)
10415 type = builtin_type (exp->gdbarch)->builtin_int;
10416 else
10417 {
d0c97917 10418 type = ada_index_type (arg1->type (), tem,
b84564fc
TT
10419 ada_attribute_name (op));
10420 if (type == NULL)
10421 type = builtin_type (exp->gdbarch)->builtin_int;
10422 }
10423
10424 switch (op)
10425 {
10426 default: /* Should never happen. */
10427 error (_("unexpected attribute encountered"));
10428 case OP_ATR_FIRST:
10429 return value_from_longest
10430 (type, ada_array_bound (arg1, tem, 0));
10431 case OP_ATR_LAST:
10432 return value_from_longest
10433 (type, ada_array_bound (arg1, tem, 1));
10434 case OP_ATR_LENGTH:
10435 return value_from_longest
10436 (type, ada_array_length (arg1, tem));
10437 }
10438 }
10439 else if (discrete_type_p (type_arg))
10440 {
10441 struct type *range_type;
10442 const char *name = ada_type_name (type_arg);
10443
10444 range_type = NULL;
10445 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10446 range_type = to_fixed_range_type (type_arg, NULL);
10447 if (range_type == NULL)
10448 range_type = type_arg;
10449 switch (op)
10450 {
10451 default:
10452 error (_("unexpected attribute encountered"));
10453 case OP_ATR_FIRST:
10454 return value_from_longest
10455 (range_type, ada_discrete_type_low_bound (range_type));
10456 case OP_ATR_LAST:
10457 return value_from_longest
10458 (range_type, ada_discrete_type_high_bound (range_type));
10459 case OP_ATR_LENGTH:
10460 error (_("the 'length attribute applies only to array types"));
10461 }
10462 }
10463 else if (type_arg->code () == TYPE_CODE_FLT)
10464 error (_("unimplemented type attribute"));
10465 else
10466 {
10467 LONGEST low, high;
10468
10469 if (ada_is_constrained_packed_array_type (type_arg))
10470 type_arg = decode_constrained_packed_array_type (type_arg);
10471
10472 struct type *type;
10473 if (op == OP_ATR_LENGTH)
10474 type = builtin_type (exp->gdbarch)->builtin_int;
10475 else
10476 {
10477 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10478 if (type == NULL)
10479 type = builtin_type (exp->gdbarch)->builtin_int;
10480 }
10481
10482 switch (op)
10483 {
10484 default:
10485 error (_("unexpected attribute encountered"));
10486 case OP_ATR_FIRST:
10487 low = ada_array_bound_from_type (type_arg, tem, 0);
10488 return value_from_longest (type, low);
10489 case OP_ATR_LAST:
10490 high = ada_array_bound_from_type (type_arg, tem, 1);
10491 return value_from_longest (type, high);
10492 case OP_ATR_LENGTH:
10493 low = ada_array_bound_from_type (type_arg, tem, 0);
10494 high = ada_array_bound_from_type (type_arg, tem, 1);
10495 return value_from_longest (type, high - low + 1);
10496 }
10497 }
10498}
10499
38dc70cf
TT
10500/* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10501
6ad3b8bf 10502struct value *
38dc70cf
TT
10503ada_binop_minmax (struct type *expect_type,
10504 struct expression *exp,
10505 enum noside noside, enum exp_opcode op,
10506 struct value *arg1, struct value *arg2)
10507{
10508 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10509 return value::zero (arg1->type (), not_lval);
38dc70cf
TT
10510 else
10511 {
10512 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
0922dc84 10513 return value_binop (arg1, arg2, op);
38dc70cf
TT
10514 }
10515}
10516
dd5fd283
TT
10517/* A helper function for BINOP_EXP. */
10518
065ec826 10519struct value *
dd5fd283
TT
10520ada_binop_exp (struct type *expect_type,
10521 struct expression *exp,
10522 enum noside noside, enum exp_opcode op,
10523 struct value *arg1, struct value *arg2)
10524{
10525 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10526 return value::zero (arg1->type (), not_lval);
dd5fd283
TT
10527 else
10528 {
10529 /* For integer exponentiation operations,
10530 only promote the first argument. */
d0c97917 10531 if (is_integral_type (arg2->type ()))
dd5fd283
TT
10532 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10533 else
10534 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10535
10536 return value_binop (arg1, arg2, op);
10537 }
10538}
10539
03070ee9
TT
10540namespace expr
10541{
10542
8b12db26
TT
10543/* See ada-exp.h. */
10544
10545operation_up
10546ada_resolvable::replace (operation_up &&owner,
10547 struct expression *exp,
10548 bool deprocedure_p,
10549 bool parse_completion,
10550 innermost_block_tracker *tracker,
10551 struct type *context_type)
10552{
10553 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10554 return (make_operation<ada_funcall_operation>
10555 (std::move (owner),
10556 std::vector<operation_up> ()));
10557 return std::move (owner);
10558}
10559
c9f66f00 10560/* Convert the character literal whose value would be VAL to the
03adb248
TT
10561 appropriate value of type TYPE, if there is a translation.
10562 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10563 the literal 'A' (VAL == 65), returns 0. */
10564
10565static LONGEST
10566convert_char_literal (struct type *type, LONGEST val)
10567{
c9f66f00 10568 char name[12];
03adb248
TT
10569 int f;
10570
10571 if (type == NULL)
10572 return val;
10573 type = check_typedef (type);
10574 if (type->code () != TYPE_CODE_ENUM)
10575 return val;
10576
10577 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10578 xsnprintf (name, sizeof (name), "Q%c", (int) val);
c9f66f00
TT
10579 else if (val >= 0 && val < 256)
10580 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10581 else if (val >= 0 && val < 0x10000)
10582 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
03adb248 10583 else
c9f66f00 10584 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
03adb248
TT
10585 size_t len = strlen (name);
10586 for (f = 0; f < type->num_fields (); f += 1)
10587 {
10588 /* Check the suffix because an enum constant in a package will
10589 have a name like "pkg__QUxx". This is safe enough because we
10590 already have the correct type, and because mangling means
10591 there can't be clashes. */
33d16dd9 10592 const char *ename = type->field (f).name ();
03adb248
TT
10593 size_t elen = strlen (ename);
10594
10595 if (elen >= len && strcmp (name, ename + elen - len) == 0)
970db518 10596 return type->field (f).loc_enumval ();
03adb248
TT
10597 }
10598 return val;
10599}
10600
b1b9c411
TT
10601value *
10602ada_char_operation::evaluate (struct type *expect_type,
10603 struct expression *exp,
10604 enum noside noside)
10605{
10606 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10607 if (expect_type != nullptr)
10608 result = ada_value_cast (expect_type, result);
10609 return result;
10610}
10611
03adb248
TT
10612/* See ada-exp.h. */
10613
10614operation_up
10615ada_char_operation::replace (operation_up &&owner,
10616 struct expression *exp,
10617 bool deprocedure_p,
10618 bool parse_completion,
10619 innermost_block_tracker *tracker,
10620 struct type *context_type)
10621{
10622 operation_up result = std::move (owner);
10623
10624 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10625 {
10626 gdb_assert (result.get () == this);
10627 std::get<0> (m_storage) = context_type;
10628 std::get<1> (m_storage)
10629 = convert_char_literal (context_type, std::get<1> (m_storage));
10630 }
10631
b1b9c411 10632 return result;
03adb248
TT
10633}
10634
03070ee9
TT
10635value *
10636ada_wrapped_operation::evaluate (struct type *expect_type,
10637 struct expression *exp,
10638 enum noside noside)
10639{
10640 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10641 if (noside == EVAL_NORMAL)
10642 result = unwrap_value (result);
10643
10644 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10645 then we need to perform the conversion manually, because
10646 evaluate_subexp_standard doesn't do it. This conversion is
10647 necessary in Ada because the different kinds of float/fixed
10648 types in Ada have different representations.
10649
10650 Similarly, we need to perform the conversion from OP_LONG
10651 ourselves. */
10652 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10653 result = ada_value_cast (expect_type, result);
10654
10655 return result;
10656}
10657
013a623f
TT
10658void
10659ada_wrapped_operation::do_generate_ax (struct expression *exp,
10660 struct agent_expr *ax,
10661 struct axs_value *value,
10662 struct type *cast_type)
10663{
10664 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10665
10666 struct type *type = value->type;
10667 if (ada_is_aligner_type (type))
10668 error (_("Aligner types cannot be handled in agent expressions"));
10669 else if (find_base_type (type) != nullptr)
10670 error (_("Dynamic types cannot be handled in agent expressions"));
10671}
10672
42fecb61
TT
10673value *
10674ada_string_operation::evaluate (struct type *expect_type,
10675 struct expression *exp,
10676 enum noside noside)
10677{
fc18a21b
TT
10678 struct type *char_type;
10679 if (expect_type != nullptr && ada_is_string_type (expect_type))
10680 char_type = ada_array_element_type (expect_type, 1);
10681 else
10682 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10683
10684 const std::string &str = std::get<0> (m_storage);
10685 const char *encoding;
df86565b 10686 switch (char_type->length ())
fc18a21b
TT
10687 {
10688 case 1:
10689 {
10690 /* Simply copy over the data -- this isn't perhaps strictly
10691 correct according to the encodings, but it is gdb's
10692 historical behavior. */
10693 struct type *stringtype
10694 = lookup_array_range_type (char_type, 1, str.length ());
317c3ed9 10695 struct value *val = value::allocate (stringtype);
bbe912ba 10696 memcpy (val->contents_raw ().data (), str.c_str (),
fc18a21b
TT
10697 str.length ());
10698 return val;
10699 }
10700
10701 case 2:
10702 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10703 encoding = "UTF-16BE";
10704 else
10705 encoding = "UTF-16LE";
10706 break;
10707
10708 case 4:
10709 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10710 encoding = "UTF-32BE";
10711 else
10712 encoding = "UTF-32LE";
10713 break;
10714
10715 default:
10716 error (_("unexpected character type size %s"),
df86565b 10717 pulongest (char_type->length ()));
fc18a21b
TT
10718 }
10719
10720 auto_obstack converted;
10721 convert_between_encodings (host_charset (), encoding,
10722 (const gdb_byte *) str.c_str (),
10723 str.length (), 1,
10724 &converted, translit_none);
10725
10726 struct type *stringtype
10727 = lookup_array_range_type (char_type, 1,
10728 obstack_object_size (&converted)
df86565b 10729 / char_type->length ());
317c3ed9 10730 struct value *val = value::allocate (stringtype);
bbe912ba 10731 memcpy (val->contents_raw ().data (),
fc18a21b
TT
10732 obstack_base (&converted),
10733 obstack_object_size (&converted));
10734 return val;
42fecb61
TT
10735}
10736
b1b9c411
TT
10737value *
10738ada_concat_operation::evaluate (struct type *expect_type,
10739 struct expression *exp,
10740 enum noside noside)
10741{
10742 /* If one side is a literal, evaluate the other side first so that
10743 the expected type can be set properly. */
10744 const operation_up &lhs_expr = std::get<0> (m_storage);
10745 const operation_up &rhs_expr = std::get<1> (m_storage);
10746
10747 value *lhs, *rhs;
10748 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10749 {
10750 rhs = rhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10751 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
b1b9c411
TT
10752 }
10753 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10754 {
10755 rhs = rhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10756 struct type *rhs_type = check_typedef (rhs->type ());
b1b9c411
TT
10757 struct type *elt_type = nullptr;
10758 if (rhs_type->code () == TYPE_CODE_ARRAY)
27710edb 10759 elt_type = rhs_type->target_type ();
b1b9c411
TT
10760 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10761 }
10762 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10763 {
10764 lhs = lhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10765 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
b1b9c411
TT
10766 }
10767 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10768 {
10769 lhs = lhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10770 struct type *lhs_type = check_typedef (lhs->type ());
b1b9c411
TT
10771 struct type *elt_type = nullptr;
10772 if (lhs_type->code () == TYPE_CODE_ARRAY)
27710edb 10773 elt_type = lhs_type->target_type ();
b1b9c411
TT
10774 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10775 }
10776 else
10777 return concat_operation::evaluate (expect_type, exp, noside);
10778
10779 return value_concat (lhs, rhs);
10780}
10781
cc6bd32e
TT
10782value *
10783ada_qual_operation::evaluate (struct type *expect_type,
10784 struct expression *exp,
10785 enum noside noside)
10786{
10787 struct type *type = std::get<1> (m_storage);
10788 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10789}
10790
fc715eb2
TT
10791value *
10792ada_ternop_range_operation::evaluate (struct type *expect_type,
10793 struct expression *exp,
10794 enum noside noside)
10795{
10796 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10797 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10798 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10799 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10800}
10801
73796c73
TT
10802value *
10803ada_binop_addsub_operation::evaluate (struct type *expect_type,
10804 struct expression *exp,
10805 enum noside noside)
10806{
10807 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10808 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10809
10810 auto do_op = [=] (LONGEST x, LONGEST y)
10811 {
10812 if (std::get<0> (m_storage) == BINOP_ADD)
10813 return x + y;
10814 return x - y;
10815 };
10816
d0c97917 10817 if (arg1->type ()->code () == TYPE_CODE_PTR)
73796c73 10818 return (value_from_longest
d0c97917 10819 (arg1->type (),
73796c73 10820 do_op (value_as_long (arg1), value_as_long (arg2))));
d0c97917 10821 if (arg2->type ()->code () == TYPE_CODE_PTR)
73796c73 10822 return (value_from_longest
d0c97917 10823 (arg2->type (),
73796c73
TT
10824 do_op (value_as_long (arg1), value_as_long (arg2))));
10825 /* Preserve the original type for use by the range case below.
10826 We cannot cast the result to a reference type, so if ARG1 is
10827 a reference type, find its underlying type. */
d0c97917 10828 struct type *type = arg1->type ();
73796c73 10829 while (type->code () == TYPE_CODE_REF)
27710edb 10830 type = type->target_type ();
73796c73
TT
10831 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10832 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10833 /* We need to special-case the result with a range.
10834 This is done for the benefit of "ptype". gdb's Ada support
10835 historically used the LHS to set the result type here, so
10836 preserve this behavior. */
10837 if (type->code () == TYPE_CODE_RANGE)
10838 arg1 = value_cast (type, arg1);
10839 return arg1;
10840}
10841
60fa02ca
TT
10842value *
10843ada_unop_atr_operation::evaluate (struct type *expect_type,
10844 struct expression *exp,
10845 enum noside noside)
10846{
10847 struct type *type_arg = nullptr;
10848 value *val = nullptr;
10849
10850 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10851 {
10852 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10853 EVAL_AVOID_SIDE_EFFECTS);
d0c97917 10854 type_arg = tem->type ();
60fa02ca
TT
10855 }
10856 else
10857 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10858
10859 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10860 val, type_arg, std::get<2> (m_storage));
10861}
10862
3f4a0053
TT
10863value *
10864ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10865 struct expression *exp,
10866 enum noside noside)
10867{
10868 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10869 return value::zero (expect_type, not_lval);
3f4a0053 10870
9c79936b
TT
10871 const bound_minimal_symbol &b = std::get<0> (m_storage);
10872 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
3f4a0053
TT
10873
10874 val = ada_value_cast (expect_type, val);
10875
10876 /* Follow the Ada language semantics that do not allow taking
10877 an address of the result of a cast (view conversion in Ada). */
736355f2 10878 if (val->lval () == lval_memory)
3f4a0053 10879 {
3ee3b270 10880 if (val->lazy ())
78259c36 10881 val->fetch_lazy ();
6f9c9d71 10882 val->set_lval (not_lval);
3f4a0053
TT
10883 }
10884 return val;
10885}
10886
99a3b1e7
TT
10887value *
10888ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10889 struct expression *exp,
10890 enum noside noside)
10891{
10892 value *val = evaluate_var_value (noside,
9e5e03df
TT
10893 std::get<0> (m_storage).block,
10894 std::get<0> (m_storage).symbol);
99a3b1e7
TT
10895
10896 val = ada_value_cast (expect_type, val);
10897
10898 /* Follow the Ada language semantics that do not allow taking
10899 an address of the result of a cast (view conversion in Ada). */
736355f2 10900 if (val->lval () == lval_memory)
99a3b1e7 10901 {
3ee3b270 10902 if (val->lazy ())
78259c36 10903 val->fetch_lazy ();
6f9c9d71 10904 val->set_lval (not_lval);
99a3b1e7
TT
10905 }
10906 return val;
10907}
10908
10909value *
10910ada_var_value_operation::evaluate (struct type *expect_type,
10911 struct expression *exp,
10912 enum noside noside)
10913{
9e5e03df 10914 symbol *sym = std::get<0> (m_storage).symbol;
99a3b1e7 10915
6c9c307c 10916 if (sym->domain () == UNDEF_DOMAIN)
99a3b1e7
TT
10917 /* Only encountered when an unresolved symbol occurs in a
10918 context other than a function call, in which case, it is
10919 invalid. */
10920 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10921 sym->print_name ());
10922
10923 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10924 {
5f9c5a63 10925 struct type *type = static_unwrap_type (sym->type ());
99a3b1e7
TT
10926 /* Check to see if this is a tagged type. We also need to handle
10927 the case where the type is a reference to a tagged type, but
10928 we have to be careful to exclude pointers to tagged types.
10929 The latter should be shown as usual (as a pointer), whereas
10930 a reference should mostly be transparent to the user. */
10931 if (ada_is_tagged_type (type, 0)
10932 || (type->code () == TYPE_CODE_REF
27710edb 10933 && ada_is_tagged_type (type->target_type (), 0)))
99a3b1e7
TT
10934 {
10935 /* Tagged types are a little special in the fact that the real
10936 type is dynamic and can only be determined by inspecting the
10937 object's tag. This means that we need to get the object's
10938 value first (EVAL_NORMAL) and then extract the actual object
10939 type from its tag.
10940
10941 Note that we cannot skip the final step where we extract
10942 the object type from its tag, because the EVAL_NORMAL phase
10943 results in dynamic components being resolved into fixed ones.
10944 This can cause problems when trying to print the type
10945 description of tagged types whose parent has a dynamic size:
10946 We use the type name of the "_parent" component in order
10947 to print the name of the ancestor type in the type description.
10948 If that component had a dynamic size, the resolution into
10949 a fixed type would result in the loss of that type name,
10950 thus preventing us from printing the name of the ancestor
10951 type in the type description. */
9863c3b5 10952 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
99a3b1e7
TT
10953
10954 if (type->code () != TYPE_CODE_REF)
10955 {
10956 struct type *actual_type;
10957
10958 actual_type = type_from_tag (ada_value_tag (arg1));
10959 if (actual_type == NULL)
10960 /* If, for some reason, we were unable to determine
10961 the actual type from the tag, then use the static
10962 approximation that we just computed as a fallback.
10963 This can happen if the debugging information is
10964 incomplete, for instance. */
10965 actual_type = type;
ee7bb294 10966 return value::zero (actual_type, not_lval);
99a3b1e7
TT
10967 }
10968 else
10969 {
10970 /* In the case of a ref, ada_coerce_ref takes care
10971 of determining the actual type. But the evaluation
10972 should return a ref as it should be valid to ask
10973 for its address; so rebuild a ref after coerce. */
10974 arg1 = ada_coerce_ref (arg1);
10975 return value_ref (arg1, TYPE_CODE_REF);
10976 }
10977 }
10978
10979 /* Records and unions for which GNAT encodings have been
10980 generated need to be statically fixed as well.
10981 Otherwise, non-static fixing produces a type where
10982 all dynamic properties are removed, which prevents "ptype"
10983 from being able to completely describe the type.
10984 For instance, a case statement in a variant record would be
10985 replaced by the relevant components based on the actual
10986 value of the discriminants. */
10987 if ((type->code () == TYPE_CODE_STRUCT
10988 && dynamic_template_type (type) != NULL)
10989 || (type->code () == TYPE_CODE_UNION
10990 && ada_find_parallel_type (type, "___XVU") != NULL))
ee7bb294 10991 return value::zero (to_static_fixed_type (type), not_lval);
99a3b1e7
TT
10992 }
10993
10994 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10995 return ada_to_fixed_value (arg1);
10996}
10997
d8a4ed8a
TT
10998bool
10999ada_var_value_operation::resolve (struct expression *exp,
11000 bool deprocedure_p,
11001 bool parse_completion,
11002 innermost_block_tracker *tracker,
11003 struct type *context_type)
11004{
9e5e03df 11005 symbol *sym = std::get<0> (m_storage).symbol;
6c9c307c 11006 if (sym->domain () == UNDEF_DOMAIN)
d8a4ed8a
TT
11007 {
11008 block_symbol resolved
9e5e03df 11009 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
d8a4ed8a
TT
11010 context_type, parse_completion,
11011 deprocedure_p, tracker);
9e5e03df 11012 std::get<0> (m_storage) = resolved;
d8a4ed8a
TT
11013 }
11014
11015 if (deprocedure_p
5f9c5a63 11016 && (std::get<0> (m_storage).symbol->type ()->code ()
9e5e03df 11017 == TYPE_CODE_FUNC))
d8a4ed8a
TT
11018 return true;
11019
11020 return false;
11021}
11022
013a623f
TT
11023void
11024ada_var_value_operation::do_generate_ax (struct expression *exp,
11025 struct agent_expr *ax,
11026 struct axs_value *value,
11027 struct type *cast_type)
11028{
11029 symbol *sym = std::get<0> (m_storage).symbol;
11030
11031 if (sym->domain () == UNDEF_DOMAIN)
11032 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11033 sym->print_name ());
11034
11035 struct type *type = static_unwrap_type (sym->type ());
11036 if (ada_is_tagged_type (type, 0)
11037 || (type->code () == TYPE_CODE_REF
11038 && ada_is_tagged_type (type->target_type (), 0)))
11039 error (_("Tagged types cannot be handled in agent expressions"));
11040
11041 if ((type->code () == TYPE_CODE_STRUCT
11042 && dynamic_template_type (type) != NULL)
11043 || (type->code () == TYPE_CODE_UNION
11044 && ada_find_parallel_type (type, "___XVU") != NULL))
11045 error (_("Dynamic types cannot be handled in agent expressions"));
11046
11047 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
11048}
11049
9e99f48f
TT
11050value *
11051ada_atr_val_operation::evaluate (struct type *expect_type,
11052 struct expression *exp,
11053 enum noside noside)
11054{
11055 value *arg = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
11056 return ada_val_atr (noside, std::get<0> (m_storage), arg);
11057}
11058
e8c33fa1
TT
11059value *
11060ada_unop_ind_operation::evaluate (struct type *expect_type,
11061 struct expression *exp,
11062 enum noside noside)
11063{
11064 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
11065
d0c97917 11066 struct type *type = ada_check_typedef (arg1->type ());
e8c33fa1
TT
11067 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11068 {
11069 if (ada_is_array_descriptor_type (type))
11070 /* GDB allows dereferencing GNAT array descriptors. */
11071 {
11072 struct type *arrType = ada_type_of_array (arg1, 0);
11073
11074 if (arrType == NULL)
11075 error (_("Attempt to dereference null array pointer."));
11076 return value_at_lazy (arrType, 0);
11077 }
11078 else if (type->code () == TYPE_CODE_PTR
11079 || type->code () == TYPE_CODE_REF
11080 /* In C you can dereference an array to get the 1st elt. */
11081 || type->code () == TYPE_CODE_ARRAY)
11082 {
11083 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11084 only be determined by inspecting the object's tag.
11085 This means that we need to evaluate completely the
11086 expression in order to get its type. */
11087
11088 if ((type->code () == TYPE_CODE_REF
11089 || type->code () == TYPE_CODE_PTR)
27710edb 11090 && ada_is_tagged_type (type->target_type (), 0))
e8c33fa1
TT
11091 {
11092 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11093 EVAL_NORMAL);
d0c97917 11094 type = ada_value_ind (arg1)->type ();
e8c33fa1
TT
11095 }
11096 else
11097 {
11098 type = to_static_fixed_type
11099 (ada_aligned_type
27710edb 11100 (ada_check_typedef (type->target_type ())));
e8c33fa1 11101 }
ee7bb294 11102 return value::zero (type, lval_memory);
e8c33fa1
TT
11103 }
11104 else if (type->code () == TYPE_CODE_INT)
11105 {
11106 /* GDB allows dereferencing an int. */
11107 if (expect_type == NULL)
ee7bb294 11108 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
e8c33fa1
TT
11109 lval_memory);
11110 else
11111 {
11112 expect_type =
11113 to_static_fixed_type (ada_aligned_type (expect_type));
ee7bb294 11114 return value::zero (expect_type, lval_memory);
e8c33fa1
TT
11115 }
11116 }
11117 else
11118 error (_("Attempt to take contents of a non-pointer value."));
11119 }
11120 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
d0c97917 11121 type = ada_check_typedef (arg1->type ());
e8c33fa1
TT
11122
11123 if (type->code () == TYPE_CODE_INT)
11124 /* GDB allows dereferencing an int. If we were given
11125 the expect_type, then use that as the target type.
11126 Otherwise, assume that the target type is an int. */
11127 {
11128 if (expect_type != NULL)
11129 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11130 arg1));
11131 else
11132 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11133 (CORE_ADDR) value_as_address (arg1));
11134 }
11135
11136 if (ada_is_array_descriptor_type (type))
11137 /* GDB allows dereferencing GNAT array descriptors. */
11138 return ada_coerce_to_simple_array (arg1);
11139 else
11140 return ada_value_ind (arg1);
11141}
11142
ebc06ad8
TT
11143value *
11144ada_structop_operation::evaluate (struct type *expect_type,
11145 struct expression *exp,
11146 enum noside noside)
11147{
11148 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11149 const char *str = std::get<1> (m_storage).c_str ();
11150 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11151 {
11152 struct type *type;
d0c97917 11153 struct type *type1 = arg1->type ();
ebc06ad8
TT
11154
11155 if (ada_is_tagged_type (type1, 1))
11156 {
11157 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11158
11159 /* If the field is not found, check if it exists in the
11160 extension of this object's type. This means that we
11161 need to evaluate completely the expression. */
11162
11163 if (type == NULL)
11164 {
11165 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11166 EVAL_NORMAL);
11167 arg1 = ada_value_struct_elt (arg1, str, 0);
11168 arg1 = unwrap_value (arg1);
d0c97917 11169 type = ada_to_fixed_value (arg1)->type ();
ebc06ad8
TT
11170 }
11171 }
11172 else
11173 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11174
ee7bb294 11175 return value::zero (ada_aligned_type (type), lval_memory);
ebc06ad8
TT
11176 }
11177 else
11178 {
11179 arg1 = ada_value_struct_elt (arg1, str, 0);
11180 arg1 = unwrap_value (arg1);
11181 return ada_to_fixed_value (arg1);
11182 }
11183}
11184
efe3af2f
TT
11185value *
11186ada_funcall_operation::evaluate (struct type *expect_type,
11187 struct expression *exp,
11188 enum noside noside)
11189{
11190 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11191 int nargs = args_up.size ();
11192 std::vector<value *> argvec (nargs);
11193 operation_up &callee_op = std::get<0> (m_storage);
11194
11195 ada_var_value_operation *avv
11196 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11197 if (avv != nullptr
6c9c307c 11198 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
efe3af2f
TT
11199 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11200 avv->get_symbol ()->print_name ());
11201
11202 value *callee = callee_op->evaluate (nullptr, exp, noside);
11203 for (int i = 0; i < args_up.size (); ++i)
11204 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11205
11206 if (ada_is_constrained_packed_array_type
d0c97917 11207 (desc_base_type (callee->type ())))
efe3af2f 11208 callee = ada_coerce_to_simple_array (callee);
d0c97917
TT
11209 else if (callee->type ()->code () == TYPE_CODE_ARRAY
11210 && TYPE_FIELD_BITSIZE (callee->type (), 0) != 0)
efe3af2f
TT
11211 /* This is a packed array that has already been fixed, and
11212 therefore already coerced to a simple array. Nothing further
11213 to do. */
11214 ;
d0c97917 11215 else if (callee->type ()->code () == TYPE_CODE_REF)
efe3af2f
TT
11216 {
11217 /* Make sure we dereference references so that all the code below
11218 feels like it's really handling the referenced value. Wrapping
11219 types (for alignment) may be there, so make sure we strip them as
11220 well. */
11221 callee = ada_to_fixed_value (coerce_ref (callee));
11222 }
d0c97917 11223 else if (callee->type ()->code () == TYPE_CODE_ARRAY
736355f2 11224 && callee->lval () == lval_memory)
efe3af2f
TT
11225 callee = value_addr (callee);
11226
d0c97917 11227 struct type *type = ada_check_typedef (callee->type ());
efe3af2f
TT
11228
11229 /* Ada allows us to implicitly dereference arrays when subscripting
11230 them. So, if this is an array typedef (encoding use for array
11231 access types encoded as fat pointers), strip it now. */
11232 if (type->code () == TYPE_CODE_TYPEDEF)
11233 type = ada_typedef_target_type (type);
11234
11235 if (type->code () == TYPE_CODE_PTR)
11236 {
27710edb 11237 switch (ada_check_typedef (type->target_type ())->code ())
efe3af2f
TT
11238 {
11239 case TYPE_CODE_FUNC:
27710edb 11240 type = ada_check_typedef (type->target_type ());
efe3af2f
TT
11241 break;
11242 case TYPE_CODE_ARRAY:
11243 break;
11244 case TYPE_CODE_STRUCT:
11245 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11246 callee = ada_value_ind (callee);
27710edb 11247 type = ada_check_typedef (type->target_type ());
efe3af2f
TT
11248 break;
11249 default:
11250 error (_("cannot subscript or call something of type `%s'"),
d0c97917 11251 ada_type_name (callee->type ()));
efe3af2f
TT
11252 break;
11253 }
11254 }
11255
11256 switch (type->code ())
11257 {
11258 case TYPE_CODE_FUNC:
11259 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11260 {
27710edb 11261 if (type->target_type () == NULL)
efe3af2f 11262 error_call_unknown_return_type (NULL);
317c3ed9 11263 return value::allocate (type->target_type ());
efe3af2f
TT
11264 }
11265 return call_function_by_hand (callee, NULL, argvec);
11266 case TYPE_CODE_INTERNAL_FUNCTION:
11267 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11268 /* We don't know anything about what the internal
11269 function might return, but we have to return
11270 something. */
ee7bb294 11271 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
efe3af2f
TT
11272 not_lval);
11273 else
11274 return call_internal_function (exp->gdbarch, exp->language_defn,
11275 callee, nargs,
11276 argvec.data ());
11277
d3c54a1c
TT
11278 case TYPE_CODE_STRUCT:
11279 {
11280 int arity;
4c4b4cd2 11281
d3c54a1c
TT
11282 arity = ada_array_arity (type);
11283 type = ada_array_element_type (type, nargs);
11284 if (type == NULL)
11285 error (_("cannot subscript or call a record"));
11286 if (arity != nargs)
11287 error (_("wrong number of subscripts; expecting %d"), arity);
11288 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 11289 return value::zero (ada_aligned_type (type), lval_memory);
d3c54a1c
TT
11290 return
11291 unwrap_value (ada_value_subscript
11292 (callee, nargs, argvec.data ()));
11293 }
11294 case TYPE_CODE_ARRAY:
14f9c5c9 11295 if (noside == EVAL_AVOID_SIDE_EFFECTS)
dda83cd7 11296 {
d3c54a1c
TT
11297 type = ada_array_element_type (type, nargs);
11298 if (type == NULL)
11299 error (_("element type of array unknown"));
dda83cd7 11300 else
ee7bb294 11301 return value::zero (ada_aligned_type (type), lval_memory);
dda83cd7 11302 }
d3c54a1c
TT
11303 return
11304 unwrap_value (ada_value_subscript
11305 (ada_coerce_to_simple_array (callee),
11306 nargs, argvec.data ()));
11307 case TYPE_CODE_PTR: /* Pointer to array */
11308 if (noside == EVAL_AVOID_SIDE_EFFECTS)
dda83cd7 11309 {
27710edb 11310 type = to_fixed_array_type (type->target_type (), NULL, 1);
d3c54a1c
TT
11311 type = ada_array_element_type (type, nargs);
11312 if (type == NULL)
11313 error (_("element type of array unknown"));
96967637 11314 else
ee7bb294 11315 return value::zero (ada_aligned_type (type), lval_memory);
dda83cd7 11316 }
d3c54a1c
TT
11317 return
11318 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11319 argvec.data ()));
6b0d7253 11320
d3c54a1c
TT
11321 default:
11322 error (_("Attempt to index or call something other than an "
11323 "array or function"));
11324 }
11325}
5b4ee69b 11326
d3c54a1c
TT
11327bool
11328ada_funcall_operation::resolve (struct expression *exp,
11329 bool deprocedure_p,
11330 bool parse_completion,
11331 innermost_block_tracker *tracker,
11332 struct type *context_type)
11333{
11334 operation_up &callee_op = std::get<0> (m_storage);
5ec18f2b 11335
d3c54a1c
TT
11336 ada_var_value_operation *avv
11337 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11338 if (avv == nullptr)
11339 return false;
5ec18f2b 11340
d3c54a1c 11341 symbol *sym = avv->get_symbol ();
6c9c307c 11342 if (sym->domain () != UNDEF_DOMAIN)
d3c54a1c 11343 return false;
dda83cd7 11344
d3c54a1c
TT
11345 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11346 int nargs = args_up.size ();
11347 std::vector<value *> argvec (nargs);
284614f0 11348
d3c54a1c
TT
11349 for (int i = 0; i < args_up.size (); ++i)
11350 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
52ce6436 11351
d3c54a1c
TT
11352 const block *block = avv->get_block ();
11353 block_symbol resolved
11354 = ada_resolve_funcall (sym, block,
11355 context_type, parse_completion,
11356 nargs, argvec.data (),
11357 tracker);
11358
11359 std::get<0> (m_storage)
9e5e03df 11360 = make_operation<ada_var_value_operation> (resolved);
d3c54a1c
TT
11361 return false;
11362}
11363
11364bool
11365ada_ternop_slice_operation::resolve (struct expression *exp,
11366 bool deprocedure_p,
11367 bool parse_completion,
11368 innermost_block_tracker *tracker,
11369 struct type *context_type)
11370{
11371 /* Historically this check was done during resolution, so we
11372 continue that here. */
11373 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11374 EVAL_AVOID_SIDE_EFFECTS);
d0c97917 11375 if (ada_is_any_packed_array_type (v->type ()))
d3c54a1c
TT
11376 error (_("cannot slice a packed array"));
11377 return false;
11378}
14f9c5c9 11379
14f9c5c9 11380}
d3c54a1c 11381
14f9c5c9 11382\f
d2e4a39e 11383
4c4b4cd2
PH
11384/* Return non-zero iff TYPE represents a System.Address type. */
11385
11386int
11387ada_is_system_address_type (struct type *type)
11388{
7d93a1e0 11389 return (type->name () && strcmp (type->name (), "system__address") == 0);
4c4b4cd2
PH
11390}
11391
14f9c5c9 11392\f
d2e4a39e 11393
dda83cd7 11394 /* Range types */
14f9c5c9
AS
11395
11396/* Scan STR beginning at position K for a discriminant name, and
11397 return the value of that discriminant field of DVAL in *PX. If
11398 PNEW_K is not null, put the position of the character beyond the
11399 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
4c4b4cd2 11400 not alter *PX and *PNEW_K if unsuccessful. */
14f9c5c9
AS
11401
11402static int
108d56a4 11403scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
dda83cd7 11404 int *pnew_k)
14f9c5c9 11405{
5f9febe0 11406 static std::string storage;
5da1a4d3 11407 const char *pstart, *pend, *bound;
d2e4a39e 11408 struct value *bound_val;
14f9c5c9
AS
11409
11410 if (dval == NULL || str == NULL || str[k] == '\0')
11411 return 0;
11412
5da1a4d3
SM
11413 pstart = str + k;
11414 pend = strstr (pstart, "__");
14f9c5c9
AS
11415 if (pend == NULL)
11416 {
5da1a4d3 11417 bound = pstart;
14f9c5c9
AS
11418 k += strlen (bound);
11419 }
d2e4a39e 11420 else
14f9c5c9 11421 {
5da1a4d3
SM
11422 int len = pend - pstart;
11423
11424 /* Strip __ and beyond. */
5f9febe0
TT
11425 storage = std::string (pstart, len);
11426 bound = storage.c_str ();
d2e4a39e 11427 k = pend - str;
14f9c5c9 11428 }
d2e4a39e 11429
d0c97917 11430 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
14f9c5c9
AS
11431 if (bound_val == NULL)
11432 return 0;
11433
11434 *px = value_as_long (bound_val);
11435 if (pnew_k != NULL)
11436 *pnew_k = k;
11437 return 1;
11438}
11439
25a1127b
TT
11440/* Value of variable named NAME. Only exact matches are considered.
11441 If no such variable found, then if ERR_MSG is null, returns 0, and
4c4b4cd2
PH
11442 otherwise causes an error with message ERR_MSG. */
11443
d2e4a39e 11444static struct value *
edb0c9cb 11445get_var_value (const char *name, const char *err_msg)
14f9c5c9 11446{
25a1127b
TT
11447 std::string quoted_name = add_angle_brackets (name);
11448
11449 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
14f9c5c9 11450
d1183b06
TT
11451 std::vector<struct block_symbol> syms
11452 = ada_lookup_symbol_list_worker (lookup_name,
11453 get_selected_block (0),
11454 VAR_DOMAIN, 1);
14f9c5c9 11455
d1183b06 11456 if (syms.size () != 1)
14f9c5c9
AS
11457 {
11458 if (err_msg == NULL)
dda83cd7 11459 return 0;
14f9c5c9 11460 else
dda83cd7 11461 error (("%s"), err_msg);
14f9c5c9
AS
11462 }
11463
54d343a2 11464 return value_of_variable (syms[0].symbol, syms[0].block);
14f9c5c9 11465}
d2e4a39e 11466
edb0c9cb
PA
11467/* Value of integer variable named NAME in the current environment.
11468 If no such variable is found, returns false. Otherwise, sets VALUE
11469 to the variable's value and returns true. */
4c4b4cd2 11470
edb0c9cb
PA
11471bool
11472get_int_var_value (const char *name, LONGEST &value)
14f9c5c9 11473{
4c4b4cd2 11474 struct value *var_val = get_var_value (name, 0);
d2e4a39e 11475
14f9c5c9 11476 if (var_val == 0)
edb0c9cb
PA
11477 return false;
11478
11479 value = value_as_long (var_val);
11480 return true;
14f9c5c9 11481}
d2e4a39e 11482
14f9c5c9
AS
11483
11484/* Return a range type whose base type is that of the range type named
11485 NAME in the current environment, and whose bounds are calculated
4c4b4cd2 11486 from NAME according to the GNAT range encoding conventions.
1ce677a4
UW
11487 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11488 corresponding range type from debug information; fall back to using it
11489 if symbol lookup fails. If a new type must be created, allocate it
11490 like ORIG_TYPE was. The bounds information, in general, is encoded
11491 in NAME, the base type given in the named range type. */
14f9c5c9 11492
d2e4a39e 11493static struct type *
28c85d6c 11494to_fixed_range_type (struct type *raw_type, struct value *dval)
14f9c5c9 11495{
0d5cff50 11496 const char *name;
14f9c5c9 11497 struct type *base_type;
108d56a4 11498 const char *subtype_info;
14f9c5c9 11499
28c85d6c 11500 gdb_assert (raw_type != NULL);
7d93a1e0 11501 gdb_assert (raw_type->name () != NULL);
dddfab26 11502
78134374 11503 if (raw_type->code () == TYPE_CODE_RANGE)
27710edb 11504 base_type = raw_type->target_type ();
14f9c5c9
AS
11505 else
11506 base_type = raw_type;
11507
7d93a1e0 11508 name = raw_type->name ();
14f9c5c9
AS
11509 subtype_info = strstr (name, "___XD");
11510 if (subtype_info == NULL)
690cc4eb 11511 {
43bbcdc2
PH
11512 LONGEST L = ada_discrete_type_low_bound (raw_type);
11513 LONGEST U = ada_discrete_type_high_bound (raw_type);
5b4ee69b 11514
690cc4eb
PH
11515 if (L < INT_MIN || U > INT_MAX)
11516 return raw_type;
11517 else
9fa83a7a
TT
11518 return create_static_range_type (type_allocator (raw_type).new_type (),
11519 raw_type, L, U);
690cc4eb 11520 }
14f9c5c9
AS
11521 else
11522 {
14f9c5c9
AS
11523 int prefix_len = subtype_info - name;
11524 LONGEST L, U;
11525 struct type *type;
108d56a4 11526 const char *bounds_str;
14f9c5c9
AS
11527 int n;
11528
14f9c5c9
AS
11529 subtype_info += 5;
11530 bounds_str = strchr (subtype_info, '_');
11531 n = 1;
11532
d2e4a39e 11533 if (*subtype_info == 'L')
dda83cd7
SM
11534 {
11535 if (!ada_scan_number (bounds_str, n, &L, &n)
11536 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11537 return raw_type;
11538 if (bounds_str[n] == '_')
11539 n += 2;
11540 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11541 n += 1;
11542 subtype_info += 1;
11543 }
d2e4a39e 11544 else
dda83cd7 11545 {
5f9febe0
TT
11546 std::string name_buf = std::string (name, prefix_len) + "___L";
11547 if (!get_int_var_value (name_buf.c_str (), L))
dda83cd7
SM
11548 {
11549 lim_warning (_("Unknown lower bound, using 1."));
11550 L = 1;
11551 }
11552 }
14f9c5c9 11553
d2e4a39e 11554 if (*subtype_info == 'U')
dda83cd7
SM
11555 {
11556 if (!ada_scan_number (bounds_str, n, &U, &n)
11557 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11558 return raw_type;
11559 }
d2e4a39e 11560 else
dda83cd7 11561 {
5f9febe0
TT
11562 std::string name_buf = std::string (name, prefix_len) + "___U";
11563 if (!get_int_var_value (name_buf.c_str (), U))
dda83cd7
SM
11564 {
11565 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11566 U = L;
11567 }
11568 }
14f9c5c9 11569
9fa83a7a 11570 type = create_static_range_type (type_allocator (raw_type).new_type (),
0c9c3474 11571 base_type, L, U);
f5a91472 11572 /* create_static_range_type alters the resulting type's length
dda83cd7
SM
11573 to match the size of the base_type, which is not what we want.
11574 Set it back to the original range type's length. */
df86565b 11575 type->set_length (raw_type->length ());
d0e39ea2 11576 type->set_name (name);
14f9c5c9
AS
11577 return type;
11578 }
11579}
11580
4c4b4cd2
PH
11581/* True iff NAME is the name of a range type. */
11582
14f9c5c9 11583int
d2e4a39e 11584ada_is_range_type_name (const char *name)
14f9c5c9
AS
11585{
11586 return (name != NULL && strstr (name, "___XD"));
d2e4a39e 11587}
14f9c5c9 11588\f
d2e4a39e 11589
dda83cd7 11590 /* Modular types */
4c4b4cd2
PH
11591
11592/* True iff TYPE is an Ada modular type. */
14f9c5c9 11593
14f9c5c9 11594int
d2e4a39e 11595ada_is_modular_type (struct type *type)
14f9c5c9 11596{
18af8284 11597 struct type *subranged_type = get_base_type (type);
14f9c5c9 11598
78134374 11599 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
dda83cd7
SM
11600 && subranged_type->code () == TYPE_CODE_INT
11601 && subranged_type->is_unsigned ());
14f9c5c9
AS
11602}
11603
4c4b4cd2
PH
11604/* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11605
61ee279c 11606ULONGEST
0056e4d5 11607ada_modulus (struct type *type)
14f9c5c9 11608{
5e500d33
SM
11609 const dynamic_prop &high = type->bounds ()->high;
11610
11611 if (high.kind () == PROP_CONST)
11612 return (ULONGEST) high.const_val () + 1;
11613
11614 /* If TYPE is unresolved, the high bound might be a location list. Return
11615 0, for lack of a better value to return. */
11616 return 0;
14f9c5c9 11617}
d2e4a39e 11618\f
f7f9143b
JB
11619
11620/* Ada exception catchpoint support:
11621 ---------------------------------
11622
11623 We support 3 kinds of exception catchpoints:
11624 . catchpoints on Ada exceptions
11625 . catchpoints on unhandled Ada exceptions
11626 . catchpoints on failed assertions
11627
11628 Exceptions raised during failed assertions, or unhandled exceptions
11629 could perfectly be caught with the general catchpoint on Ada exceptions.
11630 However, we can easily differentiate these two special cases, and having
11631 the option to distinguish these two cases from the rest can be useful
11632 to zero-in on certain situations.
11633
11634 Exception catchpoints are a specialized form of breakpoint,
11635 since they rely on inserting breakpoints inside known routines
11636 of the GNAT runtime. The implementation therefore uses a standard
11637 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11638 of breakpoint_ops.
11639
0259addd
JB
11640 Support in the runtime for exception catchpoints have been changed
11641 a few times already, and these changes affect the implementation
11642 of these catchpoints. In order to be able to support several
11643 variants of the runtime, we use a sniffer that will determine
28010a5d 11644 the runtime variant used by the program being debugged. */
f7f9143b 11645
82eacd52
JB
11646/* Ada's standard exceptions.
11647
11648 The Ada 83 standard also defined Numeric_Error. But there so many
11649 situations where it was unclear from the Ada 83 Reference Manual
11650 (RM) whether Constraint_Error or Numeric_Error should be raised,
11651 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11652 Interpretation saying that anytime the RM says that Numeric_Error
11653 should be raised, the implementation may raise Constraint_Error.
11654 Ada 95 went one step further and pretty much removed Numeric_Error
11655 from the list of standard exceptions (it made it a renaming of
11656 Constraint_Error, to help preserve compatibility when compiling
11657 an Ada83 compiler). As such, we do not include Numeric_Error from
11658 this list of standard exceptions. */
3d0b0fa3 11659
27087b7f 11660static const char * const standard_exc[] = {
3d0b0fa3
JB
11661 "constraint_error",
11662 "program_error",
11663 "storage_error",
11664 "tasking_error"
11665};
11666
0259addd
JB
11667typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11668
11669/* A structure that describes how to support exception catchpoints
11670 for a given executable. */
11671
11672struct exception_support_info
11673{
11674 /* The name of the symbol to break on in order to insert
11675 a catchpoint on exceptions. */
11676 const char *catch_exception_sym;
11677
11678 /* The name of the symbol to break on in order to insert
11679 a catchpoint on unhandled exceptions. */
11680 const char *catch_exception_unhandled_sym;
11681
11682 /* The name of the symbol to break on in order to insert
11683 a catchpoint on failed assertions. */
11684 const char *catch_assert_sym;
11685
9f757bf7
XR
11686 /* The name of the symbol to break on in order to insert
11687 a catchpoint on exception handling. */
11688 const char *catch_handlers_sym;
11689
0259addd
JB
11690 /* Assuming that the inferior just triggered an unhandled exception
11691 catchpoint, this function is responsible for returning the address
11692 in inferior memory where the name of that exception is stored.
11693 Return zero if the address could not be computed. */
11694 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11695};
11696
11697static CORE_ADDR ada_unhandled_exception_name_addr (void);
11698static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11699
11700/* The following exception support info structure describes how to
11701 implement exception catchpoints with the latest version of the
ca683e3a 11702 Ada runtime (as of 2019-08-??). */
0259addd
JB
11703
11704static const struct exception_support_info default_exception_support_info =
ca683e3a
AO
11705{
11706 "__gnat_debug_raise_exception", /* catch_exception_sym */
11707 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11708 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11709 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11710 ada_unhandled_exception_name_addr
11711};
11712
11713/* The following exception support info structure describes how to
11714 implement exception catchpoints with an earlier version of the
11715 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11716
11717static const struct exception_support_info exception_support_info_v0 =
0259addd
JB
11718{
11719 "__gnat_debug_raise_exception", /* catch_exception_sym */
11720 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11721 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
9f757bf7 11722 "__gnat_begin_handler", /* catch_handlers_sym */
0259addd
JB
11723 ada_unhandled_exception_name_addr
11724};
11725
11726/* The following exception support info structure describes how to
11727 implement exception catchpoints with a slightly older version
11728 of the Ada runtime. */
11729
11730static const struct exception_support_info exception_support_info_fallback =
11731{
11732 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11733 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11734 "system__assertions__raise_assert_failure", /* catch_assert_sym */
9f757bf7 11735 "__gnat_begin_handler", /* catch_handlers_sym */
0259addd
JB
11736 ada_unhandled_exception_name_addr_from_raise
11737};
11738
f17011e0
JB
11739/* Return nonzero if we can detect the exception support routines
11740 described in EINFO.
11741
11742 This function errors out if an abnormal situation is detected
11743 (for instance, if we find the exception support routines, but
11744 that support is found to be incomplete). */
11745
11746static int
11747ada_has_this_exception_support (const struct exception_support_info *einfo)
11748{
11749 struct symbol *sym;
11750
11751 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11752 that should be compiled with debugging information. As a result, we
11753 expect to find that symbol in the symtabs. */
11754
11755 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11756 if (sym == NULL)
a6af7abe
JB
11757 {
11758 /* Perhaps we did not find our symbol because the Ada runtime was
11759 compiled without debugging info, or simply stripped of it.
11760 It happens on some GNU/Linux distributions for instance, where
11761 users have to install a separate debug package in order to get
11762 the runtime's debugging info. In that situation, let the user
11763 know why we cannot insert an Ada exception catchpoint.
11764
11765 Note: Just for the purpose of inserting our Ada exception
11766 catchpoint, we could rely purely on the associated minimal symbol.
11767 But we would be operating in degraded mode anyway, since we are
11768 still lacking the debugging info needed later on to extract
11769 the name of the exception being raised (this name is printed in
11770 the catchpoint message, and is also used when trying to catch
11771 a specific exception). We do not handle this case for now. */
3b7344d5 11772 struct bound_minimal_symbol msym
1c8e84b0
JB
11773 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11774
60f62e2b 11775 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
a6af7abe
JB
11776 error (_("Your Ada runtime appears to be missing some debugging "
11777 "information.\nCannot insert Ada exception catchpoint "
11778 "in this configuration."));
11779
11780 return 0;
11781 }
f17011e0
JB
11782
11783 /* Make sure that the symbol we found corresponds to a function. */
11784
66d7f48f 11785 if (sym->aclass () != LOC_BLOCK)
fe043185
TT
11786 error (_("Symbol \"%s\" is not a function (class = %d)"),
11787 sym->linkage_name (), sym->aclass ());
ca683e3a
AO
11788
11789 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11790 if (sym == NULL)
11791 {
11792 struct bound_minimal_symbol msym
11793 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11794
60f62e2b 11795 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
ca683e3a
AO
11796 error (_("Your Ada runtime appears to be missing some debugging "
11797 "information.\nCannot insert Ada exception catchpoint "
11798 "in this configuration."));
11799
11800 return 0;
11801 }
11802
11803 /* Make sure that the symbol we found corresponds to a function. */
11804
66d7f48f 11805 if (sym->aclass () != LOC_BLOCK)
fe043185
TT
11806 error (_("Symbol \"%s\" is not a function (class = %d)"),
11807 sym->linkage_name (), sym->aclass ());
f17011e0
JB
11808
11809 return 1;
11810}
11811
0259addd
JB
11812/* Inspect the Ada runtime and determine which exception info structure
11813 should be used to provide support for exception catchpoints.
11814
3eecfa55
JB
11815 This function will always set the per-inferior exception_info,
11816 or raise an error. */
0259addd
JB
11817
11818static void
11819ada_exception_support_info_sniffer (void)
11820{
3eecfa55 11821 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
0259addd
JB
11822
11823 /* If the exception info is already known, then no need to recompute it. */
3eecfa55 11824 if (data->exception_info != NULL)
0259addd
JB
11825 return;
11826
11827 /* Check the latest (default) exception support info. */
f17011e0 11828 if (ada_has_this_exception_support (&default_exception_support_info))
0259addd 11829 {
3eecfa55 11830 data->exception_info = &default_exception_support_info;
0259addd
JB
11831 return;
11832 }
11833
ca683e3a
AO
11834 /* Try the v0 exception suport info. */
11835 if (ada_has_this_exception_support (&exception_support_info_v0))
11836 {
11837 data->exception_info = &exception_support_info_v0;
11838 return;
11839 }
11840
0259addd 11841 /* Try our fallback exception suport info. */
f17011e0 11842 if (ada_has_this_exception_support (&exception_support_info_fallback))
0259addd 11843 {
3eecfa55 11844 data->exception_info = &exception_support_info_fallback;
0259addd
JB
11845 return;
11846 }
11847
11848 /* Sometimes, it is normal for us to not be able to find the routine
11849 we are looking for. This happens when the program is linked with
11850 the shared version of the GNAT runtime, and the program has not been
11851 started yet. Inform the user of these two possible causes if
11852 applicable. */
11853
ccefe4c4 11854 if (ada_update_initial_language (language_unknown) != language_ada)
0259addd
JB
11855 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
11856
11857 /* If the symbol does not exist, then check that the program is
11858 already started, to make sure that shared libraries have been
11859 loaded. If it is not started, this may mean that the symbol is
11860 in a shared library. */
11861
e99b03dc 11862 if (inferior_ptid.pid () == 0)
0259addd
JB
11863 error (_("Unable to insert catchpoint. Try to start the program first."));
11864
11865 /* At this point, we know that we are debugging an Ada program and
11866 that the inferior has been started, but we still are not able to
0963b4bd 11867 find the run-time symbols. That can mean that we are in
0259addd
JB
11868 configurable run time mode, or that a-except as been optimized
11869 out by the linker... In any case, at this point it is not worth
11870 supporting this feature. */
11871
7dda8cff 11872 error (_("Cannot insert Ada exception catchpoints in this configuration."));
0259addd
JB
11873}
11874
f7f9143b
JB
11875/* True iff FRAME is very likely to be that of a function that is
11876 part of the runtime system. This is all very heuristic, but is
11877 intended to be used as advice as to what frames are uninteresting
11878 to most users. */
11879
11880static int
bd2b40ac 11881is_known_support_routine (frame_info_ptr frame)
f7f9143b 11882{
692465f1 11883 enum language func_lang;
f7f9143b 11884 int i;
f35a17b5 11885 const char *fullname;
f7f9143b 11886
4ed6b5be
JB
11887 /* If this code does not have any debugging information (no symtab),
11888 This cannot be any user code. */
f7f9143b 11889
51abb421 11890 symtab_and_line sal = find_frame_sal (frame);
f7f9143b
JB
11891 if (sal.symtab == NULL)
11892 return 1;
11893
4ed6b5be
JB
11894 /* If there is a symtab, but the associated source file cannot be
11895 located, then assume this is not user code: Selecting a frame
11896 for which we cannot display the code would not be very helpful
11897 for the user. This should also take care of case such as VxWorks
11898 where the kernel has some debugging info provided for a few units. */
f7f9143b 11899
f35a17b5
JK
11900 fullname = symtab_to_fullname (sal.symtab);
11901 if (access (fullname, R_OK) != 0)
f7f9143b
JB
11902 return 1;
11903
85102364 11904 /* Check the unit filename against the Ada runtime file naming.
4ed6b5be
JB
11905 We also check the name of the objfile against the name of some
11906 known system libraries that sometimes come with debugging info
11907 too. */
11908
f7f9143b
JB
11909 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11910 {
11911 re_comp (known_runtime_file_name_patterns[i]);
f69c91ad 11912 if (re_exec (lbasename (sal.symtab->filename)))
dda83cd7 11913 return 1;
3c86fae3
SM
11914 if (sal.symtab->compunit ()->objfile () != NULL
11915 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
dda83cd7 11916 return 1;
f7f9143b
JB
11917 }
11918
4ed6b5be 11919 /* Check whether the function is a GNAT-generated entity. */
f7f9143b 11920
c6dc63a1
TT
11921 gdb::unique_xmalloc_ptr<char> func_name
11922 = find_frame_funname (frame, &func_lang, NULL);
f7f9143b
JB
11923 if (func_name == NULL)
11924 return 1;
11925
11926 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11927 {
11928 re_comp (known_auxiliary_function_name_patterns[i]);
c6dc63a1
TT
11929 if (re_exec (func_name.get ()))
11930 return 1;
f7f9143b
JB
11931 }
11932
11933 return 0;
11934}
11935
11936/* Find the first frame that contains debugging information and that is not
11937 part of the Ada run-time, starting from FI and moving upward. */
11938
0ef643c8 11939void
bd2b40ac 11940ada_find_printable_frame (frame_info_ptr fi)
f7f9143b
JB
11941{
11942 for (; fi != NULL; fi = get_prev_frame (fi))
11943 {
11944 if (!is_known_support_routine (fi))
dda83cd7
SM
11945 {
11946 select_frame (fi);
11947 break;
11948 }
f7f9143b
JB
11949 }
11950
11951}
11952
11953/* Assuming that the inferior just triggered an unhandled exception
11954 catchpoint, return the address in inferior memory where the name
11955 of the exception is stored.
11956
11957 Return zero if the address could not be computed. */
11958
11959static CORE_ADDR
11960ada_unhandled_exception_name_addr (void)
0259addd
JB
11961{
11962 return parse_and_eval_address ("e.full_name");
11963}
11964
11965/* Same as ada_unhandled_exception_name_addr, except that this function
11966 should be used when the inferior uses an older version of the runtime,
11967 where the exception name needs to be extracted from a specific frame
11968 several frames up in the callstack. */
11969
11970static CORE_ADDR
11971ada_unhandled_exception_name_addr_from_raise (void)
f7f9143b
JB
11972{
11973 int frame_level;
bd2b40ac 11974 frame_info_ptr fi;
3eecfa55 11975 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
f7f9143b
JB
11976
11977 /* To determine the name of this exception, we need to select
11978 the frame corresponding to RAISE_SYM_NAME. This frame is
11979 at least 3 levels up, so we simply skip the first 3 frames
11980 without checking the name of their associated function. */
11981 fi = get_current_frame ();
11982 for (frame_level = 0; frame_level < 3; frame_level += 1)
11983 if (fi != NULL)
11984 fi = get_prev_frame (fi);
11985
11986 while (fi != NULL)
11987 {
692465f1
JB
11988 enum language func_lang;
11989
c6dc63a1
TT
11990 gdb::unique_xmalloc_ptr<char> func_name
11991 = find_frame_funname (fi, &func_lang, NULL);
55b87a52
KS
11992 if (func_name != NULL)
11993 {
dda83cd7 11994 if (strcmp (func_name.get (),
55b87a52
KS
11995 data->exception_info->catch_exception_sym) == 0)
11996 break; /* We found the frame we were looking for... */
55b87a52 11997 }
fb44b1a7 11998 fi = get_prev_frame (fi);
f7f9143b
JB
11999 }
12000
12001 if (fi == NULL)
12002 return 0;
12003
12004 select_frame (fi);
12005 return parse_and_eval_address ("id.full_name");
12006}
12007
12008/* Assuming the inferior just triggered an Ada exception catchpoint
12009 (of any type), return the address in inferior memory where the name
12010 of the exception is stored, if applicable.
12011
45db7c09
PA
12012 Assumes the selected frame is the current frame.
12013
f7f9143b
JB
12014 Return zero if the address could not be computed, or if not relevant. */
12015
12016static CORE_ADDR
7bd86313 12017ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
f7f9143b 12018{
3eecfa55
JB
12019 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12020
f7f9143b
JB
12021 switch (ex)
12022 {
761269c8 12023 case ada_catch_exception:
dda83cd7
SM
12024 return (parse_and_eval_address ("e.full_name"));
12025 break;
f7f9143b 12026
761269c8 12027 case ada_catch_exception_unhandled:
dda83cd7
SM
12028 return data->exception_info->unhandled_exception_name_addr ();
12029 break;
9f757bf7
XR
12030
12031 case ada_catch_handlers:
dda83cd7 12032 return 0; /* The runtimes does not provide access to the exception
9f757bf7 12033 name. */
dda83cd7 12034 break;
9f757bf7 12035
761269c8 12036 case ada_catch_assert:
dda83cd7
SM
12037 return 0; /* Exception name is not relevant in this case. */
12038 break;
f7f9143b
JB
12039
12040 default:
f34652de 12041 internal_error (_("unexpected catchpoint type"));
dda83cd7 12042 break;
f7f9143b
JB
12043 }
12044
12045 return 0; /* Should never be reached. */
12046}
12047
e547c119
JB
12048/* Assuming the inferior is stopped at an exception catchpoint,
12049 return the message which was associated to the exception, if
12050 available. Return NULL if the message could not be retrieved.
12051
e547c119
JB
12052 Note: The exception message can be associated to an exception
12053 either through the use of the Raise_Exception function, or
12054 more simply (Ada 2005 and later), via:
12055
12056 raise Exception_Name with "exception message";
12057
12058 */
12059
6f46ac85 12060static gdb::unique_xmalloc_ptr<char>
e547c119
JB
12061ada_exception_message_1 (void)
12062{
12063 struct value *e_msg_val;
e547c119 12064 int e_msg_len;
e547c119
JB
12065
12066 /* For runtimes that support this feature, the exception message
12067 is passed as an unbounded string argument called "message". */
12068 e_msg_val = parse_and_eval ("message");
12069 if (e_msg_val == NULL)
12070 return NULL; /* Exception message not supported. */
12071
12072 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12073 gdb_assert (e_msg_val != NULL);
d0c97917 12074 e_msg_len = e_msg_val->type ()->length ();
e547c119
JB
12075
12076 /* If the message string is empty, then treat it as if there was
12077 no exception message. */
12078 if (e_msg_len <= 0)
12079 return NULL;
12080
15f3b077 12081 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
9feb2d07 12082 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
15f3b077
TT
12083 e_msg_len);
12084 e_msg.get ()[e_msg_len] = '\0';
12085
12086 return e_msg;
e547c119
JB
12087}
12088
12089/* Same as ada_exception_message_1, except that all exceptions are
12090 contained here (returning NULL instead). */
12091
6f46ac85 12092static gdb::unique_xmalloc_ptr<char>
e547c119
JB
12093ada_exception_message (void)
12094{
6f46ac85 12095 gdb::unique_xmalloc_ptr<char> e_msg;
e547c119 12096
a70b8144 12097 try
e547c119
JB
12098 {
12099 e_msg = ada_exception_message_1 ();
12100 }
230d2906 12101 catch (const gdb_exception_error &e)
e547c119 12102 {
6f46ac85 12103 e_msg.reset (nullptr);
e547c119 12104 }
e547c119
JB
12105
12106 return e_msg;
12107}
12108
f7f9143b
JB
12109/* Same as ada_exception_name_addr_1, except that it intercepts and contains
12110 any error that ada_exception_name_addr_1 might cause to be thrown.
12111 When an error is intercepted, a warning with the error message is printed,
12112 and zero is returned. */
12113
12114static CORE_ADDR
7bd86313 12115ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
f7f9143b 12116{
f7f9143b
JB
12117 CORE_ADDR result = 0;
12118
a70b8144 12119 try
f7f9143b 12120 {
7bd86313 12121 result = ada_exception_name_addr_1 (ex);
f7f9143b
JB
12122 }
12123
230d2906 12124 catch (const gdb_exception_error &e)
f7f9143b 12125 {
3d6e9d23 12126 warning (_("failed to get exception name: %s"), e.what ());
f7f9143b
JB
12127 return 0;
12128 }
12129
12130 return result;
12131}
12132
cb7de75e 12133static std::string ada_exception_catchpoint_cond_string
9f757bf7
XR
12134 (const char *excep_string,
12135 enum ada_exception_catchpoint_kind ex);
28010a5d
PA
12136
12137/* Ada catchpoints.
12138
12139 In the case of catchpoints on Ada exceptions, the catchpoint will
12140 stop the target on every exception the program throws. When a user
12141 specifies the name of a specific exception, we translate this
12142 request into a condition expression (in text form), and then parse
12143 it into an expression stored in each of the catchpoint's locations.
12144 We then use this condition to check whether the exception that was
12145 raised is the one the user is interested in. If not, then the
12146 target is resumed again. We store the name of the requested
12147 exception, in order to be able to re-set the condition expression
12148 when symbols change. */
12149
c1fc2657 12150/* An instance of this type is used to represent an Ada catchpoint. */
28010a5d 12151
74421c0b 12152struct ada_catchpoint : public code_breakpoint
28010a5d 12153{
73063f51 12154 ada_catchpoint (struct gdbarch *gdbarch_,
bd21b6c9
PA
12155 enum ada_exception_catchpoint_kind kind,
12156 struct symtab_and_line sal,
12157 const char *addr_string_,
12158 bool tempflag,
12159 bool enabled,
12160 bool from_tty)
74421c0b 12161 : code_breakpoint (gdbarch_, bp_catchpoint),
73063f51 12162 m_kind (kind)
37f6a7f4 12163 {
bd21b6c9
PA
12164 add_location (sal);
12165
74421c0b 12166 /* Unlike most code_breakpoint types, Ada catchpoints are
bd21b6c9
PA
12167 pspace-specific. */
12168 gdb_assert (sal.pspace != nullptr);
12169 this->pspace = sal.pspace;
12170
12171 if (from_tty)
12172 {
12173 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12174 if (!loc_gdbarch)
12175 loc_gdbarch = gdbarch;
12176
12177 describe_other_breakpoints (loc_gdbarch,
12178 sal.pspace, sal.pc, sal.section, -1);
12179 /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12180 version for exception catchpoints, because two catchpoints
12181 used for different exception names will use the same address.
12182 In this case, a "breakpoint ... also set at..." warning is
12183 unproductive. Besides, the warning phrasing is also a bit
12184 inappropriate, we should use the word catchpoint, and tell
12185 the user what type of catchpoint it is. The above is good
12186 enough for now, though. */
12187 }
12188
12189 enable_state = enabled ? bp_enabled : bp_disabled;
12190 disposition = tempflag ? disp_del : disp_donttouch;
264f9890
PA
12191 locspec = string_to_location_spec (&addr_string_,
12192 language_def (language_ada));
bd21b6c9 12193 language = language_ada;
37f6a7f4
TT
12194 }
12195
ae72050b
TT
12196 struct bp_location *allocate_location () override;
12197 void re_set () override;
12198 void check_status (struct bpstat *bs) override;
7bd86313 12199 enum print_stop_action print_it (const bpstat *bs) const override;
a67bcaba 12200 bool print_one (bp_location **) const override;
b713485d 12201 void print_mention () const override;
4d1ae558 12202 void print_recreate (struct ui_file *fp) const override;
ae72050b 12203
28010a5d 12204 /* The name of the specific exception the user specified. */
bc18fbb5 12205 std::string excep_string;
37f6a7f4
TT
12206
12207 /* What kind of catchpoint this is. */
12208 enum ada_exception_catchpoint_kind m_kind;
28010a5d
PA
12209};
12210
8cd0bf5e
PA
12211/* An instance of this type is used to represent an Ada catchpoint
12212 breakpoint location. */
12213
12214class ada_catchpoint_location : public bp_location
12215{
12216public:
12217 explicit ada_catchpoint_location (ada_catchpoint *owner)
12218 : bp_location (owner, bp_loc_software_breakpoint)
12219 {}
12220
12221 /* The condition that checks whether the exception that was raised
12222 is the specific exception the user specified on catchpoint
12223 creation. */
12224 expression_up excep_cond_expr;
12225};
12226
28010a5d
PA
12227/* Parse the exception condition string in the context of each of the
12228 catchpoint's locations, and store them for later evaluation. */
12229
12230static void
9f757bf7 12231create_excep_cond_exprs (struct ada_catchpoint *c,
dda83cd7 12232 enum ada_exception_catchpoint_kind ex)
28010a5d 12233{
28010a5d 12234 /* Nothing to do if there's no specific exception to catch. */
bc18fbb5 12235 if (c->excep_string.empty ())
28010a5d
PA
12236 return;
12237
12238 /* Same if there are no locations... */
c1fc2657 12239 if (c->loc == NULL)
28010a5d
PA
12240 return;
12241
fccf9de1
TT
12242 /* Compute the condition expression in text form, from the specific
12243 expection we want to catch. */
12244 std::string cond_string
12245 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
28010a5d 12246
fccf9de1
TT
12247 /* Iterate over all the catchpoint's locations, and parse an
12248 expression for each. */
40cb8ca5 12249 for (bp_location *bl : c->locations ())
28010a5d
PA
12250 {
12251 struct ada_catchpoint_location *ada_loc
fccf9de1 12252 = (struct ada_catchpoint_location *) bl;
4d01a485 12253 expression_up exp;
28010a5d 12254
fccf9de1 12255 if (!bl->shlib_disabled)
28010a5d 12256 {
bbc13ae3 12257 const char *s;
28010a5d 12258
cb7de75e 12259 s = cond_string.c_str ();
a70b8144 12260 try
28010a5d 12261 {
fccf9de1
TT
12262 exp = parse_exp_1 (&s, bl->address,
12263 block_for_pc (bl->address),
036e657b 12264 0);
28010a5d 12265 }
230d2906 12266 catch (const gdb_exception_error &e)
849f2b52
JB
12267 {
12268 warning (_("failed to reevaluate internal exception condition "
12269 "for catchpoint %d: %s"),
3d6e9d23 12270 c->number, e.what ());
849f2b52 12271 }
28010a5d
PA
12272 }
12273
b22e99fd 12274 ada_loc->excep_cond_expr = std::move (exp);
28010a5d 12275 }
28010a5d
PA
12276}
12277
ae72050b
TT
12278/* Implement the ALLOCATE_LOCATION method in the structure for all
12279 exception catchpoint kinds. */
28010a5d 12280
ae72050b
TT
12281struct bp_location *
12282ada_catchpoint::allocate_location ()
28010a5d 12283{
ae72050b 12284 return new ada_catchpoint_location (this);
28010a5d
PA
12285}
12286
ae72050b
TT
12287/* Implement the RE_SET method in the structure for all exception
12288 catchpoint kinds. */
28010a5d 12289
ae72050b
TT
12290void
12291ada_catchpoint::re_set ()
28010a5d 12292{
28010a5d
PA
12293 /* Call the base class's method. This updates the catchpoint's
12294 locations. */
74421c0b 12295 this->code_breakpoint::re_set ();
28010a5d
PA
12296
12297 /* Reparse the exception conditional expressions. One for each
12298 location. */
ae72050b 12299 create_excep_cond_exprs (this, m_kind);
28010a5d
PA
12300}
12301
12302/* Returns true if we should stop for this breakpoint hit. If the
12303 user specified a specific exception, we only want to cause a stop
12304 if the program thrown that exception. */
12305
7ebaa5f7 12306static bool
28010a5d
PA
12307should_stop_exception (const struct bp_location *bl)
12308{
12309 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
12310 const struct ada_catchpoint_location *ada_loc
12311 = (const struct ada_catchpoint_location *) bl;
7ebaa5f7 12312 bool stop;
28010a5d 12313
37f6a7f4
TT
12314 struct internalvar *var = lookup_internalvar ("_ada_exception");
12315 if (c->m_kind == ada_catch_assert)
12316 clear_internalvar (var);
12317 else
12318 {
12319 try
12320 {
12321 const char *expr;
12322
12323 if (c->m_kind == ada_catch_handlers)
12324 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12325 ".all.occurrence.id");
12326 else
12327 expr = "e";
12328
12329 struct value *exc = parse_and_eval (expr);
12330 set_internalvar (var, exc);
12331 }
12332 catch (const gdb_exception_error &ex)
12333 {
12334 clear_internalvar (var);
12335 }
12336 }
12337
28010a5d 12338 /* With no specific exception, should always stop. */
bc18fbb5 12339 if (c->excep_string.empty ())
7ebaa5f7 12340 return true;
28010a5d
PA
12341
12342 if (ada_loc->excep_cond_expr == NULL)
12343 {
12344 /* We will have a NULL expression if back when we were creating
12345 the expressions, this location's had failed to parse. */
7ebaa5f7 12346 return true;
28010a5d
PA
12347 }
12348
7ebaa5f7 12349 stop = true;
a70b8144 12350 try
28010a5d 12351 {
65558ca5 12352 scoped_value_mark mark;
4d01a485 12353 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
28010a5d 12354 }
b1ffd112 12355 catch (const gdb_exception_error &ex)
492d29ea
PA
12356 {
12357 exception_fprintf (gdb_stderr, ex,
12358 _("Error in testing exception condition:\n"));
12359 }
492d29ea 12360
28010a5d
PA
12361 return stop;
12362}
12363
ae72050b
TT
12364/* Implement the CHECK_STATUS method in the structure for all
12365 exception catchpoint kinds. */
28010a5d 12366
ae72050b
TT
12367void
12368ada_catchpoint::check_status (bpstat *bs)
28010a5d 12369{
b6433ede 12370 bs->stop = should_stop_exception (bs->bp_location_at.get ());
28010a5d
PA
12371}
12372
ae72050b
TT
12373/* Implement the PRINT_IT method in the structure for all exception
12374 catchpoint kinds. */
f7f9143b 12375
ae72050b 12376enum print_stop_action
7bd86313 12377ada_catchpoint::print_it (const bpstat *bs) const
f7f9143b 12378{
79a45e25 12379 struct ui_out *uiout = current_uiout;
348d480f 12380
ae72050b 12381 annotate_catchpoint (number);
f7f9143b 12382
112e8700 12383 if (uiout->is_mi_like_p ())
f7f9143b 12384 {
112e8700 12385 uiout->field_string ("reason",
956a9fb9 12386 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
ae72050b 12387 uiout->field_string ("disp", bpdisp_text (disposition));
f7f9143b
JB
12388 }
12389
ae72050b 12390 uiout->text (disposition == disp_del
112e8700 12391 ? "\nTemporary catchpoint " : "\nCatchpoint ");
78805ff8 12392 print_num_locno (bs, uiout);
112e8700 12393 uiout->text (", ");
f7f9143b 12394
45db7c09
PA
12395 /* ada_exception_name_addr relies on the selected frame being the
12396 current frame. Need to do this here because this function may be
12397 called more than once when printing a stop, and below, we'll
12398 select the first frame past the Ada run-time (see
12399 ada_find_printable_frame). */
12400 select_frame (get_current_frame ());
12401
ae72050b 12402 switch (m_kind)
f7f9143b 12403 {
761269c8
JB
12404 case ada_catch_exception:
12405 case ada_catch_exception_unhandled:
9f757bf7 12406 case ada_catch_handlers:
956a9fb9 12407 {
7bd86313 12408 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
956a9fb9
JB
12409 char exception_name[256];
12410
12411 if (addr != 0)
12412 {
c714b426
PA
12413 read_memory (addr, (gdb_byte *) exception_name,
12414 sizeof (exception_name) - 1);
956a9fb9
JB
12415 exception_name [sizeof (exception_name) - 1] = '\0';
12416 }
12417 else
12418 {
12419 /* For some reason, we were unable to read the exception
12420 name. This could happen if the Runtime was compiled
12421 without debugging info, for instance. In that case,
12422 just replace the exception name by the generic string
12423 "exception" - it will read as "an exception" in the
12424 notification we are about to print. */
967cff16 12425 memcpy (exception_name, "exception", sizeof ("exception"));
956a9fb9
JB
12426 }
12427 /* In the case of unhandled exception breakpoints, we print
12428 the exception name as "unhandled EXCEPTION_NAME", to make
12429 it clearer to the user which kind of catchpoint just got
12430 hit. We used ui_out_text to make sure that this extra
12431 info does not pollute the exception name in the MI case. */
ae72050b 12432 if (m_kind == ada_catch_exception_unhandled)
112e8700
SM
12433 uiout->text ("unhandled ");
12434 uiout->field_string ("exception-name", exception_name);
956a9fb9
JB
12435 }
12436 break;
761269c8 12437 case ada_catch_assert:
956a9fb9
JB
12438 /* In this case, the name of the exception is not really
12439 important. Just print "failed assertion" to make it clearer
12440 that his program just hit an assertion-failure catchpoint.
12441 We used ui_out_text because this info does not belong in
12442 the MI output. */
112e8700 12443 uiout->text ("failed assertion");
956a9fb9 12444 break;
f7f9143b 12445 }
e547c119 12446
6f46ac85 12447 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
e547c119
JB
12448 if (exception_message != NULL)
12449 {
e547c119 12450 uiout->text (" (");
6f46ac85 12451 uiout->field_string ("exception-message", exception_message.get ());
e547c119 12452 uiout->text (")");
e547c119
JB
12453 }
12454
112e8700 12455 uiout->text (" at ");
956a9fb9 12456 ada_find_printable_frame (get_current_frame ());
f7f9143b
JB
12457
12458 return PRINT_SRC_AND_LOC;
12459}
12460
ae72050b
TT
12461/* Implement the PRINT_ONE method in the structure for all exception
12462 catchpoint kinds. */
f7f9143b 12463
ae72050b 12464bool
a67bcaba 12465ada_catchpoint::print_one (bp_location **last_loc) const
f7f9143b 12466{
79a45e25 12467 struct ui_out *uiout = current_uiout;
79a45b7d
TT
12468 struct value_print_options opts;
12469
12470 get_user_print_options (&opts);
f06f1252 12471
79a45b7d 12472 if (opts.addressprint)
f06f1252 12473 uiout->field_skip ("addr");
f7f9143b
JB
12474
12475 annotate_field (5);
ae72050b 12476 switch (m_kind)
f7f9143b 12477 {
761269c8 12478 case ada_catch_exception:
ae72050b 12479 if (!excep_string.empty ())
dda83cd7 12480 {
bc18fbb5 12481 std::string msg = string_printf (_("`%s' Ada exception"),
ae72050b 12482 excep_string.c_str ());
28010a5d 12483
dda83cd7
SM
12484 uiout->field_string ("what", msg);
12485 }
12486 else
12487 uiout->field_string ("what", "all Ada exceptions");
12488
12489 break;
f7f9143b 12490
761269c8 12491 case ada_catch_exception_unhandled:
dda83cd7
SM
12492 uiout->field_string ("what", "unhandled Ada exceptions");
12493 break;
f7f9143b 12494
9f757bf7 12495 case ada_catch_handlers:
ae72050b 12496 if (!excep_string.empty ())
dda83cd7 12497 {
9f757bf7
XR
12498 uiout->field_fmt ("what",
12499 _("`%s' Ada exception handlers"),
ae72050b 12500 excep_string.c_str ());
dda83cd7
SM
12501 }
12502 else
9f757bf7 12503 uiout->field_string ("what", "all Ada exceptions handlers");
dda83cd7 12504 break;
9f757bf7 12505
761269c8 12506 case ada_catch_assert:
dda83cd7
SM
12507 uiout->field_string ("what", "failed Ada assertions");
12508 break;
f7f9143b
JB
12509
12510 default:
f34652de 12511 internal_error (_("unexpected catchpoint type"));
dda83cd7 12512 break;
f7f9143b 12513 }
c01e038b
TT
12514
12515 return true;
f7f9143b
JB
12516}
12517
12518/* Implement the PRINT_MENTION method in the breakpoint_ops structure
12519 for all exception catchpoint kinds. */
12520
ae72050b 12521void
b713485d 12522ada_catchpoint::print_mention () const
f7f9143b 12523{
79a45e25 12524 struct ui_out *uiout = current_uiout;
28010a5d 12525
ae72050b 12526 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
dda83cd7 12527 : _("Catchpoint "));
ae72050b 12528 uiout->field_signed ("bkptno", number);
112e8700 12529 uiout->text (": ");
00eb2c4a 12530
ae72050b 12531 switch (m_kind)
f7f9143b 12532 {
761269c8 12533 case ada_catch_exception:
ae72050b 12534 if (!excep_string.empty ())
00eb2c4a 12535 {
862d101a 12536 std::string info = string_printf (_("`%s' Ada exception"),
ae72050b 12537 excep_string.c_str ());
4915bfdc 12538 uiout->text (info);
00eb2c4a 12539 }
dda83cd7
SM
12540 else
12541 uiout->text (_("all Ada exceptions"));
12542 break;
f7f9143b 12543
761269c8 12544 case ada_catch_exception_unhandled:
dda83cd7
SM
12545 uiout->text (_("unhandled Ada exceptions"));
12546 break;
9f757bf7
XR
12547
12548 case ada_catch_handlers:
ae72050b 12549 if (!excep_string.empty ())
9f757bf7
XR
12550 {
12551 std::string info
12552 = string_printf (_("`%s' Ada exception handlers"),
ae72050b 12553 excep_string.c_str ());
4915bfdc 12554 uiout->text (info);
9f757bf7 12555 }
dda83cd7
SM
12556 else
12557 uiout->text (_("all Ada exceptions handlers"));
12558 break;
9f757bf7 12559
761269c8 12560 case ada_catch_assert:
dda83cd7
SM
12561 uiout->text (_("failed Ada assertions"));
12562 break;
f7f9143b
JB
12563
12564 default:
f34652de 12565 internal_error (_("unexpected catchpoint type"));
dda83cd7 12566 break;
f7f9143b
JB
12567 }
12568}
12569
ae72050b
TT
12570/* Implement the PRINT_RECREATE method in the structure for all
12571 exception catchpoint kinds. */
6149aea9 12572
ae72050b 12573void
4d1ae558 12574ada_catchpoint::print_recreate (struct ui_file *fp) const
6149aea9 12575{
ae72050b 12576 switch (m_kind)
6149aea9 12577 {
761269c8 12578 case ada_catch_exception:
6cb06a8c 12579 gdb_printf (fp, "catch exception");
ae72050b
TT
12580 if (!excep_string.empty ())
12581 gdb_printf (fp, " %s", excep_string.c_str ());
6149aea9
PA
12582 break;
12583
761269c8 12584 case ada_catch_exception_unhandled:
6cb06a8c 12585 gdb_printf (fp, "catch exception unhandled");
6149aea9
PA
12586 break;
12587
9f757bf7 12588 case ada_catch_handlers:
6cb06a8c 12589 gdb_printf (fp, "catch handlers");
9f757bf7
XR
12590 break;
12591
761269c8 12592 case ada_catch_assert:
6cb06a8c 12593 gdb_printf (fp, "catch assert");
6149aea9
PA
12594 break;
12595
12596 default:
f34652de 12597 internal_error (_("unexpected catchpoint type"));
6149aea9 12598 }
04d0163c 12599 print_recreate_thread (fp);
6149aea9
PA
12600}
12601
f06f1252
TT
12602/* See ada-lang.h. */
12603
12604bool
12605is_ada_exception_catchpoint (breakpoint *bp)
12606{
ae72050b 12607 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
f06f1252
TT
12608}
12609
f7f9143b
JB
12610/* Split the arguments specified in a "catch exception" command.
12611 Set EX to the appropriate catchpoint type.
28010a5d 12612 Set EXCEP_STRING to the name of the specific exception if
5845583d 12613 specified by the user.
9f757bf7
XR
12614 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12615 "catch handlers" command. False otherwise.
5845583d
JB
12616 If a condition is found at the end of the arguments, the condition
12617 expression is stored in COND_STRING (memory must be deallocated
12618 after use). Otherwise COND_STRING is set to NULL. */
f7f9143b
JB
12619
12620static void
a121b7c1 12621catch_ada_exception_command_split (const char *args,
9f757bf7 12622 bool is_catch_handlers_cmd,
dda83cd7 12623 enum ada_exception_catchpoint_kind *ex,
bc18fbb5
TT
12624 std::string *excep_string,
12625 std::string *cond_string)
f7f9143b 12626{
bc18fbb5 12627 std::string exception_name;
f7f9143b 12628
bc18fbb5
TT
12629 exception_name = extract_arg (&args);
12630 if (exception_name == "if")
5845583d
JB
12631 {
12632 /* This is not an exception name; this is the start of a condition
12633 expression for a catchpoint on all exceptions. So, "un-get"
12634 this token, and set exception_name to NULL. */
bc18fbb5 12635 exception_name.clear ();
5845583d
JB
12636 args -= 2;
12637 }
f7f9143b 12638
5845583d 12639 /* Check to see if we have a condition. */
f7f9143b 12640
f1735a53 12641 args = skip_spaces (args);
61012eef 12642 if (startswith (args, "if")
5845583d
JB
12643 && (isspace (args[2]) || args[2] == '\0'))
12644 {
12645 args += 2;
f1735a53 12646 args = skip_spaces (args);
5845583d
JB
12647
12648 if (args[0] == '\0')
dda83cd7 12649 error (_("Condition missing after `if' keyword"));
bc18fbb5 12650 *cond_string = args;
5845583d
JB
12651
12652 args += strlen (args);
12653 }
12654
12655 /* Check that we do not have any more arguments. Anything else
12656 is unexpected. */
f7f9143b
JB
12657
12658 if (args[0] != '\0')
12659 error (_("Junk at end of expression"));
12660
9f757bf7
XR
12661 if (is_catch_handlers_cmd)
12662 {
12663 /* Catch handling of exceptions. */
12664 *ex = ada_catch_handlers;
12665 *excep_string = exception_name;
12666 }
bc18fbb5 12667 else if (exception_name.empty ())
f7f9143b
JB
12668 {
12669 /* Catch all exceptions. */
761269c8 12670 *ex = ada_catch_exception;
bc18fbb5 12671 excep_string->clear ();
f7f9143b 12672 }
bc18fbb5 12673 else if (exception_name == "unhandled")
f7f9143b
JB
12674 {
12675 /* Catch unhandled exceptions. */
761269c8 12676 *ex = ada_catch_exception_unhandled;
bc18fbb5 12677 excep_string->clear ();
f7f9143b
JB
12678 }
12679 else
12680 {
12681 /* Catch a specific exception. */
761269c8 12682 *ex = ada_catch_exception;
28010a5d 12683 *excep_string = exception_name;
f7f9143b
JB
12684 }
12685}
12686
12687/* Return the name of the symbol on which we should break in order to
12688 implement a catchpoint of the EX kind. */
12689
12690static const char *
761269c8 12691ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
f7f9143b 12692{
3eecfa55
JB
12693 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12694
12695 gdb_assert (data->exception_info != NULL);
0259addd 12696
f7f9143b
JB
12697 switch (ex)
12698 {
761269c8 12699 case ada_catch_exception:
dda83cd7
SM
12700 return (data->exception_info->catch_exception_sym);
12701 break;
761269c8 12702 case ada_catch_exception_unhandled:
dda83cd7
SM
12703 return (data->exception_info->catch_exception_unhandled_sym);
12704 break;
761269c8 12705 case ada_catch_assert:
dda83cd7
SM
12706 return (data->exception_info->catch_assert_sym);
12707 break;
9f757bf7 12708 case ada_catch_handlers:
dda83cd7
SM
12709 return (data->exception_info->catch_handlers_sym);
12710 break;
f7f9143b 12711 default:
f34652de 12712 internal_error (_("unexpected catchpoint kind (%d)"), ex);
f7f9143b
JB
12713 }
12714}
12715
f7f9143b
JB
12716/* Return the condition that will be used to match the current exception
12717 being raised with the exception that the user wants to catch. This
12718 assumes that this condition is used when the inferior just triggered
12719 an exception catchpoint.
cb7de75e 12720 EX: the type of catchpoints used for catching Ada exceptions. */
f7f9143b 12721
cb7de75e 12722static std::string
9f757bf7 12723ada_exception_catchpoint_cond_string (const char *excep_string,
dda83cd7 12724 enum ada_exception_catchpoint_kind ex)
f7f9143b 12725{
fccf9de1 12726 bool is_standard_exc = false;
cb7de75e 12727 std::string result;
9f757bf7
XR
12728
12729 if (ex == ada_catch_handlers)
12730 {
12731 /* For exception handlers catchpoints, the condition string does
dda83cd7 12732 not use the same parameter as for the other exceptions. */
fccf9de1
TT
12733 result = ("long_integer (GNAT_GCC_exception_Access"
12734 "(gcc_exception).all.occurrence.id)");
9f757bf7
XR
12735 }
12736 else
fccf9de1 12737 result = "long_integer (e)";
3d0b0fa3 12738
0963b4bd 12739 /* The standard exceptions are a special case. They are defined in
3d0b0fa3 12740 runtime units that have been compiled without debugging info; if
28010a5d 12741 EXCEP_STRING is the not-fully-qualified name of a standard
3d0b0fa3
JB
12742 exception (e.g. "constraint_error") then, during the evaluation
12743 of the condition expression, the symbol lookup on this name would
0963b4bd 12744 *not* return this standard exception. The catchpoint condition
3d0b0fa3
JB
12745 may then be set only on user-defined exceptions which have the
12746 same not-fully-qualified name (e.g. my_package.constraint_error).
12747
12748 To avoid this unexcepted behavior, these standard exceptions are
0963b4bd 12749 systematically prefixed by "standard". This means that "catch
3d0b0fa3
JB
12750 exception constraint_error" is rewritten into "catch exception
12751 standard.constraint_error".
12752
85102364 12753 If an exception named constraint_error is defined in another package of
3d0b0fa3
JB
12754 the inferior program, then the only way to specify this exception as a
12755 breakpoint condition is to use its fully-qualified named:
fccf9de1 12756 e.g. my_package.constraint_error. */
3d0b0fa3 12757
696d6f4d 12758 for (const char *name : standard_exc)
3d0b0fa3 12759 {
696d6f4d 12760 if (strcmp (name, excep_string) == 0)
3d0b0fa3 12761 {
fccf9de1 12762 is_standard_exc = true;
9f757bf7 12763 break;
3d0b0fa3
JB
12764 }
12765 }
9f757bf7 12766
fccf9de1
TT
12767 result += " = ";
12768
12769 if (is_standard_exc)
12770 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12771 else
12772 string_appendf (result, "long_integer (&%s)", excep_string);
9f757bf7 12773
9f757bf7 12774 return result;
f7f9143b
JB
12775}
12776
12777/* Return the symtab_and_line that should be used to insert an exception
12778 catchpoint of the TYPE kind.
12779
28010a5d
PA
12780 ADDR_STRING returns the name of the function where the real
12781 breakpoint that implements the catchpoints is set, depending on the
12782 type of catchpoint we need to create. */
f7f9143b
JB
12783
12784static struct symtab_and_line
bc18fbb5 12785ada_exception_sal (enum ada_exception_catchpoint_kind ex,
ae72050b 12786 std::string *addr_string)
f7f9143b
JB
12787{
12788 const char *sym_name;
12789 struct symbol *sym;
f7f9143b 12790
0259addd
JB
12791 /* First, find out which exception support info to use. */
12792 ada_exception_support_info_sniffer ();
12793
12794 /* Then lookup the function on which we will break in order to catch
f7f9143b 12795 the Ada exceptions requested by the user. */
f7f9143b
JB
12796 sym_name = ada_exception_sym_name (ex);
12797 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12798
57aff202
JB
12799 if (sym == NULL)
12800 error (_("Catchpoint symbol not found: %s"), sym_name);
12801
66d7f48f 12802 if (sym->aclass () != LOC_BLOCK)
57aff202 12803 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
f7f9143b
JB
12804
12805 /* Set ADDR_STRING. */
cc12f4a8 12806 *addr_string = sym_name;
f7f9143b 12807
f17011e0 12808 return find_function_start_sal (sym, 1);
f7f9143b
JB
12809}
12810
b4a5b78b 12811/* Create an Ada exception catchpoint.
f7f9143b 12812
b4a5b78b 12813 EX_KIND is the kind of exception catchpoint to be created.
5845583d 12814
bc18fbb5 12815 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
2df4d1d5 12816 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
bc18fbb5 12817 of the exception to which this catchpoint applies.
2df4d1d5 12818
bc18fbb5 12819 COND_STRING, if not empty, is the catchpoint condition.
f7f9143b 12820
b4a5b78b
JB
12821 TEMPFLAG, if nonzero, means that the underlying breakpoint
12822 should be temporary.
28010a5d 12823
b4a5b78b 12824 FROM_TTY is the usual argument passed to all commands implementations. */
28010a5d 12825
349774ef 12826void
28010a5d 12827create_ada_exception_catchpoint (struct gdbarch *gdbarch,
761269c8 12828 enum ada_exception_catchpoint_kind ex_kind,
bc18fbb5 12829 const std::string &excep_string,
56ecd069 12830 const std::string &cond_string,
28010a5d 12831 int tempflag,
12d67b37 12832 int enabled,
28010a5d
PA
12833 int from_tty)
12834{
cc12f4a8 12835 std::string addr_string;
ae72050b 12836 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string);
28010a5d 12837
bd21b6c9
PA
12838 std::unique_ptr<ada_catchpoint> c
12839 (new ada_catchpoint (gdbarch, ex_kind, sal, addr_string.c_str (),
12d67b37 12840 tempflag, enabled, from_tty));
28010a5d 12841 c->excep_string = excep_string;
9f757bf7 12842 create_excep_cond_exprs (c.get (), ex_kind);
56ecd069 12843 if (!cond_string.empty ())
733d554a 12844 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty, false);
b270e6f9 12845 install_breakpoint (0, std::move (c), 1);
f7f9143b
JB
12846}
12847
9ac4176b
PA
12848/* Implement the "catch exception" command. */
12849
12850static void
eb4c3f4a 12851catch_ada_exception_command (const char *arg_entry, int from_tty,
9ac4176b
PA
12852 struct cmd_list_element *command)
12853{
a121b7c1 12854 const char *arg = arg_entry;
9ac4176b
PA
12855 struct gdbarch *gdbarch = get_current_arch ();
12856 int tempflag;
761269c8 12857 enum ada_exception_catchpoint_kind ex_kind;
bc18fbb5 12858 std::string excep_string;
56ecd069 12859 std::string cond_string;
9ac4176b 12860
0f8e2034 12861 tempflag = command->context () == CATCH_TEMPORARY;
9ac4176b
PA
12862
12863 if (!arg)
12864 arg = "";
9f757bf7 12865 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
bc18fbb5 12866 &cond_string);
9f757bf7
XR
12867 create_ada_exception_catchpoint (gdbarch, ex_kind,
12868 excep_string, cond_string,
12869 tempflag, 1 /* enabled */,
12870 from_tty);
12871}
12872
12873/* Implement the "catch handlers" command. */
12874
12875static void
12876catch_ada_handlers_command (const char *arg_entry, int from_tty,
12877 struct cmd_list_element *command)
12878{
12879 const char *arg = arg_entry;
12880 struct gdbarch *gdbarch = get_current_arch ();
12881 int tempflag;
12882 enum ada_exception_catchpoint_kind ex_kind;
bc18fbb5 12883 std::string excep_string;
56ecd069 12884 std::string cond_string;
9f757bf7 12885
0f8e2034 12886 tempflag = command->context () == CATCH_TEMPORARY;
9f757bf7
XR
12887
12888 if (!arg)
12889 arg = "";
12890 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
bc18fbb5 12891 &cond_string);
b4a5b78b
JB
12892 create_ada_exception_catchpoint (gdbarch, ex_kind,
12893 excep_string, cond_string,
349774ef
JB
12894 tempflag, 1 /* enabled */,
12895 from_tty);
9ac4176b
PA
12896}
12897
71bed2db
TT
12898/* Completion function for the Ada "catch" commands. */
12899
12900static void
12901catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12902 const char *text, const char *word)
12903{
12904 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12905
12906 for (const ada_exc_info &info : exceptions)
12907 {
12908 if (startswith (info.name, word))
b02f78f9 12909 tracker.add_completion (make_unique_xstrdup (info.name));
71bed2db
TT
12910 }
12911}
12912
b4a5b78b 12913/* Split the arguments specified in a "catch assert" command.
5845583d 12914
b4a5b78b
JB
12915 ARGS contains the command's arguments (or the empty string if
12916 no arguments were passed).
5845583d
JB
12917
12918 If ARGS contains a condition, set COND_STRING to that condition
b4a5b78b 12919 (the memory needs to be deallocated after use). */
5845583d 12920
b4a5b78b 12921static void
56ecd069 12922catch_ada_assert_command_split (const char *args, std::string &cond_string)
f7f9143b 12923{
f1735a53 12924 args = skip_spaces (args);
f7f9143b 12925
5845583d 12926 /* Check whether a condition was provided. */
61012eef 12927 if (startswith (args, "if")
5845583d 12928 && (isspace (args[2]) || args[2] == '\0'))
f7f9143b 12929 {
5845583d 12930 args += 2;
f1735a53 12931 args = skip_spaces (args);
5845583d 12932 if (args[0] == '\0')
dda83cd7 12933 error (_("condition missing after `if' keyword"));
56ecd069 12934 cond_string.assign (args);
f7f9143b
JB
12935 }
12936
5845583d
JB
12937 /* Otherwise, there should be no other argument at the end of
12938 the command. */
12939 else if (args[0] != '\0')
12940 error (_("Junk at end of arguments."));
f7f9143b
JB
12941}
12942
9ac4176b
PA
12943/* Implement the "catch assert" command. */
12944
12945static void
eb4c3f4a 12946catch_assert_command (const char *arg_entry, int from_tty,
9ac4176b
PA
12947 struct cmd_list_element *command)
12948{
a121b7c1 12949 const char *arg = arg_entry;
9ac4176b
PA
12950 struct gdbarch *gdbarch = get_current_arch ();
12951 int tempflag;
56ecd069 12952 std::string cond_string;
9ac4176b 12953
0f8e2034 12954 tempflag = command->context () == CATCH_TEMPORARY;
9ac4176b
PA
12955
12956 if (!arg)
12957 arg = "";
56ecd069 12958 catch_ada_assert_command_split (arg, cond_string);
761269c8 12959 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
241db429 12960 "", cond_string,
349774ef
JB
12961 tempflag, 1 /* enabled */,
12962 from_tty);
9ac4176b 12963}
778865d3
JB
12964
12965/* Return non-zero if the symbol SYM is an Ada exception object. */
12966
12967static int
12968ada_is_exception_sym (struct symbol *sym)
12969{
5f9c5a63 12970 const char *type_name = sym->type ()->name ();
778865d3 12971
66d7f48f
SM
12972 return (sym->aclass () != LOC_TYPEDEF
12973 && sym->aclass () != LOC_BLOCK
12974 && sym->aclass () != LOC_CONST
12975 && sym->aclass () != LOC_UNRESOLVED
dda83cd7 12976 && type_name != NULL && strcmp (type_name, "exception") == 0);
778865d3
JB
12977}
12978
12979/* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12980 Ada exception object. This matches all exceptions except the ones
12981 defined by the Ada language. */
12982
12983static int
12984ada_is_non_standard_exception_sym (struct symbol *sym)
12985{
778865d3
JB
12986 if (!ada_is_exception_sym (sym))
12987 return 0;
12988
696d6f4d
TT
12989 for (const char *name : standard_exc)
12990 if (strcmp (sym->linkage_name (), name) == 0)
778865d3
JB
12991 return 0; /* A standard exception. */
12992
12993 /* Numeric_Error is also a standard exception, so exclude it.
12994 See the STANDARD_EXC description for more details as to why
12995 this exception is not listed in that array. */
987012b8 12996 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
778865d3
JB
12997 return 0;
12998
12999 return 1;
13000}
13001
ab816a27 13002/* A helper function for std::sort, comparing two struct ada_exc_info
778865d3
JB
13003 objects.
13004
13005 The comparison is determined first by exception name, and then
13006 by exception address. */
13007
ab816a27 13008bool
cc536b21 13009ada_exc_info::operator< (const ada_exc_info &other) const
778865d3 13010{
778865d3
JB
13011 int result;
13012
ab816a27
TT
13013 result = strcmp (name, other.name);
13014 if (result < 0)
13015 return true;
13016 if (result == 0 && addr < other.addr)
13017 return true;
13018 return false;
13019}
778865d3 13020
ab816a27 13021bool
cc536b21 13022ada_exc_info::operator== (const ada_exc_info &other) const
ab816a27
TT
13023{
13024 return addr == other.addr && strcmp (name, other.name) == 0;
778865d3
JB
13025}
13026
13027/* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
13028 routine, but keeping the first SKIP elements untouched.
13029
13030 All duplicates are also removed. */
13031
13032static void
ab816a27 13033sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
778865d3
JB
13034 int skip)
13035{
ab816a27
TT
13036 std::sort (exceptions->begin () + skip, exceptions->end ());
13037 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13038 exceptions->end ());
778865d3
JB
13039}
13040
778865d3
JB
13041/* Add all exceptions defined by the Ada standard whose name match
13042 a regular expression.
13043
13044 If PREG is not NULL, then this regexp_t object is used to
13045 perform the symbol name matching. Otherwise, no name-based
13046 filtering is performed.
13047
13048 EXCEPTIONS is a vector of exceptions to which matching exceptions
13049 gets pushed. */
13050
13051static void
2d7cc5c7 13052ada_add_standard_exceptions (compiled_regex *preg,
ab816a27 13053 std::vector<ada_exc_info> *exceptions)
778865d3 13054{
696d6f4d 13055 for (const char *name : standard_exc)
778865d3 13056 {
696d6f4d 13057 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
778865d3 13058 {
4326580d
MM
13059 symbol_name_match_type match_type = name_match_type_from_name (name);
13060 lookup_name_info lookup_name (name, match_type);
778865d3 13061
4326580d
MM
13062 symbol_name_matcher_ftype *match_name
13063 = ada_get_symbol_name_matcher (lookup_name);
778865d3 13064
4326580d
MM
13065 /* Iterate over all objfiles irrespective of scope or linker
13066 namespaces so we get all exceptions anywhere in the
13067 progspace. */
13068 for (objfile *objfile : current_program_space->objfiles ())
13069 {
13070 for (minimal_symbol *msymbol : objfile->msymbols ())
13071 {
13072 if (match_name (msymbol->linkage_name (), lookup_name,
13073 nullptr)
13074 && msymbol->type () != mst_solib_trampoline)
13075 {
13076 ada_exc_info info
13077 = {name, msymbol->value_address (objfile)};
13078
13079 exceptions->push_back (info);
13080 }
13081 }
778865d3
JB
13082 }
13083 }
13084 }
13085}
13086
13087/* Add all Ada exceptions defined locally and accessible from the given
13088 FRAME.
13089
13090 If PREG is not NULL, then this regexp_t object is used to
13091 perform the symbol name matching. Otherwise, no name-based
13092 filtering is performed.
13093
13094 EXCEPTIONS is a vector of exceptions to which matching exceptions
13095 gets pushed. */
13096
13097static void
2d7cc5c7 13098ada_add_exceptions_from_frame (compiled_regex *preg,
bd2b40ac 13099 frame_info_ptr frame,
ab816a27 13100 std::vector<ada_exc_info> *exceptions)
778865d3 13101{
3977b71f 13102 const struct block *block = get_frame_block (frame, 0);
778865d3
JB
13103
13104 while (block != 0)
13105 {
548a89df 13106 for (struct symbol *sym : block_iterator_range (block))
778865d3 13107 {
66d7f48f 13108 switch (sym->aclass ())
778865d3
JB
13109 {
13110 case LOC_TYPEDEF:
13111 case LOC_BLOCK:
13112 case LOC_CONST:
13113 break;
13114 default:
13115 if (ada_is_exception_sym (sym))
13116 {
987012b8 13117 struct ada_exc_info info = {sym->print_name (),
4aeddc50 13118 sym->value_address ()};
778865d3 13119
ab816a27 13120 exceptions->push_back (info);
778865d3
JB
13121 }
13122 }
13123 }
6c00f721 13124 if (block->function () != NULL)
778865d3 13125 break;
f135fe72 13126 block = block->superblock ();
778865d3
JB
13127 }
13128}
13129
14bc53a8
PA
13130/* Return true if NAME matches PREG or if PREG is NULL. */
13131
13132static bool
2d7cc5c7 13133name_matches_regex (const char *name, compiled_regex *preg)
14bc53a8
PA
13134{
13135 return (preg == NULL
f945dedf 13136 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
14bc53a8
PA
13137}
13138
778865d3
JB
13139/* Add all exceptions defined globally whose name name match
13140 a regular expression, excluding standard exceptions.
13141
13142 The reason we exclude standard exceptions is that they need
13143 to be handled separately: Standard exceptions are defined inside
13144 a runtime unit which is normally not compiled with debugging info,
13145 and thus usually do not show up in our symbol search. However,
13146 if the unit was in fact built with debugging info, we need to
13147 exclude them because they would duplicate the entry we found
13148 during the special loop that specifically searches for those
13149 standard exceptions.
13150
13151 If PREG is not NULL, then this regexp_t object is used to
13152 perform the symbol name matching. Otherwise, no name-based
13153 filtering is performed.
13154
13155 EXCEPTIONS is a vector of exceptions to which matching exceptions
13156 gets pushed. */
13157
13158static void
2d7cc5c7 13159ada_add_global_exceptions (compiled_regex *preg,
ab816a27 13160 std::vector<ada_exc_info> *exceptions)
778865d3 13161{
14bc53a8
PA
13162 /* In Ada, the symbol "search name" is a linkage name, whereas the
13163 regular expression used to do the matching refers to the natural
13164 name. So match against the decoded name. */
13165 expand_symtabs_matching (NULL,
b5ec771e 13166 lookup_name_info::match_any (),
14bc53a8
PA
13167 [&] (const char *search_name)
13168 {
f945dedf
CB
13169 std::string decoded = ada_decode (search_name);
13170 return name_matches_regex (decoded.c_str (), preg);
14bc53a8
PA
13171 },
13172 NULL,
03a8ea51 13173 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
14bc53a8 13174 VARIABLES_DOMAIN);
778865d3 13175
4326580d
MM
13176 /* Iterate over all objfiles irrespective of scope or linker namespaces
13177 so we get all exceptions anywhere in the progspace. */
2030c079 13178 for (objfile *objfile : current_program_space->objfiles ())
778865d3 13179 {
b669c953 13180 for (compunit_symtab *s : objfile->compunits ())
778865d3 13181 {
af39c5c8 13182 const struct blockvector *bv = s->blockvector ();
d8aeb77f 13183 int i;
778865d3 13184
d8aeb77f
TT
13185 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13186 {
63d609de 13187 const struct block *b = bv->block (i);
778865d3 13188
548a89df 13189 for (struct symbol *sym : block_iterator_range (b))
d8aeb77f 13190 if (ada_is_non_standard_exception_sym (sym)
987012b8 13191 && name_matches_regex (sym->natural_name (), preg))
d8aeb77f
TT
13192 {
13193 struct ada_exc_info info
4aeddc50 13194 = {sym->print_name (), sym->value_address ()};
d8aeb77f
TT
13195
13196 exceptions->push_back (info);
13197 }
13198 }
778865d3
JB
13199 }
13200 }
13201}
13202
13203/* Implements ada_exceptions_list with the regular expression passed
13204 as a regex_t, rather than a string.
13205
13206 If not NULL, PREG is used to filter out exceptions whose names
13207 do not match. Otherwise, all exceptions are listed. */
13208
ab816a27 13209static std::vector<ada_exc_info>
2d7cc5c7 13210ada_exceptions_list_1 (compiled_regex *preg)
778865d3 13211{
ab816a27 13212 std::vector<ada_exc_info> result;
778865d3
JB
13213 int prev_len;
13214
13215 /* First, list the known standard exceptions. These exceptions
13216 need to be handled separately, as they are usually defined in
13217 runtime units that have been compiled without debugging info. */
13218
13219 ada_add_standard_exceptions (preg, &result);
13220
13221 /* Next, find all exceptions whose scope is local and accessible
13222 from the currently selected frame. */
13223
13224 if (has_stack_frames ())
13225 {
ab816a27 13226 prev_len = result.size ();
778865d3
JB
13227 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13228 &result);
ab816a27 13229 if (result.size () > prev_len)
778865d3
JB
13230 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13231 }
13232
13233 /* Add all exceptions whose scope is global. */
13234
ab816a27 13235 prev_len = result.size ();
778865d3 13236 ada_add_global_exceptions (preg, &result);
ab816a27 13237 if (result.size () > prev_len)
778865d3
JB
13238 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13239
778865d3
JB
13240 return result;
13241}
13242
13243/* Return a vector of ada_exc_info.
13244
13245 If REGEXP is NULL, all exceptions are included in the result.
13246 Otherwise, it should contain a valid regular expression,
13247 and only the exceptions whose names match that regular expression
13248 are included in the result.
13249
13250 The exceptions are sorted in the following order:
13251 - Standard exceptions (defined by the Ada language), in
13252 alphabetical order;
13253 - Exceptions only visible from the current frame, in
13254 alphabetical order;
13255 - Exceptions whose scope is global, in alphabetical order. */
13256
ab816a27 13257std::vector<ada_exc_info>
778865d3
JB
13258ada_exceptions_list (const char *regexp)
13259{
2d7cc5c7
PA
13260 if (regexp == NULL)
13261 return ada_exceptions_list_1 (NULL);
778865d3 13262
2d7cc5c7
PA
13263 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13264 return ada_exceptions_list_1 (&reg);
778865d3
JB
13265}
13266
13267/* Implement the "info exceptions" command. */
13268
13269static void
1d12d88f 13270info_exceptions_command (const char *regexp, int from_tty)
778865d3 13271{
778865d3 13272 struct gdbarch *gdbarch = get_current_arch ();
778865d3 13273
ab816a27 13274 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
778865d3
JB
13275
13276 if (regexp != NULL)
6cb06a8c 13277 gdb_printf
778865d3
JB
13278 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13279 else
6cb06a8c 13280 gdb_printf (_("All defined Ada exceptions:\n"));
778865d3 13281
ab816a27 13282 for (const ada_exc_info &info : exceptions)
6cb06a8c 13283 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
778865d3
JB
13284}
13285
6c038f32
PH
13286\f
13287 /* Language vector */
13288
b5ec771e
PA
13289/* symbol_name_matcher_ftype adapter for wild_match. */
13290
13291static bool
13292do_wild_match (const char *symbol_search_name,
13293 const lookup_name_info &lookup_name,
a207cff2 13294 completion_match_result *comp_match_res)
b5ec771e
PA
13295{
13296 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13297}
13298
13299/* symbol_name_matcher_ftype adapter for full_match. */
13300
13301static bool
13302do_full_match (const char *symbol_search_name,
13303 const lookup_name_info &lookup_name,
a207cff2 13304 completion_match_result *comp_match_res)
b5ec771e 13305{
959d6a67
TT
13306 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13307
13308 /* If both symbols start with "_ada_", just let the loop below
13309 handle the comparison. However, if only the symbol name starts
13310 with "_ada_", skip the prefix and let the match proceed as
13311 usual. */
13312 if (startswith (symbol_search_name, "_ada_")
13313 && !startswith (lname, "_ada"))
86b44259 13314 symbol_search_name += 5;
81eaa506
TT
13315 /* Likewise for ghost entities. */
13316 if (startswith (symbol_search_name, "___ghost_")
13317 && !startswith (lname, "___ghost_"))
13318 symbol_search_name += 9;
86b44259 13319
86b44259
TT
13320 int uscore_count = 0;
13321 while (*lname != '\0')
13322 {
13323 if (*symbol_search_name != *lname)
13324 {
13325 if (*symbol_search_name == 'B' && uscore_count == 2
13326 && symbol_search_name[1] == '_')
13327 {
13328 symbol_search_name += 2;
13329 while (isdigit (*symbol_search_name))
13330 ++symbol_search_name;
13331 if (symbol_search_name[0] == '_'
13332 && symbol_search_name[1] == '_')
13333 {
13334 symbol_search_name += 2;
13335 continue;
13336 }
13337 }
13338 return false;
13339 }
13340
13341 if (*symbol_search_name == '_')
13342 ++uscore_count;
13343 else
13344 uscore_count = 0;
13345
13346 ++symbol_search_name;
13347 ++lname;
13348 }
13349
13350 return is_name_suffix (symbol_search_name);
b5ec771e
PA
13351}
13352
a2cd4f14
JB
13353/* symbol_name_matcher_ftype for exact (verbatim) matches. */
13354
13355static bool
13356do_exact_match (const char *symbol_search_name,
13357 const lookup_name_info &lookup_name,
13358 completion_match_result *comp_match_res)
13359{
13360 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13361}
13362
b5ec771e
PA
13363/* Build the Ada lookup name for LOOKUP_NAME. */
13364
13365ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13366{
e0802d59 13367 gdb::string_view user_name = lookup_name.name ();
b5ec771e 13368
6a780b67 13369 if (!user_name.empty () && user_name[0] == '<')
b5ec771e
PA
13370 {
13371 if (user_name.back () == '>')
e0802d59 13372 m_encoded_name
5ac58899 13373 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
b5ec771e 13374 else
e0802d59 13375 m_encoded_name
5ac58899 13376 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
b5ec771e
PA
13377 m_encoded_p = true;
13378 m_verbatim_p = true;
13379 m_wild_match_p = false;
13380 m_standard_p = false;
13381 }
13382 else
13383 {
13384 m_verbatim_p = false;
13385
e0802d59 13386 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
b5ec771e
PA
13387
13388 if (!m_encoded_p)
13389 {
e0802d59 13390 const char *folded = ada_fold_name (user_name);
5c4258f4
TT
13391 m_encoded_name = ada_encode_1 (folded, false);
13392 if (m_encoded_name.empty ())
5ac58899 13393 m_encoded_name = gdb::to_string (user_name);
b5ec771e
PA
13394 }
13395 else
5ac58899 13396 m_encoded_name = gdb::to_string (user_name);
b5ec771e
PA
13397
13398 /* Handle the 'package Standard' special case. See description
13399 of m_standard_p. */
13400 if (startswith (m_encoded_name.c_str (), "standard__"))
13401 {
13402 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13403 m_standard_p = true;
13404 }
13405 else
13406 m_standard_p = false;
74ccd7f5 13407
b5ec771e
PA
13408 /* If the name contains a ".", then the user is entering a fully
13409 qualified entity name, and the match must not be done in wild
13410 mode. Similarly, if the user wants to complete what looks
13411 like an encoded name, the match must not be done in wild
13412 mode. Also, in the standard__ special case always do
13413 non-wild matching. */
13414 m_wild_match_p
13415 = (lookup_name.match_type () != symbol_name_match_type::FULL
13416 && !m_encoded_p
13417 && !m_standard_p
13418 && user_name.find ('.') == std::string::npos);
13419 }
13420}
13421
13422/* symbol_name_matcher_ftype method for Ada. This only handles
13423 completion mode. */
13424
13425static bool
13426ada_symbol_name_matches (const char *symbol_search_name,
13427 const lookup_name_info &lookup_name,
a207cff2 13428 completion_match_result *comp_match_res)
74ccd7f5 13429{
b5ec771e
PA
13430 return lookup_name.ada ().matches (symbol_search_name,
13431 lookup_name.match_type (),
a207cff2 13432 comp_match_res);
b5ec771e
PA
13433}
13434
de63c46b
PA
13435/* A name matcher that matches the symbol name exactly, with
13436 strcmp. */
13437
13438static bool
13439literal_symbol_name_matcher (const char *symbol_search_name,
13440 const lookup_name_info &lookup_name,
13441 completion_match_result *comp_match_res)
13442{
e0802d59 13443 gdb::string_view name_view = lookup_name.name ();
de63c46b 13444
e0802d59
TT
13445 if (lookup_name.completion_mode ()
13446 ? (strncmp (symbol_search_name, name_view.data (),
13447 name_view.size ()) == 0)
13448 : symbol_search_name == name_view)
de63c46b
PA
13449 {
13450 if (comp_match_res != NULL)
13451 comp_match_res->set_match (symbol_search_name);
13452 return true;
13453 }
13454 else
13455 return false;
13456}
13457
c9debfb9 13458/* Implement the "get_symbol_name_matcher" language_defn method for
b5ec771e
PA
13459 Ada. */
13460
13461static symbol_name_matcher_ftype *
13462ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13463{
de63c46b
PA
13464 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13465 return literal_symbol_name_matcher;
13466
b5ec771e
PA
13467 if (lookup_name.completion_mode ())
13468 return ada_symbol_name_matches;
74ccd7f5 13469 else
b5ec771e
PA
13470 {
13471 if (lookup_name.ada ().wild_match_p ())
13472 return do_wild_match;
a2cd4f14
JB
13473 else if (lookup_name.ada ().verbatim_p ())
13474 return do_exact_match;
b5ec771e
PA
13475 else
13476 return do_full_match;
13477 }
74ccd7f5
JB
13478}
13479
0874fd07
AB
13480/* Class representing the Ada language. */
13481
13482class ada_language : public language_defn
13483{
13484public:
13485 ada_language ()
0e25e767 13486 : language_defn (language_ada)
0874fd07 13487 { /* Nothing. */ }
5bd40f2a 13488
6f7664a9
AB
13489 /* See language.h. */
13490
13491 const char *name () const override
13492 { return "ada"; }
13493
13494 /* See language.h. */
13495
13496 const char *natural_name () const override
13497 { return "Ada"; }
13498
e171d6f1
AB
13499 /* See language.h. */
13500
13501 const std::vector<const char *> &filename_extensions () const override
13502 {
13503 static const std::vector<const char *> extensions
13504 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13505 return extensions;
13506 }
13507
5bd40f2a
AB
13508 /* Print an array element index using the Ada syntax. */
13509
13510 void print_array_index (struct type *index_type,
13511 LONGEST index,
13512 struct ui_file *stream,
13513 const value_print_options *options) const override
13514 {
13515 struct value *index_value = val_atr (index_type, index);
13516
00c696a6 13517 value_print (index_value, stream, options);
6cb06a8c 13518 gdb_printf (stream, " => ");
5bd40f2a 13519 }
15e5fd35
AB
13520
13521 /* Implement the "read_var_value" language_defn method for Ada. */
13522
13523 struct value *read_var_value (struct symbol *var,
13524 const struct block *var_block,
bd2b40ac 13525 frame_info_ptr frame) const override
15e5fd35
AB
13526 {
13527 /* The only case where default_read_var_value is not sufficient
13528 is when VAR is a renaming... */
13529 if (frame != nullptr)
13530 {
13531 const struct block *frame_block = get_frame_block (frame, NULL);
13532 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13533 return ada_read_renaming_var_value (var, frame_block);
13534 }
13535
13536 /* This is a typical case where we expect the default_read_var_value
13537 function to work. */
13538 return language_defn::read_var_value (var, var_block, frame);
13539 }
1fb314aa 13540
2c71f639 13541 /* See language.h. */
496feb16 13542 bool symbol_printing_suppressed (struct symbol *symbol) const override
2c71f639 13543 {
496feb16 13544 return symbol->is_artificial ();
2c71f639
TV
13545 }
13546
1fb314aa
AB
13547 /* See language.h. */
13548 void language_arch_info (struct gdbarch *gdbarch,
13549 struct language_arch_info *lai) const override
13550 {
13551 const struct builtin_type *builtin = builtin_type (gdbarch);
13552
7bea47f0
AB
13553 /* Helper function to allow shorter lines below. */
13554 auto add = [&] (struct type *t)
13555 {
13556 lai->add_primitive_type (t);
13557 };
13558
cc495054 13559 type_allocator alloc (gdbarch);
2d39ccd3 13560 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0 13561 0, "integer"));
2d39ccd3 13562 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
7bea47f0 13563 0, "long_integer"));
2d39ccd3 13564 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
7bea47f0 13565 0, "short_integer"));
f50b437c 13566 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
c9f66f00 13567 1, "character");
7bea47f0
AB
13568 lai->set_string_char_type (char_type);
13569 add (char_type);
f50b437c
TT
13570 add (init_character_type (alloc, 16, 1, "wide_character"));
13571 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
77c5f496 13572 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
7bea47f0 13573 "float", gdbarch_float_format (gdbarch)));
77c5f496 13574 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
7bea47f0 13575 "long_float", gdbarch_double_format (gdbarch)));
2d39ccd3 13576 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
7bea47f0 13577 0, "long_long_integer"));
77c5f496 13578 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
7bea47f0
AB
13579 "long_long_float",
13580 gdbarch_long_double_format (gdbarch)));
2d39ccd3 13581 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0 13582 0, "natural"));
2d39ccd3 13583 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0
AB
13584 0, "positive"));
13585 add (builtin->builtin_void);
13586
13587 struct type *system_addr_ptr
cc495054
TT
13588 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13589 "void"));
7bea47f0
AB
13590 system_addr_ptr->set_name ("system__address");
13591 add (system_addr_ptr);
1fb314aa
AB
13592
13593 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13594 type. This is a signed integral type whose size is the same as
13595 the size of addresses. */
df86565b 13596 unsigned int addr_length = system_addr_ptr->length ();
2d39ccd3 13597 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
7bea47f0 13598 "storage_offset"));
1fb314aa 13599
7bea47f0 13600 lai->set_bool_type (builtin->builtin_bool);
1fb314aa 13601 }
4009ee92
AB
13602
13603 /* See language.h. */
13604
13605 bool iterate_over_symbols
13606 (const struct block *block, const lookup_name_info &name,
13607 domain_enum domain,
13608 gdb::function_view<symbol_found_callback_ftype> callback) const override
13609 {
d1183b06
TT
13610 std::vector<struct block_symbol> results
13611 = ada_lookup_symbol_list_worker (name, block, domain, 0);
4009ee92
AB
13612 for (block_symbol &sym : results)
13613 {
13614 if (!callback (&sym))
13615 return false;
13616 }
13617
13618 return true;
13619 }
6f827019
AB
13620
13621 /* See language.h. */
3456e70c
TT
13622 bool sniff_from_mangled_name
13623 (const char *mangled,
13624 gdb::unique_xmalloc_ptr<char> *out) const override
6f827019
AB
13625 {
13626 std::string demangled = ada_decode (mangled);
13627
13628 *out = NULL;
13629
13630 if (demangled != mangled && demangled[0] != '<')
13631 {
13632 /* Set the gsymbol language to Ada, but still return 0.
13633 Two reasons for that:
13634
13635 1. For Ada, we prefer computing the symbol's decoded name
13636 on the fly rather than pre-compute it, in order to save
13637 memory (Ada projects are typically very large).
13638
13639 2. There are some areas in the definition of the GNAT
13640 encoding where, with a bit of bad luck, we might be able
13641 to decode a non-Ada symbol, generating an incorrect
13642 demangled name (Eg: names ending with "TB" for instance
13643 are identified as task bodies and so stripped from
13644 the decoded name returned).
13645
13646 Returning true, here, but not setting *DEMANGLED, helps us get
13647 a little bit of the best of both worlds. Because we're last,
13648 we should not affect any of the other languages that were
13649 able to demangle the symbol before us; we get to correctly
13650 tag Ada symbols as such; and even if we incorrectly tagged a
13651 non-Ada symbol, which should be rare, any routing through the
13652 Ada language should be transparent (Ada tries to behave much
13653 like C/C++ with non-Ada symbols). */
13654 return true;
13655 }
13656
13657 return false;
13658 }
fbfb0a46
AB
13659
13660 /* See language.h. */
13661
3456e70c
TT
13662 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13663 int options) const override
0a50df5d 13664 {
3456e70c 13665 return make_unique_xstrdup (ada_decode (mangled).c_str ());
0a50df5d
AB
13666 }
13667
13668 /* See language.h. */
13669
fbfb0a46
AB
13670 void print_type (struct type *type, const char *varstring,
13671 struct ui_file *stream, int show, int level,
13672 const struct type_print_options *flags) const override
13673 {
13674 ada_print_type (type, varstring, stream, show, level, flags);
13675 }
c9debfb9 13676
53fc67f8
AB
13677 /* See language.h. */
13678
13679 const char *word_break_characters (void) const override
13680 {
13681 return ada_completer_word_break_characters;
13682 }
13683
7e56227d
AB
13684 /* See language.h. */
13685
13686 void collect_symbol_completion_matches (completion_tracker &tracker,
13687 complete_symbol_mode mode,
13688 symbol_name_match_type name_match_type,
13689 const char *text, const char *word,
13690 enum type_code code) const override
13691 {
7e56227d 13692 const struct block *b, *surrounding_static_block = 0;
7e56227d
AB
13693
13694 gdb_assert (code == TYPE_CODE_UNDEF);
13695
13696 lookup_name_info lookup_name (text, name_match_type, true);
13697
13698 /* First, look at the partial symtab symbols. */
13699 expand_symtabs_matching (NULL,
13700 lookup_name,
13701 NULL,
13702 NULL,
03a8ea51 13703 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
7e56227d
AB
13704 ALL_DOMAIN);
13705
13706 /* At this point scan through the misc symbol vectors and add each
13707 symbol you find to the list. Eventually we want to ignore
13708 anything that isn't a text symbol (everything else will be
13709 handled by the psymtab code above). */
13710
13711 for (objfile *objfile : current_program_space->objfiles ())
13712 {
13713 for (minimal_symbol *msymbol : objfile->msymbols ())
13714 {
13715 QUIT;
13716
13717 if (completion_skip_symbol (mode, msymbol))
13718 continue;
13719
13720 language symbol_language = msymbol->language ();
13721
13722 /* Ada minimal symbols won't have their language set to Ada. If
13723 we let completion_list_add_name compare using the
13724 default/C-like matcher, then when completing e.g., symbols in a
13725 package named "pck", we'd match internal Ada symbols like
13726 "pckS", which are invalid in an Ada expression, unless you wrap
13727 them in '<' '>' to request a verbatim match.
13728
13729 Unfortunately, some Ada encoded names successfully demangle as
13730 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13731 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13732 with the wrong language set. Paper over that issue here. */
13733 if (symbol_language == language_auto
13734 || symbol_language == language_cplus)
13735 symbol_language = language_ada;
13736
13737 completion_list_add_name (tracker,
13738 symbol_language,
13739 msymbol->linkage_name (),
13740 lookup_name, text, word);
13741 }
13742 }
13743
13744 /* Search upwards from currently selected frame (so that we can
13745 complete on local vars. */
13746
f135fe72 13747 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
7e56227d 13748 {
f135fe72 13749 if (!b->superblock ())
7e56227d
AB
13750 surrounding_static_block = b; /* For elmin of dups */
13751
548a89df 13752 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13753 {
13754 if (completion_skip_symbol (mode, sym))
13755 continue;
13756
13757 completion_list_add_name (tracker,
13758 sym->language (),
13759 sym->linkage_name (),
13760 lookup_name, text, word);
13761 }
13762 }
13763
13764 /* Go through the symtabs and check the externs and statics for
13765 symbols which match. */
13766
13767 for (objfile *objfile : current_program_space->objfiles ())
13768 {
13769 for (compunit_symtab *s : objfile->compunits ())
13770 {
13771 QUIT;
63d609de 13772 b = s->blockvector ()->global_block ();
548a89df 13773 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13774 {
13775 if (completion_skip_symbol (mode, sym))
13776 continue;
13777
13778 completion_list_add_name (tracker,
13779 sym->language (),
13780 sym->linkage_name (),
13781 lookup_name, text, word);
13782 }
13783 }
13784 }
13785
13786 for (objfile *objfile : current_program_space->objfiles ())
13787 {
13788 for (compunit_symtab *s : objfile->compunits ())
13789 {
13790 QUIT;
63d609de 13791 b = s->blockvector ()->static_block ();
7e56227d
AB
13792 /* Don't do this block twice. */
13793 if (b == surrounding_static_block)
13794 continue;
548a89df 13795 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13796 {
13797 if (completion_skip_symbol (mode, sym))
13798 continue;
13799
13800 completion_list_add_name (tracker,
13801 sym->language (),
13802 sym->linkage_name (),
13803 lookup_name, text, word);
13804 }
13805 }
13806 }
13807 }
13808
f16a9f57
AB
13809 /* See language.h. */
13810
13811 gdb::unique_xmalloc_ptr<char> watch_location_expression
13812 (struct type *type, CORE_ADDR addr) const override
13813 {
27710edb 13814 type = check_typedef (check_typedef (type)->target_type ());
f16a9f57 13815 std::string name = type_to_string (type);
8579fd13 13816 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
f16a9f57
AB
13817 }
13818
a1d1fa3e
AB
13819 /* See language.h. */
13820
13821 void value_print (struct value *val, struct ui_file *stream,
13822 const struct value_print_options *options) const override
13823 {
13824 return ada_value_print (val, stream, options);
13825 }
13826
ebe2334e
AB
13827 /* See language.h. */
13828
13829 void value_print_inner
13830 (struct value *val, struct ui_file *stream, int recurse,
13831 const struct value_print_options *options) const override
13832 {
13833 return ada_value_print_inner (val, stream, recurse, options);
13834 }
13835
a78a19b1
AB
13836 /* See language.h. */
13837
13838 struct block_symbol lookup_symbol_nonlocal
13839 (const char *name, const struct block *block,
13840 const domain_enum domain) const override
13841 {
13842 struct block_symbol sym;
13843
78004096
TT
13844 sym = ada_lookup_symbol (name,
13845 (block == nullptr
13846 ? nullptr
d24e14a0 13847 : block->static_block ()),
78004096 13848 domain);
a78a19b1
AB
13849 if (sym.symbol != NULL)
13850 return sym;
13851
13852 /* If we haven't found a match at this point, try the primitive
13853 types. In other languages, this search is performed before
13854 searching for global symbols in order to short-circuit that
13855 global-symbol search if it happens that the name corresponds
13856 to a primitive type. But we cannot do the same in Ada, because
13857 it is perfectly legitimate for a program to declare a type which
13858 has the same name as a standard type. If looking up a type in
13859 that situation, we have traditionally ignored the primitive type
13860 in favor of user-defined types. This is why, unlike most other
13861 languages, we search the primitive types this late and only after
13862 having searched the global symbols without success. */
13863
13864 if (domain == VAR_DOMAIN)
13865 {
13866 struct gdbarch *gdbarch;
13867
13868 if (block == NULL)
13869 gdbarch = target_gdbarch ();
13870 else
7f5937df 13871 gdbarch = block->gdbarch ();
a78a19b1
AB
13872 sym.symbol
13873 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13874 if (sym.symbol != NULL)
13875 return sym;
13876 }
13877
13878 return {};
13879 }
13880
87afa652
AB
13881 /* See language.h. */
13882
13883 int parser (struct parser_state *ps) const override
13884 {
13885 warnings_issued = 0;
13886 return ada_parse (ps);
13887 }
13888
ec8cec5b
AB
13889 /* See language.h. */
13890
13891 void emitchar (int ch, struct type *chtype,
13892 struct ui_file *stream, int quoter) const override
13893 {
13894 ada_emit_char (ch, chtype, stream, quoter, 1);
13895 }
13896
52b50f2c
AB
13897 /* See language.h. */
13898
13899 void printchar (int ch, struct type *chtype,
13900 struct ui_file *stream) const override
13901 {
13902 ada_printchar (ch, chtype, stream);
13903 }
13904
d711ee67
AB
13905 /* See language.h. */
13906
13907 void printstr (struct ui_file *stream, struct type *elttype,
13908 const gdb_byte *string, unsigned int length,
13909 const char *encoding, int force_ellipses,
13910 const struct value_print_options *options) const override
13911 {
13912 ada_printstr (stream, elttype, string, length, encoding,
13913 force_ellipses, options);
13914 }
13915
4ffc13fb
AB
13916 /* See language.h. */
13917
13918 void print_typedef (struct type *type, struct symbol *new_symbol,
13919 struct ui_file *stream) const override
13920 {
13921 ada_print_typedef (type, new_symbol, stream);
13922 }
13923
39e7ecca
AB
13924 /* See language.h. */
13925
13926 bool is_string_type_p (struct type *type) const override
13927 {
13928 return ada_is_string_type (type);
13929 }
13930
22e3f3ed
AB
13931 /* See language.h. */
13932
13933 const char *struct_too_deep_ellipsis () const override
13934 { return "(...)"; }
39e7ecca 13935
67bd3fd5
AB
13936 /* See language.h. */
13937
13938 bool c_style_arrays_p () const override
13939 { return false; }
13940
d3355e4d
AB
13941 /* See language.h. */
13942
13943 bool store_sym_names_in_linkage_form_p () const override
13944 { return true; }
13945
b63a3f3f
AB
13946 /* See language.h. */
13947
13948 const struct lang_varobj_ops *varobj_ops () const override
13949 { return &ada_varobj_ops; }
13950
c9debfb9
AB
13951protected:
13952 /* See language.h. */
13953
13954 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13955 (const lookup_name_info &lookup_name) const override
13956 {
13957 return ada_get_symbol_name_matcher (lookup_name);
13958 }
0874fd07
AB
13959};
13960
13961/* Single instance of the Ada language class. */
13962
13963static ada_language ada_language_defn;
13964
5bf03f13
JB
13965/* Command-list for the "set/show ada" prefix command. */
13966static struct cmd_list_element *set_ada_list;
13967static struct cmd_list_element *show_ada_list;
13968
3d9434b5
JB
13969/* This module's 'new_objfile' observer. */
13970
13971static void
13972ada_new_objfile_observer (struct objfile *objfile)
13973{
13974 ada_clear_symbol_cache ();
13975}
13976
13977/* This module's 'free_objfile' observer. */
13978
13979static void
13980ada_free_objfile_observer (struct objfile *objfile)
13981{
13982 ada_clear_symbol_cache ();
13983}
13984
315e4ebb
TT
13985/* Charsets known to GNAT. */
13986static const char * const gnat_source_charsets[] =
13987{
13988 /* Note that code below assumes that the default comes first.
13989 Latin-1 is the default here, because that is also GNAT's
13990 default. */
13991 "ISO-8859-1",
13992 "ISO-8859-2",
13993 "ISO-8859-3",
13994 "ISO-8859-4",
13995 "ISO-8859-5",
13996 "ISO-8859-15",
13997 "CP437",
13998 "CP850",
13999 /* Note that this value is special-cased in the encoder and
14000 decoder. */
14001 ada_utf8,
14002 nullptr
14003};
14004
6c265988 14005void _initialize_ada_language ();
d2e4a39e 14006void
6c265988 14007_initialize_ada_language ()
14f9c5c9 14008{
f54bdb6d
SM
14009 add_setshow_prefix_cmd
14010 ("ada", no_class,
14011 _("Prefix command for changing Ada-specific settings."),
14012 _("Generic command for showing Ada-specific settings."),
14013 &set_ada_list, &show_ada_list,
14014 &setlist, &showlist);
5bf03f13
JB
14015
14016 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
dda83cd7 14017 &trust_pad_over_xvs, _("\
590042fc
PW
14018Enable or disable an optimization trusting PAD types over XVS types."), _("\
14019Show whether an optimization trusting PAD types over XVS types is activated."),
dda83cd7 14020 _("\
5bf03f13
JB
14021This is related to the encoding used by the GNAT compiler. The debugger\n\
14022should normally trust the contents of PAD types, but certain older versions\n\
14023of GNAT have a bug that sometimes causes the information in the PAD type\n\
14024to be incorrect. Turning this setting \"off\" allows the debugger to\n\
14025work around this bug. It is always safe to turn this option \"off\", but\n\
14026this incurs a slight performance penalty, so it is recommended to NOT change\n\
14027this option to \"off\" unless necessary."),
dda83cd7 14028 NULL, NULL, &set_ada_list, &show_ada_list);
5bf03f13 14029
d72413e6
PMR
14030 add_setshow_boolean_cmd ("print-signatures", class_vars,
14031 &print_signatures, _("\
14032Enable or disable the output of formal and return types for functions in the \
590042fc 14033overloads selection menu."), _("\
d72413e6 14034Show whether the output of formal and return types for functions in the \
590042fc 14035overloads selection menu is activated."),
d72413e6
PMR
14036 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
14037
315e4ebb
TT
14038 ada_source_charset = gnat_source_charsets[0];
14039 add_setshow_enum_cmd ("source-charset", class_files,
14040 gnat_source_charsets,
14041 &ada_source_charset, _("\
14042Set the Ada source character set."), _("\
14043Show the Ada source character set."), _("\
14044The character set used for Ada source files.\n\
14045This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
14046 nullptr, nullptr,
14047 &set_ada_list, &show_ada_list);
14048
9ac4176b
PA
14049 add_catch_command ("exception", _("\
14050Catch Ada exceptions, when raised.\n\
9bf7038b 14051Usage: catch exception [ARG] [if CONDITION]\n\
60a90376
JB
14052Without any argument, stop when any Ada exception is raised.\n\
14053If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
14054being raised does not have a handler (and will therefore lead to the task's\n\
14055termination).\n\
14056Otherwise, the catchpoint only stops when the name of the exception being\n\
9bf7038b
TT
14057raised is the same as ARG.\n\
14058CONDITION is a boolean expression that is evaluated to see whether the\n\
14059exception should cause a stop."),
9ac4176b 14060 catch_ada_exception_command,
71bed2db 14061 catch_ada_completer,
9ac4176b
PA
14062 CATCH_PERMANENT,
14063 CATCH_TEMPORARY);
9f757bf7
XR
14064
14065 add_catch_command ("handlers", _("\
14066Catch Ada exceptions, when handled.\n\
9bf7038b
TT
14067Usage: catch handlers [ARG] [if CONDITION]\n\
14068Without any argument, stop when any Ada exception is handled.\n\
14069With an argument, catch only exceptions with the given name.\n\
14070CONDITION is a boolean expression that is evaluated to see whether the\n\
14071exception should cause a stop."),
9f757bf7 14072 catch_ada_handlers_command,
dda83cd7 14073 catch_ada_completer,
9f757bf7
XR
14074 CATCH_PERMANENT,
14075 CATCH_TEMPORARY);
9ac4176b
PA
14076 add_catch_command ("assert", _("\
14077Catch failed Ada assertions, when raised.\n\
9bf7038b
TT
14078Usage: catch assert [if CONDITION]\n\
14079CONDITION is a boolean expression that is evaluated to see whether the\n\
14080exception should cause a stop."),
9ac4176b 14081 catch_assert_command,
dda83cd7 14082 NULL,
9ac4176b
PA
14083 CATCH_PERMANENT,
14084 CATCH_TEMPORARY);
14085
778865d3
JB
14086 add_info ("exceptions", info_exceptions_command,
14087 _("\
14088List all Ada exception names.\n\
9bf7038b 14089Usage: info exceptions [REGEXP]\n\
778865d3
JB
14090If a regular expression is passed as an argument, only those matching\n\
14091the regular expression are listed."));
14092
f54bdb6d
SM
14093 add_setshow_prefix_cmd ("ada", class_maintenance,
14094 _("Set Ada maintenance-related variables."),
14095 _("Show Ada maintenance-related variables."),
14096 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14097 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
c6044dd1
JB
14098
14099 add_setshow_boolean_cmd
14100 ("ignore-descriptive-types", class_maintenance,
14101 &ada_ignore_descriptive_types_p,
14102 _("Set whether descriptive types generated by GNAT should be ignored."),
14103 _("Show whether descriptive types generated by GNAT should be ignored."),
14104 _("\
14105When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14106DWARF attribute."),
14107 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14108
2698f5ea
TT
14109 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14110 htab_eq_string,
459a2e4c 14111 NULL, xcalloc, xfree);
6b69afc4 14112
3d9434b5 14113 /* The ada-lang observers. */
c90e7d63
SM
14114 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
14115 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14116 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
14f9c5c9 14117}