]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/ada-lang.c
gdb: move a bunch of quit-related things to event-top.{c,h}
[thirdparty/binutils-gdb.git] / gdb / ada-lang.c
CommitLineData
6e681866 1/* Ada language support routines for GDB, the GNU debugger.
10a2c479 2
1d506c26 3 Copyright (C) 1992-2024 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
14f9c5c9 21#include <ctype.h>
e5dc0d5d 22#include "event-top.h"
ec452525 23#include "extract-store-integer.h"
d322d6d6 24#include "gdbsupport/gdb_regex.h"
4de283e4
TT
25#include "frame.h"
26#include "symtab.h"
27#include "gdbtypes.h"
14f9c5c9 28#include "gdbcmd.h"
4de283e4
TT
29#include "expression.h"
30#include "parser-defs.h"
31#include "language.h"
32#include "varobj.h"
4de283e4
TT
33#include "inferior.h"
34#include "symfile.h"
35#include "objfiles.h"
36#include "breakpoint.h"
14f9c5c9 37#include "gdbcore.h"
4c4b4cd2 38#include "hashtab.h"
bf31fd38 39#include "gdbsupport/gdb_obstack.h"
4de283e4
TT
40#include "ada-lang.h"
41#include "completer.h"
4de283e4
TT
42#include "ui-out.h"
43#include "block.h"
04714b91 44#include "infcall.h"
4de283e4
TT
45#include "annotate.h"
46#include "valprint.h"
d55e5aa6 47#include "source.h"
4de283e4 48#include "observable.h"
692465f1 49#include "stack.h"
79d43c61 50#include "typeprint.h"
4de283e4 51#include "namespace.h"
7f6aba03 52#include "cli/cli-style.h"
0f8e2034 53#include "cli/cli-decode.h"
4de283e4 54
40bc484c 55#include "value.h"
4de283e4
TT
56#include "mi/mi-common.h"
57#include "arch-utils.h"
58#include "cli/cli-utils.h"
268a13a5
TT
59#include "gdbsupport/function-view.h"
60#include "gdbsupport/byte-vector.h"
033bc52b 61#include "gdbsupport/selftest.h"
4de283e4 62#include <algorithm>
03070ee9 63#include "ada-exp.h"
315e4ebb 64#include "charset.h"
013a623f 65#include "ax-gdb.h"
ccefe4c4 66
d2e4a39e 67static struct type *desc_base_type (struct type *);
14f9c5c9 68
d2e4a39e 69static struct type *desc_bounds_type (struct type *);
14f9c5c9 70
d2e4a39e 71static struct value *desc_bounds (struct value *);
14f9c5c9 72
d2e4a39e 73static int fat_pntr_bounds_bitpos (struct type *);
14f9c5c9 74
d2e4a39e 75static int fat_pntr_bounds_bitsize (struct type *);
14f9c5c9 76
556bdfd4 77static struct type *desc_data_target_type (struct type *);
14f9c5c9 78
d2e4a39e 79static struct value *desc_data (struct value *);
14f9c5c9 80
d2e4a39e 81static int fat_pntr_data_bitpos (struct type *);
14f9c5c9 82
d2e4a39e 83static int fat_pntr_data_bitsize (struct type *);
14f9c5c9 84
d2e4a39e 85static struct value *desc_one_bound (struct value *, int, int);
14f9c5c9 86
d2e4a39e 87static int desc_bound_bitpos (struct type *, int, int);
14f9c5c9 88
d2e4a39e 89static int desc_bound_bitsize (struct type *, int, int);
14f9c5c9 90
d2e4a39e 91static struct type *desc_index_type (struct type *, int);
14f9c5c9 92
d2e4a39e 93static int desc_arity (struct type *);
14f9c5c9 94
d2e4a39e 95static int ada_args_match (struct symbol *, struct value **, int);
14f9c5c9 96
40bc484c 97static struct value *make_array_descriptor (struct type *, struct value *);
14f9c5c9 98
d1183b06 99static void ada_add_block_symbols (std::vector<struct block_symbol> &,
b5ec771e
PA
100 const struct block *,
101 const lookup_name_info &lookup_name,
6c015214 102 domain_search_flags, struct objfile *);
14f9c5c9 103
d1183b06
TT
104static void ada_add_all_symbols (std::vector<struct block_symbol> &,
105 const struct block *,
b5ec771e 106 const lookup_name_info &lookup_name,
6c015214 107 domain_search_flags, int, int *);
22cee43f 108
d1183b06 109static int is_nonfunction (const std::vector<struct block_symbol> &);
14f9c5c9 110
d1183b06
TT
111static void add_defn_to_vec (std::vector<struct block_symbol> &,
112 struct symbol *,
dda83cd7 113 const struct block *);
14f9c5c9 114
d2e4a39e 115static int possible_user_operator_p (enum exp_opcode, struct value **);
14f9c5c9 116
4c4b4cd2 117static const char *ada_decoded_op_name (enum exp_opcode);
14f9c5c9 118
d2e4a39e 119static int numeric_type_p (struct type *);
14f9c5c9 120
d2e4a39e 121static int integer_type_p (struct type *);
14f9c5c9 122
d2e4a39e 123static int scalar_type_p (struct type *);
14f9c5c9 124
d2e4a39e 125static int discrete_type_p (struct type *);
14f9c5c9 126
a121b7c1 127static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
dda83cd7 128 int, int);
4c4b4cd2 129
b4ba55a1 130static struct type *ada_find_parallel_type_with_name (struct type *,
dda83cd7 131 const char *);
b4ba55a1 132
d2e4a39e 133static int is_dynamic_field (struct type *, int);
14f9c5c9 134
10a2c479 135static struct type *to_fixed_variant_branch_type (struct type *,
fc1a4b47 136 const gdb_byte *,
dda83cd7 137 CORE_ADDR, struct value *);
4c4b4cd2
PH
138
139static struct type *to_fixed_array_type (struct type *, struct value *, int);
14f9c5c9 140
28c85d6c 141static struct type *to_fixed_range_type (struct type *, struct value *);
14f9c5c9 142
d2e4a39e 143static struct type *to_static_fixed_type (struct type *);
f192137b 144static struct type *static_unwrap_type (struct type *type);
14f9c5c9 145
d2e4a39e 146static struct value *unwrap_value (struct value *);
14f9c5c9 147
ad82864c 148static struct type *constrained_packed_array_type (struct type *, long *);
14f9c5c9 149
ad82864c 150static struct type *decode_constrained_packed_array_type (struct type *);
14f9c5c9 151
ad82864c
JB
152static long decode_packed_array_bitsize (struct type *);
153
154static struct value *decode_constrained_packed_array (struct value *);
155
ad82864c 156static int ada_is_unconstrained_packed_array_type (struct type *);
14f9c5c9 157
d2e4a39e 158static struct value *value_subscript_packed (struct value *, int,
dda83cd7 159 struct value **);
14f9c5c9 160
4c4b4cd2 161static struct value *coerce_unspec_val_to_type (struct value *,
dda83cd7 162 struct type *);
14f9c5c9 163
d2e4a39e 164static int lesseq_defined_than (struct symbol *, struct symbol *);
14f9c5c9 165
d2e4a39e 166static int equiv_types (struct type *, struct type *);
14f9c5c9 167
d2e4a39e 168static int is_name_suffix (const char *);
14f9c5c9 169
59c8a30b 170static int advance_wild_match (const char **, const char *, char);
73589123 171
b5ec771e 172static bool wild_match (const char *name, const char *patn);
14f9c5c9 173
d2e4a39e 174static struct value *ada_coerce_ref (struct value *);
14f9c5c9 175
4c4b4cd2
PH
176static LONGEST pos_atr (struct value *);
177
53a47a3e
TT
178static struct value *val_atr (struct type *, LONGEST);
179
108d56a4 180static struct value *ada_search_struct_field (const char *, struct value *, int,
dda83cd7 181 struct type *);
4c4b4cd2 182
0d5cff50 183static int find_struct_field (const char *, struct type *, int,
dda83cd7 184 struct type **, int *, int *, int *, int *);
4c4b4cd2 185
d1183b06 186static int ada_resolve_function (std::vector<struct block_symbol> &,
dda83cd7 187 struct value **, int, const char *,
7056f312 188 struct type *, bool);
4c4b4cd2 189
4c4b4cd2
PH
190static int ada_is_direct_array_type (struct type *);
191
52ce6436
PH
192static struct value *ada_index_struct_field (int, struct value *, int,
193 struct type *);
194
852dff6c 195static struct type *ada_find_any_type (const char *name);
b5ec771e
PA
196
197static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
198 (const lookup_name_info &lookup_name);
199
ef136c7f
TV
200static int symbols_are_identical_enums
201 (const std::vector<struct block_symbol> &syms);
74c36641
TV
202
203static int ada_identical_enum_types_p (struct type *type1, struct type *type2);
4c4b4cd2
PH
204\f
205
315e4ebb
TT
206/* The character set used for source files. */
207static const char *ada_source_charset;
208
209/* The string "UTF-8". This is here so we can check for the UTF-8
210 charset using == rather than strcmp. */
211static const char ada_utf8[] = "UTF-8";
212
213/* Each entry in the UTF-32 case-folding table is of this form. */
214struct utf8_entry
215{
216 /* The start and end, inclusive, of this range of codepoints. */
217 uint32_t start, end;
218 /* The delta to apply to get the upper-case form. 0 if this is
219 already upper-case. */
220 int upper_delta;
221 /* The delta to apply to get the lower-case form. 0 if this is
222 already lower-case. */
223 int lower_delta;
224
225 bool operator< (uint32_t val) const
226 {
227 return end < val;
228 }
229};
230
231static const utf8_entry ada_case_fold[] =
232{
233#include "ada-casefold.h"
234};
235
236\f
237
67cb5b2d 238static const char ada_completer_word_break_characters[] =
4c4b4cd2
PH
239#ifdef VMS
240 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
241#else
14f9c5c9 242 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
4c4b4cd2 243#endif
14f9c5c9 244
4c4b4cd2 245/* The name of the symbol to use to get the name of the main subprogram. */
76a01679 246static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
4c4b4cd2 247 = "__gnat_ada_main_program_name";
14f9c5c9 248
4c4b4cd2
PH
249/* Limit on the number of warnings to raise per expression evaluation. */
250static int warning_limit = 2;
251
252/* Number of warning messages issued; reset to 0 by cleanups after
253 expression evaluation. */
254static int warnings_issued = 0;
255
27087b7f 256static const char * const known_runtime_file_name_patterns[] = {
4c4b4cd2
PH
257 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
258};
259
27087b7f 260static const char * const known_auxiliary_function_name_patterns[] = {
4c4b4cd2
PH
261 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
262};
263
c6044dd1
JB
264/* Maintenance-related settings for this module. */
265
266static struct cmd_list_element *maint_set_ada_cmdlist;
267static struct cmd_list_element *maint_show_ada_cmdlist;
268
c6044dd1
JB
269/* The "maintenance ada set/show ignore-descriptive-type" value. */
270
491144b5 271static bool ada_ignore_descriptive_types_p = false;
c6044dd1 272
e802dbe0
JB
273 /* Inferior-specific data. */
274
275/* Per-inferior data for this module. */
276
277struct ada_inferior_data
278{
279 /* The ada__tags__type_specific_data type, which is used when decoding
280 tagged types. With older versions of GNAT, this type was directly
281 accessible through a component ("tsd") in the object tag. But this
282 is no longer the case, so we cache it for each inferior. */
f37b313d 283 struct type *tsd_type = nullptr;
3eecfa55
JB
284
285 /* The exception_support_info data. This data is used to determine
286 how to implement support for Ada exception catchpoints in a given
287 inferior. */
f37b313d 288 const struct exception_support_info *exception_info = nullptr;
e802dbe0
JB
289};
290
291/* Our key to this module's inferior data. */
08b8a139 292static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
e802dbe0
JB
293
294/* Return our inferior data for the given inferior (INF).
295
296 This function always returns a valid pointer to an allocated
297 ada_inferior_data structure. If INF's inferior data has not
298 been previously set, this functions creates a new one with all
299 fields set to zero, sets INF's inferior to it, and then returns
300 a pointer to that newly allocated ada_inferior_data. */
301
302static struct ada_inferior_data *
303get_ada_inferior_data (struct inferior *inf)
304{
305 struct ada_inferior_data *data;
306
f37b313d 307 data = ada_inferior_data.get (inf);
e802dbe0 308 if (data == NULL)
f37b313d 309 data = ada_inferior_data.emplace (inf);
e802dbe0
JB
310
311 return data;
312}
313
314/* Perform all necessary cleanups regarding our module's inferior data
315 that is required after the inferior INF just exited. */
316
317static void
318ada_inferior_exit (struct inferior *inf)
319{
f37b313d 320 ada_inferior_data.clear (inf);
e802dbe0
JB
321}
322
ee01b665
JB
323
324 /* program-space-specific data. */
325
9d1c303d
TT
326/* The result of a symbol lookup to be stored in our symbol cache. */
327
328struct cache_entry
ee01b665 329{
9d1c303d
TT
330 /* The name used to perform the lookup. */
331 std::string name;
332 /* The namespace used during the lookup. */
6c015214 333 domain_search_flags domain = 0;
9d1c303d
TT
334 /* The symbol returned by the lookup, or NULL if no matching symbol
335 was found. */
336 struct symbol *sym = nullptr;
337 /* The block where the symbol was found, or NULL if no matching
338 symbol was found. */
339 const struct block *block = nullptr;
ee01b665
JB
340};
341
9d1c303d
TT
342/* The symbol cache uses this type when searching. */
343
344struct cache_entry_search
345{
346 const char *name;
6c015214 347 domain_search_flags domain;
9d1c303d
TT
348
349 hashval_t hash () const
350 {
351 /* This must agree with hash_cache_entry, below. */
352 return htab_hash_string (name);
353 }
354};
355
356/* Hash function for cache_entry. */
357
358static hashval_t
359hash_cache_entry (const void *v)
360{
361 const cache_entry *entry = (const cache_entry *) v;
362 return htab_hash_string (entry->name.c_str ());
363}
364
365/* Equality function for cache_entry. */
366
367static int
368eq_cache_entry (const void *a, const void *b)
369{
370 const cache_entry *entrya = (const cache_entry *) a;
371 const cache_entry_search *entryb = (const cache_entry_search *) b;
372
373 return entrya->domain == entryb->domain && entrya->name == entryb->name;
374}
375
ee01b665 376/* Key to our per-program-space data. */
9d1c303d 377static const registry<program_space>::key<htab, htab_deleter>
08b8a139 378 ada_pspace_data_handle;
ee01b665
JB
379
380/* Return this module's data for the given program space (PSPACE).
381 If not is found, add a zero'ed one now.
382
383 This function always returns a valid object. */
384
9d1c303d 385static htab_t
ee01b665
JB
386get_ada_pspace_data (struct program_space *pspace)
387{
9d1c303d
TT
388 htab_t data = ada_pspace_data_handle.get (pspace);
389 if (data == nullptr)
390 {
391 data = htab_create_alloc (10, hash_cache_entry, eq_cache_entry,
392 htab_delete_entry<cache_entry>,
393 xcalloc, xfree);
394 ada_pspace_data_handle.set (pspace, data);
395 }
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
9c0fb734 676 if (high.is_constant ())
d1fd641e
SM
677 return high.const_val ();
678 else
679 {
a8b16509 680 gdb_assert (!high.is_available ());
d1fd641e
SM
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
9c0fb734 711 if (low.is_constant ())
d1fd641e
SM
712 return low.const_val ();
713 else
714 {
a8b16509 715 gdb_assert (!low.is_available ());
d1fd641e
SM
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 792
96d887e8
PH
793/* If the main procedure is written in Ada, then return its name.
794 The result is good until the next call. Return NULL if the main
795 procedure doesn't appear to be in Ada. */
796
6f63b61d
TT
797const char *
798ada_main_name ()
96d887e8 799{
3b7344d5 800 struct bound_minimal_symbol msym;
e83e4e24 801 static gdb::unique_xmalloc_ptr<char> main_program_name;
6c038f32 802
96d887e8
PH
803 /* For Ada, the name of the main procedure is stored in a specific
804 string constant, generated by the binder. Look for that symbol,
805 extract its address, and then read that string. If we didn't find
806 that string, then most probably the main procedure is not written
807 in Ada. */
808 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
809
3b7344d5 810 if (msym.minsym != NULL)
96d887e8 811 {
4aeddc50 812 CORE_ADDR main_program_name_addr = msym.value_address ();
96d887e8 813 if (main_program_name_addr == 0)
dda83cd7 814 error (_("Invalid address for Ada main program name."));
96d887e8 815
358be6e7
TT
816 /* Force trust_readonly, because we always want to fetch this
817 string from the executable, not from inferior memory. If the
818 user changes the exec-file and invokes "start", we want to
819 pick the "main" from the new executable, not one that may
820 come from the still-live inferior. */
821 scoped_restore save_trust_readonly
822 = make_scoped_restore (&trust_readonly, true);
66920317 823 main_program_name = target_read_string (main_program_name_addr, 1024);
e83e4e24 824 return main_program_name.get ();
96d887e8
PH
825 }
826
827 /* The main procedure doesn't seem to be in Ada. */
828 return NULL;
829}
14f9c5c9 830\f
dda83cd7 831 /* Symbols */
d2e4a39e 832
4c4b4cd2
PH
833/* Table of Ada operators and their GNAT-encoded names. Last entry is pair
834 of NULLs. */
14f9c5c9 835
d2e4a39e
AS
836const struct ada_opname_map ada_opname_table[] = {
837 {"Oadd", "\"+\"", BINOP_ADD},
838 {"Osubtract", "\"-\"", BINOP_SUB},
839 {"Omultiply", "\"*\"", BINOP_MUL},
840 {"Odivide", "\"/\"", BINOP_DIV},
841 {"Omod", "\"mod\"", BINOP_MOD},
842 {"Orem", "\"rem\"", BINOP_REM},
843 {"Oexpon", "\"**\"", BINOP_EXP},
844 {"Olt", "\"<\"", BINOP_LESS},
845 {"Ole", "\"<=\"", BINOP_LEQ},
846 {"Ogt", "\">\"", BINOP_GTR},
847 {"Oge", "\">=\"", BINOP_GEQ},
848 {"Oeq", "\"=\"", BINOP_EQUAL},
849 {"One", "\"/=\"", BINOP_NOTEQUAL},
850 {"Oand", "\"and\"", BINOP_BITWISE_AND},
851 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
852 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
853 {"Oconcat", "\"&\"", BINOP_CONCAT},
854 {"Oabs", "\"abs\"", UNOP_ABS},
855 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
856 {"Oadd", "\"+\"", UNOP_PLUS},
857 {"Osubtract", "\"-\"", UNOP_NEG},
858 {NULL, NULL}
14f9c5c9
AS
859};
860
965bc1df
TT
861/* If STR is a decoded version of a compiler-provided suffix (like the
862 "[cold]" in "symbol[cold]"), return true. Otherwise, return
863 false. */
864
865static bool
866is_compiler_suffix (const char *str)
867{
868 gdb_assert (*str == '[');
869 ++str;
870 while (*str != '\0' && isalpha (*str))
871 ++str;
872 /* We accept a missing "]" in order to support completion. */
873 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
874}
875
315e4ebb
TT
876/* Append a non-ASCII character to RESULT. */
877static void
878append_hex_encoded (std::string &result, uint32_t one_char)
879{
880 if (one_char <= 0xff)
881 {
882 result.append ("U");
883 result.append (phex (one_char, 1));
884 }
885 else if (one_char <= 0xffff)
886 {
887 result.append ("W");
888 result.append (phex (one_char, 2));
889 }
890 else
891 {
892 result.append ("WW");
893 result.append (phex (one_char, 4));
894 }
895}
896
897/* Return a string that is a copy of the data in STORAGE, with
898 non-ASCII characters replaced by the appropriate hex encoding. A
899 template is used because, for UTF-8, we actually want to work with
900 UTF-32 codepoints. */
901template<typename T>
902std::string
903copy_and_hex_encode (struct obstack *storage)
904{
905 const T *chars = (T *) obstack_base (storage);
906 int num_chars = obstack_object_size (storage) / sizeof (T);
907 std::string result;
908 for (int i = 0; i < num_chars; ++i)
909 {
910 if (chars[i] <= 0x7f)
911 {
912 /* The host character set has to be a superset of ASCII, as
913 are all the other character sets we can use. */
914 result.push_back (chars[i]);
915 }
916 else
917 append_hex_encoded (result, chars[i]);
918 }
919 return result;
920}
921
5c4258f4 922/* The "encoded" form of DECODED, according to GNAT conventions. If
b5ec771e 923 THROW_ERRORS, throw an error if invalid operator name is found.
5c4258f4 924 Otherwise, return the empty string in that case. */
4c4b4cd2 925
5c4258f4 926static std::string
b5ec771e 927ada_encode_1 (const char *decoded, bool throw_errors)
14f9c5c9 928{
4c4b4cd2 929 if (decoded == NULL)
5c4258f4 930 return {};
14f9c5c9 931
5c4258f4 932 std::string encoding_buffer;
315e4ebb 933 bool saw_non_ascii = false;
5c4258f4 934 for (const char *p = decoded; *p != '\0'; p += 1)
14f9c5c9 935 {
315e4ebb
TT
936 if ((*p & 0x80) != 0)
937 saw_non_ascii = true;
938
cdc7bb92 939 if (*p == '.')
5c4258f4 940 encoding_buffer.append ("__");
965bc1df
TT
941 else if (*p == '[' && is_compiler_suffix (p))
942 {
943 encoding_buffer = encoding_buffer + "." + (p + 1);
944 if (encoding_buffer.back () == ']')
945 encoding_buffer.pop_back ();
946 break;
947 }
14f9c5c9 948 else if (*p == '"')
dda83cd7
SM
949 {
950 const struct ada_opname_map *mapping;
951
952 for (mapping = ada_opname_table;
953 mapping->encoded != NULL
954 && !startswith (p, mapping->decoded); mapping += 1)
955 ;
956 if (mapping->encoded == NULL)
b5ec771e
PA
957 {
958 if (throw_errors)
959 error (_("invalid Ada operator name: %s"), p);
960 else
5c4258f4 961 return {};
b5ec771e 962 }
5c4258f4 963 encoding_buffer.append (mapping->encoded);
dda83cd7
SM
964 break;
965 }
d2e4a39e 966 else
5c4258f4 967 encoding_buffer.push_back (*p);
14f9c5c9
AS
968 }
969
315e4ebb
TT
970 /* If a non-ASCII character is seen, we must convert it to the
971 appropriate hex form. As this is more expensive, we keep track
972 of whether it is even necessary. */
973 if (saw_non_ascii)
974 {
975 auto_obstack storage;
976 bool is_utf8 = ada_source_charset == ada_utf8;
977 try
978 {
979 convert_between_encodings
980 (host_charset (),
981 is_utf8 ? HOST_UTF32 : ada_source_charset,
982 (const gdb_byte *) encoding_buffer.c_str (),
983 encoding_buffer.length (), 1,
984 &storage, translit_none);
985 }
986 catch (const gdb_exception &)
987 {
988 static bool warned = false;
989
990 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
991 might like to know why. */
992 if (!warned)
993 {
994 warned = true;
995 warning (_("charset conversion failure for '%s'.\n"
996 "You may have the wrong value for 'set ada source-charset'."),
997 encoding_buffer.c_str ());
998 }
999
1000 /* We don't try to recover from errors. */
1001 return encoding_buffer;
1002 }
1003
1004 if (is_utf8)
1005 return copy_and_hex_encode<uint32_t> (&storage);
1006 return copy_and_hex_encode<gdb_byte> (&storage);
1007 }
1008
4c4b4cd2 1009 return encoding_buffer;
14f9c5c9
AS
1010}
1011
315e4ebb
TT
1012/* Find the entry for C in the case-folding table. Return nullptr if
1013 the entry does not cover C. */
1014static const utf8_entry *
1015find_case_fold_entry (uint32_t c)
b5ec771e 1016{
315e4ebb
TT
1017 auto iter = std::lower_bound (std::begin (ada_case_fold),
1018 std::end (ada_case_fold),
1019 c);
1020 if (iter == std::end (ada_case_fold)
1021 || c < iter->start
1022 || c > iter->end)
1023 return nullptr;
1024 return &*iter;
b5ec771e
PA
1025}
1026
14f9c5c9 1027/* Return NAME folded to lower case, or, if surrounded by single
315e4ebb
TT
1028 quotes, unfolded, but with the quotes stripped away. If
1029 THROW_ON_ERROR is true, encoding failures will throw an exception
1030 rather than emitting a warning. Result good to next call. */
4c4b4cd2 1031
5f9febe0 1032static const char *
8082468f 1033ada_fold_name (std::string_view name, bool throw_on_error = false)
14f9c5c9 1034{
5f9febe0 1035 static std::string fold_storage;
14f9c5c9 1036
6a780b67 1037 if (!name.empty () && name[0] == '\'')
882b0505 1038 fold_storage = name.substr (1, name.size () - 2);
14f9c5c9
AS
1039 else
1040 {
315e4ebb
TT
1041 /* Why convert to UTF-32 and implement our own case-folding,
1042 rather than convert to wchar_t and use the platform's
1043 functions? I'm glad you asked.
1044
1045 The main problem is that GNAT implements an unusual rule for
1046 case folding. For ASCII letters, letters in single-byte
1047 encodings (such as ISO-8859-*), and Unicode letters that fit
1048 in a single byte (i.e., code point is <= 0xff), the letter is
1049 folded to lower case. Other Unicode letters are folded to
1050 upper case.
1051
1052 This rule means that the code must be able to examine the
1053 value of the character. And, some hosts do not use Unicode
1054 for wchar_t, so examining the value of such characters is
1055 forbidden. */
1056 auto_obstack storage;
1057 try
1058 {
1059 convert_between_encodings
1060 (host_charset (), HOST_UTF32,
1061 (const gdb_byte *) name.data (),
1062 name.length (), 1,
1063 &storage, translit_none);
1064 }
1065 catch (const gdb_exception &)
1066 {
1067 if (throw_on_error)
1068 throw;
1069
1070 static bool warned = false;
1071
1072 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1073 might like to know why. */
1074 if (!warned)
1075 {
1076 warned = true;
1077 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1078 "This normally should not happen, please file a bug report."),
882b0505 1079 std::string (name).c_str (), host_charset ());
315e4ebb
TT
1080 }
1081
1082 /* We don't try to recover from errors; just return the
1083 original string. */
882b0505 1084 fold_storage = name;
315e4ebb
TT
1085 return fold_storage.c_str ();
1086 }
1087
1088 bool is_utf8 = ada_source_charset == ada_utf8;
1089 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1090 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1091 for (int i = 0; i < num_chars; ++i)
1092 {
1093 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1094 if (entry != nullptr)
1095 {
1096 uint32_t low = chars[i] + entry->lower_delta;
1097 if (!is_utf8 || low <= 0xff)
1098 chars[i] = low;
1099 else
1100 chars[i] = chars[i] + entry->upper_delta;
1101 }
1102 }
1103
1104 /* Now convert back to ordinary characters. */
1105 auto_obstack reconverted;
1106 try
1107 {
1108 convert_between_encodings (HOST_UTF32,
1109 host_charset (),
1110 (const gdb_byte *) chars,
1111 num_chars * sizeof (uint32_t),
1112 sizeof (uint32_t),
1113 &reconverted,
1114 translit_none);
1115 obstack_1grow (&reconverted, '\0');
1116 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1117 }
1118 catch (const gdb_exception &)
1119 {
1120 if (throw_on_error)
1121 throw;
1122
1123 static bool warned = false;
1124
1125 /* Converting back from UTF-32 shouldn't normally fail, but
1126 there are some host encodings without upper/lower
1127 equivalence. */
1128 if (!warned)
1129 {
1130 warned = true;
1131 warning (_("could not convert the lower-cased variant of '%s'\n"
1132 "from UTF-32 to the host encoding (%s)."),
882b0505 1133 std::string (name).c_str (), host_charset ());
315e4ebb
TT
1134 }
1135
1136 /* We don't try to recover from errors; just return the
1137 original string. */
882b0505 1138 fold_storage = name;
315e4ebb 1139 }
14f9c5c9
AS
1140 }
1141
5f9febe0 1142 return fold_storage.c_str ();
14f9c5c9
AS
1143}
1144
5fea9794
TT
1145/* The "encoded" form of DECODED, according to GNAT conventions. If
1146 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1147 with <...> quoting are not folded in any case. */
315e4ebb
TT
1148
1149std::string
5fea9794 1150ada_encode (const char *decoded, bool fold)
315e4ebb 1151{
5fea9794 1152 if (fold && decoded[0] != '<')
315e4ebb
TT
1153 decoded = ada_fold_name (decoded);
1154 return ada_encode_1 (decoded, true);
1155}
1156
529cad9c
PH
1157/* Return nonzero if C is either a digit or a lowercase alphabet character. */
1158
1159static int
1160is_lower_alphanum (const char c)
1161{
1162 return (isdigit (c) || (isalpha (c) && islower (c)));
1163}
1164
c90092fe
JB
1165/* ENCODED is the linkage name of a symbol and LEN contains its length.
1166 This function saves in LEN the length of that same symbol name but
1167 without either of these suffixes:
29480c32
JB
1168 . .{DIGIT}+
1169 . ${DIGIT}+
1170 . ___{DIGIT}+
1171 . __{DIGIT}+.
c90092fe 1172
29480c32
JB
1173 These are suffixes introduced by the compiler for entities such as
1174 nested subprogram for instance, in order to avoid name clashes.
1175 They do not serve any purpose for the debugger. */
1176
1177static void
1178ada_remove_trailing_digits (const char *encoded, int *len)
1179{
1180 if (*len > 1 && isdigit (encoded[*len - 1]))
1181 {
1182 int i = *len - 2;
5b4ee69b 1183
29480c32 1184 while (i > 0 && isdigit (encoded[i]))
dda83cd7 1185 i--;
29480c32 1186 if (i >= 0 && encoded[i] == '.')
dda83cd7 1187 *len = i;
29480c32 1188 else if (i >= 0 && encoded[i] == '$')
dda83cd7 1189 *len = i;
61012eef 1190 else if (i >= 2 && startswith (encoded + i - 2, "___"))
dda83cd7 1191 *len = i - 2;
61012eef 1192 else if (i >= 1 && startswith (encoded + i - 1, "__"))
dda83cd7 1193 *len = i - 1;
29480c32
JB
1194 }
1195}
1196
1197/* Remove the suffix introduced by the compiler for protected object
1198 subprograms. */
1199
1200static void
1201ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1202{
1203 /* Remove trailing N. */
1204
1205 /* Protected entry subprograms are broken into two
1206 separate subprograms: The first one is unprotected, and has
1207 a 'N' suffix; the second is the protected version, and has
0963b4bd 1208 the 'P' suffix. The second calls the first one after handling
29480c32
JB
1209 the protection. Since the P subprograms are internally generated,
1210 we leave these names undecoded, giving the user a clue that this
1211 entity is internal. */
1212
1213 if (*len > 1
1214 && encoded[*len - 1] == 'N'
1215 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1216 *len = *len - 1;
1217}
1218
965bc1df
TT
1219/* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1220 then update *LEN to remove the suffix and return the offset of the
1221 character just past the ".". Otherwise, return -1. */
1222
1223static int
1224remove_compiler_suffix (const char *encoded, int *len)
1225{
1226 int offset = *len - 1;
1227 while (offset > 0 && isalpha (encoded[offset]))
1228 --offset;
1229 if (offset > 0 && encoded[offset] == '.')
1230 {
1231 *len = offset;
1232 return offset + 1;
1233 }
1234 return -1;
1235}
1236
315e4ebb
TT
1237/* Convert an ASCII hex string to a number. Reads exactly N
1238 characters from STR. Returns true on success, false if one of the
1239 digits was not a hex digit. */
1240static bool
1241convert_hex (const char *str, int n, uint32_t *out)
1242{
1243 uint32_t result = 0;
1244
1245 for (int i = 0; i < n; ++i)
1246 {
1247 if (!isxdigit (str[i]))
1248 return false;
1249 result <<= 4;
1250 result |= fromhex (str[i]);
1251 }
1252
1253 *out = result;
1254 return true;
1255}
1256
1257/* Convert a wide character from its ASCII hex representation in STR
1258 (consisting of exactly N characters) to the host encoding,
1259 appending the resulting bytes to OUT. If N==2 and the Ada source
1260 charset is not UTF-8, then hex refers to an encoding in the
1261 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1262 Return false and do not modify OUT on conversion failure. */
1263static bool
1264convert_from_hex_encoded (std::string &out, const char *str, int n)
1265{
1266 uint32_t value;
1267
1268 if (!convert_hex (str, n, &value))
1269 return false;
1270 try
1271 {
1272 auto_obstack bytes;
1273 /* In the 'U' case, the hex digits encode the character in the
1274 Ada source charset. However, if the source charset is UTF-8,
1275 this really means it is a single-byte UTF-32 character. */
1276 if (n == 2 && ada_source_charset != ada_utf8)
1277 {
1278 gdb_byte one_char = (gdb_byte) value;
1279
1280 convert_between_encodings (ada_source_charset, host_charset (),
1281 &one_char,
1282 sizeof (one_char), sizeof (one_char),
1283 &bytes, translit_none);
1284 }
1285 else
1286 convert_between_encodings (HOST_UTF32, host_charset (),
1287 (const gdb_byte *) &value,
1288 sizeof (value), sizeof (value),
1289 &bytes, translit_none);
1290 obstack_1grow (&bytes, '\0');
1291 out.append ((const char *) obstack_base (&bytes));
1292 }
1293 catch (const gdb_exception &)
1294 {
1295 /* On failure, the caller will just let the encoded form
1296 through, which seems basically reasonable. */
1297 return false;
1298 }
1299
1300 return true;
1301}
1302
8a3df5ac 1303/* See ada-lang.h. */
14f9c5c9 1304
f945dedf 1305std::string
957ce537 1306ada_decode (const char *encoded, bool wrap, bool operators, bool wide)
14f9c5c9 1307{
36f5ca53 1308 int i;
14f9c5c9 1309 int len0;
d2e4a39e 1310 const char *p;
14f9c5c9 1311 int at_start_name;
f945dedf 1312 std::string decoded;
965bc1df 1313 int suffix = -1;
d2e4a39e 1314
0d81f350
JG
1315 /* With function descriptors on PPC64, the value of a symbol named
1316 ".FN", if it exists, is the entry point of the function "FN". */
1317 if (encoded[0] == '.')
1318 encoded += 1;
1319
29480c32
JB
1320 /* The name of the Ada main procedure starts with "_ada_".
1321 This prefix is not part of the decoded name, so skip this part
1322 if we see this prefix. */
61012eef 1323 if (startswith (encoded, "_ada_"))
4c4b4cd2 1324 encoded += 5;
81eaa506
TT
1325 /* The "___ghost_" prefix is used for ghost entities. Normally
1326 these aren't preserved but when they are, it's useful to see
1327 them. */
1328 if (startswith (encoded, "___ghost_"))
1329 encoded += 9;
14f9c5c9 1330
29480c32
JB
1331 /* If the name starts with '_', then it is not a properly encoded
1332 name, so do not attempt to decode it. Similarly, if the name
1333 starts with '<', the name should not be decoded. */
4c4b4cd2 1334 if (encoded[0] == '_' || encoded[0] == '<')
14f9c5c9
AS
1335 goto Suppress;
1336
4c4b4cd2 1337 len0 = strlen (encoded);
4c4b4cd2 1338
965bc1df
TT
1339 suffix = remove_compiler_suffix (encoded, &len0);
1340
29480c32
JB
1341 ada_remove_trailing_digits (encoded, &len0);
1342 ada_remove_po_subprogram_suffix (encoded, &len0);
529cad9c 1343
4c4b4cd2
PH
1344 /* Remove the ___X.* suffix if present. Do not forget to verify that
1345 the suffix is located before the current "end" of ENCODED. We want
1346 to avoid re-matching parts of ENCODED that have previously been
1347 marked as discarded (by decrementing LEN0). */
1348 p = strstr (encoded, "___");
1349 if (p != NULL && p - encoded < len0 - 3)
14f9c5c9
AS
1350 {
1351 if (p[3] == 'X')
dda83cd7 1352 len0 = p - encoded;
14f9c5c9 1353 else
dda83cd7 1354 goto Suppress;
14f9c5c9 1355 }
4c4b4cd2 1356
29480c32
JB
1357 /* Remove any trailing TKB suffix. It tells us that this symbol
1358 is for the body of a task, but that information does not actually
1359 appear in the decoded name. */
1360
61012eef 1361 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
14f9c5c9 1362 len0 -= 3;
76a01679 1363
a10967fa
JB
1364 /* Remove any trailing TB suffix. The TB suffix is slightly different
1365 from the TKB suffix because it is used for non-anonymous task
1366 bodies. */
1367
61012eef 1368 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
a10967fa
JB
1369 len0 -= 2;
1370
29480c32
JB
1371 /* Remove trailing "B" suffixes. */
1372 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1373
61012eef 1374 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
14f9c5c9
AS
1375 len0 -= 1;
1376
29480c32
JB
1377 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1378
4c4b4cd2 1379 if (len0 > 1 && isdigit (encoded[len0 - 1]))
d2e4a39e 1380 {
4c4b4cd2
PH
1381 i = len0 - 2;
1382 while ((i >= 0 && isdigit (encoded[i]))
dda83cd7
SM
1383 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1384 i -= 1;
4c4b4cd2 1385 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
dda83cd7 1386 len0 = i - 1;
033bc52b 1387 else if (i >= 0 && encoded[i] == '$')
dda83cd7 1388 len0 = i;
d2e4a39e 1389 }
14f9c5c9 1390
29480c32
JB
1391 /* The first few characters that are not alphabetic are not part
1392 of any encoding we use, so we can copy them over verbatim. */
1393
36f5ca53
TT
1394 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1395 decoded.push_back (encoded[i]);
14f9c5c9
AS
1396
1397 at_start_name = 1;
1398 while (i < len0)
1399 {
29480c32 1400 /* Is this a symbol function? */
5c94f938 1401 if (operators && at_start_name && encoded[i] == 'O')
dda83cd7
SM
1402 {
1403 int k;
1404
1405 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1406 {
1407 int op_len = strlen (ada_opname_table[k].encoded);
1408 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1409 op_len - 1) == 0)
1410 && !isalnum (encoded[i + op_len]))
1411 {
36f5ca53 1412 decoded.append (ada_opname_table[k].decoded);
dda83cd7
SM
1413 at_start_name = 0;
1414 i += op_len;
dda83cd7
SM
1415 break;
1416 }
1417 }
1418 if (ada_opname_table[k].encoded != NULL)
1419 continue;
1420 }
14f9c5c9
AS
1421 at_start_name = 0;
1422
529cad9c 1423 /* Replace "TK__" with "__", which will eventually be translated
dda83cd7 1424 into "." (just below). */
529cad9c 1425
61012eef 1426 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
dda83cd7 1427 i += 2;
529cad9c 1428
29480c32 1429 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
dda83cd7
SM
1430 be translated into "." (just below). These are internal names
1431 generated for anonymous blocks inside which our symbol is nested. */
29480c32
JB
1432
1433 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
dda83cd7
SM
1434 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1435 && isdigit (encoded [i+4]))
1436 {
1437 int k = i + 5;
1438
1439 while (k < len0 && isdigit (encoded[k]))
1440 k++; /* Skip any extra digit. */
1441
1442 /* Double-check that the "__B_{DIGITS}+" sequence we found
1443 is indeed followed by "__". */
1444 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1445 i = k;
1446 }
29480c32 1447
529cad9c
PH
1448 /* Remove _E{DIGITS}+[sb] */
1449
1450 /* Just as for protected object subprograms, there are 2 categories
dda83cd7
SM
1451 of subprograms created by the compiler for each entry. The first
1452 one implements the actual entry code, and has a suffix following
1453 the convention above; the second one implements the barrier and
1454 uses the same convention as above, except that the 'E' is replaced
1455 by a 'B'.
529cad9c 1456
dda83cd7
SM
1457 Just as above, we do not decode the name of barrier functions
1458 to give the user a clue that the code he is debugging has been
1459 internally generated. */
529cad9c
PH
1460
1461 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
dda83cd7
SM
1462 && isdigit (encoded[i+2]))
1463 {
1464 int k = i + 3;
1465
1466 while (k < len0 && isdigit (encoded[k]))
1467 k++;
1468
1469 if (k < len0
1470 && (encoded[k] == 'b' || encoded[k] == 's'))
1471 {
1472 k++;
1473 /* Just as an extra precaution, make sure that if this
1474 suffix is followed by anything else, it is a '_'.
1475 Otherwise, we matched this sequence by accident. */
1476 if (k == len0
1477 || (k < len0 && encoded[k] == '_'))
1478 i = k;
1479 }
1480 }
529cad9c
PH
1481
1482 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
dda83cd7 1483 the GNAT front-end in protected object subprograms. */
529cad9c
PH
1484
1485 if (i < len0 + 3
dda83cd7
SM
1486 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1487 {
1488 /* Backtrack a bit up until we reach either the begining of
1489 the encoded name, or "__". Make sure that we only find
1490 digits or lowercase characters. */
1491 const char *ptr = encoded + i - 1;
1492
1493 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1494 ptr--;
1495 if (ptr < encoded
1496 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1497 i++;
1498 }
529cad9c 1499
957ce537 1500 if (wide && i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
315e4ebb
TT
1501 {
1502 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1503 {
1504 i += 3;
1505 continue;
1506 }
1507 }
957ce537 1508 else if (wide && i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
315e4ebb
TT
1509 {
1510 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1511 {
1512 i += 5;
1513 continue;
1514 }
1515 }
957ce537 1516 else if (wide && i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
315e4ebb
TT
1517 && isxdigit (encoded[i + 2]))
1518 {
1519 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1520 {
1521 i += 10;
1522 continue;
1523 }
1524 }
1525
4c4b4cd2 1526 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
dda83cd7
SM
1527 {
1528 /* This is a X[bn]* sequence not separated from the previous
1529 part of the name with a non-alpha-numeric character (in other
1530 words, immediately following an alpha-numeric character), then
1531 verify that it is placed at the end of the encoded name. If
1532 not, then the encoding is not valid and we should abort the
1533 decoding. Otherwise, just skip it, it is used in body-nested
1534 package names. */
1535 do
1536 i += 1;
1537 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1538 if (i < len0)
1539 goto Suppress;
1540 }
cdc7bb92 1541 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
dda83cd7
SM
1542 {
1543 /* Replace '__' by '.'. */
36f5ca53 1544 decoded.push_back ('.');
dda83cd7
SM
1545 at_start_name = 1;
1546 i += 2;
dda83cd7 1547 }
14f9c5c9 1548 else
dda83cd7
SM
1549 {
1550 /* It's a character part of the decoded name, so just copy it
1551 over. */
36f5ca53 1552 decoded.push_back (encoded[i]);
dda83cd7 1553 i += 1;
dda83cd7 1554 }
14f9c5c9 1555 }
14f9c5c9 1556
29480c32
JB
1557 /* Decoded names should never contain any uppercase character.
1558 Double-check this, and abort the decoding if we find one. */
1559
5c94f938
TT
1560 if (operators)
1561 {
1562 for (i = 0; i < decoded.length(); ++i)
1563 if (isupper (decoded[i]) || decoded[i] == ' ')
1564 goto Suppress;
1565 }
14f9c5c9 1566
965bc1df
TT
1567 /* If the compiler added a suffix, append it now. */
1568 if (suffix >= 0)
1569 decoded = decoded + "[" + &encoded[suffix] + "]";
1570
f945dedf 1571 return decoded;
14f9c5c9
AS
1572
1573Suppress:
8a3df5ac
TT
1574 if (!wrap)
1575 return {};
1576
4c4b4cd2 1577 if (encoded[0] == '<')
f945dedf 1578 decoded = encoded;
14f9c5c9 1579 else
f945dedf 1580 decoded = '<' + std::string(encoded) + '>';
4c4b4cd2 1581 return decoded;
4c4b4cd2
PH
1582}
1583
033bc52b
TT
1584#ifdef GDB_SELF_TEST
1585
1586static void
1587ada_decode_tests ()
1588{
1589 /* This isn't valid, but used to cause a crash. PR gdb/30639. The
1590 result does not really matter very much. */
1591 SELF_CHECK (ada_decode ("44") == "44");
1592}
1593
1594#endif
1595
4c4b4cd2
PH
1596/* Table for keeping permanent unique copies of decoded names. Once
1597 allocated, names in this table are never released. While this is a
1598 storage leak, it should not be significant unless there are massive
1599 changes in the set of decoded names in successive versions of a
1600 symbol table loaded during a single session. */
1601static struct htab *decoded_names_store;
1602
1603/* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1604 in the language-specific part of GSYMBOL, if it has not been
1605 previously computed. Tries to save the decoded name in the same
1606 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1607 in any case, the decoded symbol has a lifetime at least that of
0963b4bd 1608 GSYMBOL).
4c4b4cd2
PH
1609 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1610 const, but nevertheless modified to a semantically equivalent form
0963b4bd 1611 when a decoded name is cached in it. */
4c4b4cd2 1612
45e6c716 1613const char *
f85f34ed 1614ada_decode_symbol (const struct general_symbol_info *arg)
4c4b4cd2 1615{
f85f34ed
TT
1616 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1617 const char **resultp =
615b3f62 1618 &gsymbol->language_specific.demangled_name;
5b4ee69b 1619
f85f34ed 1620 if (!gsymbol->ada_mangled)
4c4b4cd2 1621 {
4d4eaa30 1622 std::string decoded = ada_decode (gsymbol->linkage_name ());
f85f34ed 1623 struct obstack *obstack = gsymbol->language_specific.obstack;
5b4ee69b 1624
f85f34ed 1625 gsymbol->ada_mangled = 1;
5b4ee69b 1626
f85f34ed 1627 if (obstack != NULL)
f945dedf 1628 *resultp = obstack_strdup (obstack, decoded.c_str ());
f85f34ed 1629 else
dda83cd7 1630 {
f85f34ed
TT
1631 /* Sometimes, we can't find a corresponding objfile, in
1632 which case, we put the result on the heap. Since we only
1633 decode when needed, we hope this usually does not cause a
1634 significant memory leak (FIXME). */
1635
dda83cd7
SM
1636 char **slot = (char **) htab_find_slot (decoded_names_store,
1637 decoded.c_str (), INSERT);
5b4ee69b 1638
dda83cd7
SM
1639 if (*slot == NULL)
1640 *slot = xstrdup (decoded.c_str ());
1641 *resultp = *slot;
1642 }
4c4b4cd2 1643 }
14f9c5c9 1644
4c4b4cd2
PH
1645 return *resultp;
1646}
76a01679 1647
14f9c5c9 1648\f
d2e4a39e 1649
dda83cd7 1650 /* Arrays */
14f9c5c9 1651
28c85d6c
JB
1652/* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1653 generated by the GNAT compiler to describe the index type used
1654 for each dimension of an array, check whether it follows the latest
1655 known encoding. If not, fix it up to conform to the latest encoding.
1656 Otherwise, do nothing. This function also does nothing if
1657 INDEX_DESC_TYPE is NULL.
1658
85102364 1659 The GNAT encoding used to describe the array index type evolved a bit.
28c85d6c
JB
1660 Initially, the information would be provided through the name of each
1661 field of the structure type only, while the type of these fields was
1662 described as unspecified and irrelevant. The debugger was then expected
1663 to perform a global type lookup using the name of that field in order
1664 to get access to the full index type description. Because these global
1665 lookups can be very expensive, the encoding was later enhanced to make
1666 the global lookup unnecessary by defining the field type as being
1667 the full index type description.
1668
1669 The purpose of this routine is to allow us to support older versions
1670 of the compiler by detecting the use of the older encoding, and by
1671 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1672 we essentially replace each field's meaningless type by the associated
1673 index subtype). */
1674
1675void
1676ada_fixup_array_indexes_type (struct type *index_desc_type)
1677{
1678 int i;
1679
1680 if (index_desc_type == NULL)
1681 return;
1f704f76 1682 gdb_assert (index_desc_type->num_fields () > 0);
28c85d6c
JB
1683
1684 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1685 to check one field only, no need to check them all). If not, return
1686 now.
1687
1688 If our INDEX_DESC_TYPE was generated using the older encoding,
1689 the field type should be a meaningless integer type whose name
1690 is not equal to the field name. */
940da03e
SM
1691 if (index_desc_type->field (0).type ()->name () != NULL
1692 && strcmp (index_desc_type->field (0).type ()->name (),
33d16dd9 1693 index_desc_type->field (0).name ()) == 0)
28c85d6c
JB
1694 return;
1695
1696 /* Fixup each field of INDEX_DESC_TYPE. */
1f704f76 1697 for (i = 0; i < index_desc_type->num_fields (); i++)
28c85d6c 1698 {
33d16dd9 1699 const char *name = index_desc_type->field (i).name ();
28c85d6c
JB
1700 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1701
1702 if (raw_type)
5d14b6e5 1703 index_desc_type->field (i).set_type (raw_type);
28c85d6c
JB
1704 }
1705}
1706
4c4b4cd2
PH
1707/* The desc_* routines return primitive portions of array descriptors
1708 (fat pointers). */
14f9c5c9
AS
1709
1710/* The descriptor or array type, if any, indicated by TYPE; removes
4c4b4cd2
PH
1711 level of indirection, if needed. */
1712
d2e4a39e
AS
1713static struct type *
1714desc_base_type (struct type *type)
14f9c5c9
AS
1715{
1716 if (type == NULL)
1717 return NULL;
61ee279c 1718 type = ada_check_typedef (type);
78134374 1719 if (type->code () == TYPE_CODE_TYPEDEF)
720d1a40
JB
1720 type = ada_typedef_target_type (type);
1721
1265e4aa 1722 if (type != NULL
78134374 1723 && (type->code () == TYPE_CODE_PTR
dda83cd7 1724 || type->code () == TYPE_CODE_REF))
27710edb 1725 return ada_check_typedef (type->target_type ());
14f9c5c9
AS
1726 else
1727 return type;
1728}
1729
4c4b4cd2
PH
1730/* True iff TYPE indicates a "thin" array pointer type. */
1731
14f9c5c9 1732static int
d2e4a39e 1733is_thin_pntr (struct type *type)
14f9c5c9 1734{
d2e4a39e 1735 return
14f9c5c9
AS
1736 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1737 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1738}
1739
4c4b4cd2
PH
1740/* The descriptor type for thin pointer type TYPE. */
1741
d2e4a39e
AS
1742static struct type *
1743thin_descriptor_type (struct type *type)
14f9c5c9 1744{
d2e4a39e 1745 struct type *base_type = desc_base_type (type);
5b4ee69b 1746
14f9c5c9
AS
1747 if (base_type == NULL)
1748 return NULL;
1749 if (is_suffix (ada_type_name (base_type), "___XVE"))
1750 return base_type;
d2e4a39e 1751 else
14f9c5c9 1752 {
d2e4a39e 1753 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
5b4ee69b 1754
14f9c5c9 1755 if (alt_type == NULL)
dda83cd7 1756 return base_type;
14f9c5c9 1757 else
dda83cd7 1758 return alt_type;
14f9c5c9
AS
1759 }
1760}
1761
4c4b4cd2
PH
1762/* A pointer to the array data for thin-pointer value VAL. */
1763
d2e4a39e
AS
1764static struct value *
1765thin_data_pntr (struct value *val)
14f9c5c9 1766{
d0c97917 1767 struct type *type = ada_check_typedef (val->type ());
556bdfd4 1768 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
5b4ee69b 1769
556bdfd4
UW
1770 data_type = lookup_pointer_type (data_type);
1771
78134374 1772 if (type->code () == TYPE_CODE_PTR)
cda03344 1773 return value_cast (data_type, val->copy ());
d2e4a39e 1774 else
9feb2d07 1775 return value_from_longest (data_type, val->address ());
14f9c5c9
AS
1776}
1777
4c4b4cd2
PH
1778/* True iff TYPE indicates a "thick" array pointer type. */
1779
14f9c5c9 1780static int
d2e4a39e 1781is_thick_pntr (struct type *type)
14f9c5c9
AS
1782{
1783 type = desc_base_type (type);
78134374 1784 return (type != NULL && type->code () == TYPE_CODE_STRUCT
dda83cd7 1785 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
14f9c5c9
AS
1786}
1787
4c4b4cd2
PH
1788/* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1789 pointer to one, the type of its bounds data; otherwise, NULL. */
76a01679 1790
d2e4a39e
AS
1791static struct type *
1792desc_bounds_type (struct type *type)
14f9c5c9 1793{
d2e4a39e 1794 struct type *r;
14f9c5c9
AS
1795
1796 type = desc_base_type (type);
1797
1798 if (type == NULL)
1799 return NULL;
1800 else if (is_thin_pntr (type))
1801 {
1802 type = thin_descriptor_type (type);
1803 if (type == NULL)
dda83cd7 1804 return NULL;
14f9c5c9
AS
1805 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1806 if (r != NULL)
dda83cd7 1807 return ada_check_typedef (r);
14f9c5c9 1808 }
78134374 1809 else if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9
AS
1810 {
1811 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1812 if (r != NULL)
27710edb 1813 return ada_check_typedef (ada_check_typedef (r)->target_type ());
14f9c5c9
AS
1814 }
1815 return NULL;
1816}
1817
1818/* If ARR is an array descriptor (fat or thin pointer), or pointer to
4c4b4cd2
PH
1819 one, a pointer to its bounds data. Otherwise NULL. */
1820
d2e4a39e
AS
1821static struct value *
1822desc_bounds (struct value *arr)
14f9c5c9 1823{
d0c97917 1824 struct type *type = ada_check_typedef (arr->type ());
5b4ee69b 1825
d2e4a39e 1826 if (is_thin_pntr (type))
14f9c5c9 1827 {
d2e4a39e 1828 struct type *bounds_type =
dda83cd7 1829 desc_bounds_type (thin_descriptor_type (type));
14f9c5c9
AS
1830 LONGEST addr;
1831
4cdfadb1 1832 if (bounds_type == NULL)
dda83cd7 1833 error (_("Bad GNAT array descriptor"));
14f9c5c9
AS
1834
1835 /* NOTE: The following calculation is not really kosher, but
dda83cd7
SM
1836 since desc_type is an XVE-encoded type (and shouldn't be),
1837 the correct calculation is a real pain. FIXME (and fix GCC). */
78134374 1838 if (type->code () == TYPE_CODE_PTR)
dda83cd7 1839 addr = value_as_long (arr);
d2e4a39e 1840 else
9feb2d07 1841 addr = arr->address ();
14f9c5c9 1842
d2e4a39e 1843 return
dda83cd7 1844 value_from_longest (lookup_pointer_type (bounds_type),
df86565b 1845 addr - bounds_type->length ());
14f9c5c9
AS
1846 }
1847
1848 else if (is_thick_pntr (type))
05e522ef 1849 {
158cc4fe 1850 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
05e522ef 1851 _("Bad GNAT array descriptor"));
d0c97917 1852 struct type *p_bounds_type = p_bounds->type ();
05e522ef
JB
1853
1854 if (p_bounds_type
78134374 1855 && p_bounds_type->code () == TYPE_CODE_PTR)
05e522ef 1856 {
27710edb 1857 struct type *target_type = p_bounds_type->target_type ();
05e522ef 1858
e46d3488 1859 if (target_type->is_stub ())
05e522ef
JB
1860 p_bounds = value_cast (lookup_pointer_type
1861 (ada_check_typedef (target_type)),
1862 p_bounds);
1863 }
1864 else
1865 error (_("Bad GNAT array descriptor"));
1866
1867 return p_bounds;
1868 }
14f9c5c9
AS
1869 else
1870 return NULL;
1871}
1872
4c4b4cd2
PH
1873/* If TYPE is the type of an array-descriptor (fat pointer), the bit
1874 position of the field containing the address of the bounds data. */
1875
14f9c5c9 1876static int
d2e4a39e 1877fat_pntr_bounds_bitpos (struct type *type)
14f9c5c9 1878{
b610c045 1879 return desc_base_type (type)->field (1).loc_bitpos ();
14f9c5c9
AS
1880}
1881
1882/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1883 size of the field containing the address of the bounds data. */
1884
14f9c5c9 1885static int
d2e4a39e 1886fat_pntr_bounds_bitsize (struct type *type)
14f9c5c9
AS
1887{
1888 type = desc_base_type (type);
1889
3757d2d4
SM
1890 if (type->field (1).bitsize () > 0)
1891 return type->field (1).bitsize ();
14f9c5c9 1892 else
df86565b 1893 return 8 * ada_check_typedef (type->field (1).type ())->length ();
14f9c5c9
AS
1894}
1895
4c4b4cd2 1896/* If TYPE is the type of an array descriptor (fat or thin pointer) or a
556bdfd4
UW
1897 pointer to one, the type of its array data (a array-with-no-bounds type);
1898 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1899 data. */
4c4b4cd2 1900
d2e4a39e 1901static struct type *
556bdfd4 1902desc_data_target_type (struct type *type)
14f9c5c9
AS
1903{
1904 type = desc_base_type (type);
1905
4c4b4cd2 1906 /* NOTE: The following is bogus; see comment in desc_bounds. */
14f9c5c9 1907 if (is_thin_pntr (type))
940da03e 1908 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
14f9c5c9 1909 else if (is_thick_pntr (type))
556bdfd4
UW
1910 {
1911 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1912
1913 if (data_type
78134374 1914 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
27710edb 1915 return ada_check_typedef (data_type->target_type ());
556bdfd4
UW
1916 }
1917
1918 return NULL;
14f9c5c9
AS
1919}
1920
1921/* If ARR is an array descriptor (fat or thin pointer), a pointer to
1922 its array data. */
4c4b4cd2 1923
d2e4a39e
AS
1924static struct value *
1925desc_data (struct value *arr)
14f9c5c9 1926{
d0c97917 1927 struct type *type = arr->type ();
5b4ee69b 1928
14f9c5c9
AS
1929 if (is_thin_pntr (type))
1930 return thin_data_pntr (arr);
1931 else if (is_thick_pntr (type))
158cc4fe 1932 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
dda83cd7 1933 _("Bad GNAT array descriptor"));
14f9c5c9
AS
1934 else
1935 return NULL;
1936}
1937
1938
1939/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1940 position of the field containing the address of the data. */
1941
14f9c5c9 1942static int
d2e4a39e 1943fat_pntr_data_bitpos (struct type *type)
14f9c5c9 1944{
b610c045 1945 return desc_base_type (type)->field (0).loc_bitpos ();
14f9c5c9
AS
1946}
1947
1948/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1949 size of the field containing the address of the data. */
1950
14f9c5c9 1951static int
d2e4a39e 1952fat_pntr_data_bitsize (struct type *type)
14f9c5c9
AS
1953{
1954 type = desc_base_type (type);
1955
3757d2d4
SM
1956 if (type->field (0).bitsize () > 0)
1957 return type->field (0).bitsize ();
d2e4a39e 1958 else
df86565b 1959 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
14f9c5c9
AS
1960}
1961
4c4b4cd2 1962/* If BOUNDS is an array-bounds structure (or pointer to one), return
14f9c5c9 1963 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1964 bound, if WHICH is 1. The first bound is I=1. */
1965
d2e4a39e
AS
1966static struct value *
1967desc_one_bound (struct value *bounds, int i, int which)
14f9c5c9 1968{
250106a7
TT
1969 char bound_name[20];
1970 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1971 which ? 'U' : 'L', i - 1);
158cc4fe 1972 return value_struct_elt (&bounds, {}, bound_name, NULL,
dda83cd7 1973 _("Bad GNAT array descriptor bounds"));
14f9c5c9
AS
1974}
1975
1976/* If BOUNDS is an array-bounds structure type, return the bit position
1977 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1978 bound, if WHICH is 1. The first bound is I=1. */
1979
14f9c5c9 1980static int
d2e4a39e 1981desc_bound_bitpos (struct type *type, int i, int which)
14f9c5c9 1982{
b610c045 1983 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
14f9c5c9
AS
1984}
1985
1986/* If BOUNDS is an array-bounds structure type, return the bit field size
1987 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1988 bound, if WHICH is 1. The first bound is I=1. */
1989
76a01679 1990static int
d2e4a39e 1991desc_bound_bitsize (struct type *type, int i, int which)
14f9c5c9
AS
1992{
1993 type = desc_base_type (type);
1994
3757d2d4
SM
1995 if (type->field (2 * i + which - 2).bitsize () > 0)
1996 return type->field (2 * i + which - 2).bitsize ();
d2e4a39e 1997 else
df86565b 1998 return 8 * type->field (2 * i + which - 2).type ()->length ();
14f9c5c9
AS
1999}
2000
2001/* If TYPE is the type of an array-bounds structure, the type of its
4c4b4cd2
PH
2002 Ith bound (numbering from 1). Otherwise, NULL. */
2003
d2e4a39e
AS
2004static struct type *
2005desc_index_type (struct type *type, int i)
14f9c5c9
AS
2006{
2007 type = desc_base_type (type);
2008
78134374 2009 if (type->code () == TYPE_CODE_STRUCT)
250106a7
TT
2010 {
2011 char bound_name[20];
2012 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2013 return lookup_struct_elt_type (type, bound_name, 1);
2014 }
d2e4a39e 2015 else
14f9c5c9
AS
2016 return NULL;
2017}
2018
4c4b4cd2
PH
2019/* The number of index positions in the array-bounds type TYPE.
2020 Return 0 if TYPE is NULL. */
2021
14f9c5c9 2022static int
d2e4a39e 2023desc_arity (struct type *type)
14f9c5c9
AS
2024{
2025 type = desc_base_type (type);
2026
2027 if (type != NULL)
1f704f76 2028 return type->num_fields () / 2;
14f9c5c9
AS
2029 return 0;
2030}
2031
4c4b4cd2
PH
2032/* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2033 an array descriptor type (representing an unconstrained array
2034 type). */
2035
76a01679
JB
2036static int
2037ada_is_direct_array_type (struct type *type)
4c4b4cd2
PH
2038{
2039 if (type == NULL)
2040 return 0;
61ee279c 2041 type = ada_check_typedef (type);
78134374 2042 return (type->code () == TYPE_CODE_ARRAY
dda83cd7 2043 || ada_is_array_descriptor_type (type));
4c4b4cd2
PH
2044}
2045
52ce6436 2046/* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
0963b4bd 2047 * to one. */
52ce6436 2048
2c0b251b 2049static int
52ce6436
PH
2050ada_is_array_type (struct type *type)
2051{
78134374
SM
2052 while (type != NULL
2053 && (type->code () == TYPE_CODE_PTR
2054 || type->code () == TYPE_CODE_REF))
27710edb 2055 type = type->target_type ();
52ce6436
PH
2056 return ada_is_direct_array_type (type);
2057}
2058
4c4b4cd2 2059/* Non-zero iff TYPE is a simple array type or pointer to one. */
14f9c5c9 2060
14f9c5c9 2061int
4c4b4cd2 2062ada_is_simple_array_type (struct type *type)
14f9c5c9
AS
2063{
2064 if (type == NULL)
2065 return 0;
61ee279c 2066 type = ada_check_typedef (type);
78134374
SM
2067 return (type->code () == TYPE_CODE_ARRAY
2068 || (type->code () == TYPE_CODE_PTR
27710edb 2069 && (ada_check_typedef (type->target_type ())->code ()
78134374 2070 == TYPE_CODE_ARRAY)));
14f9c5c9
AS
2071}
2072
4c4b4cd2
PH
2073/* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2074
14f9c5c9 2075int
4c4b4cd2 2076ada_is_array_descriptor_type (struct type *type)
14f9c5c9 2077{
556bdfd4 2078 struct type *data_type = desc_data_target_type (type);
14f9c5c9
AS
2079
2080 if (type == NULL)
2081 return 0;
61ee279c 2082 type = ada_check_typedef (type);
556bdfd4 2083 return (data_type != NULL
78134374 2084 && data_type->code () == TYPE_CODE_ARRAY
556bdfd4 2085 && desc_arity (desc_bounds_type (type)) > 0);
14f9c5c9
AS
2086}
2087
4c4b4cd2 2088/* If ARR has a record type in the form of a standard GNAT array descriptor,
14f9c5c9 2089 (fat pointer) returns the type of the array data described---specifically,
4c4b4cd2 2090 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
14f9c5c9 2091 in from the descriptor; otherwise, they are left unspecified. If
4c4b4cd2
PH
2092 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2093 returns NULL. The result is simply the type of ARR if ARR is not
14f9c5c9 2094 a descriptor. */
de93309a
SM
2095
2096static struct type *
d2e4a39e 2097ada_type_of_array (struct value *arr, int bounds)
14f9c5c9 2098{
d0c97917
TT
2099 if (ada_is_constrained_packed_array_type (arr->type ()))
2100 return decode_constrained_packed_array_type (arr->type ());
14f9c5c9 2101
d0c97917
TT
2102 if (!ada_is_array_descriptor_type (arr->type ()))
2103 return arr->type ();
d2e4a39e
AS
2104
2105 if (!bounds)
ad82864c
JB
2106 {
2107 struct type *array_type =
d0c97917 2108 ada_check_typedef (desc_data_target_type (arr->type ()));
ad82864c 2109
d0c97917 2110 if (ada_is_unconstrained_packed_array_type (arr->type ()))
886176b8
SM
2111 array_type->field (0).set_bitsize
2112 (decode_packed_array_bitsize (arr->type ()));
2113
ad82864c
JB
2114 return array_type;
2115 }
14f9c5c9
AS
2116 else
2117 {
d2e4a39e 2118 struct type *elt_type;
14f9c5c9 2119 int arity;
d2e4a39e 2120 struct value *descriptor;
14f9c5c9 2121
d0c97917
TT
2122 elt_type = ada_array_element_type (arr->type (), -1);
2123 arity = ada_array_arity (arr->type ());
14f9c5c9 2124
d2e4a39e 2125 if (elt_type == NULL || arity == 0)
d0c97917 2126 return ada_check_typedef (arr->type ());
14f9c5c9
AS
2127
2128 descriptor = desc_bounds (arr);
d2e4a39e 2129 if (value_as_long (descriptor) == 0)
dda83cd7 2130 return NULL;
d2e4a39e 2131 while (arity > 0)
dda83cd7 2132 {
9fa83a7a 2133 type_allocator alloc (arr->type ());
dda83cd7
SM
2134 struct value *low = desc_one_bound (descriptor, arity, 0);
2135 struct value *high = desc_one_bound (descriptor, arity, 1);
2136
2137 arity -= 1;
e727c536
TT
2138 struct type *range_type
2139 = create_static_range_type (alloc, low->type (),
2140 longest_to_int (value_as_long (low)),
2141 longest_to_int (value_as_long (high)));
9e76b17a 2142 elt_type = create_array_type (alloc, elt_type, range_type);
cf1eca3c 2143 INIT_GNAT_SPECIFIC (elt_type);
ad82864c 2144
d0c97917 2145 if (ada_is_unconstrained_packed_array_type (arr->type ()))
e67ad678
JB
2146 {
2147 /* We need to store the element packed bitsize, as well as
dda83cd7 2148 recompute the array size, because it was previously
e67ad678
JB
2149 computed based on the unpacked element size. */
2150 LONGEST lo = value_as_long (low);
2151 LONGEST hi = value_as_long (high);
2152
886176b8
SM
2153 elt_type->field (0).set_bitsize
2154 (decode_packed_array_bitsize (arr->type ()));
2155
e67ad678 2156 /* If the array has no element, then the size is already
dda83cd7 2157 zero, and does not need to be recomputed. */
e67ad678
JB
2158 if (lo < hi)
2159 {
2160 int array_bitsize =
3757d2d4 2161 (hi - lo + 1) * elt_type->field (0).bitsize ();
e67ad678 2162
9e76b17a 2163 elt_type->set_length ((array_bitsize + 7) / 8);
e67ad678
JB
2164 }
2165 }
dda83cd7 2166 }
14f9c5c9
AS
2167
2168 return lookup_pointer_type (elt_type);
2169 }
2170}
2171
2172/* If ARR does not represent an array, returns ARR unchanged.
4c4b4cd2
PH
2173 Otherwise, returns either a standard GDB array with bounds set
2174 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2175 GDB array. Returns NULL if ARR is a null fat pointer. */
2176
d2e4a39e
AS
2177struct value *
2178ada_coerce_to_simple_array_ptr (struct value *arr)
14f9c5c9 2179{
d0c97917 2180 if (ada_is_array_descriptor_type (arr->type ()))
14f9c5c9 2181 {
d2e4a39e 2182 struct type *arrType = ada_type_of_array (arr, 1);
5b4ee69b 2183
14f9c5c9 2184 if (arrType == NULL)
dda83cd7 2185 return NULL;
cda03344 2186 return value_cast (arrType, desc_data (arr)->copy ());
14f9c5c9 2187 }
d0c97917 2188 else if (ada_is_constrained_packed_array_type (arr->type ()))
ad82864c 2189 return decode_constrained_packed_array (arr);
14f9c5c9
AS
2190 else
2191 return arr;
2192}
2193
2194/* If ARR does not represent an array, returns ARR unchanged.
2195 Otherwise, returns a standard GDB array describing ARR (which may
4c4b4cd2
PH
2196 be ARR itself if it already is in the proper form). */
2197
720d1a40 2198struct value *
d2e4a39e 2199ada_coerce_to_simple_array (struct value *arr)
14f9c5c9 2200{
d0c97917 2201 if (ada_is_array_descriptor_type (arr->type ()))
14f9c5c9 2202 {
d2e4a39e 2203 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
5b4ee69b 2204
14f9c5c9 2205 if (arrVal == NULL)
dda83cd7 2206 error (_("Bounds unavailable for null array pointer."));
14f9c5c9
AS
2207 return value_ind (arrVal);
2208 }
d0c97917 2209 else if (ada_is_constrained_packed_array_type (arr->type ()))
ad82864c 2210 return decode_constrained_packed_array (arr);
d2e4a39e 2211 else
14f9c5c9
AS
2212 return arr;
2213}
2214
2215/* If TYPE represents a GNAT array type, return it translated to an
2216 ordinary GDB array type (possibly with BITSIZE fields indicating
4c4b4cd2
PH
2217 packing). For other types, is the identity. */
2218
d2e4a39e
AS
2219struct type *
2220ada_coerce_to_simple_array_type (struct type *type)
14f9c5c9 2221{
ad82864c
JB
2222 if (ada_is_constrained_packed_array_type (type))
2223 return decode_constrained_packed_array_type (type);
17280b9f
UW
2224
2225 if (ada_is_array_descriptor_type (type))
556bdfd4 2226 return ada_check_typedef (desc_data_target_type (type));
17280b9f
UW
2227
2228 return type;
14f9c5c9
AS
2229}
2230
4c4b4cd2
PH
2231/* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2232
ad82864c 2233static int
57567375 2234ada_is_gnat_encoded_packed_array_type (struct type *type)
14f9c5c9
AS
2235{
2236 if (type == NULL)
2237 return 0;
4c4b4cd2 2238 type = desc_base_type (type);
61ee279c 2239 type = ada_check_typedef (type);
d2e4a39e 2240 return
14f9c5c9
AS
2241 ada_type_name (type) != NULL
2242 && strstr (ada_type_name (type), "___XP") != NULL;
2243}
2244
ad82864c
JB
2245/* Non-zero iff TYPE represents a standard GNAT constrained
2246 packed-array type. */
2247
2248int
2249ada_is_constrained_packed_array_type (struct type *type)
2250{
57567375 2251 return ada_is_gnat_encoded_packed_array_type (type)
ad82864c
JB
2252 && !ada_is_array_descriptor_type (type);
2253}
2254
2255/* Non-zero iff TYPE represents an array descriptor for a
2256 unconstrained packed-array type. */
2257
2258static int
2259ada_is_unconstrained_packed_array_type (struct type *type)
2260{
57567375
TT
2261 if (!ada_is_array_descriptor_type (type))
2262 return 0;
2263
2264 if (ada_is_gnat_encoded_packed_array_type (type))
2265 return 1;
2266
2267 /* If we saw GNAT encodings, then the above code is sufficient.
2268 However, with minimal encodings, we will just have a thick
2269 pointer instead. */
2270 if (is_thick_pntr (type))
2271 {
2272 type = desc_base_type (type);
2273 /* The structure's first field is a pointer to an array, so this
2274 fetches the array type. */
27710edb 2275 type = type->field (0).type ()->target_type ();
af5300fe
TV
2276 if (type->code () == TYPE_CODE_TYPEDEF)
2277 type = ada_typedef_target_type (type);
57567375 2278 /* Now we can see if the array elements are packed. */
3757d2d4 2279 return type->field (0).bitsize () > 0;
57567375
TT
2280 }
2281
2282 return 0;
ad82864c
JB
2283}
2284
c9a28cbe
TT
2285/* Return true if TYPE is a (Gnat-encoded) constrained packed array
2286 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2287
2288static bool
2289ada_is_any_packed_array_type (struct type *type)
2290{
2291 return (ada_is_constrained_packed_array_type (type)
2292 || (type->code () == TYPE_CODE_ARRAY
3757d2d4 2293 && type->field (0).bitsize () % 8 != 0));
c9a28cbe
TT
2294}
2295
ad82864c
JB
2296/* Given that TYPE encodes a packed array type (constrained or unconstrained),
2297 return the size of its elements in bits. */
2298
2299static long
2300decode_packed_array_bitsize (struct type *type)
2301{
0d5cff50
DE
2302 const char *raw_name;
2303 const char *tail;
ad82864c
JB
2304 long bits;
2305
720d1a40
JB
2306 /* Access to arrays implemented as fat pointers are encoded as a typedef
2307 of the fat pointer type. We need the name of the fat pointer type
2308 to do the decoding, so strip the typedef layer. */
78134374 2309 if (type->code () == TYPE_CODE_TYPEDEF)
720d1a40
JB
2310 type = ada_typedef_target_type (type);
2311
2312 raw_name = ada_type_name (ada_check_typedef (type));
ad82864c
JB
2313 if (!raw_name)
2314 raw_name = ada_type_name (desc_base_type (type));
2315
2316 if (!raw_name)
2317 return 0;
2318
2319 tail = strstr (raw_name, "___XP");
57567375
TT
2320 if (tail == nullptr)
2321 {
2322 gdb_assert (is_thick_pntr (type));
2323 /* The structure's first field is a pointer to an array, so this
2324 fetches the array type. */
27710edb 2325 type = type->field (0).type ()->target_type ();
57567375 2326 /* Now we can see if the array elements are packed. */
3757d2d4 2327 return type->field (0).bitsize ();
57567375 2328 }
ad82864c
JB
2329
2330 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2331 {
2332 lim_warning
2333 (_("could not understand bit size information on packed array"));
2334 return 0;
2335 }
2336
2337 return bits;
2338}
2339
14f9c5c9
AS
2340/* Given that TYPE is a standard GDB array type with all bounds filled
2341 in, and that the element size of its ultimate scalar constituents
2342 (that is, either its elements, or, if it is an array of arrays, its
2343 elements' elements, etc.) is *ELT_BITS, return an identical type,
2344 but with the bit sizes of its elements (and those of any
2345 constituent arrays) recorded in the BITSIZE components of its
4c4b4cd2 2346 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
4a46959e
JB
2347 in bits.
2348
2349 Note that, for arrays whose index type has an XA encoding where
2350 a bound references a record discriminant, getting that discriminant,
2351 and therefore the actual value of that bound, is not possible
2352 because none of the given parameters gives us access to the record.
2353 This function assumes that it is OK in the context where it is being
2354 used to return an array whose bounds are still dynamic and where
2355 the length is arbitrary. */
4c4b4cd2 2356
d2e4a39e 2357static struct type *
ad82864c 2358constrained_packed_array_type (struct type *type, long *elt_bits)
14f9c5c9 2359{
d2e4a39e
AS
2360 struct type *new_elt_type;
2361 struct type *new_type;
99b1c762
JB
2362 struct type *index_type_desc;
2363 struct type *index_type;
14f9c5c9
AS
2364 LONGEST low_bound, high_bound;
2365
61ee279c 2366 type = ada_check_typedef (type);
78134374 2367 if (type->code () != TYPE_CODE_ARRAY)
14f9c5c9
AS
2368 return type;
2369
99b1c762
JB
2370 index_type_desc = ada_find_parallel_type (type, "___XA");
2371 if (index_type_desc)
940da03e 2372 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
99b1c762
JB
2373 NULL);
2374 else
3d967001 2375 index_type = type->index_type ();
99b1c762 2376
9e76b17a 2377 type_allocator alloc (type);
ad82864c 2378 new_elt_type =
27710edb 2379 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
ad82864c 2380 elt_bits);
9e76b17a 2381 new_type = create_array_type (alloc, new_elt_type, index_type);
886176b8 2382 new_type->field (0).set_bitsize (*elt_bits);
d0e39ea2 2383 new_type->set_name (ada_type_name (type));
14f9c5c9 2384
78134374 2385 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
4a46959e 2386 && is_dynamic_type (check_typedef (index_type)))
1f8d2881 2387 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
14f9c5c9
AS
2388 low_bound = high_bound = 0;
2389 if (high_bound < low_bound)
b6cdbc9a
SM
2390 {
2391 *elt_bits = 0;
2392 new_type->set_length (0);
2393 }
d2e4a39e 2394 else
14f9c5c9
AS
2395 {
2396 *elt_bits *= (high_bound - low_bound + 1);
b6cdbc9a 2397 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
14f9c5c9
AS
2398 }
2399
9cdd0d12 2400 new_type->set_is_fixed_instance (true);
14f9c5c9
AS
2401 return new_type;
2402}
2403
ad82864c
JB
2404/* The array type encoded by TYPE, where
2405 ada_is_constrained_packed_array_type (TYPE). */
4c4b4cd2 2406
d2e4a39e 2407static struct type *
ad82864c 2408decode_constrained_packed_array_type (struct type *type)
d2e4a39e 2409{
0d5cff50 2410 const char *raw_name = ada_type_name (ada_check_typedef (type));
727e3d2e 2411 char *name;
0d5cff50 2412 const char *tail;
d2e4a39e 2413 struct type *shadow_type;
14f9c5c9 2414 long bits;
14f9c5c9 2415
727e3d2e
JB
2416 if (!raw_name)
2417 raw_name = ada_type_name (desc_base_type (type));
2418
2419 if (!raw_name)
2420 return NULL;
2421
2422 name = (char *) alloca (strlen (raw_name) + 1);
2423 tail = strstr (raw_name, "___XP");
4c4b4cd2
PH
2424 type = desc_base_type (type);
2425
14f9c5c9
AS
2426 memcpy (name, raw_name, tail - raw_name);
2427 name[tail - raw_name] = '\000';
2428
b4ba55a1
JB
2429 shadow_type = ada_find_parallel_type_with_name (type, name);
2430
2431 if (shadow_type == NULL)
14f9c5c9 2432 {
323e0a4a 2433 lim_warning (_("could not find bounds information on packed array"));
14f9c5c9
AS
2434 return NULL;
2435 }
f168693b 2436 shadow_type = check_typedef (shadow_type);
14f9c5c9 2437
78134374 2438 if (shadow_type->code () != TYPE_CODE_ARRAY)
14f9c5c9 2439 {
0963b4bd
MS
2440 lim_warning (_("could not understand bounds "
2441 "information on packed array"));
14f9c5c9
AS
2442 return NULL;
2443 }
d2e4a39e 2444
ad82864c
JB
2445 bits = decode_packed_array_bitsize (type);
2446 return constrained_packed_array_type (shadow_type, &bits);
14f9c5c9
AS
2447}
2448
a7400e44
TT
2449/* Helper function for decode_constrained_packed_array. Set the field
2450 bitsize on a series of packed arrays. Returns the number of
2451 elements in TYPE. */
2452
2453static LONGEST
2454recursively_update_array_bitsize (struct type *type)
2455{
2456 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2457
2458 LONGEST low, high;
1f8d2881 2459 if (!get_discrete_bounds (type->index_type (), &low, &high)
a7400e44
TT
2460 || low > high)
2461 return 0;
2462 LONGEST our_len = high - low + 1;
2463
27710edb 2464 struct type *elt_type = type->target_type ();
a7400e44
TT
2465 if (elt_type->code () == TYPE_CODE_ARRAY)
2466 {
2467 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
3757d2d4 2468 LONGEST elt_bitsize = elt_len * elt_type->field (0).bitsize ();
886176b8 2469 type->field (0).set_bitsize (elt_bitsize);
a7400e44 2470
b6cdbc9a
SM
2471 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2472 / HOST_CHAR_BIT));
a7400e44
TT
2473 }
2474
2475 return our_len;
2476}
2477
ad82864c
JB
2478/* Given that ARR is a struct value *indicating a GNAT constrained packed
2479 array, returns a simple array that denotes that array. Its type is a
14f9c5c9
AS
2480 standard GDB array type except that the BITSIZEs of the array
2481 target types are set to the number of bits in each element, and the
4c4b4cd2 2482 type length is set appropriately. */
14f9c5c9 2483
d2e4a39e 2484static struct value *
ad82864c 2485decode_constrained_packed_array (struct value *arr)
14f9c5c9 2486{
4c4b4cd2 2487 struct type *type;
14f9c5c9 2488
11aa919a
PMR
2489 /* If our value is a pointer, then dereference it. Likewise if
2490 the value is a reference. Make sure that this operation does not
2491 cause the target type to be fixed, as this would indirectly cause
2492 this array to be decoded. The rest of the routine assumes that
2493 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2494 and "value_ind" routines to perform the dereferencing, as opposed
2495 to using "ada_coerce_ref" or "ada_value_ind". */
2496 arr = coerce_ref (arr);
d0c97917 2497 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
284614f0 2498 arr = value_ind (arr);
4c4b4cd2 2499
d0c97917 2500 type = decode_constrained_packed_array_type (arr->type ());
14f9c5c9
AS
2501 if (type == NULL)
2502 {
323e0a4a 2503 error (_("can't unpack array"));
14f9c5c9
AS
2504 return NULL;
2505 }
61ee279c 2506
a7400e44
TT
2507 /* Decoding the packed array type could not correctly set the field
2508 bitsizes for any dimension except the innermost, because the
2509 bounds may be variable and were not passed to that function. So,
2510 we further resolve the array bounds here and then update the
2511 sizes. */
efaf1ae0 2512 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
9feb2d07 2513 CORE_ADDR address = arr->address ();
a7400e44 2514 gdb::array_view<const gdb_byte> view
df86565b 2515 = gdb::make_array_view (valaddr, type->length ());
a7400e44
TT
2516 type = resolve_dynamic_type (type, view, address);
2517 recursively_update_array_bitsize (type);
2518
d0c97917
TT
2519 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2520 && ada_is_modular_type (arr->type ()))
61ee279c
PH
2521 {
2522 /* This is a (right-justified) modular type representing a packed
24b21115
SM
2523 array with no wrapper. In order to interpret the value through
2524 the (left-justified) packed array type we just built, we must
2525 first left-justify it. */
61ee279c
PH
2526 int bit_size, bit_pos;
2527 ULONGEST mod;
2528
d0c97917 2529 mod = ada_modulus (arr->type ()) - 1;
61ee279c
PH
2530 bit_size = 0;
2531 while (mod > 0)
2532 {
2533 bit_size += 1;
2534 mod >>= 1;
2535 }
d0c97917 2536 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
61ee279c
PH
2537 arr = ada_value_primitive_packed_val (arr, NULL,
2538 bit_pos / HOST_CHAR_BIT,
2539 bit_pos % HOST_CHAR_BIT,
2540 bit_size,
2541 type);
2542 }
2543
4c4b4cd2 2544 return coerce_unspec_val_to_type (arr, type);
14f9c5c9
AS
2545}
2546
2547
2548/* The value of the element of packed array ARR at the ARITY indices
4c4b4cd2 2549 given in IND. ARR must be a simple array. */
14f9c5c9 2550
d2e4a39e
AS
2551static struct value *
2552value_subscript_packed (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
2553{
2554 int i;
2555 int bits, elt_off, bit_off;
2556 long elt_total_bit_offset;
d2e4a39e
AS
2557 struct type *elt_type;
2558 struct value *v;
14f9c5c9
AS
2559
2560 bits = 0;
2561 elt_total_bit_offset = 0;
d0c97917 2562 elt_type = ada_check_typedef (arr->type ());
d2e4a39e 2563 for (i = 0; i < arity; i += 1)
14f9c5c9 2564 {
78134374 2565 if (elt_type->code () != TYPE_CODE_ARRAY
3757d2d4 2566 || elt_type->field (0).bitsize () == 0)
dda83cd7
SM
2567 error
2568 (_("attempt to do packed indexing of "
0963b4bd 2569 "something other than a packed array"));
14f9c5c9 2570 else
dda83cd7
SM
2571 {
2572 struct type *range_type = elt_type->index_type ();
2573 LONGEST lowerbound, upperbound;
2574 LONGEST idx;
2575
1f8d2881 2576 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
dda83cd7
SM
2577 {
2578 lim_warning (_("don't know bounds of array"));
2579 lowerbound = upperbound = 0;
2580 }
2581
2582 idx = pos_atr (ind[i]);
2583 if (idx < lowerbound || idx > upperbound)
2584 lim_warning (_("packed array index %ld out of bounds"),
0963b4bd 2585 (long) idx);
3757d2d4 2586 bits = elt_type->field (0).bitsize ();
dda83cd7 2587 elt_total_bit_offset += (idx - lowerbound) * bits;
27710edb 2588 elt_type = ada_check_typedef (elt_type->target_type ());
dda83cd7 2589 }
14f9c5c9
AS
2590 }
2591 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2592 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
d2e4a39e
AS
2593
2594 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
dda83cd7 2595 bits, elt_type);
14f9c5c9
AS
2596 return v;
2597}
2598
4c4b4cd2 2599/* Non-zero iff TYPE includes negative integer values. */
14f9c5c9
AS
2600
2601static int
d2e4a39e 2602has_negatives (struct type *type)
14f9c5c9 2603{
78134374 2604 switch (type->code ())
d2e4a39e
AS
2605 {
2606 default:
2607 return 0;
2608 case TYPE_CODE_INT:
c6d940a9 2609 return !type->is_unsigned ();
d2e4a39e 2610 case TYPE_CODE_RANGE:
5537ddd0 2611 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
d2e4a39e 2612 }
14f9c5c9 2613}
d2e4a39e 2614
f93fca70 2615/* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
5b639dea 2616 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
f93fca70 2617 the unpacked buffer.
14f9c5c9 2618
5b639dea
JB
2619 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2620 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2621
f93fca70
JB
2622 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2623 zero otherwise.
14f9c5c9 2624
f93fca70 2625 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
a1c95e6b 2626
f93fca70
JB
2627 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2628
2629static void
2630ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2631 gdb_byte *unpacked, int unpacked_len,
2632 int is_big_endian, int is_signed_type,
2633 int is_scalar)
2634{
a1c95e6b
JB
2635 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2636 int src_idx; /* Index into the source area */
2637 int src_bytes_left; /* Number of source bytes left to process. */
2638 int srcBitsLeft; /* Number of source bits left to move */
2639 int unusedLS; /* Number of bits in next significant
dda83cd7 2640 byte of source that are unused */
a1c95e6b 2641
a1c95e6b
JB
2642 int unpacked_idx; /* Index into the unpacked buffer */
2643 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2644
4c4b4cd2 2645 unsigned long accum; /* Staging area for bits being transferred */
a1c95e6b 2646 int accumSize; /* Number of meaningful bits in accum */
14f9c5c9 2647 unsigned char sign;
a1c95e6b 2648
4c4b4cd2
PH
2649 /* Transmit bytes from least to most significant; delta is the direction
2650 the indices move. */
f93fca70 2651 int delta = is_big_endian ? -1 : 1;
14f9c5c9 2652
5b639dea
JB
2653 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2654 bits from SRC. .*/
2655 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2656 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2657 bit_size, unpacked_len);
2658
14f9c5c9 2659 srcBitsLeft = bit_size;
086ca51f 2660 src_bytes_left = src_len;
f93fca70 2661 unpacked_bytes_left = unpacked_len;
14f9c5c9 2662 sign = 0;
f93fca70
JB
2663
2664 if (is_big_endian)
14f9c5c9 2665 {
086ca51f 2666 src_idx = src_len - 1;
f93fca70
JB
2667 if (is_signed_type
2668 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
dda83cd7 2669 sign = ~0;
d2e4a39e
AS
2670
2671 unusedLS =
dda83cd7
SM
2672 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2673 % HOST_CHAR_BIT;
14f9c5c9 2674
f93fca70
JB
2675 if (is_scalar)
2676 {
dda83cd7
SM
2677 accumSize = 0;
2678 unpacked_idx = unpacked_len - 1;
f93fca70
JB
2679 }
2680 else
2681 {
dda83cd7
SM
2682 /* Non-scalar values must be aligned at a byte boundary... */
2683 accumSize =
2684 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2685 /* ... And are placed at the beginning (most-significant) bytes
2686 of the target. */
2687 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2688 unpacked_bytes_left = unpacked_idx + 1;
f93fca70 2689 }
14f9c5c9 2690 }
d2e4a39e 2691 else
14f9c5c9
AS
2692 {
2693 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2694
086ca51f 2695 src_idx = unpacked_idx = 0;
14f9c5c9
AS
2696 unusedLS = bit_offset;
2697 accumSize = 0;
2698
f93fca70 2699 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
dda83cd7 2700 sign = ~0;
14f9c5c9 2701 }
d2e4a39e 2702
14f9c5c9 2703 accum = 0;
086ca51f 2704 while (src_bytes_left > 0)
14f9c5c9
AS
2705 {
2706 /* Mask for removing bits of the next source byte that are not
dda83cd7 2707 part of the value. */
d2e4a39e 2708 unsigned int unusedMSMask =
dda83cd7
SM
2709 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2710 1;
4c4b4cd2 2711 /* Sign-extend bits for this byte. */
14f9c5c9 2712 unsigned int signMask = sign & ~unusedMSMask;
5b4ee69b 2713
d2e4a39e 2714 accum |=
dda83cd7 2715 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
14f9c5c9 2716 accumSize += HOST_CHAR_BIT - unusedLS;
d2e4a39e 2717 if (accumSize >= HOST_CHAR_BIT)
dda83cd7
SM
2718 {
2719 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2720 accumSize -= HOST_CHAR_BIT;
2721 accum >>= HOST_CHAR_BIT;
2722 unpacked_bytes_left -= 1;
2723 unpacked_idx += delta;
2724 }
14f9c5c9
AS
2725 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2726 unusedLS = 0;
086ca51f
JB
2727 src_bytes_left -= 1;
2728 src_idx += delta;
14f9c5c9 2729 }
086ca51f 2730 while (unpacked_bytes_left > 0)
14f9c5c9
AS
2731 {
2732 accum |= sign << accumSize;
db297a65 2733 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
14f9c5c9 2734 accumSize -= HOST_CHAR_BIT;
9cd4d857
JB
2735 if (accumSize < 0)
2736 accumSize = 0;
14f9c5c9 2737 accum >>= HOST_CHAR_BIT;
086ca51f
JB
2738 unpacked_bytes_left -= 1;
2739 unpacked_idx += delta;
14f9c5c9 2740 }
f93fca70
JB
2741}
2742
2743/* Create a new value of type TYPE from the contents of OBJ starting
2744 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2745 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2746 assigning through the result will set the field fetched from.
2747 VALADDR is ignored unless OBJ is NULL, in which case,
2748 VALADDR+OFFSET must address the start of storage containing the
2749 packed value. The value returned in this case is never an lval.
2750 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2751
2752struct value *
2753ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2754 long offset, int bit_offset, int bit_size,
dda83cd7 2755 struct type *type)
f93fca70
JB
2756{
2757 struct value *v;
bfb1c796 2758 const gdb_byte *src; /* First byte containing data to unpack */
f93fca70 2759 gdb_byte *unpacked;
220475ed 2760 const int is_scalar = is_scalar_type (type);
d5a22e77 2761 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
d5722aa2 2762 gdb::byte_vector staging;
f93fca70
JB
2763
2764 type = ada_check_typedef (type);
2765
d0a9e810 2766 if (obj == NULL)
bfb1c796 2767 src = valaddr + offset;
d0a9e810 2768 else
efaf1ae0 2769 src = obj->contents ().data () + offset;
d0a9e810
JB
2770
2771 if (is_dynamic_type (type))
2772 {
2773 /* The length of TYPE might by dynamic, so we need to resolve
2774 TYPE in order to know its actual size, which we then use
2775 to create the contents buffer of the value we return.
2776 The difficulty is that the data containing our object is
2777 packed, and therefore maybe not at a byte boundary. So, what
2778 we do, is unpack the data into a byte-aligned buffer, and then
2779 use that buffer as our object's value for resolving the type. */
d5722aa2
PA
2780 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2781 staging.resize (staging_len);
d0a9e810
JB
2782
2783 ada_unpack_from_contents (src, bit_offset, bit_size,
dda83cd7 2784 staging.data (), staging.size (),
d0a9e810
JB
2785 is_big_endian, has_negatives (type),
2786 is_scalar);
b249d2c2 2787 type = resolve_dynamic_type (type, staging, 0);
df86565b 2788 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
0cafa88c
JB
2789 {
2790 /* This happens when the length of the object is dynamic,
2791 and is actually smaller than the space reserved for it.
2792 For instance, in an array of variant records, the bit_size
2793 we're given is the array stride, which is constant and
2794 normally equal to the maximum size of its element.
2795 But, in reality, each element only actually spans a portion
2796 of that stride. */
df86565b 2797 bit_size = type->length () * HOST_CHAR_BIT;
0cafa88c 2798 }
d0a9e810
JB
2799 }
2800
f93fca70
JB
2801 if (obj == NULL)
2802 {
317c3ed9 2803 v = value::allocate (type);
bfb1c796 2804 src = valaddr + offset;
f93fca70 2805 }
736355f2 2806 else if (obj->lval () == lval_memory && obj->lazy ())
f93fca70 2807 {
0cafa88c 2808 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
bfb1c796 2809 gdb_byte *buf;
0cafa88c 2810
9feb2d07 2811 v = value_at (type, obj->address () + offset);
bfb1c796 2812 buf = (gdb_byte *) alloca (src_len);
9feb2d07 2813 read_memory (v->address (), buf, src_len);
bfb1c796 2814 src = buf;
f93fca70
JB
2815 }
2816 else
2817 {
317c3ed9 2818 v = value::allocate (type);
efaf1ae0 2819 src = obj->contents ().data () + offset;
f93fca70
JB
2820 }
2821
2822 if (obj != NULL)
2823 {
2824 long new_offset = offset;
2825
8181b7b6 2826 v->set_component_location (obj);
5011c493 2827 v->set_bitpos (bit_offset + obj->bitpos ());
f49d5fa2 2828 v->set_bitsize (bit_size);
5011c493 2829 if (v->bitpos () >= HOST_CHAR_BIT)
dda83cd7 2830 {
f93fca70 2831 ++new_offset;
5011c493 2832 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
dda83cd7 2833 }
76675c4d 2834 v->set_offset (new_offset);
f93fca70
JB
2835
2836 /* Also set the parent value. This is needed when trying to
2837 assign a new value (in inferior memory). */
fac7bdaa 2838 v->set_parent (obj);
f93fca70
JB
2839 }
2840 else
f49d5fa2 2841 v->set_bitsize (bit_size);
bbe912ba 2842 unpacked = v->contents_writeable ().data ();
f93fca70
JB
2843
2844 if (bit_size == 0)
2845 {
df86565b 2846 memset (unpacked, 0, type->length ());
f93fca70
JB
2847 return v;
2848 }
2849
df86565b 2850 if (staging.size () == type->length ())
f93fca70 2851 {
d0a9e810
JB
2852 /* Small short-cut: If we've unpacked the data into a buffer
2853 of the same size as TYPE's length, then we can reuse that,
2854 instead of doing the unpacking again. */
d5722aa2 2855 memcpy (unpacked, staging.data (), staging.size ());
f93fca70 2856 }
d0a9e810
JB
2857 else
2858 ada_unpack_from_contents (src, bit_offset, bit_size,
df86565b 2859 unpacked, type->length (),
d0a9e810 2860 is_big_endian, has_negatives (type), is_scalar);
f93fca70 2861
14f9c5c9
AS
2862 return v;
2863}
d2e4a39e 2864
14f9c5c9
AS
2865/* Store the contents of FROMVAL into the location of TOVAL.
2866 Return a new value with the location of TOVAL and contents of
2867 FROMVAL. Handles assignment into packed fields that have
4c4b4cd2 2868 floating-point or non-scalar types. */
14f9c5c9 2869
d2e4a39e
AS
2870static struct value *
2871ada_value_assign (struct value *toval, struct value *fromval)
14f9c5c9 2872{
d0c97917 2873 struct type *type = toval->type ();
f49d5fa2 2874 int bits = toval->bitsize ();
14f9c5c9 2875
52ce6436
PH
2876 toval = ada_coerce_ref (toval);
2877 fromval = ada_coerce_ref (fromval);
2878
d0c97917 2879 if (ada_is_direct_array_type (toval->type ()))
52ce6436 2880 toval = ada_coerce_to_simple_array (toval);
d0c97917 2881 if (ada_is_direct_array_type (fromval->type ()))
52ce6436
PH
2882 fromval = ada_coerce_to_simple_array (fromval);
2883
4b53ca88 2884 if (!toval->deprecated_modifiable ())
323e0a4a 2885 error (_("Left operand of assignment is not a modifiable lvalue."));
14f9c5c9 2886
736355f2 2887 if (toval->lval () == lval_memory
14f9c5c9 2888 && bits > 0
78134374 2889 && (type->code () == TYPE_CODE_FLT
dda83cd7 2890 || type->code () == TYPE_CODE_STRUCT))
14f9c5c9 2891 {
5011c493 2892 int len = (toval->bitpos ()
df407dfe 2893 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
aced2898 2894 int from_size;
224c3ddb 2895 gdb_byte *buffer = (gdb_byte *) alloca (len);
d2e4a39e 2896 struct value *val;
9feb2d07 2897 CORE_ADDR to_addr = toval->address ();
14f9c5c9 2898
78134374 2899 if (type->code () == TYPE_CODE_FLT)
dda83cd7 2900 fromval = value_cast (type, fromval);
14f9c5c9 2901
52ce6436 2902 read_memory (to_addr, buffer, len);
f49d5fa2 2903 from_size = fromval->bitsize ();
aced2898 2904 if (from_size == 0)
d0c97917 2905 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
d48e62f4 2906
d5a22e77 2907 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
d48e62f4 2908 ULONGEST from_offset = 0;
d0c97917 2909 if (is_big_endian && is_scalar_type (fromval->type ()))
d48e62f4 2910 from_offset = from_size - bits;
5011c493 2911 copy_bitwise (buffer, toval->bitpos (),
efaf1ae0 2912 fromval->contents ().data (), from_offset,
d48e62f4 2913 bits, is_big_endian);
972daa01 2914 write_memory_with_notification (to_addr, buffer, len);
8cebebb9 2915
cda03344 2916 val = toval->copy ();
bbe912ba 2917 memcpy (val->contents_raw ().data (),
efaf1ae0 2918 fromval->contents ().data (),
df86565b 2919 type->length ());
81ae560c 2920 val->deprecated_set_type (type);
d2e4a39e 2921
14f9c5c9
AS
2922 return val;
2923 }
2924
2925 return value_assign (toval, fromval);
2926}
2927
2928
7c512744
JB
2929/* Given that COMPONENT is a memory lvalue that is part of the lvalue
2930 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2931 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2932 COMPONENT, and not the inferior's memory. The current contents
2933 of COMPONENT are ignored.
2934
2935 Although not part of the initial design, this function also works
2936 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2937 had a null address, and COMPONENT had an address which is equal to
2938 its offset inside CONTAINER. */
2939
52ce6436
PH
2940static void
2941value_assign_to_component (struct value *container, struct value *component,
2942 struct value *val)
2943{
2944 LONGEST offset_in_container =
9feb2d07 2945 (LONGEST) (component->address () - container->address ());
7c512744 2946 int bit_offset_in_container =
5011c493 2947 component->bitpos () - container->bitpos ();
52ce6436 2948 int bits;
7c512744 2949
d0c97917 2950 val = value_cast (component->type (), val);
52ce6436 2951
f49d5fa2 2952 if (component->bitsize () == 0)
d0c97917 2953 bits = TARGET_CHAR_BIT * component->type ()->length ();
52ce6436 2954 else
f49d5fa2 2955 bits = component->bitsize ();
52ce6436 2956
d0c97917 2957 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2a62dfa9
JB
2958 {
2959 int src_offset;
2960
d0c97917 2961 if (is_scalar_type (check_typedef (component->type ())))
dda83cd7 2962 src_offset
d0c97917 2963 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2a62dfa9
JB
2964 else
2965 src_offset = 0;
bbe912ba 2966 copy_bitwise ((container->contents_writeable ().data ()
50888e42 2967 + offset_in_container),
5011c493 2968 container->bitpos () + bit_offset_in_container,
efaf1ae0 2969 val->contents ().data (), src_offset, bits, 1);
2a62dfa9 2970 }
52ce6436 2971 else
bbe912ba 2972 copy_bitwise ((container->contents_writeable ().data ()
50888e42 2973 + offset_in_container),
5011c493 2974 container->bitpos () + bit_offset_in_container,
efaf1ae0 2975 val->contents ().data (), 0, bits, 0);
7c512744
JB
2976}
2977
736ade86
XR
2978/* Determine if TYPE is an access to an unconstrained array. */
2979
d91e9ea8 2980bool
736ade86
XR
2981ada_is_access_to_unconstrained_array (struct type *type)
2982{
78134374 2983 return (type->code () == TYPE_CODE_TYPEDEF
736ade86
XR
2984 && is_thick_pntr (ada_typedef_target_type (type)));
2985}
2986
4c4b4cd2
PH
2987/* The value of the element of array ARR at the ARITY indices given in IND.
2988 ARR may be either a simple array, GNAT array descriptor, or pointer
14f9c5c9
AS
2989 thereto. */
2990
d2e4a39e
AS
2991struct value *
2992ada_value_subscript (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
2993{
2994 int k;
d2e4a39e
AS
2995 struct value *elt;
2996 struct type *elt_type;
14f9c5c9
AS
2997
2998 elt = ada_coerce_to_simple_array (arr);
2999
d0c97917 3000 elt_type = ada_check_typedef (elt->type ());
78134374 3001 if (elt_type->code () == TYPE_CODE_ARRAY
3757d2d4 3002 && elt_type->field (0).bitsize () > 0)
14f9c5c9
AS
3003 return value_subscript_packed (elt, arity, ind);
3004
3005 for (k = 0; k < arity; k += 1)
3006 {
27710edb 3007 struct type *saved_elt_type = elt_type->target_type ();
b9c50e9a 3008
78134374 3009 if (elt_type->code () != TYPE_CODE_ARRAY)
dda83cd7 3010 error (_("too many subscripts (%d expected)"), k);
b9c50e9a 3011
2497b498 3012 elt = value_subscript (elt, pos_atr (ind[k]));
b9c50e9a
XR
3013
3014 if (ada_is_access_to_unconstrained_array (saved_elt_type)
d0c97917 3015 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
b9c50e9a
XR
3016 {
3017 /* The element is a typedef to an unconstrained array,
3018 except that the value_subscript call stripped the
3019 typedef layer. The typedef layer is GNAT's way to
3020 specify that the element is, at the source level, an
3021 access to the unconstrained array, rather than the
3022 unconstrained array. So, we need to restore that
3023 typedef layer, which we can do by forcing the element's
3024 type back to its original type. Otherwise, the returned
3025 value is going to be printed as the array, rather
3026 than as an access. Another symptom of the same issue
3027 would be that an expression trying to dereference the
3028 element would also be improperly rejected. */
81ae560c 3029 elt->deprecated_set_type (saved_elt_type);
b9c50e9a
XR
3030 }
3031
d0c97917 3032 elt_type = ada_check_typedef (elt->type ());
14f9c5c9 3033 }
b9c50e9a 3034
14f9c5c9
AS
3035 return elt;
3036}
3037
deede10c
JB
3038/* Assuming ARR is a pointer to a GDB array, the value of the element
3039 of *ARR at the ARITY indices given in IND.
919e6dbe
PMR
3040 Does not read the entire array into memory.
3041
3042 Note: Unlike what one would expect, this function is used instead of
3043 ada_value_subscript for basically all non-packed array types. The reason
3044 for this is that a side effect of doing our own pointer arithmetics instead
3045 of relying on value_subscript is that there is no implicit typedef peeling.
3046 This is important for arrays of array accesses, where it allows us to
3047 preserve the fact that the array's element is an array access, where the
3048 access part os encoded in a typedef layer. */
14f9c5c9 3049
2c0b251b 3050static struct value *
deede10c 3051ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
3052{
3053 int k;
919e6dbe 3054 struct value *array_ind = ada_value_ind (arr);
deede10c 3055 struct type *type
463b870d 3056 = check_typedef (array_ind->enclosing_type ());
919e6dbe 3057
78134374 3058 if (type->code () == TYPE_CODE_ARRAY
3757d2d4 3059 && type->field (0).bitsize () > 0)
919e6dbe 3060 return value_subscript_packed (array_ind, arity, ind);
14f9c5c9
AS
3061
3062 for (k = 0; k < arity; k += 1)
3063 {
3064 LONGEST lwb, upb;
14f9c5c9 3065
78134374 3066 if (type->code () != TYPE_CODE_ARRAY)
dda83cd7 3067 error (_("too many subscripts (%d expected)"), k);
27710edb 3068 arr = value_cast (lookup_pointer_type (type->target_type ()),
cda03344 3069 arr->copy ());
3d967001 3070 get_discrete_bounds (type->index_type (), &lwb, &upb);
53a47a3e 3071 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
27710edb 3072 type = type->target_type ();
14f9c5c9
AS
3073 }
3074
3075 return value_ind (arr);
3076}
3077
0b5d8877 3078/* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
aa715135
JG
3079 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3080 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3081 this array is LOW, as per Ada rules. */
0b5d8877 3082static struct value *
f5938064 3083ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
dda83cd7 3084 int low, int high)
0b5d8877 3085{
b0dd7688 3086 struct type *type0 = ada_check_typedef (type);
27710edb 3087 struct type *base_index_type = type0->index_type ()->target_type ();
e727c536 3088 type_allocator alloc (base_index_type);
0c9c3474 3089 struct type *index_type
e727c536 3090 = create_static_range_type (alloc, base_index_type, low, high);
9fe561ab 3091 struct type *slice_type = create_array_type_with_stride
9e76b17a 3092 (alloc, type0->target_type (), index_type,
24e99c6c 3093 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3757d2d4 3094 type0->field (0).bitsize ());
3d967001 3095 int base_low = ada_discrete_type_low_bound (type0->index_type ());
6b09f134 3096 std::optional<LONGEST> base_low_pos, low_pos;
aa715135
JG
3097 CORE_ADDR base;
3098
6244c119
SM
3099 low_pos = discrete_position (base_index_type, low);
3100 base_low_pos = discrete_position (base_index_type, base_low);
3101
3102 if (!low_pos.has_value () || !base_low_pos.has_value ())
aa715135
JG
3103 {
3104 warning (_("unable to get positions in slice, use bounds instead"));
3105 low_pos = low;
3106 base_low_pos = base_low;
3107 }
5b4ee69b 3108
3757d2d4 3109 ULONGEST stride = slice_type->field (0).bitsize () / 8;
7ff5b937 3110 if (stride == 0)
df86565b 3111 stride = type0->target_type ()->length ();
7ff5b937 3112
6244c119 3113 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
f5938064 3114 return value_at_lazy (slice_type, base);
0b5d8877
PH
3115}
3116
3117
3118static struct value *
3119ada_value_slice (struct value *array, int low, int high)
3120{
d0c97917 3121 struct type *type = ada_check_typedef (array->type ());
27710edb 3122 struct type *base_index_type = type->index_type ()->target_type ();
e727c536 3123 type_allocator alloc (type->index_type ());
0c9c3474 3124 struct type *index_type
e727c536 3125 = create_static_range_type (alloc, type->index_type (), low, high);
9fe561ab 3126 struct type *slice_type = create_array_type_with_stride
9e76b17a 3127 (alloc, type->target_type (), index_type,
24e99c6c 3128 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3757d2d4 3129 type->field (0).bitsize ());
6b09f134 3130 std::optional<LONGEST> low_pos, high_pos;
6244c119 3131
5b4ee69b 3132
6244c119
SM
3133 low_pos = discrete_position (base_index_type, low);
3134 high_pos = discrete_position (base_index_type, high);
3135
3136 if (!low_pos.has_value () || !high_pos.has_value ())
aa715135
JG
3137 {
3138 warning (_("unable to get positions in slice, use bounds instead"));
3139 low_pos = low;
3140 high_pos = high;
3141 }
3142
3143 return value_cast (slice_type,
6244c119 3144 value_slice (array, low, *high_pos - *low_pos + 1));
0b5d8877
PH
3145}
3146
14f9c5c9
AS
3147/* If type is a record type in the form of a standard GNAT array
3148 descriptor, returns the number of dimensions for type. If arr is a
3149 simple array, returns the number of "array of"s that prefix its
4c4b4cd2 3150 type designation. Otherwise, returns 0. */
14f9c5c9
AS
3151
3152int
d2e4a39e 3153ada_array_arity (struct type *type)
14f9c5c9
AS
3154{
3155 int arity;
3156
3157 if (type == NULL)
3158 return 0;
3159
3160 type = desc_base_type (type);
3161
3162 arity = 0;
78134374 3163 if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9 3164 return desc_arity (desc_bounds_type (type));
d2e4a39e 3165 else
78134374 3166 while (type->code () == TYPE_CODE_ARRAY)
14f9c5c9 3167 {
dda83cd7 3168 arity += 1;
27710edb 3169 type = ada_check_typedef (type->target_type ());
14f9c5c9 3170 }
d2e4a39e 3171
14f9c5c9
AS
3172 return arity;
3173}
3174
3175/* If TYPE is a record type in the form of a standard GNAT array
3176 descriptor or a simple array type, returns the element type for
3177 TYPE after indexing by NINDICES indices, or by all indices if
4c4b4cd2 3178 NINDICES is -1. Otherwise, returns NULL. */
14f9c5c9 3179
d2e4a39e
AS
3180struct type *
3181ada_array_element_type (struct type *type, int nindices)
14f9c5c9
AS
3182{
3183 type = desc_base_type (type);
3184
78134374 3185 if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9
AS
3186 {
3187 int k;
d2e4a39e 3188 struct type *p_array_type;
14f9c5c9 3189
556bdfd4 3190 p_array_type = desc_data_target_type (type);
14f9c5c9
AS
3191
3192 k = ada_array_arity (type);
3193 if (k == 0)
dda83cd7 3194 return NULL;
d2e4a39e 3195
4c4b4cd2 3196 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
14f9c5c9 3197 if (nindices >= 0 && k > nindices)
dda83cd7 3198 k = nindices;
d2e4a39e 3199 while (k > 0 && p_array_type != NULL)
dda83cd7 3200 {
27710edb 3201 p_array_type = ada_check_typedef (p_array_type->target_type ());
dda83cd7
SM
3202 k -= 1;
3203 }
14f9c5c9
AS
3204 return p_array_type;
3205 }
78134374 3206 else if (type->code () == TYPE_CODE_ARRAY)
14f9c5c9 3207 {
78134374 3208 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
dda83cd7 3209 {
27710edb 3210 type = type->target_type ();
6a40c6e4
TT
3211 /* A multi-dimensional array is represented using a sequence
3212 of array types. If one of these types has a name, then
3213 it is not another dimension of the outer array, but
3214 rather the element type of the outermost array. */
3215 if (type->name () != nullptr)
3216 break;
dda83cd7
SM
3217 nindices -= 1;
3218 }
14f9c5c9
AS
3219 return type;
3220 }
3221
3222 return NULL;
3223}
3224
08a057e6 3225/* See ada-lang.h. */
14f9c5c9 3226
08a057e6 3227struct type *
1eea4ebd 3228ada_index_type (struct type *type, int n, const char *name)
14f9c5c9 3229{
4c4b4cd2
PH
3230 struct type *result_type;
3231
14f9c5c9
AS
3232 type = desc_base_type (type);
3233
1eea4ebd
UW
3234 if (n < 0 || n > ada_array_arity (type))
3235 error (_("invalid dimension number to '%s"), name);
14f9c5c9 3236
4c4b4cd2 3237 if (ada_is_simple_array_type (type))
14f9c5c9
AS
3238 {
3239 int i;
3240
3241 for (i = 1; i < n; i += 1)
2869ac4b
TT
3242 {
3243 type = ada_check_typedef (type);
27710edb 3244 type = type->target_type ();
2869ac4b 3245 }
27710edb 3246 result_type = ada_check_typedef (type)->index_type ()->target_type ();
4c4b4cd2 3247 /* FIXME: The stabs type r(0,0);bound;bound in an array type
dda83cd7
SM
3248 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3249 perhaps stabsread.c would make more sense. */
78134374 3250 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
dda83cd7 3251 result_type = NULL;
14f9c5c9 3252 }
d2e4a39e 3253 else
1eea4ebd
UW
3254 {
3255 result_type = desc_index_type (desc_bounds_type (type), n);
3256 if (result_type == NULL)
3257 error (_("attempt to take bound of something that is not an array"));
3258 }
3259
3260 return result_type;
14f9c5c9
AS
3261}
3262
3263/* Given that arr is an array type, returns the lower bound of the
3264 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
4c4b4cd2 3265 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
1eea4ebd
UW
3266 array-descriptor type. It works for other arrays with bounds supplied
3267 by run-time quantities other than discriminants. */
14f9c5c9 3268
abb68b3e 3269static LONGEST
fb5e3d5c 3270ada_array_bound_from_type (struct type *arr_type, int n, int which)
14f9c5c9 3271{
8a48ac95 3272 struct type *type, *index_type_desc, *index_type;
1ce677a4 3273 int i;
262452ec
JK
3274
3275 gdb_assert (which == 0 || which == 1);
14f9c5c9 3276
ad82864c
JB
3277 if (ada_is_constrained_packed_array_type (arr_type))
3278 arr_type = decode_constrained_packed_array_type (arr_type);
14f9c5c9 3279
4c4b4cd2 3280 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
66cf9350 3281 return - which;
14f9c5c9 3282
78134374 3283 if (arr_type->code () == TYPE_CODE_PTR)
27710edb 3284 type = arr_type->target_type ();
14f9c5c9
AS
3285 else
3286 type = arr_type;
3287
22c4c60c 3288 if (type->is_fixed_instance ())
bafffb51
JB
3289 {
3290 /* The array has already been fixed, so we do not need to
3291 check the parallel ___XA type again. That encoding has
3292 already been applied, so ignore it now. */
3293 index_type_desc = NULL;
3294 }
3295 else
3296 {
3297 index_type_desc = ada_find_parallel_type (type, "___XA");
3298 ada_fixup_array_indexes_type (index_type_desc);
3299 }
3300
262452ec 3301 if (index_type_desc != NULL)
940da03e 3302 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
28c85d6c 3303 NULL);
262452ec 3304 else
8a48ac95
JB
3305 {
3306 struct type *elt_type = check_typedef (type);
3307
3308 for (i = 1; i < n; i++)
27710edb 3309 elt_type = check_typedef (elt_type->target_type ());
8a48ac95 3310
3d967001 3311 index_type = elt_type->index_type ();
8a48ac95 3312 }
262452ec 3313
66cf9350
TT
3314 return (which == 0
3315 ? ada_discrete_type_low_bound (index_type)
3316 : ada_discrete_type_high_bound (index_type));
14f9c5c9
AS
3317}
3318
3319/* Given that arr is an array value, returns the lower bound of the
abb68b3e
JB
3320 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3321 WHICH is 1. This routine will also work for arrays with bounds
4c4b4cd2 3322 supplied by run-time quantities other than discriminants. */
14f9c5c9 3323
1eea4ebd 3324static LONGEST
4dc81987 3325ada_array_bound (struct value *arr, int n, int which)
14f9c5c9 3326{
eb479039
JB
3327 struct type *arr_type;
3328
d0c97917 3329 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
eb479039 3330 arr = value_ind (arr);
463b870d 3331 arr_type = arr->enclosing_type ();
14f9c5c9 3332
ad82864c
JB
3333 if (ada_is_constrained_packed_array_type (arr_type))
3334 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
4c4b4cd2 3335 else if (ada_is_simple_array_type (arr_type))
1eea4ebd 3336 return ada_array_bound_from_type (arr_type, n, which);
14f9c5c9 3337 else
1eea4ebd 3338 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
14f9c5c9
AS
3339}
3340
3341/* Given that arr is an array value, returns the length of the
3342 nth index. This routine will also work for arrays with bounds
4c4b4cd2
PH
3343 supplied by run-time quantities other than discriminants.
3344 Does not work for arrays indexed by enumeration types with representation
3345 clauses at the moment. */
14f9c5c9 3346
1eea4ebd 3347static LONGEST
d2e4a39e 3348ada_array_length (struct value *arr, int n)
14f9c5c9 3349{
aa715135
JG
3350 struct type *arr_type, *index_type;
3351 int low, high;
eb479039 3352
d0c97917 3353 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
eb479039 3354 arr = value_ind (arr);
463b870d 3355 arr_type = arr->enclosing_type ();
14f9c5c9 3356
ad82864c
JB
3357 if (ada_is_constrained_packed_array_type (arr_type))
3358 return ada_array_length (decode_constrained_packed_array (arr), n);
14f9c5c9 3359
4c4b4cd2 3360 if (ada_is_simple_array_type (arr_type))
aa715135
JG
3361 {
3362 low = ada_array_bound_from_type (arr_type, n, 0);
3363 high = ada_array_bound_from_type (arr_type, n, 1);
3364 }
14f9c5c9 3365 else
aa715135
JG
3366 {
3367 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3368 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3369 }
3370
f168693b 3371 arr_type = check_typedef (arr_type);
7150d33c 3372 index_type = ada_index_type (arr_type, n, "length");
aa715135
JG
3373 if (index_type != NULL)
3374 {
3375 struct type *base_type;
78134374 3376 if (index_type->code () == TYPE_CODE_RANGE)
27710edb 3377 base_type = index_type->target_type ();
aa715135
JG
3378 else
3379 base_type = index_type;
3380
3381 low = pos_atr (value_from_longest (base_type, low));
3382 high = pos_atr (value_from_longest (base_type, high));
3383 }
3384 return high - low + 1;
4c4b4cd2
PH
3385}
3386
bff8c71f
TT
3387/* An array whose type is that of ARR_TYPE (an array type), with
3388 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3389 less than LOW, then LOW-1 is used. */
4c4b4cd2
PH
3390
3391static struct value *
bff8c71f 3392empty_array (struct type *arr_type, int low, int high)
4c4b4cd2 3393{
b0dd7688 3394 struct type *arr_type0 = ada_check_typedef (arr_type);
e727c536 3395 type_allocator alloc (arr_type0->index_type ()->target_type ());
0c9c3474
SA
3396 struct type *index_type
3397 = create_static_range_type
e727c536 3398 (alloc, arr_type0->index_type ()->target_type (), low,
bff8c71f 3399 high < low ? low - 1 : high);
b0dd7688 3400 struct type *elt_type = ada_array_element_type (arr_type0, 1);
5b4ee69b 3401
9e76b17a 3402 return value::allocate (create_array_type (alloc, elt_type, index_type));
14f9c5c9 3403}
14f9c5c9 3404\f
d2e4a39e 3405
dda83cd7 3406 /* Name resolution */
14f9c5c9 3407
4c4b4cd2
PH
3408/* The "decoded" name for the user-definable Ada operator corresponding
3409 to OP. */
14f9c5c9 3410
d2e4a39e 3411static const char *
4c4b4cd2 3412ada_decoded_op_name (enum exp_opcode op)
14f9c5c9
AS
3413{
3414 int i;
3415
4c4b4cd2 3416 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
14f9c5c9
AS
3417 {
3418 if (ada_opname_table[i].op == op)
dda83cd7 3419 return ada_opname_table[i].decoded;
14f9c5c9 3420 }
323e0a4a 3421 error (_("Could not find operator name for opcode"));
14f9c5c9
AS
3422}
3423
de93309a
SM
3424/* Returns true (non-zero) iff decoded name N0 should appear before N1
3425 in a listing of choices during disambiguation (see sort_choices, below).
3426 The idea is that overloadings of a subprogram name from the
3427 same package should sort in their source order. We settle for ordering
3428 such symbols by their trailing number (__N or $N). */
14f9c5c9 3429
de93309a
SM
3430static int
3431encoded_ordered_before (const char *N0, const char *N1)
14f9c5c9 3432{
de93309a
SM
3433 if (N1 == NULL)
3434 return 0;
3435 else if (N0 == NULL)
3436 return 1;
3437 else
3438 {
3439 int k0, k1;
30b15541 3440
de93309a 3441 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
dda83cd7 3442 ;
de93309a 3443 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
dda83cd7 3444 ;
de93309a 3445 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
dda83cd7
SM
3446 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3447 {
3448 int n0, n1;
3449
3450 n0 = k0;
3451 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3452 n0 -= 1;
3453 n1 = k1;
3454 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3455 n1 -= 1;
3456 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3457 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3458 }
de93309a
SM
3459 return (strcmp (N0, N1) < 0);
3460 }
14f9c5c9
AS
3461}
3462
de93309a
SM
3463/* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3464 encoded names. */
14f9c5c9 3465
de93309a
SM
3466static void
3467sort_choices (struct block_symbol syms[], int nsyms)
14f9c5c9 3468{
14f9c5c9 3469 int i;
14f9c5c9 3470
de93309a 3471 for (i = 1; i < nsyms; i += 1)
14f9c5c9 3472 {
de93309a
SM
3473 struct block_symbol sym = syms[i];
3474 int j;
3475
3476 for (j = i - 1; j >= 0; j -= 1)
dda83cd7
SM
3477 {
3478 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3479 sym.symbol->linkage_name ()))
3480 break;
3481 syms[j + 1] = syms[j];
3482 }
de93309a
SM
3483 syms[j + 1] = sym;
3484 }
3485}
14f9c5c9 3486
de93309a
SM
3487/* Whether GDB should display formals and return types for functions in the
3488 overloads selection menu. */
3489static bool print_signatures = true;
4c4b4cd2 3490
de93309a
SM
3491/* Print the signature for SYM on STREAM according to the FLAGS options. For
3492 all but functions, the signature is just the name of the symbol. For
3493 functions, this is the name of the function, the list of types for formals
3494 and the return type (if any). */
4c4b4cd2 3495
de93309a
SM
3496static void
3497ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3498 const struct type_print_options *flags)
3499{
5f9c5a63 3500 struct type *type = sym->type ();
14f9c5c9 3501
6cb06a8c 3502 gdb_printf (stream, "%s", sym->print_name ());
de93309a
SM
3503 if (!print_signatures
3504 || type == NULL
78134374 3505 || type->code () != TYPE_CODE_FUNC)
de93309a 3506 return;
4c4b4cd2 3507
1f704f76 3508 if (type->num_fields () > 0)
de93309a
SM
3509 {
3510 int i;
14f9c5c9 3511
6cb06a8c 3512 gdb_printf (stream, " (");
1f704f76 3513 for (i = 0; i < type->num_fields (); ++i)
de93309a
SM
3514 {
3515 if (i > 0)
6cb06a8c 3516 gdb_printf (stream, "; ");
940da03e 3517 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
de93309a
SM
3518 flags);
3519 }
6cb06a8c 3520 gdb_printf (stream, ")");
de93309a 3521 }
27710edb
SM
3522 if (type->target_type () != NULL
3523 && type->target_type ()->code () != TYPE_CODE_VOID)
de93309a 3524 {
6cb06a8c 3525 gdb_printf (stream, " return ");
27710edb 3526 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
de93309a
SM
3527 }
3528}
14f9c5c9 3529
de93309a
SM
3530/* Read and validate a set of numeric choices from the user in the
3531 range 0 .. N_CHOICES-1. Place the results in increasing
3532 order in CHOICES[0 .. N-1], and return N.
14f9c5c9 3533
de93309a
SM
3534 The user types choices as a sequence of numbers on one line
3535 separated by blanks, encoding them as follows:
14f9c5c9 3536
de93309a
SM
3537 + A choice of 0 means to cancel the selection, throwing an error.
3538 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3539 + The user chooses k by typing k+IS_ALL_CHOICE+1.
14f9c5c9 3540
de93309a 3541 The user is not allowed to choose more than MAX_RESULTS values.
14f9c5c9 3542
de93309a
SM
3543 ANNOTATION_SUFFIX, if present, is used to annotate the input
3544 prompts (for use with the -f switch). */
14f9c5c9 3545
de93309a
SM
3546static int
3547get_selections (int *choices, int n_choices, int max_results,
dda83cd7 3548 int is_all_choice, const char *annotation_suffix)
de93309a 3549{
992a7040 3550 const char *args;
de93309a
SM
3551 const char *prompt;
3552 int n_chosen;
3553 int first_choice = is_all_choice ? 2 : 1;
14f9c5c9 3554
de93309a
SM
3555 prompt = getenv ("PS2");
3556 if (prompt == NULL)
3557 prompt = "> ";
4c4b4cd2 3558
f8631e5e
SM
3559 std::string buffer;
3560 args = command_line_input (buffer, prompt, annotation_suffix);
4c4b4cd2 3561
de93309a
SM
3562 if (args == NULL)
3563 error_no_arg (_("one or more choice numbers"));
14f9c5c9 3564
de93309a 3565 n_chosen = 0;
4c4b4cd2 3566
de93309a
SM
3567 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3568 order, as given in args. Choices are validated. */
3569 while (1)
14f9c5c9 3570 {
de93309a
SM
3571 char *args2;
3572 int choice, j;
76a01679 3573
de93309a
SM
3574 args = skip_spaces (args);
3575 if (*args == '\0' && n_chosen == 0)
dda83cd7 3576 error_no_arg (_("one or more choice numbers"));
de93309a 3577 else if (*args == '\0')
dda83cd7 3578 break;
76a01679 3579
de93309a
SM
3580 choice = strtol (args, &args2, 10);
3581 if (args == args2 || choice < 0
dda83cd7
SM
3582 || choice > n_choices + first_choice - 1)
3583 error (_("Argument must be choice number"));
de93309a 3584 args = args2;
76a01679 3585
de93309a 3586 if (choice == 0)
dda83cd7 3587 error (_("cancelled"));
76a01679 3588
de93309a 3589 if (choice < first_choice)
dda83cd7
SM
3590 {
3591 n_chosen = n_choices;
3592 for (j = 0; j < n_choices; j += 1)
3593 choices[j] = j;
3594 break;
3595 }
de93309a 3596 choice -= first_choice;
76a01679 3597
de93309a 3598 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
dda83cd7
SM
3599 {
3600 }
4c4b4cd2 3601
de93309a 3602 if (j < 0 || choice != choices[j])
dda83cd7
SM
3603 {
3604 int k;
4c4b4cd2 3605
dda83cd7
SM
3606 for (k = n_chosen - 1; k > j; k -= 1)
3607 choices[k + 1] = choices[k];
3608 choices[j + 1] = choice;
3609 n_chosen += 1;
3610 }
14f9c5c9
AS
3611 }
3612
de93309a
SM
3613 if (n_chosen > max_results)
3614 error (_("Select no more than %d of the above"), max_results);
3615
3616 return n_chosen;
14f9c5c9
AS
3617}
3618
de93309a
SM
3619/* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3620 by asking the user (if necessary), returning the number selected,
3621 and setting the first elements of SYMS items. Error if no symbols
3622 selected. */
3623
3624/* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3625 to be re-integrated one of these days. */
14f9c5c9
AS
3626
3627static int
de93309a 3628user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
14f9c5c9 3629{
de93309a
SM
3630 int i;
3631 int *chosen = XALLOCAVEC (int , nsyms);
3632 int n_chosen;
3633 int first_choice = (max_results == 1) ? 1 : 2;
3634 const char *select_mode = multiple_symbols_select_mode ();
14f9c5c9 3635
de93309a
SM
3636 if (max_results < 1)
3637 error (_("Request to select 0 symbols!"));
3638 if (nsyms <= 1)
3639 return nsyms;
14f9c5c9 3640
de93309a
SM
3641 if (select_mode == multiple_symbols_cancel)
3642 error (_("\
3643canceled because the command is ambiguous\n\
3644See set/show multiple-symbol."));
14f9c5c9 3645
de93309a
SM
3646 /* If select_mode is "all", then return all possible symbols.
3647 Only do that if more than one symbol can be selected, of course.
3648 Otherwise, display the menu as usual. */
3649 if (select_mode == multiple_symbols_all && max_results > 1)
3650 return nsyms;
14f9c5c9 3651
6cb06a8c 3652 gdb_printf (_("[0] cancel\n"));
de93309a 3653 if (max_results > 1)
6cb06a8c 3654 gdb_printf (_("[1] all\n"));
14f9c5c9 3655
de93309a 3656 sort_choices (syms, nsyms);
14f9c5c9 3657
de93309a
SM
3658 for (i = 0; i < nsyms; i += 1)
3659 {
3660 if (syms[i].symbol == NULL)
dda83cd7 3661 continue;
14f9c5c9 3662
66d7f48f 3663 if (syms[i].symbol->aclass () == LOC_BLOCK)
dda83cd7
SM
3664 {
3665 struct symtab_and_line sal =
3666 find_function_start_sal (syms[i].symbol, 1);
14f9c5c9 3667
6cb06a8c 3668 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3669 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3670 &type_print_raw_options);
3671 if (sal.symtab == NULL)
6cb06a8c
TT
3672 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3673 metadata_style.style ().ptr (), nullptr, sal.line);
de93309a 3674 else
6cb06a8c 3675 gdb_printf
de93309a
SM
3676 (_(" at %ps:%d\n"),
3677 styled_string (file_name_style.style (),
3678 symtab_to_filename_for_display (sal.symtab)),
3679 sal.line);
dda83cd7
SM
3680 continue;
3681 }
76a01679 3682 else
dda83cd7
SM
3683 {
3684 int is_enumeral =
66d7f48f 3685 (syms[i].symbol->aclass () == LOC_CONST
5f9c5a63
SM
3686 && syms[i].symbol->type () != NULL
3687 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
de93309a 3688 struct symtab *symtab = NULL;
4c4b4cd2 3689
7b3ecc75 3690 if (syms[i].symbol->is_objfile_owned ())
4206d69e 3691 symtab = syms[i].symbol->symtab ();
de93309a 3692
5d0027b9 3693 if (syms[i].symbol->line () != 0 && symtab != NULL)
de93309a 3694 {
6cb06a8c 3695 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3696 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3697 &type_print_raw_options);
6cb06a8c
TT
3698 gdb_printf (_(" at %s:%d\n"),
3699 symtab_to_filename_for_display (symtab),
3700 syms[i].symbol->line ());
de93309a 3701 }
dda83cd7 3702 else if (is_enumeral
5f9c5a63 3703 && syms[i].symbol->type ()->name () != NULL)
dda83cd7 3704 {
6cb06a8c 3705 gdb_printf (("[%d] "), i + first_choice);
5f9c5a63 3706 ada_print_type (syms[i].symbol->type (), NULL,
dda83cd7 3707 gdb_stdout, -1, 0, &type_print_raw_options);
6cb06a8c
TT
3708 gdb_printf (_("'(%s) (enumeral)\n"),
3709 syms[i].symbol->print_name ());
dda83cd7 3710 }
de93309a
SM
3711 else
3712 {
6cb06a8c 3713 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3714 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3715 &type_print_raw_options);
3716
3717 if (symtab != NULL)
6cb06a8c
TT
3718 gdb_printf (is_enumeral
3719 ? _(" in %s (enumeral)\n")
3720 : _(" at %s:?\n"),
3721 symtab_to_filename_for_display (symtab));
de93309a 3722 else
6cb06a8c
TT
3723 gdb_printf (is_enumeral
3724 ? _(" (enumeral)\n")
3725 : _(" at ?\n"));
de93309a 3726 }
dda83cd7 3727 }
14f9c5c9 3728 }
14f9c5c9 3729
de93309a 3730 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
dda83cd7 3731 "overload-choice");
14f9c5c9 3732
de93309a
SM
3733 for (i = 0; i < n_chosen; i += 1)
3734 syms[i] = syms[chosen[i]];
14f9c5c9 3735
de93309a
SM
3736 return n_chosen;
3737}
14f9c5c9 3738
cd9a3148
TT
3739/* See ada-lang.h. */
3740
3741block_symbol
7056f312 3742ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
cd9a3148
TT
3743 int nargs, value *argvec[])
3744{
3745 if (possible_user_operator_p (op, argvec))
3746 {
3747 std::vector<struct block_symbol> candidates
3748 = ada_lookup_symbol_list (ada_decoded_op_name (op),
6c015214 3749 NULL, SEARCH_VFT);
cd9a3148
TT
3750
3751 int i = ada_resolve_function (candidates, argvec,
3752 nargs, ada_decoded_op_name (op), NULL,
3753 parse_completion);
3754 if (i >= 0)
3755 return candidates[i];
3756 }
3757 return {};
3758}
3759
3760/* See ada-lang.h. */
3761
3762block_symbol
3763ada_resolve_funcall (struct symbol *sym, const struct block *block,
3764 struct type *context_type,
7056f312 3765 bool parse_completion,
cd9a3148
TT
3766 int nargs, value *argvec[],
3767 innermost_block_tracker *tracker)
3768{
3769 std::vector<struct block_symbol> candidates
6c015214 3770 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
cd9a3148
TT
3771
3772 int i;
3773 if (candidates.size () == 1)
3774 i = 0;
3775 else
3776 {
3777 i = ada_resolve_function
3778 (candidates,
3779 argvec, nargs,
3780 sym->linkage_name (),
3781 context_type, parse_completion);
3782 if (i < 0)
3783 error (_("Could not find a match for %s"), sym->print_name ());
3784 }
3785
3786 tracker->update (candidates[i]);
3787 return candidates[i];
3788}
3789
ba8694b6
TT
3790/* Resolve a mention of a name where the context type is an
3791 enumeration type. */
3792
3793static int
3794ada_resolve_enum (std::vector<struct block_symbol> &syms,
3795 const char *name, struct type *context_type,
3796 bool parse_completion)
3797{
3798 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3799 context_type = ada_check_typedef (context_type);
3800
74c36641
TV
3801 /* We already know the name matches, so we're just looking for
3802 an element of the correct enum type. */
3803 struct type *type1 = context_type;
3804 for (int i = 0; i < syms.size (); ++i)
3805 {
3806 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3807 if (type1 == type2)
3808 return i;
3809 }
3810
ba8694b6
TT
3811 for (int i = 0; i < syms.size (); ++i)
3812 {
74c36641
TV
3813 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3814 if (type1->num_fields () != type2->num_fields ())
3815 continue;
3816 if (strcmp (type1->name (), type2->name ()) != 0)
3817 continue;
3818 if (ada_identical_enum_types_p (type1, type2))
ba8694b6
TT
3819 return i;
3820 }
3821
3822 error (_("No name '%s' in enumeration type '%s'"), name,
3823 ada_type_name (context_type));
3824}
3825
cd9a3148
TT
3826/* See ada-lang.h. */
3827
3828block_symbol
3829ada_resolve_variable (struct symbol *sym, const struct block *block,
3830 struct type *context_type,
7056f312 3831 bool parse_completion,
cd9a3148
TT
3832 int deprocedure_p,
3833 innermost_block_tracker *tracker)
3834{
3835 std::vector<struct block_symbol> candidates
6c015214 3836 = ada_lookup_symbol_list (sym->linkage_name (), block, SEARCH_VFT);
cd9a3148
TT
3837
3838 if (std::any_of (candidates.begin (),
3839 candidates.end (),
3840 [] (block_symbol &bsym)
3841 {
66d7f48f 3842 switch (bsym.symbol->aclass ())
cd9a3148
TT
3843 {
3844 case LOC_REGISTER:
3845 case LOC_ARG:
3846 case LOC_REF_ARG:
3847 case LOC_REGPARM_ADDR:
3848 case LOC_LOCAL:
3849 case LOC_COMPUTED:
3850 return true;
3851 default:
3852 return false;
3853 }
3854 }))
3855 {
3856 /* Types tend to get re-introduced locally, so if there
3857 are any local symbols that are not types, first filter
3858 out all types. */
3859 candidates.erase
3860 (std::remove_if
3861 (candidates.begin (),
3862 candidates.end (),
3863 [] (block_symbol &bsym)
3864 {
66d7f48f 3865 return bsym.symbol->aclass () == LOC_TYPEDEF;
cd9a3148
TT
3866 }),
3867 candidates.end ());
3868 }
3869
2c71f639
TV
3870 /* Filter out artificial symbols. */
3871 candidates.erase
3872 (std::remove_if
3873 (candidates.begin (),
3874 candidates.end (),
3875 [] (block_symbol &bsym)
3876 {
496feb16 3877 return bsym.symbol->is_artificial ();
2c71f639
TV
3878 }),
3879 candidates.end ());
3880
cd9a3148
TT
3881 int i;
3882 if (candidates.empty ())
3883 error (_("No definition found for %s"), sym->print_name ());
3884 else if (candidates.size () == 1)
3885 i = 0;
ba8694b6
TT
3886 else if (context_type != nullptr
3887 && context_type->code () == TYPE_CODE_ENUM)
3888 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3889 parse_completion);
ef136c7f
TV
3890 else if (context_type == nullptr
3891 && symbols_are_identical_enums (candidates))
3892 {
3893 /* If all the remaining symbols are identical enumerals, then
3894 just keep the first one and discard the rest.
3895
3896 Unlike what we did previously, we do not discard any entry
3897 unless they are ALL identical. This is because the symbol
3898 comparison is not a strict comparison, but rather a practical
3899 comparison. If all symbols are considered identical, then
3900 we can just go ahead and use the first one and discard the rest.
3901 But if we cannot reduce the list to a single element, we have
3902 to ask the user to disambiguate anyways. And if we have to
3903 present a multiple-choice menu, it's less confusing if the list
3904 isn't missing some choices that were identical and yet distinct. */
3905 candidates.resize (1);
3906 i = 0;
3907 }
cd9a3148
TT
3908 else if (deprocedure_p && !is_nonfunction (candidates))
3909 {
3910 i = ada_resolve_function
3911 (candidates, NULL, 0,
3912 sym->linkage_name (),
3913 context_type, parse_completion);
3914 if (i < 0)
3915 error (_("Could not find a match for %s"), sym->print_name ());
3916 }
3917 else
3918 {
6cb06a8c 3919 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
cd9a3148
TT
3920 user_select_syms (candidates.data (), candidates.size (), 1);
3921 i = 0;
3922 }
3923
3924 tracker->update (candidates[i]);
3925 return candidates[i];
3926}
3927
d56fdf1b
TT
3928static bool ada_type_match (struct type *ftype, struct type *atype);
3929
3930/* Helper for ada_type_match that checks that two array types are
3931 compatible. As with that function, FTYPE is the formal type and
3932 ATYPE is the actual type. */
3933
3934static bool
3935ada_type_match_arrays (struct type *ftype, struct type *atype)
3936{
3937 if (ftype->code () != TYPE_CODE_ARRAY
3938 && !ada_is_array_descriptor_type (ftype))
3939 return false;
3940 if (atype->code () != TYPE_CODE_ARRAY
3941 && !ada_is_array_descriptor_type (atype))
3942 return false;
3943
3944 if (ada_array_arity (ftype) != ada_array_arity (atype))
3945 return false;
3946
3947 struct type *f_elt_type = ada_array_element_type (ftype, -1);
3948 struct type *a_elt_type = ada_array_element_type (atype, -1);
3949 return ada_type_match (f_elt_type, a_elt_type);
3950}
3951
3952/* Return non-zero if formal type FTYPE matches actual type ATYPE.
3953 The term "match" here is rather loose. The match is heuristic and
3954 liberal -- while it tries to reject matches that are obviously
3955 incorrect, it may still let through some that do not strictly
3956 correspond to Ada rules. */
14f9c5c9 3957
1414fbf9 3958static bool
db2534b7 3959ada_type_match (struct type *ftype, struct type *atype)
14f9c5c9 3960{
de93309a
SM
3961 ftype = ada_check_typedef (ftype);
3962 atype = ada_check_typedef (atype);
14f9c5c9 3963
78134374 3964 if (ftype->code () == TYPE_CODE_REF)
27710edb 3965 ftype = ftype->target_type ();
78134374 3966 if (atype->code () == TYPE_CODE_REF)
27710edb 3967 atype = atype->target_type ();
14f9c5c9 3968
78134374 3969 switch (ftype->code ())
14f9c5c9 3970 {
de93309a 3971 default:
78134374 3972 return ftype->code () == atype->code ();
de93309a 3973 case TYPE_CODE_PTR:
db2534b7 3974 if (atype->code () != TYPE_CODE_PTR)
1414fbf9 3975 return false;
27710edb 3976 atype = atype->target_type ();
db2534b7 3977 /* This can only happen if the actual argument is 'null'. */
df86565b 3978 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
1414fbf9 3979 return true;
27710edb 3980 return ada_type_match (ftype->target_type (), atype);
de93309a
SM
3981 case TYPE_CODE_INT:
3982 case TYPE_CODE_ENUM:
3983 case TYPE_CODE_RANGE:
78134374 3984 switch (atype->code ())
dda83cd7
SM
3985 {
3986 case TYPE_CODE_INT:
3987 case TYPE_CODE_ENUM:
3988 case TYPE_CODE_RANGE:
1414fbf9 3989 return true;
dda83cd7 3990 default:
1414fbf9 3991 return false;
dda83cd7 3992 }
d2e4a39e 3993
de93309a 3994 case TYPE_CODE_STRUCT:
d56fdf1b 3995 if (!ada_is_array_descriptor_type (ftype))
dda83cd7
SM
3996 return (atype->code () == TYPE_CODE_STRUCT
3997 && !ada_is_array_descriptor_type (atype));
14f9c5c9 3998
d56fdf1b
TT
3999 [[fallthrough]];
4000 case TYPE_CODE_ARRAY:
4001 return ada_type_match_arrays (ftype, atype);
4002
de93309a
SM
4003 case TYPE_CODE_UNION:
4004 case TYPE_CODE_FLT:
78134374 4005 return (atype->code () == ftype->code ());
de93309a 4006 }
14f9c5c9
AS
4007}
4008
de93309a
SM
4009/* Return non-zero if the formals of FUNC "sufficiently match" the
4010 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
4011 may also be an enumeral, in which case it is treated as a 0-
4012 argument function. */
14f9c5c9 4013
de93309a
SM
4014static int
4015ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
4016{
4017 int i;
5f9c5a63 4018 struct type *func_type = func->type ();
14f9c5c9 4019
66d7f48f 4020 if (func->aclass () == LOC_CONST
78134374 4021 && func_type->code () == TYPE_CODE_ENUM)
de93309a 4022 return (n_actuals == 0);
78134374 4023 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
de93309a 4024 return 0;
14f9c5c9 4025
1f704f76 4026 if (func_type->num_fields () != n_actuals)
de93309a 4027 return 0;
14f9c5c9 4028
de93309a
SM
4029 for (i = 0; i < n_actuals; i += 1)
4030 {
4031 if (actuals[i] == NULL)
dda83cd7 4032 return 0;
de93309a 4033 else
dda83cd7
SM
4034 {
4035 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
d0c97917 4036 struct type *atype = ada_check_typedef (actuals[i]->type ());
14f9c5c9 4037
db2534b7 4038 if (!ada_type_match (ftype, atype))
dda83cd7
SM
4039 return 0;
4040 }
de93309a
SM
4041 }
4042 return 1;
4043}
d2e4a39e 4044
de93309a
SM
4045/* False iff function type FUNC_TYPE definitely does not produce a value
4046 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4047 FUNC_TYPE is not a valid function type with a non-null return type
4048 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
14f9c5c9 4049
de93309a
SM
4050static int
4051return_match (struct type *func_type, struct type *context_type)
4052{
4053 struct type *return_type;
d2e4a39e 4054
de93309a
SM
4055 if (func_type == NULL)
4056 return 1;
14f9c5c9 4057
78134374 4058 if (func_type->code () == TYPE_CODE_FUNC)
27710edb 4059 return_type = get_base_type (func_type->target_type ());
de93309a
SM
4060 else
4061 return_type = get_base_type (func_type);
4062 if (return_type == NULL)
4063 return 1;
76a01679 4064
de93309a 4065 context_type = get_base_type (context_type);
14f9c5c9 4066
78134374 4067 if (return_type->code () == TYPE_CODE_ENUM)
de93309a
SM
4068 return context_type == NULL || return_type == context_type;
4069 else if (context_type == NULL)
78134374 4070 return return_type->code () != TYPE_CODE_VOID;
de93309a 4071 else
78134374 4072 return return_type->code () == context_type->code ();
de93309a 4073}
14f9c5c9 4074
14f9c5c9 4075
1bfa81ac 4076/* Returns the index in SYMS that contains the symbol for the
de93309a
SM
4077 function (if any) that matches the types of the NARGS arguments in
4078 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4079 that returns that type, then eliminate matches that don't. If
4080 CONTEXT_TYPE is void and there is at least one match that does not
4081 return void, eliminate all matches that do.
14f9c5c9 4082
de93309a
SM
4083 Asks the user if there is more than one match remaining. Returns -1
4084 if there is no such symbol or none is selected. NAME is used
4085 solely for messages. May re-arrange and modify SYMS in
4086 the process; the index returned is for the modified vector. */
14f9c5c9 4087
de93309a 4088static int
d1183b06
TT
4089ada_resolve_function (std::vector<struct block_symbol> &syms,
4090 struct value **args, int nargs,
dda83cd7 4091 const char *name, struct type *context_type,
7056f312 4092 bool parse_completion)
de93309a
SM
4093{
4094 int fallback;
4095 int k;
4096 int m; /* Number of hits */
14f9c5c9 4097
de93309a
SM
4098 m = 0;
4099 /* In the first pass of the loop, we only accept functions matching
4100 context_type. If none are found, we add a second pass of the loop
4101 where every function is accepted. */
4102 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4103 {
d1183b06 4104 for (k = 0; k < syms.size (); k += 1)
dda83cd7 4105 {
5f9c5a63 4106 struct type *type = ada_check_typedef (syms[k].symbol->type ());
5b4ee69b 4107
dda83cd7
SM
4108 if (ada_args_match (syms[k].symbol, args, nargs)
4109 && (fallback || return_match (type, context_type)))
4110 {
4111 syms[m] = syms[k];
4112 m += 1;
4113 }
4114 }
14f9c5c9
AS
4115 }
4116
de93309a
SM
4117 /* If we got multiple matches, ask the user which one to use. Don't do this
4118 interactive thing during completion, though, as the purpose of the
4119 completion is providing a list of all possible matches. Prompting the
4120 user to filter it down would be completely unexpected in this case. */
4121 if (m == 0)
4122 return -1;
4123 else if (m > 1 && !parse_completion)
4124 {
6cb06a8c 4125 gdb_printf (_("Multiple matches for %s\n"), name);
d1183b06 4126 user_select_syms (syms.data (), m, 1);
de93309a
SM
4127 return 0;
4128 }
4129 return 0;
14f9c5c9
AS
4130}
4131
14f9c5c9
AS
4132/* Type-class predicates */
4133
4c4b4cd2
PH
4134/* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4135 or FLOAT). */
14f9c5c9
AS
4136
4137static int
d2e4a39e 4138numeric_type_p (struct type *type)
14f9c5c9
AS
4139{
4140 if (type == NULL)
4141 return 0;
d2e4a39e
AS
4142 else
4143 {
78134374 4144 switch (type->code ())
dda83cd7
SM
4145 {
4146 case TYPE_CODE_INT:
4147 case TYPE_CODE_FLT:
c04da66c 4148 case TYPE_CODE_FIXED_POINT:
dda83cd7
SM
4149 return 1;
4150 case TYPE_CODE_RANGE:
27710edb
SM
4151 return (type == type->target_type ()
4152 || numeric_type_p (type->target_type ()));
dda83cd7
SM
4153 default:
4154 return 0;
4155 }
d2e4a39e 4156 }
14f9c5c9
AS
4157}
4158
4c4b4cd2 4159/* True iff TYPE is integral (an INT or RANGE of INTs). */
14f9c5c9
AS
4160
4161static int
d2e4a39e 4162integer_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 return 1;
4172 case TYPE_CODE_RANGE:
27710edb
SM
4173 return (type == type->target_type ()
4174 || integer_type_p (type->target_type ()));
dda83cd7
SM
4175 default:
4176 return 0;
4177 }
d2e4a39e 4178 }
14f9c5c9
AS
4179}
4180
4c4b4cd2 4181/* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
14f9c5c9
AS
4182
4183static int
d2e4a39e 4184scalar_type_p (struct type *type)
14f9c5c9
AS
4185{
4186 if (type == NULL)
4187 return 0;
d2e4a39e
AS
4188 else
4189 {
78134374 4190 switch (type->code ())
dda83cd7
SM
4191 {
4192 case TYPE_CODE_INT:
4193 case TYPE_CODE_RANGE:
4194 case TYPE_CODE_ENUM:
4195 case TYPE_CODE_FLT:
c04da66c 4196 case TYPE_CODE_FIXED_POINT:
dda83cd7
SM
4197 return 1;
4198 default:
4199 return 0;
4200 }
d2e4a39e 4201 }
14f9c5c9
AS
4202}
4203
98847c1e
TT
4204/* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4205 This essentially means one of (INT, RANGE, ENUM) -- but note that
4206 "enum" includes character and boolean as well. */
14f9c5c9
AS
4207
4208static int
d2e4a39e 4209discrete_type_p (struct type *type)
14f9c5c9
AS
4210{
4211 if (type == NULL)
4212 return 0;
d2e4a39e
AS
4213 else
4214 {
78134374 4215 switch (type->code ())
dda83cd7
SM
4216 {
4217 case TYPE_CODE_INT:
4218 case TYPE_CODE_RANGE:
4219 case TYPE_CODE_ENUM:
4220 case TYPE_CODE_BOOL:
98847c1e 4221 case TYPE_CODE_CHAR:
dda83cd7
SM
4222 return 1;
4223 default:
4224 return 0;
4225 }
d2e4a39e 4226 }
14f9c5c9
AS
4227}
4228
4c4b4cd2
PH
4229/* Returns non-zero if OP with operands in the vector ARGS could be
4230 a user-defined function. Errs on the side of pre-defined operators
4231 (i.e., result 0). */
14f9c5c9
AS
4232
4233static int
d2e4a39e 4234possible_user_operator_p (enum exp_opcode op, struct value *args[])
14f9c5c9 4235{
76a01679 4236 struct type *type0 =
d0c97917 4237 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
d2e4a39e 4238 struct type *type1 =
d0c97917 4239 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
d2e4a39e 4240
4c4b4cd2
PH
4241 if (type0 == NULL)
4242 return 0;
4243
14f9c5c9
AS
4244 switch (op)
4245 {
4246 default:
4247 return 0;
4248
4249 case BINOP_ADD:
4250 case BINOP_SUB:
4251 case BINOP_MUL:
4252 case BINOP_DIV:
d2e4a39e 4253 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
14f9c5c9
AS
4254
4255 case BINOP_REM:
4256 case BINOP_MOD:
4257 case BINOP_BITWISE_AND:
4258 case BINOP_BITWISE_IOR:
4259 case BINOP_BITWISE_XOR:
d2e4a39e 4260 return (!(integer_type_p (type0) && integer_type_p (type1)));
14f9c5c9
AS
4261
4262 case BINOP_EQUAL:
4263 case BINOP_NOTEQUAL:
4264 case BINOP_LESS:
4265 case BINOP_GTR:
4266 case BINOP_LEQ:
4267 case BINOP_GEQ:
d2e4a39e 4268 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
14f9c5c9
AS
4269
4270 case BINOP_CONCAT:
ee90b9ab 4271 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
14f9c5c9
AS
4272
4273 case BINOP_EXP:
d2e4a39e 4274 return (!(numeric_type_p (type0) && integer_type_p (type1)));
14f9c5c9
AS
4275
4276 case UNOP_NEG:
4277 case UNOP_PLUS:
4278 case UNOP_LOGICAL_NOT:
d2e4a39e
AS
4279 case UNOP_ABS:
4280 return (!numeric_type_p (type0));
14f9c5c9
AS
4281
4282 }
4283}
4284\f
dda83cd7 4285 /* Renaming */
14f9c5c9 4286
aeb5907d
JB
4287/* NOTES:
4288
4289 1. In the following, we assume that a renaming type's name may
4290 have an ___XD suffix. It would be nice if this went away at some
4291 point.
4292 2. We handle both the (old) purely type-based representation of
4293 renamings and the (new) variable-based encoding. At some point,
4294 it is devoutly to be hoped that the former goes away
4295 (FIXME: hilfinger-2007-07-09).
4296 3. Subprogram renamings are not implemented, although the XRS
4297 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4298
4299/* If SYM encodes a renaming,
4300
4301 <renaming> renames <renamed entity>,
4302
4303 sets *LEN to the length of the renamed entity's name,
4304 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4305 the string describing the subcomponent selected from the renamed
0963b4bd 4306 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
aeb5907d
JB
4307 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4308 are undefined). Otherwise, returns a value indicating the category
4309 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4310 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4311 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4312 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4313 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4314 may be NULL, in which case they are not assigned.
4315
4316 [Currently, however, GCC does not generate subprogram renamings.] */
4317
4318enum ada_renaming_category
4319ada_parse_renaming (struct symbol *sym,
4320 const char **renamed_entity, int *len,
4321 const char **renaming_expr)
4322{
4323 enum ada_renaming_category kind;
4324 const char *info;
4325 const char *suffix;
4326
4327 if (sym == NULL)
4328 return ADA_NOT_RENAMING;
66d7f48f 4329 switch (sym->aclass ())
14f9c5c9 4330 {
aeb5907d
JB
4331 default:
4332 return ADA_NOT_RENAMING;
aeb5907d
JB
4333 case LOC_LOCAL:
4334 case LOC_STATIC:
4335 case LOC_COMPUTED:
4336 case LOC_OPTIMIZED_OUT:
987012b8 4337 info = strstr (sym->linkage_name (), "___XR");
aeb5907d
JB
4338 if (info == NULL)
4339 return ADA_NOT_RENAMING;
4340 switch (info[5])
4341 {
4342 case '_':
4343 kind = ADA_OBJECT_RENAMING;
4344 info += 6;
4345 break;
4346 case 'E':
4347 kind = ADA_EXCEPTION_RENAMING;
4348 info += 7;
4349 break;
4350 case 'P':
4351 kind = ADA_PACKAGE_RENAMING;
4352 info += 7;
4353 break;
4354 case 'S':
4355 kind = ADA_SUBPROGRAM_RENAMING;
4356 info += 7;
4357 break;
4358 default:
4359 return ADA_NOT_RENAMING;
4360 }
14f9c5c9 4361 }
4c4b4cd2 4362
de93309a
SM
4363 if (renamed_entity != NULL)
4364 *renamed_entity = info;
4365 suffix = strstr (info, "___XE");
4366 if (suffix == NULL || suffix == info)
4367 return ADA_NOT_RENAMING;
4368 if (len != NULL)
4369 *len = strlen (info) - strlen (suffix);
4370 suffix += 5;
4371 if (renaming_expr != NULL)
4372 *renaming_expr = suffix;
4373 return kind;
4374}
4375
4376/* Compute the value of the given RENAMING_SYM, which is expected to
4377 be a symbol encoding a renaming expression. BLOCK is the block
4378 used to evaluate the renaming. */
4379
4380static struct value *
4381ada_read_renaming_var_value (struct symbol *renaming_sym,
4382 const struct block *block)
4383{
4384 const char *sym_name;
4385
987012b8 4386 sym_name = renaming_sym->linkage_name ();
de93309a 4387 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
43048e46 4388 return expr->evaluate ();
de93309a
SM
4389}
4390\f
4391
dda83cd7 4392 /* Evaluation: Function Calls */
de93309a
SM
4393
4394/* Return an lvalue containing the value VAL. This is the identity on
4395 lvalues, and otherwise has the side-effect of allocating memory
4396 in the inferior where a copy of the value contents is copied. */
4397
4398static struct value *
4399ensure_lval (struct value *val)
4400{
736355f2
TT
4401 if (val->lval () == not_lval
4402 || val->lval () == lval_internalvar)
de93309a 4403 {
d0c97917 4404 int len = ada_check_typedef (val->type ())->length ();
de93309a 4405 const CORE_ADDR addr =
dda83cd7 4406 value_as_long (value_allocate_space_in_inferior (len));
de93309a 4407
6f9c9d71 4408 val->set_lval (lval_memory);
9feb2d07 4409 val->set_address (addr);
efaf1ae0 4410 write_memory (addr, val->contents ().data (), len);
de93309a
SM
4411 }
4412
4413 return val;
4414}
4415
4416/* Given ARG, a value of type (pointer or reference to a)*
4417 structure/union, extract the component named NAME from the ultimate
4418 target structure/union and return it as a value with its
4419 appropriate type.
4420
4421 The routine searches for NAME among all members of the structure itself
4422 and (recursively) among all members of any wrapper members
4423 (e.g., '_parent').
4424
4425 If NO_ERR, then simply return NULL in case of error, rather than
4426 calling error. */
4427
4428static struct value *
4429ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4430{
4431 struct type *t, *t1;
4432 struct value *v;
4433 int check_tag;
4434
4435 v = NULL;
d0c97917 4436 t1 = t = ada_check_typedef (arg->type ());
78134374 4437 if (t->code () == TYPE_CODE_REF)
de93309a 4438 {
27710edb 4439 t1 = t->target_type ();
de93309a
SM
4440 if (t1 == NULL)
4441 goto BadValue;
4442 t1 = ada_check_typedef (t1);
78134374 4443 if (t1->code () == TYPE_CODE_PTR)
dda83cd7
SM
4444 {
4445 arg = coerce_ref (arg);
4446 t = t1;
4447 }
de93309a
SM
4448 }
4449
78134374 4450 while (t->code () == TYPE_CODE_PTR)
de93309a 4451 {
27710edb 4452 t1 = t->target_type ();
de93309a
SM
4453 if (t1 == NULL)
4454 goto BadValue;
4455 t1 = ada_check_typedef (t1);
78134374 4456 if (t1->code () == TYPE_CODE_PTR)
dda83cd7
SM
4457 {
4458 arg = value_ind (arg);
4459 t = t1;
4460 }
de93309a 4461 else
dda83cd7 4462 break;
de93309a 4463 }
aeb5907d 4464
78134374 4465 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
de93309a 4466 goto BadValue;
52ce6436 4467
de93309a
SM
4468 if (t1 == t)
4469 v = ada_search_struct_field (name, arg, 0, t);
4470 else
4471 {
4472 int bit_offset, bit_size, byte_offset;
4473 struct type *field_type;
4474 CORE_ADDR address;
a5ee536b 4475
78134374 4476 if (t->code () == TYPE_CODE_PTR)
9feb2d07 4477 address = ada_value_ind (arg)->address ();
de93309a 4478 else
9feb2d07 4479 address = ada_coerce_ref (arg)->address ();
d2e4a39e 4480
de93309a 4481 /* Check to see if this is a tagged type. We also need to handle
dda83cd7
SM
4482 the case where the type is a reference to a tagged type, but
4483 we have to be careful to exclude pointers to tagged types.
4484 The latter should be shown as usual (as a pointer), whereas
4485 a reference should mostly be transparent to the user. */
14f9c5c9 4486
de93309a 4487 if (ada_is_tagged_type (t1, 0)
dda83cd7 4488 || (t1->code () == TYPE_CODE_REF
27710edb 4489 && ada_is_tagged_type (t1->target_type (), 0)))
dda83cd7
SM
4490 {
4491 /* We first try to find the searched field in the current type.
de93309a 4492 If not found then let's look in the fixed type. */
14f9c5c9 4493
dda83cd7 4494 if (!find_struct_field (name, t1, 0,
4d1795ac
TT
4495 nullptr, nullptr, nullptr,
4496 nullptr, nullptr))
de93309a
SM
4497 check_tag = 1;
4498 else
4499 check_tag = 0;
dda83cd7 4500 }
de93309a
SM
4501 else
4502 check_tag = 0;
c3e5cd34 4503
de93309a
SM
4504 /* Convert to fixed type in all cases, so that we have proper
4505 offsets to each field in unconstrained record types. */
4506 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4507 address, NULL, check_tag);
4508
24aa1b02
TT
4509 /* Resolve the dynamic type as well. */
4510 arg = value_from_contents_and_address (t1, nullptr, address);
d0c97917 4511 t1 = arg->type ();
24aa1b02 4512
de93309a 4513 if (find_struct_field (name, t1, 0,
dda83cd7
SM
4514 &field_type, &byte_offset, &bit_offset,
4515 &bit_size, NULL))
4516 {
4517 if (bit_size != 0)
4518 {
4519 if (t->code () == TYPE_CODE_REF)
4520 arg = ada_coerce_ref (arg);
4521 else
4522 arg = ada_value_ind (arg);
4523 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4524 bit_offset, bit_size,
4525 field_type);
4526 }
4527 else
4528 v = value_at_lazy (field_type, address + byte_offset);
4529 }
c3e5cd34 4530 }
14f9c5c9 4531
de93309a
SM
4532 if (v != NULL || no_err)
4533 return v;
4534 else
4535 error (_("There is no member named %s."), name);
4536
4537 BadValue:
4538 if (no_err)
4539 return NULL;
4540 else
4541 error (_("Attempt to extract a component of "
4542 "a value that is not a record."));
14f9c5c9
AS
4543}
4544
4545/* Return the value ACTUAL, converted to be an appropriate value for a
4546 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4547 allocating any necessary descriptors (fat pointers), or copies of
4c4b4cd2 4548 values not residing in memory, updating it as needed. */
14f9c5c9 4549
a93c0eb6 4550struct value *
40bc484c 4551ada_convert_actual (struct value *actual, struct type *formal_type0)
14f9c5c9 4552{
d0c97917 4553 struct type *actual_type = ada_check_typedef (actual->type ());
61ee279c 4554 struct type *formal_type = ada_check_typedef (formal_type0);
d2e4a39e 4555 struct type *formal_target =
78134374 4556 formal_type->code () == TYPE_CODE_PTR
27710edb 4557 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
d2e4a39e 4558 struct type *actual_target =
78134374 4559 actual_type->code () == TYPE_CODE_PTR
27710edb 4560 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
14f9c5c9 4561
4c4b4cd2 4562 if (ada_is_array_descriptor_type (formal_target)
78134374 4563 && actual_target->code () == TYPE_CODE_ARRAY)
40bc484c 4564 return make_array_descriptor (formal_type, actual);
78134374
SM
4565 else if (formal_type->code () == TYPE_CODE_PTR
4566 || formal_type->code () == TYPE_CODE_REF)
14f9c5c9 4567 {
a84a8a0d 4568 struct value *result;
5b4ee69b 4569
78134374 4570 if (formal_target->code () == TYPE_CODE_ARRAY
dda83cd7 4571 && ada_is_array_descriptor_type (actual_target))
a84a8a0d 4572 result = desc_data (actual);
78134374 4573 else if (formal_type->code () != TYPE_CODE_PTR)
dda83cd7 4574 {
736355f2 4575 if (actual->lval () != lval_memory)
dda83cd7
SM
4576 {
4577 struct value *val;
4578
d0c97917 4579 actual_type = ada_check_typedef (actual->type ());
317c3ed9 4580 val = value::allocate (actual_type);
efaf1ae0 4581 copy (actual->contents (), val->contents_raw ());
dda83cd7
SM
4582 actual = ensure_lval (val);
4583 }
4584 result = value_addr (actual);
4585 }
a84a8a0d
JB
4586 else
4587 return actual;
b1af9e97 4588 return value_cast_pointers (formal_type, result, 0);
14f9c5c9 4589 }
78134374 4590 else if (actual_type->code () == TYPE_CODE_PTR)
14f9c5c9 4591 return ada_value_ind (actual);
8344af1e
JB
4592 else if (ada_is_aligner_type (formal_type))
4593 {
4594 /* We need to turn this parameter into an aligner type
4595 as well. */
317c3ed9 4596 struct value *aligner = value::allocate (formal_type);
8344af1e
JB
4597 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4598
4599 value_assign_to_component (aligner, component, actual);
4600 return aligner;
4601 }
14f9c5c9
AS
4602
4603 return actual;
4604}
4605
438c98a1
JB
4606/* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4607 type TYPE. This is usually an inefficient no-op except on some targets
4608 (such as AVR) where the representation of a pointer and an address
4609 differs. */
4610
4611static CORE_ADDR
4612value_pointer (struct value *value, struct type *type)
4613{
df86565b 4614 unsigned len = type->length ();
224c3ddb 4615 gdb_byte *buf = (gdb_byte *) alloca (len);
438c98a1
JB
4616 CORE_ADDR addr;
4617
9feb2d07 4618 addr = value->address ();
8ee511af 4619 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
34877895 4620 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
438c98a1
JB
4621 return addr;
4622}
4623
14f9c5c9 4624
4c4b4cd2
PH
4625/* Push a descriptor of type TYPE for array value ARR on the stack at
4626 *SP, updating *SP to reflect the new descriptor. Return either
14f9c5c9 4627 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4c4b4cd2
PH
4628 to-descriptor type rather than a descriptor type), a struct value *
4629 representing a pointer to this descriptor. */
14f9c5c9 4630
d2e4a39e 4631static struct value *
40bc484c 4632make_array_descriptor (struct type *type, struct value *arr)
14f9c5c9 4633{
d2e4a39e
AS
4634 struct type *bounds_type = desc_bounds_type (type);
4635 struct type *desc_type = desc_base_type (type);
317c3ed9
TT
4636 struct value *descriptor = value::allocate (desc_type);
4637 struct value *bounds = value::allocate (bounds_type);
14f9c5c9 4638 int i;
d2e4a39e 4639
d0c97917 4640 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
0963b4bd 4641 i > 0; i -= 1)
14f9c5c9 4642 {
d0c97917 4643 modify_field (bounds->type (),
bbe912ba 4644 bounds->contents_writeable ().data (),
19f220c3
JK
4645 ada_array_bound (arr, i, 0),
4646 desc_bound_bitpos (bounds_type, i, 0),
4647 desc_bound_bitsize (bounds_type, i, 0));
d0c97917 4648 modify_field (bounds->type (),
bbe912ba 4649 bounds->contents_writeable ().data (),
19f220c3
JK
4650 ada_array_bound (arr, i, 1),
4651 desc_bound_bitpos (bounds_type, i, 1),
4652 desc_bound_bitsize (bounds_type, i, 1));
14f9c5c9 4653 }
d2e4a39e 4654
40bc484c 4655 bounds = ensure_lval (bounds);
d2e4a39e 4656
d0c97917 4657 modify_field (descriptor->type (),
bbe912ba 4658 descriptor->contents_writeable ().data (),
19f220c3 4659 value_pointer (ensure_lval (arr),
940da03e 4660 desc_type->field (0).type ()),
19f220c3
JK
4661 fat_pntr_data_bitpos (desc_type),
4662 fat_pntr_data_bitsize (desc_type));
4663
d0c97917 4664 modify_field (descriptor->type (),
bbe912ba 4665 descriptor->contents_writeable ().data (),
19f220c3 4666 value_pointer (bounds,
940da03e 4667 desc_type->field (1).type ()),
19f220c3
JK
4668 fat_pntr_bounds_bitpos (desc_type),
4669 fat_pntr_bounds_bitsize (desc_type));
14f9c5c9 4670
40bc484c 4671 descriptor = ensure_lval (descriptor);
14f9c5c9 4672
78134374 4673 if (type->code () == TYPE_CODE_PTR)
14f9c5c9
AS
4674 return value_addr (descriptor);
4675 else
4676 return descriptor;
4677}
14f9c5c9 4678\f
dda83cd7 4679 /* Symbol Cache Module */
3d9434b5 4680
3d9434b5 4681/* Performance measurements made as of 2010-01-15 indicate that
ee01b665 4682 this cache does bring some noticeable improvements. Depending
3d9434b5
JB
4683 on the type of entity being printed, the cache can make it as much
4684 as an order of magnitude faster than without it.
4685
4686 The descriptive type DWARF extension has significantly reduced
4687 the need for this cache, at least when DWARF is being used. However,
4688 even in this case, some expensive name-based symbol searches are still
4689 sometimes necessary - to find an XVZ variable, mostly. */
4690
3d9434b5
JB
4691/* Clear all entries from the symbol cache. */
4692
4693static void
6114d650 4694ada_clear_symbol_cache (program_space *pspace)
3d9434b5 4695{
6114d650 4696 ada_pspace_data_handle.clear (pspace);
3d9434b5
JB
4697}
4698
fe978cb0 4699/* Search the symbol cache for an entry matching NAME and DOMAIN.
3d9434b5
JB
4700 Return 1 if found, 0 otherwise.
4701
4702 If an entry was found and SYM is not NULL, set *SYM to the entry's
4703 SYM. Same principle for BLOCK if not NULL. */
96d887e8 4704
96d887e8 4705static int
6c015214 4706lookup_cached_symbol (const char *name, domain_search_flags domain,
dda83cd7 4707 struct symbol **sym, const struct block **block)
96d887e8 4708{
9d1c303d
TT
4709 htab_t tab = get_ada_pspace_data (current_program_space);
4710 cache_entry_search search;
4711 search.name = name;
4712 search.domain = domain;
3d9434b5 4713
9d1c303d
TT
4714 cache_entry *e = (cache_entry *) htab_find_with_hash (tab, &search,
4715 search.hash ());
4716 if (e == nullptr)
3d9434b5 4717 return 0;
9d1c303d
TT
4718 if (sym != nullptr)
4719 *sym = e->sym;
4720 if (block != nullptr)
4721 *block = e->block;
3d9434b5 4722 return 1;
96d887e8
PH
4723}
4724
3d9434b5 4725/* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
fe978cb0 4726 in domain DOMAIN, save this result in our symbol cache. */
3d9434b5 4727
96d887e8 4728static void
6c015214
TT
4729cache_symbol (const char *name, domain_search_flags domain,
4730 struct symbol *sym, const struct block *block)
96d887e8 4731{
1994afbf
DE
4732 /* Symbols for builtin types don't have a block.
4733 For now don't cache such symbols. */
7b3ecc75 4734 if (sym != NULL && !sym->is_objfile_owned ())
1994afbf
DE
4735 return;
4736
3d9434b5
JB
4737 /* If the symbol is a local symbol, then do not cache it, as a search
4738 for that symbol depends on the context. To determine whether
4739 the symbol is local or not, we check the block where we found it
4740 against the global and static blocks of its associated symtab. */
63d609de
SM
4741 if (sym != nullptr)
4742 {
4743 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4744
4745 if (bv.global_block () != block && bv.static_block () != block)
4746 return;
4747 }
3d9434b5 4748
9d1c303d
TT
4749 htab_t tab = get_ada_pspace_data (current_program_space);
4750 cache_entry_search search;
4751 search.name = name;
4752 search.domain = domain;
4753
4754 void **slot = htab_find_slot_with_hash (tab, &search,
4755 search.hash (), INSERT);
4756
4757 cache_entry *e = new cache_entry;
4758 e->name = name;
fe978cb0 4759 e->domain = domain;
9d1c303d 4760 e->sym = sym;
3d9434b5 4761 e->block = block;
9d1c303d
TT
4762
4763 *slot = e;
96d887e8 4764}
4c4b4cd2 4765\f
dda83cd7 4766 /* Symbol Lookup */
4c4b4cd2 4767
b5ec771e
PA
4768/* Return the symbol name match type that should be used used when
4769 searching for all symbols matching LOOKUP_NAME.
c0431670
JB
4770
4771 LOOKUP_NAME is expected to be a symbol name after transformation
f98b2e33 4772 for Ada lookups. */
c0431670 4773
b5ec771e
PA
4774static symbol_name_match_type
4775name_match_type_from_name (const char *lookup_name)
c0431670 4776{
b5ec771e
PA
4777 return (strstr (lookup_name, "__") == NULL
4778 ? symbol_name_match_type::WILD
4779 : symbol_name_match_type::FULL);
c0431670
JB
4780}
4781
4c4b4cd2
PH
4782/* Return the result of a standard (literal, C-like) lookup of NAME in
4783 given DOMAIN, visible from lexical block BLOCK. */
4784
4785static struct symbol *
4786standard_lookup (const char *name, const struct block *block,
6c015214 4787 domain_search_flags domain)
4c4b4cd2 4788{
acbd605d 4789 /* Initialize it just to avoid a GCC false warning. */
6640a367 4790 struct block_symbol sym = {};
4c4b4cd2 4791
d12307c1
PMR
4792 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4793 return sym.symbol;
a2cd4f14 4794 ada_lookup_encoded_symbol (name, block, domain, &sym);
d12307c1
PMR
4795 cache_symbol (name, domain, sym.symbol, sym.block);
4796 return sym.symbol;
4c4b4cd2
PH
4797}
4798
4799
4800/* Non-zero iff there is at least one non-function/non-enumeral symbol
1bfa81ac 4801 in the symbol fields of SYMS. We treat enumerals as functions,
4c4b4cd2
PH
4802 since they contend in overloading in the same way. */
4803static int
d1183b06 4804is_nonfunction (const std::vector<struct block_symbol> &syms)
4c4b4cd2 4805{
d1183b06 4806 for (const block_symbol &sym : syms)
5f9c5a63
SM
4807 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4808 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
66d7f48f 4809 || sym.symbol->aclass () != LOC_CONST))
14f9c5c9
AS
4810 return 1;
4811
4812 return 0;
4813}
4814
4815/* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4c4b4cd2 4816 struct types. Otherwise, they may not. */
14f9c5c9
AS
4817
4818static int
d2e4a39e 4819equiv_types (struct type *type0, struct type *type1)
14f9c5c9 4820{
d2e4a39e 4821 if (type0 == type1)
14f9c5c9 4822 return 1;
d2e4a39e 4823 if (type0 == NULL || type1 == NULL
78134374 4824 || type0->code () != type1->code ())
14f9c5c9 4825 return 0;
78134374
SM
4826 if ((type0->code () == TYPE_CODE_STRUCT
4827 || type0->code () == TYPE_CODE_ENUM)
14f9c5c9 4828 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4c4b4cd2 4829 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
14f9c5c9 4830 return 1;
d2e4a39e 4831
14f9c5c9
AS
4832 return 0;
4833}
4834
4835/* True iff SYM0 represents the same entity as SYM1, or one that is
4c4b4cd2 4836 no more defined than that of SYM1. */
14f9c5c9
AS
4837
4838static int
d2e4a39e 4839lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
14f9c5c9
AS
4840{
4841 if (sym0 == sym1)
4842 return 1;
6c9c307c 4843 if (sym0->domain () != sym1->domain ()
66d7f48f 4844 || sym0->aclass () != sym1->aclass ())
14f9c5c9
AS
4845 return 0;
4846
66d7f48f 4847 switch (sym0->aclass ())
14f9c5c9
AS
4848 {
4849 case LOC_UNDEF:
4850 return 1;
4851 case LOC_TYPEDEF:
4852 {
5f9c5a63
SM
4853 struct type *type0 = sym0->type ();
4854 struct type *type1 = sym1->type ();
dda83cd7
SM
4855 const char *name0 = sym0->linkage_name ();
4856 const char *name1 = sym1->linkage_name ();
4857 int len0 = strlen (name0);
4858
4859 return
4860 type0->code () == type1->code ()
4861 && (equiv_types (type0, type1)
4862 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4863 && startswith (name1 + len0, "___XV")));
14f9c5c9
AS
4864 }
4865 case LOC_CONST:
4aeddc50 4866 return sym0->value_longest () == sym1->value_longest ()
5f9c5a63 4867 && equiv_types (sym0->type (), sym1->type ());
4b610737
TT
4868
4869 case LOC_STATIC:
4870 {
dda83cd7
SM
4871 const char *name0 = sym0->linkage_name ();
4872 const char *name1 = sym1->linkage_name ();
4873 return (strcmp (name0, name1) == 0
4aeddc50 4874 && sym0->value_address () == sym1->value_address ());
4b610737
TT
4875 }
4876
d2e4a39e
AS
4877 default:
4878 return 0;
14f9c5c9
AS
4879 }
4880}
4881
d1183b06
TT
4882/* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4883 records in RESULT. Do nothing if SYM is a duplicate. */
14f9c5c9
AS
4884
4885static void
d1183b06 4886add_defn_to_vec (std::vector<struct block_symbol> &result,
dda83cd7
SM
4887 struct symbol *sym,
4888 const struct block *block)
14f9c5c9 4889{
529cad9c
PH
4890 /* Do not try to complete stub types, as the debugger is probably
4891 already scanning all symbols matching a certain name at the
4892 time when this function is called. Trying to replace the stub
4893 type by its associated full type will cause us to restart a scan
4894 which may lead to an infinite recursion. Instead, the client
4895 collecting the matching symbols will end up collecting several
4896 matches, with at least one of them complete. It can then filter
4897 out the stub ones if needed. */
4898
d1183b06 4899 for (int i = result.size () - 1; i >= 0; i -= 1)
4c4b4cd2 4900 {
d1183b06 4901 if (lesseq_defined_than (sym, result[i].symbol))
dda83cd7 4902 return;
d1183b06 4903 else if (lesseq_defined_than (result[i].symbol, sym))
dda83cd7 4904 {
d1183b06
TT
4905 result[i].symbol = sym;
4906 result[i].block = block;
dda83cd7
SM
4907 return;
4908 }
4c4b4cd2
PH
4909 }
4910
d1183b06
TT
4911 struct block_symbol info;
4912 info.symbol = sym;
4913 info.block = block;
4914 result.push_back (info);
4c4b4cd2
PH
4915}
4916
7c7b6655
TT
4917/* Return a bound minimal symbol matching NAME according to Ada
4918 decoding rules. Returns an invalid symbol if there is no such
4919 minimal symbol. Names prefixed with "standard__" are handled
4920 specially: "standard__" is first stripped off, and only static and
4921 global symbols are searched. */
4c4b4cd2 4922
7c7b6655 4923struct bound_minimal_symbol
06a670e2 4924ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4c4b4cd2 4925{
7c7b6655 4926 struct bound_minimal_symbol result;
4c4b4cd2 4927
b5ec771e
PA
4928 symbol_name_match_type match_type = name_match_type_from_name (name);
4929 lookup_name_info lookup_name (name, match_type);
4930
4931 symbol_name_matcher_ftype *match_name
4932 = ada_get_symbol_name_matcher (lookup_name);
4c4b4cd2 4933
06a670e2 4934 gdbarch_iterate_over_objfiles_in_search_order
99d9c3b9 4935 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
06a670e2
MM
4936 [&result, lookup_name, match_name] (struct objfile *obj)
4937 {
4938 for (minimal_symbol *msymbol : obj->msymbols ())
4939 {
4940 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4941 && msymbol->type () != mst_solib_trampoline)
4942 {
4943 result.minsym = msymbol;
4944 result.objfile = obj;
4945 return 1;
4946 }
4947 }
4948
4949 return 0;
4950 }, objfile);
4c4b4cd2 4951
7c7b6655 4952 return result;
96d887e8 4953}
4c4b4cd2 4954
96d887e8
PH
4955/* True if TYPE is definitely an artificial type supplied to a symbol
4956 for which no debugging information was given in the symbol file. */
14f9c5c9 4957
96d887e8
PH
4958static int
4959is_nondebugging_type (struct type *type)
4960{
0d5cff50 4961 const char *name = ada_type_name (type);
5b4ee69b 4962
96d887e8
PH
4963 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4964}
4c4b4cd2 4965
8f17729f
JB
4966/* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4967 that are deemed "identical" for practical purposes.
4968
4969 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4970 types and that their number of enumerals is identical (in other
1f704f76 4971 words, type1->num_fields () == type2->num_fields ()). */
8f17729f
JB
4972
4973static int
4974ada_identical_enum_types_p (struct type *type1, struct type *type2)
4975{
4976 int i;
4977
4978 /* The heuristic we use here is fairly conservative. We consider
4979 that 2 enumerate types are identical if they have the same
4980 number of enumerals and that all enumerals have the same
4981 underlying value and name. */
4982
4983 /* All enums in the type should have an identical underlying value. */
1f704f76 4984 for (i = 0; i < type1->num_fields (); i++)
970db518 4985 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
8f17729f
JB
4986 return 0;
4987
4988 /* All enumerals should also have the same name (modulo any numerical
4989 suffix). */
1f704f76 4990 for (i = 0; i < type1->num_fields (); i++)
8f17729f 4991 {
33d16dd9
SM
4992 const char *name_1 = type1->field (i).name ();
4993 const char *name_2 = type2->field (i).name ();
8f17729f
JB
4994 int len_1 = strlen (name_1);
4995 int len_2 = strlen (name_2);
4996
33d16dd9
SM
4997 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4998 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
8f17729f 4999 if (len_1 != len_2
33d16dd9
SM
5000 || strncmp (type1->field (i).name (),
5001 type2->field (i).name (),
8f17729f
JB
5002 len_1) != 0)
5003 return 0;
5004 }
5005
5006 return 1;
5007}
5008
5009/* Return nonzero if all the symbols in SYMS are all enumeral symbols
5010 that are deemed "identical" for practical purposes. Sometimes,
5011 enumerals are not strictly identical, but their types are so similar
5012 that they can be considered identical.
5013
5014 For instance, consider the following code:
5015
5016 type Color is (Black, Red, Green, Blue, White);
5017 type RGB_Color is new Color range Red .. Blue;
5018
5019 Type RGB_Color is a subrange of an implicit type which is a copy
5020 of type Color. If we call that implicit type RGB_ColorB ("B" is
5021 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5022 As a result, when an expression references any of the enumeral
5023 by name (Eg. "print green"), the expression is technically
5024 ambiguous and the user should be asked to disambiguate. But
5025 doing so would only hinder the user, since it wouldn't matter
5026 what choice he makes, the outcome would always be the same.
5027 So, for practical purposes, we consider them as the same. */
5028
5029static int
54d343a2 5030symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
8f17729f
JB
5031{
5032 int i;
5033
5034 /* Before performing a thorough comparison check of each type,
5035 we perform a series of inexpensive checks. We expect that these
5036 checks will quickly fail in the vast majority of cases, and thus
5037 help prevent the unnecessary use of a more expensive comparison.
5038 Said comparison also expects us to make some of these checks
5039 (see ada_identical_enum_types_p). */
5040
5041 /* Quick check: All symbols should have an enum type. */
54d343a2 5042 for (i = 0; i < syms.size (); i++)
5f9c5a63 5043 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
8f17729f
JB
5044 return 0;
5045
5046 /* Quick check: They should all have the same value. */
54d343a2 5047 for (i = 1; i < syms.size (); i++)
4aeddc50 5048 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
8f17729f
JB
5049 return 0;
5050
5051 /* Quick check: They should all have the same number of enumerals. */
54d343a2 5052 for (i = 1; i < syms.size (); i++)
5f9c5a63
SM
5053 if (syms[i].symbol->type ()->num_fields ()
5054 != syms[0].symbol->type ()->num_fields ())
8f17729f
JB
5055 return 0;
5056
5057 /* All the sanity checks passed, so we might have a set of
5058 identical enumeration types. Perform a more complete
5059 comparison of the type of each symbol. */
54d343a2 5060 for (i = 1; i < syms.size (); i++)
5f9c5a63
SM
5061 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5062 syms[0].symbol->type ()))
8f17729f
JB
5063 return 0;
5064
5065 return 1;
5066}
5067
54d343a2 5068/* Remove any non-debugging symbols in SYMS that definitely
96d887e8
PH
5069 duplicate other symbols in the list (The only case I know of where
5070 this happens is when object files containing stabs-in-ecoff are
5071 linked with files containing ordinary ecoff debugging symbols (or no
1bfa81ac 5072 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
4c4b4cd2 5073
d1183b06 5074static void
ff4631e2 5075remove_extra_symbols (std::vector<struct block_symbol> &syms)
96d887e8
PH
5076{
5077 int i, j;
4c4b4cd2 5078
8f17729f
JB
5079 /* We should never be called with less than 2 symbols, as there
5080 cannot be any extra symbol in that case. But it's easy to
5081 handle, since we have nothing to do in that case. */
ff4631e2 5082 if (syms.size () < 2)
d1183b06 5083 return;
8f17729f 5084
96d887e8 5085 i = 0;
ff4631e2 5086 while (i < syms.size ())
96d887e8 5087 {
44a37a98 5088 bool remove_p = false;
339c13b6
JB
5089
5090 /* If two symbols have the same name and one of them is a stub type,
dda83cd7 5091 the get rid of the stub. */
339c13b6 5092
ff4631e2
TT
5093 if (syms[i].symbol->type ()->is_stub ()
5094 && syms[i].symbol->linkage_name () != NULL)
dda83cd7 5095 {
44a37a98 5096 for (j = 0; !remove_p && j < syms.size (); j++)
dda83cd7
SM
5097 {
5098 if (j != i
ff4631e2
TT
5099 && !syms[j].symbol->type ()->is_stub ()
5100 && syms[j].symbol->linkage_name () != NULL
5101 && strcmp (syms[i].symbol->linkage_name (),
5102 syms[j].symbol->linkage_name ()) == 0)
44a37a98 5103 remove_p = true;
dda83cd7
SM
5104 }
5105 }
339c13b6
JB
5106
5107 /* Two symbols with the same name, same class and same address
dda83cd7 5108 should be identical. */
339c13b6 5109
ff4631e2
TT
5110 else if (syms[i].symbol->linkage_name () != NULL
5111 && syms[i].symbol->aclass () == LOC_STATIC
5112 && is_nondebugging_type (syms[i].symbol->type ()))
dda83cd7 5113 {
44a37a98 5114 for (j = 0; !remove_p && j < syms.size (); j += 1)
dda83cd7
SM
5115 {
5116 if (i != j
ff4631e2
TT
5117 && syms[j].symbol->linkage_name () != NULL
5118 && strcmp (syms[i].symbol->linkage_name (),
5119 syms[j].symbol->linkage_name ()) == 0
5120 && (syms[i].symbol->aclass ()
5121 == syms[j].symbol->aclass ())
5122 && syms[i].symbol->value_address ()
5123 == syms[j].symbol->value_address ())
44a37a98 5124 remove_p = true;
dda83cd7
SM
5125 }
5126 }
339c13b6 5127
e9151f7d
TT
5128 /* Two functions with the same block are identical. */
5129
5130 else if (syms[i].symbol->aclass () == LOC_BLOCK)
5131 {
5132 for (j = 0; !remove_p && j < syms.size (); j += 1)
5133 {
5134 if (i != j
5135 && syms[j].symbol->aclass () == LOC_BLOCK
5136 && (syms[i].symbol->value_block ()
5137 == syms[j].symbol->value_block ()))
5138 remove_p = true;
5139 }
5140 }
5141
a35ddb44 5142 if (remove_p)
ff4631e2 5143 syms.erase (syms.begin () + i);
1b788fb6
TT
5144 else
5145 i += 1;
14f9c5c9 5146 }
14f9c5c9
AS
5147}
5148
96d887e8
PH
5149/* Given a type that corresponds to a renaming entity, use the type name
5150 to extract the scope (package name or function name, fully qualified,
5151 and following the GNAT encoding convention) where this renaming has been
49d83361 5152 defined. */
4c4b4cd2 5153
49d83361 5154static std::string
96d887e8 5155xget_renaming_scope (struct type *renaming_type)
14f9c5c9 5156{
96d887e8 5157 /* The renaming types adhere to the following convention:
0963b4bd 5158 <scope>__<rename>___<XR extension>.
96d887e8
PH
5159 So, to extract the scope, we search for the "___XR" extension,
5160 and then backtrack until we find the first "__". */
76a01679 5161
7d93a1e0 5162 const char *name = renaming_type->name ();
108d56a4
SM
5163 const char *suffix = strstr (name, "___XR");
5164 const char *last;
14f9c5c9 5165
96d887e8
PH
5166 /* Now, backtrack a bit until we find the first "__". Start looking
5167 at suffix - 3, as the <rename> part is at least one character long. */
14f9c5c9 5168
96d887e8
PH
5169 for (last = suffix - 3; last > name; last--)
5170 if (last[0] == '_' && last[1] == '_')
5171 break;
76a01679 5172
96d887e8 5173 /* Make a copy of scope and return it. */
49d83361 5174 return std::string (name, last);
4c4b4cd2
PH
5175}
5176
96d887e8 5177/* Return nonzero if NAME corresponds to a package name. */
4c4b4cd2 5178
96d887e8
PH
5179static int
5180is_package_name (const char *name)
4c4b4cd2 5181{
96d887e8
PH
5182 /* Here, We take advantage of the fact that no symbols are generated
5183 for packages, while symbols are generated for each function.
5184 So the condition for NAME represent a package becomes equivalent
5185 to NAME not existing in our list of symbols. There is only one
5186 small complication with library-level functions (see below). */
4c4b4cd2 5187
96d887e8
PH
5188 /* If it is a function that has not been defined at library level,
5189 then we should be able to look it up in the symbols. */
6c015214 5190 if (standard_lookup (name, NULL, SEARCH_VFT) != NULL)
96d887e8 5191 return 0;
14f9c5c9 5192
96d887e8
PH
5193 /* Library-level function names start with "_ada_". See if function
5194 "_ada_" followed by NAME can be found. */
14f9c5c9 5195
96d887e8 5196 /* Do a quick check that NAME does not contain "__", since library-level
e1d5a0d2 5197 functions names cannot contain "__" in them. */
96d887e8
PH
5198 if (strstr (name, "__") != NULL)
5199 return 0;
4c4b4cd2 5200
528e1572 5201 std::string fun_name = string_printf ("_ada_%s", name);
14f9c5c9 5202
6c015214 5203 return (standard_lookup (fun_name.c_str (), NULL, SEARCH_VFT) == NULL);
96d887e8 5204}
14f9c5c9 5205
96d887e8 5206/* Return nonzero if SYM corresponds to a renaming entity that is
aeb5907d 5207 not visible from FUNCTION_NAME. */
14f9c5c9 5208
96d887e8 5209static int
0d5cff50 5210old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
96d887e8 5211{
66d7f48f 5212 if (sym->aclass () != LOC_TYPEDEF)
aeb5907d
JB
5213 return 0;
5214
5f9c5a63 5215 std::string scope = xget_renaming_scope (sym->type ());
14f9c5c9 5216
96d887e8 5217 /* If the rename has been defined in a package, then it is visible. */
49d83361
TT
5218 if (is_package_name (scope.c_str ()))
5219 return 0;
14f9c5c9 5220
96d887e8
PH
5221 /* Check that the rename is in the current function scope by checking
5222 that its name starts with SCOPE. */
76a01679 5223
96d887e8
PH
5224 /* If the function name starts with "_ada_", it means that it is
5225 a library-level function. Strip this prefix before doing the
5226 comparison, as the encoding for the renaming does not contain
5227 this prefix. */
61012eef 5228 if (startswith (function_name, "_ada_"))
96d887e8 5229 function_name += 5;
f26caa11 5230
49d83361 5231 return !startswith (function_name, scope.c_str ());
f26caa11
PH
5232}
5233
aeb5907d
JB
5234/* Remove entries from SYMS that corresponds to a renaming entity that
5235 is not visible from the function associated with CURRENT_BLOCK or
5236 that is superfluous due to the presence of more specific renaming
5237 information. Places surviving symbols in the initial entries of
d1183b06
TT
5238 SYMS.
5239
96d887e8 5240 Rationale:
aeb5907d
JB
5241 First, in cases where an object renaming is implemented as a
5242 reference variable, GNAT may produce both the actual reference
5243 variable and the renaming encoding. In this case, we discard the
5244 latter.
5245
5246 Second, GNAT emits a type following a specified encoding for each renaming
96d887e8
PH
5247 entity. Unfortunately, STABS currently does not support the definition
5248 of types that are local to a given lexical block, so all renamings types
5249 are emitted at library level. As a consequence, if an application
5250 contains two renaming entities using the same name, and a user tries to
5251 print the value of one of these entities, the result of the ada symbol
5252 lookup will also contain the wrong renaming type.
f26caa11 5253
96d887e8
PH
5254 This function partially covers for this limitation by attempting to
5255 remove from the SYMS list renaming symbols that should be visible
5256 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5257 method with the current information available. The implementation
5258 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5259
5260 - When the user tries to print a rename in a function while there
dda83cd7
SM
5261 is another rename entity defined in a package: Normally, the
5262 rename in the function has precedence over the rename in the
5263 package, so the latter should be removed from the list. This is
5264 currently not the case.
5265
96d887e8 5266 - This function will incorrectly remove valid renames if
dda83cd7
SM
5267 the CURRENT_BLOCK corresponds to a function which symbol name
5268 has been changed by an "Export" pragma. As a consequence,
5269 the user will be unable to print such rename entities. */
4c4b4cd2 5270
d1183b06 5271static void
54d343a2
TT
5272remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5273 const struct block *current_block)
4c4b4cd2
PH
5274{
5275 struct symbol *current_function;
0d5cff50 5276 const char *current_function_name;
4c4b4cd2 5277 int i;
aeb5907d
JB
5278 int is_new_style_renaming;
5279
5280 /* If there is both a renaming foo___XR... encoded as a variable and
5281 a simple variable foo in the same block, discard the latter.
0963b4bd 5282 First, zero out such symbols, then compress. */
aeb5907d 5283 is_new_style_renaming = 0;
54d343a2 5284 for (i = 0; i < syms->size (); i += 1)
aeb5907d 5285 {
54d343a2
TT
5286 struct symbol *sym = (*syms)[i].symbol;
5287 const struct block *block = (*syms)[i].block;
aeb5907d
JB
5288 const char *name;
5289 const char *suffix;
5290
66d7f48f 5291 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
aeb5907d 5292 continue;
987012b8 5293 name = sym->linkage_name ();
aeb5907d
JB
5294 suffix = strstr (name, "___XR");
5295
5296 if (suffix != NULL)
5297 {
5298 int name_len = suffix - name;
5299 int j;
5b4ee69b 5300
aeb5907d 5301 is_new_style_renaming = 1;
54d343a2
TT
5302 for (j = 0; j < syms->size (); j += 1)
5303 if (i != j && (*syms)[j].symbol != NULL
987012b8 5304 && strncmp (name, (*syms)[j].symbol->linkage_name (),
aeb5907d 5305 name_len) == 0
54d343a2
TT
5306 && block == (*syms)[j].block)
5307 (*syms)[j].symbol = NULL;
aeb5907d
JB
5308 }
5309 }
5310 if (is_new_style_renaming)
5311 {
5312 int j, k;
5313
54d343a2
TT
5314 for (j = k = 0; j < syms->size (); j += 1)
5315 if ((*syms)[j].symbol != NULL)
aeb5907d 5316 {
54d343a2 5317 (*syms)[k] = (*syms)[j];
aeb5907d
JB
5318 k += 1;
5319 }
d1183b06
TT
5320 syms->resize (k);
5321 return;
aeb5907d 5322 }
4c4b4cd2
PH
5323
5324 /* Extract the function name associated to CURRENT_BLOCK.
5325 Abort if unable to do so. */
76a01679 5326
4c4b4cd2 5327 if (current_block == NULL)
d1183b06 5328 return;
76a01679 5329
3c9d0506 5330 current_function = current_block->linkage_function ();
4c4b4cd2 5331 if (current_function == NULL)
d1183b06 5332 return;
4c4b4cd2 5333
987012b8 5334 current_function_name = current_function->linkage_name ();
4c4b4cd2 5335 if (current_function_name == NULL)
d1183b06 5336 return;
4c4b4cd2
PH
5337
5338 /* Check each of the symbols, and remove it from the list if it is
5339 a type corresponding to a renaming that is out of the scope of
5340 the current block. */
5341
5342 i = 0;
54d343a2 5343 while (i < syms->size ())
4c4b4cd2 5344 {
54d343a2 5345 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
dda83cd7
SM
5346 == ADA_OBJECT_RENAMING
5347 && old_renaming_is_invisible ((*syms)[i].symbol,
54d343a2
TT
5348 current_function_name))
5349 syms->erase (syms->begin () + i);
4c4b4cd2 5350 else
dda83cd7 5351 i += 1;
4c4b4cd2 5352 }
4c4b4cd2
PH
5353}
5354
d1183b06 5355/* Add to RESULT all symbols from BLOCK (and its super-blocks)
cd458349 5356 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
339c13b6 5357
cd458349 5358 Note: This function assumes that RESULT is empty. */
339c13b6
JB
5359
5360static void
d1183b06 5361ada_add_local_symbols (std::vector<struct block_symbol> &result,
b5ec771e 5362 const lookup_name_info &lookup_name,
6c015214 5363 const struct block *block, domain_search_flags domain)
339c13b6 5364{
339c13b6
JB
5365 while (block != NULL)
5366 {
d1183b06 5367 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
339c13b6 5368
ba8694b6
TT
5369 /* If we found a non-function match, assume that's the one. We
5370 only check this when finding a function boundary, so that we
5371 can accumulate all results from intervening blocks first. */
6c00f721 5372 if (block->function () != nullptr && is_nonfunction (result))
dda83cd7 5373 return;
339c13b6 5374
f135fe72 5375 block = block->superblock ();
339c13b6 5376 }
339c13b6
JB
5377}
5378
2315bb2d 5379/* An object of this type is used as the callback argument when
40658b94 5380 calling the map_matching_symbols method. */
ccefe4c4 5381
40658b94 5382struct match_data
ccefe4c4 5383{
1bfa81ac
TT
5384 explicit match_data (std::vector<struct block_symbol> *rp)
5385 : resultp (rp)
5386 {
5387 }
5388 DISABLE_COPY_AND_ASSIGN (match_data);
5389
2315bb2d
TT
5390 bool operator() (struct block_symbol *bsym);
5391
1bfa81ac 5392 struct objfile *objfile = nullptr;
d1183b06 5393 std::vector<struct block_symbol> *resultp;
1bfa81ac 5394 struct symbol *arg_sym = nullptr;
1178743e 5395 bool found_sym = false;
ccefe4c4
TT
5396};
5397
2315bb2d
TT
5398/* A callback for add_nonlocal_symbols that adds symbol, found in
5399 BSYM, to a list of symbols. */
ccefe4c4 5400
2315bb2d
TT
5401bool
5402match_data::operator() (struct block_symbol *bsym)
ccefe4c4 5403{
199b4314
TT
5404 const struct block *block = bsym->block;
5405 struct symbol *sym = bsym->symbol;
5406
40658b94
PH
5407 if (sym == NULL)
5408 {
2315bb2d 5409 if (!found_sym && arg_sym != NULL)
dae58e04 5410 add_defn_to_vec (*resultp, arg_sym, block);
2315bb2d
TT
5411 found_sym = false;
5412 arg_sym = NULL;
40658b94
PH
5413 }
5414 else
5415 {
66d7f48f 5416 if (sym->aclass () == LOC_UNRESOLVED)
199b4314 5417 return true;
d9743061 5418 else if (sym->is_argument ())
2315bb2d 5419 arg_sym = sym;
40658b94
PH
5420 else
5421 {
2315bb2d 5422 found_sym = true;
dae58e04 5423 add_defn_to_vec (*resultp, sym, block);
40658b94
PH
5424 }
5425 }
199b4314 5426 return true;
40658b94
PH
5427}
5428
b5ec771e
PA
5429/* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5430 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
1bfa81ac 5431 symbols to RESULT. Return whether we found such symbols. */
22cee43f
PMR
5432
5433static int
d1183b06 5434ada_add_block_renamings (std::vector<struct block_symbol> &result,
22cee43f 5435 const struct block *block,
b5ec771e 5436 const lookup_name_info &lookup_name,
6c015214 5437 domain_search_flags domain)
22cee43f
PMR
5438{
5439 struct using_direct *renaming;
d1183b06 5440 int defns_mark = result.size ();
22cee43f 5441
b5ec771e
PA
5442 symbol_name_matcher_ftype *name_match
5443 = ada_get_symbol_name_matcher (lookup_name);
5444
3c45e9f9 5445 for (renaming = block->get_using ();
22cee43f
PMR
5446 renaming != NULL;
5447 renaming = renaming->next)
5448 {
5449 const char *r_name;
22cee43f
PMR
5450
5451 /* Avoid infinite recursions: skip this renaming if we are actually
5452 already traversing it.
5453
5454 Currently, symbol lookup in Ada don't use the namespace machinery from
5455 C++/Fortran support: skip namespace imports that use them. */
5456 if (renaming->searched
5457 || (renaming->import_src != NULL
5458 && renaming->import_src[0] != '\0')
5459 || (renaming->import_dest != NULL
5460 && renaming->import_dest[0] != '\0'))
5461 continue;
5462 renaming->searched = 1;
5463
5464 /* TODO: here, we perform another name-based symbol lookup, which can
5465 pull its own multiple overloads. In theory, we should be able to do
5466 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5467 not a simple name. But in order to do this, we would need to enhance
5468 the DWARF reader to associate a symbol to this renaming, instead of a
5469 name. So, for now, we do something simpler: re-use the C++/Fortran
5470 namespace machinery. */
5471 r_name = (renaming->alias != NULL
5472 ? renaming->alias
5473 : renaming->declaration);
b5ec771e
PA
5474 if (name_match (r_name, lookup_name, NULL))
5475 {
5476 lookup_name_info decl_lookup_name (renaming->declaration,
5477 lookup_name.match_type ());
d1183b06 5478 ada_add_all_symbols (result, block, decl_lookup_name, domain,
b5ec771e
PA
5479 1, NULL);
5480 }
22cee43f
PMR
5481 renaming->searched = 0;
5482 }
d1183b06 5483 return result.size () != defns_mark;
22cee43f
PMR
5484}
5485
b5ec771e
PA
5486/* Convenience function to get at the Ada encoded lookup name for
5487 LOOKUP_NAME, as a C string. */
5488
5489static const char *
5490ada_lookup_name (const lookup_name_info &lookup_name)
5491{
5492 return lookup_name.ada ().lookup_name ().c_str ();
5493}
5494
957ce537 5495/* A helper for add_nonlocal_symbols. Expand all necessary symtabs
0b7b2c2a
TT
5496 for OBJFILE, then walk the objfile's symtabs and update the
5497 results. */
5498
5499static void
5500map_matching_symbols (struct objfile *objfile,
5501 const lookup_name_info &lookup_name,
6c015214 5502 domain_search_flags domain,
0b7b2c2a
TT
5503 int global,
5504 match_data &data)
5505{
5506 data.objfile = objfile;
957ce537
TT
5507 objfile->expand_symtabs_matching (nullptr, &lookup_name,
5508 nullptr, nullptr,
5509 global
5510 ? SEARCH_GLOBAL_BLOCK
5511 : SEARCH_STATIC_BLOCK,
6c015214 5512 domain);
0b7b2c2a
TT
5513
5514 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5515 for (compunit_symtab *symtab : objfile->compunits ())
5516 {
5517 const struct block *block
63d609de 5518 = symtab->blockvector ()->block (block_kind);
0b7b2c2a
TT
5519 if (!iterate_over_symbols_terminated (block, lookup_name,
5520 domain, data))
5521 break;
5522 }
5523}
5524
1bfa81ac 5525/* Add to RESULT all non-local symbols whose name and domain match
b5ec771e
PA
5526 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5527 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5528 symbols otherwise. */
339c13b6
JB
5529
5530static void
d1183b06 5531add_nonlocal_symbols (std::vector<struct block_symbol> &result,
b5ec771e 5532 const lookup_name_info &lookup_name,
6c015214 5533 domain_search_flags domain, int global)
339c13b6 5534{
1bfa81ac 5535 struct match_data data (&result);
339c13b6 5536
b5ec771e
PA
5537 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5538
2030c079 5539 for (objfile *objfile : current_program_space->objfiles ())
40658b94 5540 {
957ce537 5541 map_matching_symbols (objfile, lookup_name, domain, global, data);
22cee43f 5542
b669c953 5543 for (compunit_symtab *cu : objfile->compunits ())
22cee43f
PMR
5544 {
5545 const struct block *global_block
63d609de 5546 = cu->blockvector ()->global_block ();
22cee43f 5547
d1183b06 5548 if (ada_add_block_renamings (result, global_block, lookup_name,
b5ec771e 5549 domain))
1178743e 5550 data.found_sym = true;
22cee43f 5551 }
40658b94
PH
5552 }
5553
d1183b06 5554 if (result.empty () && global && !is_wild_match)
40658b94 5555 {
b5ec771e 5556 const char *name = ada_lookup_name (lookup_name);
e0802d59
TT
5557 std::string bracket_name = std::string ("<_ada_") + name + '>';
5558 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
b5ec771e 5559
2030c079 5560 for (objfile *objfile : current_program_space->objfiles ())
957ce537 5561 map_matching_symbols (objfile, name1, domain, global, data);
0b7b2c2a 5562 }
339c13b6
JB
5563}
5564
b5ec771e
PA
5565/* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5566 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
1bfa81ac 5567 returning the number of matches. Add these to RESULT.
4eeaa230 5568
22cee43f
PMR
5569 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5570 symbol match within the nest of blocks whose innermost member is BLOCK,
4c4b4cd2 5571 is the one match returned (no other matches in that or
d9680e73 5572 enclosing blocks is returned). If there are any matches in or
22cee43f 5573 surrounding BLOCK, then these alone are returned.
4eeaa230 5574
b5ec771e
PA
5575 Names prefixed with "standard__" are handled specially:
5576 "standard__" is first stripped off (by the lookup_name
5577 constructor), and only static and global symbols are searched.
14f9c5c9 5578
22cee43f
PMR
5579 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5580 to lookup global symbols. */
5581
5582static void
d1183b06 5583ada_add_all_symbols (std::vector<struct block_symbol> &result,
22cee43f 5584 const struct block *block,
b5ec771e 5585 const lookup_name_info &lookup_name,
6c015214 5586 domain_search_flags domain,
22cee43f
PMR
5587 int full_search,
5588 int *made_global_lookup_p)
14f9c5c9
AS
5589{
5590 struct symbol *sym;
14f9c5c9 5591
22cee43f
PMR
5592 if (made_global_lookup_p)
5593 *made_global_lookup_p = 0;
339c13b6
JB
5594
5595 /* Special case: If the user specifies a symbol name inside package
5596 Standard, do a non-wild matching of the symbol name without
5597 the "standard__" prefix. This was primarily introduced in order
5598 to allow the user to specifically access the standard exceptions
5599 using, for instance, Standard.Constraint_Error when Constraint_Error
5600 is ambiguous (due to the user defining its own Constraint_Error
5601 entity inside its program). */
b5ec771e
PA
5602 if (lookup_name.ada ().standard_p ())
5603 block = NULL;
4c4b4cd2 5604
339c13b6 5605 /* Check the non-global symbols. If we have ANY match, then we're done. */
14f9c5c9 5606
4eeaa230
DE
5607 if (block != NULL)
5608 {
5609 if (full_search)
d1183b06 5610 ada_add_local_symbols (result, lookup_name, block, domain);
4eeaa230
DE
5611 else
5612 {
5613 /* In the !full_search case we're are being called by
4009ee92 5614 iterate_over_symbols, and we don't want to search
4eeaa230 5615 superblocks. */
d1183b06 5616 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
4eeaa230 5617 }
d1183b06 5618 if (!result.empty () || !full_search)
22cee43f 5619 return;
4eeaa230 5620 }
d2e4a39e 5621
339c13b6
JB
5622 /* No non-global symbols found. Check our cache to see if we have
5623 already performed this search before. If we have, then return
5624 the same result. */
5625
b5ec771e
PA
5626 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5627 domain, &sym, &block))
4c4b4cd2
PH
5628 {
5629 if (sym != NULL)
d1183b06 5630 add_defn_to_vec (result, sym, block);
22cee43f 5631 return;
4c4b4cd2 5632 }
14f9c5c9 5633
22cee43f
PMR
5634 if (made_global_lookup_p)
5635 *made_global_lookup_p = 1;
b1eedac9 5636
339c13b6
JB
5637 /* Search symbols from all global blocks. */
5638
d1183b06 5639 add_nonlocal_symbols (result, lookup_name, domain, 1);
d2e4a39e 5640
4c4b4cd2 5641 /* Now add symbols from all per-file blocks if we've gotten no hits
339c13b6 5642 (not strictly correct, but perhaps better than an error). */
d2e4a39e 5643
d1183b06
TT
5644 if (result.empty ())
5645 add_nonlocal_symbols (result, lookup_name, domain, 0);
22cee43f
PMR
5646}
5647
b5ec771e 5648/* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
d1183b06
TT
5649 is non-zero, enclosing scope and in global scopes.
5650
5651 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5652 blocks and symbol tables (if any) in which they were found.
22cee43f
PMR
5653
5654 When full_search is non-zero, any non-function/non-enumeral
5655 symbol match within the nest of blocks whose innermost member is BLOCK,
5656 is the one match returned (no other matches in that or
5657 enclosing blocks is returned). If there are any matches in or
5658 surrounding BLOCK, then these alone are returned.
5659
5660 Names prefixed with "standard__" are handled specially: "standard__"
5661 is first stripped off, and only static and global symbols are searched. */
5662
d1183b06 5663static std::vector<struct block_symbol>
b5ec771e
PA
5664ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5665 const struct block *block,
6c015214 5666 domain_search_flags domain,
22cee43f
PMR
5667 int full_search)
5668{
22cee43f 5669 int syms_from_global_search;
d1183b06 5670 std::vector<struct block_symbol> results;
22cee43f 5671
d1183b06 5672 ada_add_all_symbols (results, block, lookup_name,
b5ec771e 5673 domain, full_search, &syms_from_global_search);
14f9c5c9 5674
ff4631e2 5675 remove_extra_symbols (results);
4c4b4cd2 5676
d1183b06 5677 if (results.empty () && full_search && syms_from_global_search)
b5ec771e 5678 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
14f9c5c9 5679
d1183b06 5680 if (results.size () == 1 && full_search && syms_from_global_search)
b5ec771e 5681 cache_symbol (ada_lookup_name (lookup_name), domain,
d1183b06 5682 results[0].symbol, results[0].block);
ec6a20c2 5683
d1183b06
TT
5684 remove_irrelevant_renamings (&results, block);
5685 return results;
14f9c5c9
AS
5686}
5687
b5ec771e 5688/* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
d1183b06 5689 in global scopes, returning (SYM,BLOCK) tuples.
ec6a20c2 5690
4eeaa230
DE
5691 See ada_lookup_symbol_list_worker for further details. */
5692
d1183b06 5693std::vector<struct block_symbol>
b5ec771e 5694ada_lookup_symbol_list (const char *name, const struct block *block,
6c015214 5695 domain_search_flags domain)
4eeaa230 5696{
b5ec771e
PA
5697 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5698 lookup_name_info lookup_name (name, name_match_type);
5699
d1183b06 5700 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
4eeaa230
DE
5701}
5702
4e5c77fe
JB
5703/* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5704 to 1, but choosing the first symbol found if there are multiple
5705 choices.
5706
5e2336be
JB
5707 The result is stored in *INFO, which must be non-NULL.
5708 If no match is found, INFO->SYM is set to NULL. */
4e5c77fe
JB
5709
5710void
5711ada_lookup_encoded_symbol (const char *name, const struct block *block,
6c015214 5712 domain_search_flags domain,
d12307c1 5713 struct block_symbol *info)
14f9c5c9 5714{
b5ec771e
PA
5715 /* Since we already have an encoded name, wrap it in '<>' to force a
5716 verbatim match. Otherwise, if the name happens to not look like
5717 an encoded name (because it doesn't include a "__"),
5718 ada_lookup_name_info would re-encode/fold it again, and that
5719 would e.g., incorrectly lowercase object renaming names like
5720 "R28b" -> "r28b". */
12932e2c 5721 std::string verbatim = add_angle_brackets (name);
b5ec771e 5722
5e2336be 5723 gdb_assert (info != NULL);
65392b3e 5724 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
4e5c77fe 5725}
aeb5907d
JB
5726
5727/* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5728 scope and in global scopes, or NULL if none. NAME is folded and
5729 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
65392b3e 5730 choosing the first symbol if there are multiple choices. */
4e5c77fe 5731
d12307c1 5732struct block_symbol
aeb5907d 5733ada_lookup_symbol (const char *name, const struct block *block0,
6c015214 5734 domain_search_flags domain)
aeb5907d 5735{
d1183b06
TT
5736 std::vector<struct block_symbol> candidates
5737 = ada_lookup_symbol_list (name, block0, domain);
f98fc17b 5738
d1183b06 5739 if (candidates.empty ())
54d343a2 5740 return {};
f98fc17b 5741
dae58e04 5742 return candidates[0];
4c4b4cd2 5743}
14f9c5c9 5744
14f9c5c9 5745
4c4b4cd2
PH
5746/* True iff STR is a possible encoded suffix of a normal Ada name
5747 that is to be ignored for matching purposes. Suffixes of parallel
5748 names (e.g., XVE) are not included here. Currently, the possible suffixes
5823c3ef 5749 are given by any of the regular expressions:
4c4b4cd2 5750
babe1480
JB
5751 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5752 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
9ac7f98e 5753 TKB [subprogram suffix for task bodies]
babe1480 5754 _E[0-9]+[bs]$ [protected object entry suffixes]
61ee279c 5755 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
babe1480
JB
5756
5757 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5758 match is performed. This sequence is used to differentiate homonyms,
5759 is an optional part of a valid name suffix. */
4c4b4cd2 5760
14f9c5c9 5761static int
d2e4a39e 5762is_name_suffix (const char *str)
14f9c5c9
AS
5763{
5764 int k;
4c4b4cd2
PH
5765 const char *matching;
5766 const int len = strlen (str);
5767
babe1480
JB
5768 /* Skip optional leading __[0-9]+. */
5769
4c4b4cd2
PH
5770 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5771 {
babe1480
JB
5772 str += 3;
5773 while (isdigit (str[0]))
dda83cd7 5774 str += 1;
4c4b4cd2 5775 }
babe1480
JB
5776
5777 /* [.$][0-9]+ */
4c4b4cd2 5778
babe1480 5779 if (str[0] == '.' || str[0] == '$')
4c4b4cd2 5780 {
babe1480 5781 matching = str + 1;
4c4b4cd2 5782 while (isdigit (matching[0]))
dda83cd7 5783 matching += 1;
4c4b4cd2 5784 if (matching[0] == '\0')
dda83cd7 5785 return 1;
4c4b4cd2
PH
5786 }
5787
5788 /* ___[0-9]+ */
babe1480 5789
4c4b4cd2
PH
5790 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5791 {
5792 matching = str + 3;
5793 while (isdigit (matching[0]))
dda83cd7 5794 matching += 1;
4c4b4cd2 5795 if (matching[0] == '\0')
dda83cd7 5796 return 1;
4c4b4cd2
PH
5797 }
5798
9ac7f98e
JB
5799 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5800
5801 if (strcmp (str, "TKB") == 0)
5802 return 1;
5803
529cad9c
PH
5804#if 0
5805 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
0963b4bd
MS
5806 with a N at the end. Unfortunately, the compiler uses the same
5807 convention for other internal types it creates. So treating
529cad9c 5808 all entity names that end with an "N" as a name suffix causes
0963b4bd
MS
5809 some regressions. For instance, consider the case of an enumerated
5810 type. To support the 'Image attribute, it creates an array whose
529cad9c
PH
5811 name ends with N.
5812 Having a single character like this as a suffix carrying some
0963b4bd 5813 information is a bit risky. Perhaps we should change the encoding
529cad9c
PH
5814 to be something like "_N" instead. In the meantime, do not do
5815 the following check. */
5816 /* Protected Object Subprograms */
5817 if (len == 1 && str [0] == 'N')
5818 return 1;
5819#endif
5820
5821 /* _E[0-9]+[bs]$ */
5822 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5823 {
5824 matching = str + 3;
5825 while (isdigit (matching[0]))
dda83cd7 5826 matching += 1;
529cad9c 5827 if ((matching[0] == 'b' || matching[0] == 's')
dda83cd7
SM
5828 && matching [1] == '\0')
5829 return 1;
529cad9c
PH
5830 }
5831
4c4b4cd2
PH
5832 /* ??? We should not modify STR directly, as we are doing below. This
5833 is fine in this case, but may become problematic later if we find
5834 that this alternative did not work, and want to try matching
5835 another one from the begining of STR. Since we modified it, we
5836 won't be able to find the begining of the string anymore! */
14f9c5c9
AS
5837 if (str[0] == 'X')
5838 {
5839 str += 1;
d2e4a39e 5840 while (str[0] != '_' && str[0] != '\0')
dda83cd7
SM
5841 {
5842 if (str[0] != 'n' && str[0] != 'b')
5843 return 0;
5844 str += 1;
5845 }
14f9c5c9 5846 }
babe1480 5847
14f9c5c9
AS
5848 if (str[0] == '\000')
5849 return 1;
babe1480 5850
d2e4a39e 5851 if (str[0] == '_')
14f9c5c9
AS
5852 {
5853 if (str[1] != '_' || str[2] == '\000')
dda83cd7 5854 return 0;
d2e4a39e 5855 if (str[2] == '_')
dda83cd7
SM
5856 {
5857 if (strcmp (str + 3, "JM") == 0)
5858 return 1;
5859 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5860 the LJM suffix in favor of the JM one. But we will
5861 still accept LJM as a valid suffix for a reasonable
5862 amount of time, just to allow ourselves to debug programs
5863 compiled using an older version of GNAT. */
5864 if (strcmp (str + 3, "LJM") == 0)
5865 return 1;
5866 if (str[3] != 'X')
5867 return 0;
5868 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5869 || str[4] == 'U' || str[4] == 'P')
5870 return 1;
5871 if (str[4] == 'R' && str[5] != 'T')
5872 return 1;
5873 return 0;
5874 }
4c4b4cd2 5875 if (!isdigit (str[2]))
dda83cd7 5876 return 0;
4c4b4cd2 5877 for (k = 3; str[k] != '\0'; k += 1)
dda83cd7
SM
5878 if (!isdigit (str[k]) && str[k] != '_')
5879 return 0;
14f9c5c9
AS
5880 return 1;
5881 }
4c4b4cd2 5882 if (str[0] == '$' && isdigit (str[1]))
14f9c5c9 5883 {
4c4b4cd2 5884 for (k = 2; str[k] != '\0'; k += 1)
dda83cd7
SM
5885 if (!isdigit (str[k]) && str[k] != '_')
5886 return 0;
14f9c5c9
AS
5887 return 1;
5888 }
5889 return 0;
5890}
d2e4a39e 5891
aeb5907d
JB
5892/* Return non-zero if the string starting at NAME and ending before
5893 NAME_END contains no capital letters. */
529cad9c
PH
5894
5895static int
5896is_valid_name_for_wild_match (const char *name0)
5897{
f945dedf 5898 std::string decoded_name = ada_decode (name0);
529cad9c
PH
5899 int i;
5900
5823c3ef
JB
5901 /* If the decoded name starts with an angle bracket, it means that
5902 NAME0 does not follow the GNAT encoding format. It should then
5903 not be allowed as a possible wild match. */
5904 if (decoded_name[0] == '<')
5905 return 0;
5906
529cad9c
PH
5907 for (i=0; decoded_name[i] != '\0'; i++)
5908 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5909 return 0;
5910
5911 return 1;
5912}
5913
59c8a30b
JB
5914/* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5915 character which could start a simple name. Assumes that *NAMEP points
5916 somewhere inside the string beginning at NAME0. */
4c4b4cd2 5917
14f9c5c9 5918static int
59c8a30b 5919advance_wild_match (const char **namep, const char *name0, char target0)
14f9c5c9 5920{
73589123 5921 const char *name = *namep;
5b4ee69b 5922
5823c3ef 5923 while (1)
14f9c5c9 5924 {
59c8a30b 5925 char t0, t1;
73589123
PH
5926
5927 t0 = *name;
5928 if (t0 == '_')
5929 {
5930 t1 = name[1];
5931 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5932 {
5933 name += 1;
61012eef 5934 if (name == name0 + 5 && startswith (name0, "_ada"))
73589123
PH
5935 break;
5936 else
5937 name += 1;
5938 }
aa27d0b3
JB
5939 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
5940 || name[2] == target0))
73589123
PH
5941 {
5942 name += 2;
5943 break;
5944 }
86b44259
TT
5945 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
5946 {
5947 /* Names like "pkg__B_N__name", where N is a number, are
5948 block-local. We can handle these by simply skipping
5949 the "B_" here. */
5950 name += 4;
5951 }
73589123
PH
5952 else
5953 return 0;
5954 }
5955 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
5956 name += 1;
5957 else
5823c3ef 5958 return 0;
73589123
PH
5959 }
5960
5961 *namep = name;
5962 return 1;
5963}
5964
b5ec771e
PA
5965/* Return true iff NAME encodes a name of the form prefix.PATN.
5966 Ignores any informational suffixes of NAME (i.e., for which
5967 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
5968 simple name. */
73589123 5969
b5ec771e 5970static bool
73589123
PH
5971wild_match (const char *name, const char *patn)
5972{
22e048c9 5973 const char *p;
73589123
PH
5974 const char *name0 = name;
5975
81eaa506
TT
5976 if (startswith (name, "___ghost_"))
5977 name += 9;
5978
73589123
PH
5979 while (1)
5980 {
5981 const char *match = name;
5982
5983 if (*name == *patn)
5984 {
5985 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
5986 if (*p != *name)
5987 break;
5988 if (*p == '\0' && is_name_suffix (name))
b5ec771e 5989 return match == name0 || is_valid_name_for_wild_match (name0);
73589123
PH
5990
5991 if (name[-1] == '_')
5992 name -= 1;
5993 }
5994 if (!advance_wild_match (&name, name0, *patn))
b5ec771e 5995 return false;
96d887e8 5996 }
96d887e8
PH
5997}
5998
d1183b06 5999/* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
b5ec771e 6000 necessary). OBJFILE is the section containing BLOCK. */
96d887e8
PH
6001
6002static void
d1183b06 6003ada_add_block_symbols (std::vector<struct block_symbol> &result,
b5ec771e
PA
6004 const struct block *block,
6005 const lookup_name_info &lookup_name,
6c015214 6006 domain_search_flags domain, struct objfile *objfile)
96d887e8 6007{
96d887e8
PH
6008 /* A matching argument symbol, if any. */
6009 struct symbol *arg_sym;
6010 /* Set true when we find a matching non-argument symbol. */
1178743e 6011 bool found_sym;
96d887e8
PH
6012
6013 arg_sym = NULL;
1178743e 6014 found_sym = false;
1c49bb45 6015 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
96d887e8 6016 {
911e1e79 6017 if (sym->matches (domain))
b5ec771e 6018 {
66d7f48f 6019 if (sym->aclass () != LOC_UNRESOLVED)
b5ec771e 6020 {
d9743061 6021 if (sym->is_argument ())
b5ec771e
PA
6022 arg_sym = sym;
6023 else
6024 {
1178743e 6025 found_sym = true;
dae58e04 6026 add_defn_to_vec (result, sym, block);
b5ec771e
PA
6027 }
6028 }
6029 }
96d887e8
PH
6030 }
6031
22cee43f
PMR
6032 /* Handle renamings. */
6033
d1183b06 6034 if (ada_add_block_renamings (result, block, lookup_name, domain))
1178743e 6035 found_sym = true;
22cee43f 6036
96d887e8
PH
6037 if (!found_sym && arg_sym != NULL)
6038 {
dae58e04 6039 add_defn_to_vec (result, arg_sym, block);
96d887e8
PH
6040 }
6041
b5ec771e 6042 if (!lookup_name.ada ().wild_match_p ())
96d887e8
PH
6043 {
6044 arg_sym = NULL;
1178743e 6045 found_sym = false;
b5ec771e
PA
6046 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6047 const char *name = ada_lookup_name.c_str ();
6048 size_t name_len = ada_lookup_name.size ();
96d887e8 6049
548a89df 6050 for (struct symbol *sym : block_iterator_range (block))
76a01679 6051 {
911e1e79 6052 if (sym->matches (domain))
dda83cd7
SM
6053 {
6054 int cmp;
6055
6056 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6057 if (cmp == 0)
6058 {
6059 cmp = !startswith (sym->linkage_name (), "_ada_");
6060 if (cmp == 0)
6061 cmp = strncmp (name, sym->linkage_name () + 5,
6062 name_len);
6063 }
6064
6065 if (cmp == 0
6066 && is_name_suffix (sym->linkage_name () + name_len + 5))
6067 {
66d7f48f 6068 if (sym->aclass () != LOC_UNRESOLVED)
2a2d4dc3 6069 {
d9743061 6070 if (sym->is_argument ())
2a2d4dc3
AS
6071 arg_sym = sym;
6072 else
6073 {
1178743e 6074 found_sym = true;
dae58e04 6075 add_defn_to_vec (result, sym, block);
2a2d4dc3
AS
6076 }
6077 }
dda83cd7
SM
6078 }
6079 }
76a01679 6080 }
96d887e8
PH
6081
6082 /* NOTE: This really shouldn't be needed for _ada_ symbols.
dda83cd7 6083 They aren't parameters, right? */
96d887e8 6084 if (!found_sym && arg_sym != NULL)
dda83cd7 6085 {
dae58e04 6086 add_defn_to_vec (result, arg_sym, block);
dda83cd7 6087 }
96d887e8
PH
6088 }
6089}
6090\f
41d27058 6091
dda83cd7 6092 /* Symbol Completion */
41d27058 6093
b5ec771e 6094/* See symtab.h. */
41d27058 6095
b5ec771e
PA
6096bool
6097ada_lookup_name_info::matches
6098 (const char *sym_name,
6099 symbol_name_match_type match_type,
a207cff2 6100 completion_match_result *comp_match_res) const
41d27058 6101{
b5ec771e
PA
6102 bool match = false;
6103 const char *text = m_encoded_name.c_str ();
6104 size_t text_len = m_encoded_name.size ();
41d27058
JB
6105
6106 /* First, test against the fully qualified name of the symbol. */
6107
6108 if (strncmp (sym_name, text, text_len) == 0)
b5ec771e 6109 match = true;
41d27058 6110
f945dedf 6111 std::string decoded_name = ada_decode (sym_name);
b5ec771e 6112 if (match && !m_encoded_p)
41d27058
JB
6113 {
6114 /* One needed check before declaring a positive match is to verify
dda83cd7
SM
6115 that iff we are doing a verbatim match, the decoded version
6116 of the symbol name starts with '<'. Otherwise, this symbol name
6117 is not a suitable completion. */
41d27058 6118
f945dedf 6119 bool has_angle_bracket = (decoded_name[0] == '<');
b5ec771e 6120 match = (has_angle_bracket == m_verbatim_p);
41d27058
JB
6121 }
6122
b5ec771e 6123 if (match && !m_verbatim_p)
41d27058
JB
6124 {
6125 /* When doing non-verbatim match, another check that needs to
dda83cd7
SM
6126 be done is to verify that the potentially matching symbol name
6127 does not include capital letters, because the ada-mode would
6128 not be able to understand these symbol names without the
6129 angle bracket notation. */
41d27058
JB
6130 const char *tmp;
6131
6132 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6133 if (*tmp != '\0')
b5ec771e 6134 match = false;
41d27058
JB
6135 }
6136
6137 /* Second: Try wild matching... */
6138
b5ec771e 6139 if (!match && m_wild_match_p)
41d27058
JB
6140 {
6141 /* Since we are doing wild matching, this means that TEXT
dda83cd7
SM
6142 may represent an unqualified symbol name. We therefore must
6143 also compare TEXT against the unqualified name of the symbol. */
f945dedf 6144 sym_name = ada_unqualified_name (decoded_name.c_str ());
41d27058
JB
6145
6146 if (strncmp (sym_name, text, text_len) == 0)
b5ec771e 6147 match = true;
41d27058
JB
6148 }
6149
b5ec771e 6150 /* Finally: If we found a match, prepare the result to return. */
41d27058
JB
6151
6152 if (!match)
b5ec771e 6153 return false;
41d27058 6154
a207cff2 6155 if (comp_match_res != NULL)
b5ec771e 6156 {
a207cff2 6157 std::string &match_str = comp_match_res->match.storage ();
41d27058 6158
b5ec771e 6159 if (!m_encoded_p)
a207cff2 6160 match_str = ada_decode (sym_name);
b5ec771e
PA
6161 else
6162 {
6163 if (m_verbatim_p)
6164 match_str = add_angle_brackets (sym_name);
6165 else
6166 match_str = sym_name;
41d27058 6167
b5ec771e 6168 }
a207cff2
PA
6169
6170 comp_match_res->set_match (match_str.c_str ());
41d27058
JB
6171 }
6172
b5ec771e 6173 return true;
41d27058
JB
6174}
6175
dda83cd7 6176 /* Field Access */
96d887e8 6177
73fb9985
JB
6178/* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6179 for tagged types. */
6180
6181static int
6182ada_is_dispatch_table_ptr_type (struct type *type)
6183{
0d5cff50 6184 const char *name;
73fb9985 6185
78134374 6186 if (type->code () != TYPE_CODE_PTR)
73fb9985
JB
6187 return 0;
6188
27710edb 6189 name = type->target_type ()->name ();
73fb9985
JB
6190 if (name == NULL)
6191 return 0;
6192
6193 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6194}
6195
ac4a2da4
JG
6196/* Return non-zero if TYPE is an interface tag. */
6197
6198static int
6199ada_is_interface_tag (struct type *type)
6200{
7d93a1e0 6201 const char *name = type->name ();
ac4a2da4
JG
6202
6203 if (name == NULL)
6204 return 0;
6205
6206 return (strcmp (name, "ada__tags__interface_tag") == 0);
6207}
6208
963a6417
PH
6209/* True if field number FIELD_NUM in struct or union type TYPE is supposed
6210 to be invisible to users. */
96d887e8 6211
963a6417
PH
6212int
6213ada_is_ignored_field (struct type *type, int field_num)
96d887e8 6214{
1f704f76 6215 if (field_num < 0 || field_num > type->num_fields ())
963a6417 6216 return 1;
ffde82bf 6217
73fb9985
JB
6218 /* Check the name of that field. */
6219 {
33d16dd9 6220 const char *name = type->field (field_num).name ();
73fb9985
JB
6221
6222 /* Anonymous field names should not be printed.
6223 brobecker/2007-02-20: I don't think this can actually happen
30baf67b 6224 but we don't want to print the value of anonymous fields anyway. */
73fb9985
JB
6225 if (name == NULL)
6226 return 1;
6227
ffde82bf
JB
6228 /* Normally, fields whose name start with an underscore ("_")
6229 are fields that have been internally generated by the compiler,
6230 and thus should not be printed. The "_parent" field is special,
6231 however: This is a field internally generated by the compiler
6232 for tagged types, and it contains the components inherited from
6233 the parent type. This field should not be printed as is, but
6234 should not be ignored either. */
61012eef 6235 if (name[0] == '_' && !startswith (name, "_parent"))
73fb9985 6236 return 1;
d537777d
TT
6237
6238 /* The compiler doesn't document this, but sometimes it emits
6239 a field whose name starts with a capital letter, like 'V148s'.
6240 These aren't marked as artificial in any way, but we know they
6241 should be ignored. However, wrapper fields should not be
6242 ignored. */
6243 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6244 {
6245 /* Wrapper field. */
6246 }
6247 else if (isupper (name[0]))
6248 return 1;
73fb9985
JB
6249 }
6250
ac4a2da4
JG
6251 /* If this is the dispatch table of a tagged type or an interface tag,
6252 then ignore. */
73fb9985 6253 if (ada_is_tagged_type (type, 1)
940da03e
SM
6254 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6255 || ada_is_interface_tag (type->field (field_num).type ())))
73fb9985
JB
6256 return 1;
6257
6258 /* Not a special field, so it should not be ignored. */
6259 return 0;
963a6417 6260}
96d887e8 6261
963a6417 6262/* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
0963b4bd 6263 pointer or reference type whose ultimate target has a tag field. */
96d887e8 6264
963a6417
PH
6265int
6266ada_is_tagged_type (struct type *type, int refok)
6267{
988f6b3d 6268 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
963a6417 6269}
96d887e8 6270
963a6417 6271/* True iff TYPE represents the type of X'Tag */
96d887e8 6272
963a6417
PH
6273int
6274ada_is_tag_type (struct type *type)
6275{
460efde1
JB
6276 type = ada_check_typedef (type);
6277
78134374 6278 if (type == NULL || type->code () != TYPE_CODE_PTR)
963a6417
PH
6279 return 0;
6280 else
96d887e8 6281 {
27710edb 6282 const char *name = ada_type_name (type->target_type ());
5b4ee69b 6283
963a6417 6284 return (name != NULL
dda83cd7 6285 && strcmp (name, "ada__tags__dispatch_table") == 0);
96d887e8 6286 }
96d887e8
PH
6287}
6288
963a6417 6289/* The type of the tag on VAL. */
76a01679 6290
de93309a 6291static struct type *
963a6417 6292ada_tag_type (struct value *val)
96d887e8 6293{
d0c97917 6294 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
963a6417 6295}
96d887e8 6296
b50d69b5
JG
6297/* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6298 retired at Ada 05). */
6299
6300static int
6301is_ada95_tag (struct value *tag)
6302{
6303 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6304}
6305
963a6417 6306/* The value of the tag on VAL. */
96d887e8 6307
de93309a 6308static struct value *
963a6417
PH
6309ada_value_tag (struct value *val)
6310{
03ee6b2e 6311 return ada_value_struct_elt (val, "_tag", 0);
96d887e8
PH
6312}
6313
963a6417
PH
6314/* The value of the tag on the object of type TYPE whose contents are
6315 saved at VALADDR, if it is non-null, or is at memory address
0963b4bd 6316 ADDRESS. */
96d887e8 6317
963a6417 6318static struct value *
10a2c479 6319value_tag_from_contents_and_address (struct type *type,
fc1a4b47 6320 const gdb_byte *valaddr,
dda83cd7 6321 CORE_ADDR address)
96d887e8 6322{
b5385fc0 6323 int tag_byte_offset;
963a6417 6324 struct type *tag_type;
5b4ee69b 6325
4d1795ac
TT
6326 gdb::array_view<const gdb_byte> contents;
6327 if (valaddr != nullptr)
df86565b 6328 contents = gdb::make_array_view (valaddr, type->length ());
4d1795ac
TT
6329 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6330 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
dda83cd7 6331 NULL, NULL, NULL))
96d887e8 6332 {
fc1a4b47 6333 const gdb_byte *valaddr1 = ((valaddr == NULL)
10a2c479
AC
6334 ? NULL
6335 : valaddr + tag_byte_offset);
963a6417 6336 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
96d887e8 6337
963a6417 6338 return value_from_contents_and_address (tag_type, valaddr1, address1);
96d887e8 6339 }
963a6417
PH
6340 return NULL;
6341}
96d887e8 6342
963a6417
PH
6343static struct type *
6344type_from_tag (struct value *tag)
6345{
f5272a3b 6346 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
5b4ee69b 6347
963a6417 6348 if (type_name != NULL)
5c4258f4 6349 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
963a6417
PH
6350 return NULL;
6351}
96d887e8 6352
b50d69b5
JG
6353/* Given a value OBJ of a tagged type, return a value of this
6354 type at the base address of the object. The base address, as
6355 defined in Ada.Tags, it is the address of the primary tag of
6356 the object, and therefore where the field values of its full
6357 view can be fetched. */
6358
6359struct value *
6360ada_tag_value_at_base_address (struct value *obj)
6361{
b50d69b5
JG
6362 struct value *val;
6363 LONGEST offset_to_top = 0;
6364 struct type *ptr_type, *obj_type;
6365 struct value *tag;
6366 CORE_ADDR base_address;
6367
d0c97917 6368 obj_type = obj->type ();
b50d69b5 6369
33b5899f 6370 /* It is the responsibility of the caller to deref pointers. */
b50d69b5 6371
78134374 6372 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
b50d69b5
JG
6373 return obj;
6374
6375 tag = ada_value_tag (obj);
6376 if (!tag)
6377 return obj;
6378
6379 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6380
6381 if (is_ada95_tag (tag))
6382 return obj;
6383
d537777d
TT
6384 struct type *offset_type
6385 = language_lookup_primitive_type (language_def (language_ada),
99d9c3b9
SM
6386 current_inferior ()->arch (),
6387 "storage_offset");
d537777d 6388 ptr_type = lookup_pointer_type (offset_type);
b50d69b5
JG
6389 val = value_cast (ptr_type, tag);
6390 if (!val)
6391 return obj;
6392
6393 /* It is perfectly possible that an exception be raised while
6394 trying to determine the base address, just like for the tag;
6395 see ada_tag_name for more details. We do not print the error
6396 message for the same reason. */
6397
a70b8144 6398 try
b50d69b5
JG
6399 {
6400 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6401 }
6402
230d2906 6403 catch (const gdb_exception_error &e)
492d29ea
PA
6404 {
6405 return obj;
6406 }
b50d69b5
JG
6407
6408 /* If offset is null, nothing to do. */
6409
6410 if (offset_to_top == 0)
6411 return obj;
6412
6413 /* -1 is a special case in Ada.Tags; however, what should be done
6414 is not quite clear from the documentation. So do nothing for
6415 now. */
6416
6417 if (offset_to_top == -1)
6418 return obj;
6419
d537777d
TT
6420 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6421 top is used. In this situation the offset is stored just after
6422 the tag, in the object itself. */
df86565b 6423 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
d537777d
TT
6424 if (offset_to_top == last)
6425 {
6426 struct value *tem = value_addr (tag);
6427 tem = value_ptradd (tem, 1);
6428 tem = value_cast (ptr_type, tem);
6429 offset_to_top = value_as_long (value_ind (tem));
6430 }
05527d8c
TV
6431
6432 if (offset_to_top > 0)
d537777d
TT
6433 {
6434 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6435 from the base address. This was however incompatible with
6436 C++ dispatch table: C++ uses a *negative* value to *add*
6437 to the base address. Ada's convention has therefore been
6438 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6439 use the same convention. Here, we support both cases by
6440 checking the sign of OFFSET_TO_TOP. */
6441 offset_to_top = -offset_to_top;
6442 }
08f49010 6443
9feb2d07 6444 base_address = obj->address () + offset_to_top;
b50d69b5
JG
6445 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6446
6447 /* Make sure that we have a proper tag at the new address.
6448 Otherwise, offset_to_top is bogus (which can happen when
6449 the object is not initialized yet). */
6450
6451 if (!tag)
6452 return obj;
6453
6454 obj_type = type_from_tag (tag);
6455
6456 if (!obj_type)
6457 return obj;
6458
6459 return value_from_contents_and_address (obj_type, NULL, base_address);
6460}
6461
1b611343
JB
6462/* Return the "ada__tags__type_specific_data" type. */
6463
6464static struct type *
6465ada_get_tsd_type (struct inferior *inf)
963a6417 6466{
1b611343 6467 struct ada_inferior_data *data = get_ada_inferior_data (inf);
4c4b4cd2 6468
1b611343 6469 if (data->tsd_type == 0)
1ab9eefe
TT
6470 data->tsd_type
6471 = lookup_transparent_type ("<ada__tags__type_specific_data>",
6472 SEARCH_TYPE_DOMAIN);
1b611343
JB
6473 return data->tsd_type;
6474}
529cad9c 6475
1b611343
JB
6476/* Return the TSD (type-specific data) associated to the given TAG.
6477 TAG is assumed to be the tag of a tagged-type entity.
529cad9c 6478
1b611343 6479 May return NULL if we are unable to get the TSD. */
4c4b4cd2 6480
1b611343
JB
6481static struct value *
6482ada_get_tsd_from_tag (struct value *tag)
4c4b4cd2 6483{
4c4b4cd2 6484 struct value *val;
1b611343 6485 struct type *type;
5b4ee69b 6486
1b611343
JB
6487 /* First option: The TSD is simply stored as a field of our TAG.
6488 Only older versions of GNAT would use this format, but we have
6489 to test it first, because there are no visible markers for
6490 the current approach except the absence of that field. */
529cad9c 6491
1b611343
JB
6492 val = ada_value_struct_elt (tag, "tsd", 1);
6493 if (val)
6494 return val;
e802dbe0 6495
1b611343
JB
6496 /* Try the second representation for the dispatch table (in which
6497 there is no explicit 'tsd' field in the referent of the tag pointer,
6498 and instead the tsd pointer is stored just before the dispatch
6499 table. */
e802dbe0 6500
1b611343
JB
6501 type = ada_get_tsd_type (current_inferior());
6502 if (type == NULL)
6503 return NULL;
6504 type = lookup_pointer_type (lookup_pointer_type (type));
6505 val = value_cast (type, tag);
6506 if (val == NULL)
6507 return NULL;
6508 return value_ind (value_ptradd (val, -1));
e802dbe0
JB
6509}
6510
1b611343
JB
6511/* Given the TSD of a tag (type-specific data), return a string
6512 containing the name of the associated type.
6513
f5272a3b 6514 May return NULL if we are unable to determine the tag name. */
1b611343 6515
f5272a3b 6516static gdb::unique_xmalloc_ptr<char>
1b611343 6517ada_tag_name_from_tsd (struct value *tsd)
529cad9c 6518{
1b611343 6519 struct value *val;
529cad9c 6520
1b611343 6521 val = ada_value_struct_elt (tsd, "expanded_name", 1);
4c4b4cd2 6522 if (val == NULL)
1b611343 6523 return NULL;
66920317
TT
6524 gdb::unique_xmalloc_ptr<char> buffer
6525 = target_read_string (value_as_address (val), INT_MAX);
6526 if (buffer == nullptr)
f5272a3b
TT
6527 return nullptr;
6528
315e4ebb 6529 try
f5272a3b 6530 {
315e4ebb
TT
6531 /* Let this throw an exception on error. If the data is
6532 uninitialized, we'd rather not have the user see a
6533 warning. */
6534 const char *folded = ada_fold_name (buffer.get (), true);
6535 return make_unique_xstrdup (folded);
6536 }
6537 catch (const gdb_exception &)
6538 {
6539 return nullptr;
f5272a3b 6540 }
4c4b4cd2
PH
6541}
6542
6543/* The type name of the dynamic type denoted by the 'tag value TAG, as
1b611343
JB
6544 a C string.
6545
6546 Return NULL if the TAG is not an Ada tag, or if we were unable to
f5272a3b 6547 determine the name of that tag. */
4c4b4cd2 6548
f5272a3b 6549gdb::unique_xmalloc_ptr<char>
4c4b4cd2
PH
6550ada_tag_name (struct value *tag)
6551{
f5272a3b 6552 gdb::unique_xmalloc_ptr<char> name;
5b4ee69b 6553
d0c97917 6554 if (!ada_is_tag_type (tag->type ()))
4c4b4cd2 6555 return NULL;
1b611343
JB
6556
6557 /* It is perfectly possible that an exception be raised while trying
6558 to determine the TAG's name, even under normal circumstances:
6559 The associated variable may be uninitialized or corrupted, for
6560 instance. We do not let any exception propagate past this point.
6561 instead we return NULL.
6562
6563 We also do not print the error message either (which often is very
6564 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6565 the caller print a more meaningful message if necessary. */
a70b8144 6566 try
1b611343
JB
6567 {
6568 struct value *tsd = ada_get_tsd_from_tag (tag);
6569
6570 if (tsd != NULL)
6571 name = ada_tag_name_from_tsd (tsd);
6572 }
230d2906 6573 catch (const gdb_exception_error &e)
492d29ea
PA
6574 {
6575 }
1b611343
JB
6576
6577 return name;
4c4b4cd2
PH
6578}
6579
6580/* The parent type of TYPE, or NULL if none. */
14f9c5c9 6581
d2e4a39e 6582struct type *
ebf56fd3 6583ada_parent_type (struct type *type)
14f9c5c9
AS
6584{
6585 int i;
6586
61ee279c 6587 type = ada_check_typedef (type);
14f9c5c9 6588
78134374 6589 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
14f9c5c9
AS
6590 return NULL;
6591
1f704f76 6592 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 6593 if (ada_is_parent_field (type, i))
0c1f74cf 6594 {
dda83cd7 6595 struct type *parent_type = type->field (i).type ();
0c1f74cf 6596
dda83cd7
SM
6597 /* If the _parent field is a pointer, then dereference it. */
6598 if (parent_type->code () == TYPE_CODE_PTR)
27710edb 6599 parent_type = parent_type->target_type ();
dda83cd7
SM
6600 /* If there is a parallel XVS type, get the actual base type. */
6601 parent_type = ada_get_base_type (parent_type);
0c1f74cf 6602
dda83cd7 6603 return ada_check_typedef (parent_type);
0c1f74cf 6604 }
14f9c5c9
AS
6605
6606 return NULL;
6607}
6608
4c4b4cd2
PH
6609/* True iff field number FIELD_NUM of structure type TYPE contains the
6610 parent-type (inherited) fields of a derived type. Assumes TYPE is
6611 a structure type with at least FIELD_NUM+1 fields. */
14f9c5c9
AS
6612
6613int
ebf56fd3 6614ada_is_parent_field (struct type *type, int field_num)
14f9c5c9 6615{
33d16dd9 6616 const char *name = ada_check_typedef (type)->field (field_num).name ();
5b4ee69b 6617
4c4b4cd2 6618 return (name != NULL
dda83cd7
SM
6619 && (startswith (name, "PARENT")
6620 || startswith (name, "_parent")));
14f9c5c9
AS
6621}
6622
4c4b4cd2 6623/* True iff field number FIELD_NUM of structure type TYPE is a
14f9c5c9 6624 transparent wrapper field (which should be silently traversed when doing
4c4b4cd2 6625 field selection and flattened when printing). Assumes TYPE is a
14f9c5c9 6626 structure type with at least FIELD_NUM+1 fields. Such fields are always
4c4b4cd2 6627 structures. */
14f9c5c9
AS
6628
6629int
ebf56fd3 6630ada_is_wrapper_field (struct type *type, int field_num)
14f9c5c9 6631{
33d16dd9 6632 const char *name = type->field (field_num).name ();
5b4ee69b 6633
dddc0e16
JB
6634 if (name != NULL && strcmp (name, "RETVAL") == 0)
6635 {
6636 /* This happens in functions with "out" or "in out" parameters
6637 which are passed by copy. For such functions, GNAT describes
6638 the function's return type as being a struct where the return
6639 value is in a field called RETVAL, and where the other "out"
6640 or "in out" parameters are fields of that struct. This is not
6641 a wrapper. */
6642 return 0;
6643 }
6644
d2e4a39e 6645 return (name != NULL
dda83cd7
SM
6646 && (startswith (name, "PARENT")
6647 || strcmp (name, "REP") == 0
6648 || startswith (name, "_parent")
6649 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
14f9c5c9
AS
6650}
6651
4c4b4cd2
PH
6652/* True iff field number FIELD_NUM of structure or union type TYPE
6653 is a variant wrapper. Assumes TYPE is a structure type with at least
6654 FIELD_NUM+1 fields. */
14f9c5c9
AS
6655
6656int
ebf56fd3 6657ada_is_variant_part (struct type *type, int field_num)
14f9c5c9 6658{
8ecb59f8
TT
6659 /* Only Ada types are eligible. */
6660 if (!ADA_TYPE_P (type))
6661 return 0;
6662
940da03e 6663 struct type *field_type = type->field (field_num).type ();
5b4ee69b 6664
78134374
SM
6665 return (field_type->code () == TYPE_CODE_UNION
6666 || (is_dynamic_field (type, field_num)
27710edb 6667 && (field_type->target_type ()->code ()
c3e5cd34 6668 == TYPE_CODE_UNION)));
14f9c5c9
AS
6669}
6670
6671/* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
4c4b4cd2 6672 whose discriminants are contained in the record type OUTER_TYPE,
7c964f07
UW
6673 returns the type of the controlling discriminant for the variant.
6674 May return NULL if the type could not be found. */
14f9c5c9 6675
d2e4a39e 6676struct type *
ebf56fd3 6677ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
14f9c5c9 6678{
a121b7c1 6679 const char *name = ada_variant_discrim_name (var_type);
5b4ee69b 6680
988f6b3d 6681 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
14f9c5c9
AS
6682}
6683
4c4b4cd2 6684/* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
14f9c5c9 6685 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
4c4b4cd2 6686 represents a 'when others' clause; otherwise 0. */
14f9c5c9 6687
de93309a 6688static int
ebf56fd3 6689ada_is_others_clause (struct type *type, int field_num)
14f9c5c9 6690{
33d16dd9 6691 const char *name = type->field (field_num).name ();
5b4ee69b 6692
14f9c5c9
AS
6693 return (name != NULL && name[0] == 'O');
6694}
6695
6696/* Assuming that TYPE0 is the type of the variant part of a record,
4c4b4cd2
PH
6697 returns the name of the discriminant controlling the variant.
6698 The value is valid until the next call to ada_variant_discrim_name. */
14f9c5c9 6699
a121b7c1 6700const char *
ebf56fd3 6701ada_variant_discrim_name (struct type *type0)
14f9c5c9 6702{
5f9febe0 6703 static std::string result;
d2e4a39e
AS
6704 struct type *type;
6705 const char *name;
6706 const char *discrim_end;
6707 const char *discrim_start;
14f9c5c9 6708
78134374 6709 if (type0->code () == TYPE_CODE_PTR)
27710edb 6710 type = type0->target_type ();
14f9c5c9
AS
6711 else
6712 type = type0;
6713
6714 name = ada_type_name (type);
6715
6716 if (name == NULL || name[0] == '\000')
6717 return "";
6718
6719 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6720 discrim_end -= 1)
6721 {
61012eef 6722 if (startswith (discrim_end, "___XVN"))
dda83cd7 6723 break;
14f9c5c9
AS
6724 }
6725 if (discrim_end == name)
6726 return "";
6727
d2e4a39e 6728 for (discrim_start = discrim_end; discrim_start != name + 3;
14f9c5c9
AS
6729 discrim_start -= 1)
6730 {
d2e4a39e 6731 if (discrim_start == name + 1)
dda83cd7 6732 return "";
76a01679 6733 if ((discrim_start > name + 3
dda83cd7
SM
6734 && startswith (discrim_start - 3, "___"))
6735 || discrim_start[-1] == '.')
6736 break;
14f9c5c9
AS
6737 }
6738
5f9febe0
TT
6739 result = std::string (discrim_start, discrim_end - discrim_start);
6740 return result.c_str ();
14f9c5c9
AS
6741}
6742
4c4b4cd2
PH
6743/* Scan STR for a subtype-encoded number, beginning at position K.
6744 Put the position of the character just past the number scanned in
6745 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6746 Return 1 if there was a valid number at the given position, and 0
6747 otherwise. A "subtype-encoded" number consists of the absolute value
6748 in decimal, followed by the letter 'm' to indicate a negative number.
6749 Assumes 0m does not occur. */
14f9c5c9
AS
6750
6751int
d2e4a39e 6752ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
14f9c5c9
AS
6753{
6754 ULONGEST RU;
6755
d2e4a39e 6756 if (!isdigit (str[k]))
14f9c5c9
AS
6757 return 0;
6758
4c4b4cd2 6759 /* Do it the hard way so as not to make any assumption about
14f9c5c9 6760 the relationship of unsigned long (%lu scan format code) and
4c4b4cd2 6761 LONGEST. */
14f9c5c9
AS
6762 RU = 0;
6763 while (isdigit (str[k]))
6764 {
d2e4a39e 6765 RU = RU * 10 + (str[k] - '0');
14f9c5c9
AS
6766 k += 1;
6767 }
6768
d2e4a39e 6769 if (str[k] == 'm')
14f9c5c9
AS
6770 {
6771 if (R != NULL)
dda83cd7 6772 *R = (-(LONGEST) (RU - 1)) - 1;
14f9c5c9
AS
6773 k += 1;
6774 }
6775 else if (R != NULL)
6776 *R = (LONGEST) RU;
6777
4c4b4cd2 6778 /* NOTE on the above: Technically, C does not say what the results of
14f9c5c9
AS
6779 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6780 number representable as a LONGEST (although either would probably work
6781 in most implementations). When RU>0, the locution in the then branch
4c4b4cd2 6782 above is always equivalent to the negative of RU. */
14f9c5c9
AS
6783
6784 if (new_k != NULL)
6785 *new_k = k;
6786 return 1;
6787}
6788
4c4b4cd2
PH
6789/* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6790 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6791 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
14f9c5c9 6792
de93309a 6793static int
ebf56fd3 6794ada_in_variant (LONGEST val, struct type *type, int field_num)
14f9c5c9 6795{
33d16dd9 6796 const char *name = type->field (field_num).name ();
14f9c5c9
AS
6797 int p;
6798
6799 p = 0;
6800 while (1)
6801 {
d2e4a39e 6802 switch (name[p])
dda83cd7
SM
6803 {
6804 case '\0':
6805 return 0;
6806 case 'S':
6807 {
6808 LONGEST W;
6809
6810 if (!ada_scan_number (name, p + 1, &W, &p))
6811 return 0;
6812 if (val == W)
6813 return 1;
6814 break;
6815 }
6816 case 'R':
6817 {
6818 LONGEST L, U;
6819
6820 if (!ada_scan_number (name, p + 1, &L, &p)
6821 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6822 return 0;
6823 if (val >= L && val <= U)
6824 return 1;
6825 break;
6826 }
6827 case 'O':
6828 return 1;
6829 default:
6830 return 0;
6831 }
4c4b4cd2
PH
6832 }
6833}
6834
0963b4bd 6835/* FIXME: Lots of redundancy below. Try to consolidate. */
4c4b4cd2
PH
6836
6837/* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6838 ARG_TYPE, extract and return the value of one of its (non-static)
6839 fields. FIELDNO says which field. Differs from value_primitive_field
6840 only in that it can handle packed values of arbitrary type. */
14f9c5c9 6841
5eb68a39 6842struct value *
d2e4a39e 6843ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
dda83cd7 6844 struct type *arg_type)
14f9c5c9 6845{
14f9c5c9
AS
6846 struct type *type;
6847
61ee279c 6848 arg_type = ada_check_typedef (arg_type);
940da03e 6849 type = arg_type->field (fieldno).type ();
14f9c5c9 6850
4504bbde
TT
6851 /* Handle packed fields. It might be that the field is not packed
6852 relative to its containing structure, but the structure itself is
6853 packed; in this case we must take the bit-field path. */
3757d2d4 6854 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
14f9c5c9 6855 {
b610c045 6856 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
3757d2d4 6857 int bit_size = arg_type->field (fieldno).bitsize ();
d2e4a39e 6858
50888e42 6859 return ada_value_primitive_packed_val (arg1,
efaf1ae0 6860 arg1->contents ().data (),
dda83cd7
SM
6861 offset + bit_pos / 8,
6862 bit_pos % 8, bit_size, type);
14f9c5c9
AS
6863 }
6864 else
6c49729e 6865 return arg1->primitive_field (offset, fieldno, arg_type);
14f9c5c9
AS
6866}
6867
52ce6436
PH
6868/* Find field with name NAME in object of type TYPE. If found,
6869 set the following for each argument that is non-null:
6870 - *FIELD_TYPE_P to the field's type;
6871 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6872 an object of that type;
6873 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6874 - *BIT_SIZE_P to its size in bits if the field is packed, and
6875 0 otherwise;
6876 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6877 fields up to but not including the desired field, or by the total
6878 number of fields if not found. A NULL value of NAME never
6879 matches; the function just counts visible fields in this case.
6880
828d5846
XR
6881 Notice that we need to handle when a tagged record hierarchy
6882 has some components with the same name, like in this scenario:
6883
6884 type Top_T is tagged record
dda83cd7
SM
6885 N : Integer := 1;
6886 U : Integer := 974;
6887 A : Integer := 48;
828d5846
XR
6888 end record;
6889
6890 type Middle_T is new Top.Top_T with record
dda83cd7
SM
6891 N : Character := 'a';
6892 C : Integer := 3;
828d5846
XR
6893 end record;
6894
6895 type Bottom_T is new Middle.Middle_T with record
dda83cd7
SM
6896 N : Float := 4.0;
6897 C : Character := '5';
6898 X : Integer := 6;
6899 A : Character := 'J';
828d5846
XR
6900 end record;
6901
6902 Let's say we now have a variable declared and initialized as follow:
6903
6904 TC : Top_A := new Bottom_T;
6905
6906 And then we use this variable to call this function
6907
6908 procedure Assign (Obj: in out Top_T; TV : Integer);
6909
6910 as follow:
6911
6912 Assign (Top_T (B), 12);
6913
6914 Now, we're in the debugger, and we're inside that procedure
6915 then and we want to print the value of obj.c:
6916
6917 Usually, the tagged record or one of the parent type owns the
6918 component to print and there's no issue but in this particular
6919 case, what does it mean to ask for Obj.C? Since the actual
6920 type for object is type Bottom_T, it could mean two things: type
6921 component C from the Middle_T view, but also component C from
6922 Bottom_T. So in that "undefined" case, when the component is
6923 not found in the non-resolved type (which includes all the
6924 components of the parent type), then resolve it and see if we
6925 get better luck once expanded.
6926
6927 In the case of homonyms in the derived tagged type, we don't
6928 guaranty anything, and pick the one that's easiest for us
6929 to program.
6930
0963b4bd 6931 Returns 1 if found, 0 otherwise. */
52ce6436 6932
4c4b4cd2 6933static int
0d5cff50 6934find_struct_field (const char *name, struct type *type, int offset,
dda83cd7
SM
6935 struct type **field_type_p,
6936 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
52ce6436 6937 int *index_p)
4c4b4cd2
PH
6938{
6939 int i;
828d5846 6940 int parent_offset = -1;
4c4b4cd2 6941
61ee279c 6942 type = ada_check_typedef (type);
76a01679 6943
52ce6436
PH
6944 if (field_type_p != NULL)
6945 *field_type_p = NULL;
6946 if (byte_offset_p != NULL)
d5d6fca5 6947 *byte_offset_p = 0;
52ce6436
PH
6948 if (bit_offset_p != NULL)
6949 *bit_offset_p = 0;
6950 if (bit_size_p != NULL)
6951 *bit_size_p = 0;
6952
1f704f76 6953 for (i = 0; i < type->num_fields (); i += 1)
4c4b4cd2 6954 {
4d1795ac
TT
6955 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
6956 type. However, we only need the values to be correct when
6957 the caller asks for them. */
6958 int bit_pos = 0, fld_offset = 0;
6959 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
6960 {
b610c045 6961 bit_pos = type->field (i).loc_bitpos ();
4d1795ac
TT
6962 fld_offset = offset + bit_pos / 8;
6963 }
6964
33d16dd9 6965 const char *t_field_name = type->field (i).name ();
76a01679 6966
4c4b4cd2 6967 if (t_field_name == NULL)
dda83cd7 6968 continue;
4c4b4cd2 6969
828d5846 6970 else if (ada_is_parent_field (type, i))
dda83cd7 6971 {
828d5846
XR
6972 /* This is a field pointing us to the parent type of a tagged
6973 type. As hinted in this function's documentation, we give
6974 preference to fields in the current record first, so what
6975 we do here is just record the index of this field before
6976 we skip it. If it turns out we couldn't find our field
6977 in the current record, then we'll get back to it and search
6978 inside it whether the field might exist in the parent. */
6979
dda83cd7
SM
6980 parent_offset = i;
6981 continue;
6982 }
828d5846 6983
52ce6436 6984 else if (name != NULL && field_name_match (t_field_name, name))
dda83cd7 6985 {
3757d2d4 6986 int bit_size = type->field (i).bitsize ();
5b4ee69b 6987
52ce6436 6988 if (field_type_p != NULL)
940da03e 6989 *field_type_p = type->field (i).type ();
52ce6436
PH
6990 if (byte_offset_p != NULL)
6991 *byte_offset_p = fld_offset;
6992 if (bit_offset_p != NULL)
6993 *bit_offset_p = bit_pos % 8;
6994 if (bit_size_p != NULL)
6995 *bit_size_p = bit_size;
dda83cd7
SM
6996 return 1;
6997 }
4c4b4cd2 6998 else if (ada_is_wrapper_field (type, i))
dda83cd7 6999 {
940da03e 7000 if (find_struct_field (name, type->field (i).type (), fld_offset,
52ce6436
PH
7001 field_type_p, byte_offset_p, bit_offset_p,
7002 bit_size_p, index_p))
dda83cd7
SM
7003 return 1;
7004 }
4c4b4cd2 7005 else if (ada_is_variant_part (type, i))
dda83cd7 7006 {
52ce6436
PH
7007 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7008 fixed type?? */
dda83cd7
SM
7009 int j;
7010 struct type *field_type
940da03e 7011 = ada_check_typedef (type->field (i).type ());
4c4b4cd2 7012
dda83cd7
SM
7013 for (j = 0; j < field_type->num_fields (); j += 1)
7014 {
7015 if (find_struct_field (name, field_type->field (j).type (),
7016 fld_offset
b610c045 7017 + field_type->field (j).loc_bitpos () / 8,
dda83cd7
SM
7018 field_type_p, byte_offset_p,
7019 bit_offset_p, bit_size_p, index_p))
7020 return 1;
7021 }
7022 }
52ce6436
PH
7023 else if (index_p != NULL)
7024 *index_p += 1;
4c4b4cd2 7025 }
828d5846
XR
7026
7027 /* Field not found so far. If this is a tagged type which
7028 has a parent, try finding that field in the parent now. */
7029
7030 if (parent_offset != -1)
7031 {
4d1795ac
TT
7032 /* As above, only compute the offset when truly needed. */
7033 int fld_offset = offset;
7034 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7035 {
b610c045 7036 int bit_pos = type->field (parent_offset).loc_bitpos ();
4d1795ac
TT
7037 fld_offset += bit_pos / 8;
7038 }
828d5846 7039
940da03e 7040 if (find_struct_field (name, type->field (parent_offset).type (),
dda83cd7
SM
7041 fld_offset, field_type_p, byte_offset_p,
7042 bit_offset_p, bit_size_p, index_p))
7043 return 1;
828d5846
XR
7044 }
7045
4c4b4cd2
PH
7046 return 0;
7047}
7048
0963b4bd 7049/* Number of user-visible fields in record type TYPE. */
4c4b4cd2 7050
52ce6436
PH
7051static int
7052num_visible_fields (struct type *type)
7053{
7054 int n;
5b4ee69b 7055
52ce6436
PH
7056 n = 0;
7057 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7058 return n;
7059}
14f9c5c9 7060
4c4b4cd2 7061/* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
14f9c5c9
AS
7062 and search in it assuming it has (class) type TYPE.
7063 If found, return value, else return NULL.
7064
828d5846
XR
7065 Searches recursively through wrapper fields (e.g., '_parent').
7066
7067 In the case of homonyms in the tagged types, please refer to the
7068 long explanation in find_struct_field's function documentation. */
14f9c5c9 7069
4c4b4cd2 7070static struct value *
108d56a4 7071ada_search_struct_field (const char *name, struct value *arg, int offset,
dda83cd7 7072 struct type *type)
14f9c5c9
AS
7073{
7074 int i;
828d5846 7075 int parent_offset = -1;
14f9c5c9 7076
5b4ee69b 7077 type = ada_check_typedef (type);
1f704f76 7078 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 7079 {
33d16dd9 7080 const char *t_field_name = type->field (i).name ();
14f9c5c9
AS
7081
7082 if (t_field_name == NULL)
dda83cd7 7083 continue;
14f9c5c9 7084
828d5846 7085 else if (ada_is_parent_field (type, i))
dda83cd7 7086 {
828d5846
XR
7087 /* This is a field pointing us to the parent type of a tagged
7088 type. As hinted in this function's documentation, we give
7089 preference to fields in the current record first, so what
7090 we do here is just record the index of this field before
7091 we skip it. If it turns out we couldn't find our field
7092 in the current record, then we'll get back to it and search
7093 inside it whether the field might exist in the parent. */
7094
dda83cd7
SM
7095 parent_offset = i;
7096 continue;
7097 }
828d5846 7098
14f9c5c9 7099 else if (field_name_match (t_field_name, name))
dda83cd7 7100 return ada_value_primitive_field (arg, offset, i, type);
14f9c5c9
AS
7101
7102 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7103 {
7104 struct value *v = /* Do not let indent join lines here. */
7105 ada_search_struct_field (name, arg,
b610c045 7106 offset + type->field (i).loc_bitpos () / 8,
dda83cd7 7107 type->field (i).type ());
5b4ee69b 7108
dda83cd7
SM
7109 if (v != NULL)
7110 return v;
7111 }
14f9c5c9
AS
7112
7113 else if (ada_is_variant_part (type, i))
dda83cd7 7114 {
0963b4bd 7115 /* PNH: Do we ever get here? See find_struct_field. */
dda83cd7
SM
7116 int j;
7117 struct type *field_type = ada_check_typedef (type->field (i).type ());
b610c045 7118 int var_offset = offset + type->field (i).loc_bitpos () / 8;
4c4b4cd2 7119
dda83cd7
SM
7120 for (j = 0; j < field_type->num_fields (); j += 1)
7121 {
7122 struct value *v = ada_search_struct_field /* Force line
0963b4bd 7123 break. */
dda83cd7 7124 (name, arg,
b610c045 7125 var_offset + field_type->field (j).loc_bitpos () / 8,
dda83cd7 7126 field_type->field (j).type ());
5b4ee69b 7127
dda83cd7
SM
7128 if (v != NULL)
7129 return v;
7130 }
7131 }
14f9c5c9 7132 }
828d5846
XR
7133
7134 /* Field not found so far. If this is a tagged type which
7135 has a parent, try finding that field in the parent now. */
7136
7137 if (parent_offset != -1)
7138 {
7139 struct value *v = ada_search_struct_field (
b610c045 7140 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
940da03e 7141 type->field (parent_offset).type ());
828d5846
XR
7142
7143 if (v != NULL)
dda83cd7 7144 return v;
828d5846
XR
7145 }
7146
14f9c5c9
AS
7147 return NULL;
7148}
d2e4a39e 7149
52ce6436
PH
7150static struct value *ada_index_struct_field_1 (int *, struct value *,
7151 int, struct type *);
7152
7153
7154/* Return field #INDEX in ARG, where the index is that returned by
7155 * find_struct_field through its INDEX_P argument. Adjust the address
7156 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
0963b4bd 7157 * If found, return value, else return NULL. */
52ce6436
PH
7158
7159static struct value *
7160ada_index_struct_field (int index, struct value *arg, int offset,
7161 struct type *type)
7162{
7163 return ada_index_struct_field_1 (&index, arg, offset, type);
7164}
7165
7166
7167/* Auxiliary function for ada_index_struct_field. Like
7168 * ada_index_struct_field, but takes index from *INDEX_P and modifies
0963b4bd 7169 * *INDEX_P. */
52ce6436
PH
7170
7171static struct value *
7172ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7173 struct type *type)
7174{
7175 int i;
7176 type = ada_check_typedef (type);
7177
1f704f76 7178 for (i = 0; i < type->num_fields (); i += 1)
52ce6436 7179 {
33d16dd9 7180 if (type->field (i).name () == NULL)
dda83cd7 7181 continue;
52ce6436 7182 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7183 {
7184 struct value *v = /* Do not let indent join lines here. */
7185 ada_index_struct_field_1 (index_p, arg,
b610c045 7186 offset + type->field (i).loc_bitpos () / 8,
940da03e 7187 type->field (i).type ());
5b4ee69b 7188
dda83cd7
SM
7189 if (v != NULL)
7190 return v;
7191 }
52ce6436
PH
7192
7193 else if (ada_is_variant_part (type, i))
dda83cd7 7194 {
52ce6436 7195 /* PNH: Do we ever get here? See ada_search_struct_field,
0963b4bd 7196 find_struct_field. */
52ce6436 7197 error (_("Cannot assign this kind of variant record"));
dda83cd7 7198 }
52ce6436 7199 else if (*index_p == 0)
dda83cd7 7200 return ada_value_primitive_field (arg, offset, i, type);
52ce6436
PH
7201 else
7202 *index_p -= 1;
7203 }
7204 return NULL;
7205}
7206
3b4de39c 7207/* Return a string representation of type TYPE. */
99bbb428 7208
3b4de39c 7209static std::string
99bbb428
PA
7210type_as_string (struct type *type)
7211{
d7e74731 7212 string_file tmp_stream;
99bbb428 7213
d7e74731 7214 type_print (type, "", &tmp_stream, -1);
99bbb428 7215
5d10a204 7216 return tmp_stream.release ();
99bbb428
PA
7217}
7218
14f9c5c9 7219/* Given a type TYPE, look up the type of the component of type named NAME.
14f9c5c9
AS
7220
7221 Matches any field whose name has NAME as a prefix, possibly
4c4b4cd2 7222 followed by "___".
14f9c5c9 7223
0963b4bd 7224 TYPE can be either a struct or union. If REFOK, TYPE may also
4c4b4cd2
PH
7225 be a (pointer or reference)+ to a struct or union, and the
7226 ultimate target type will be searched.
14f9c5c9
AS
7227
7228 Looks recursively into variant clauses and parent types.
7229
828d5846
XR
7230 In the case of homonyms in the tagged types, please refer to the
7231 long explanation in find_struct_field's function documentation.
7232
4c4b4cd2
PH
7233 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7234 TYPE is not a type of the right kind. */
14f9c5c9 7235
4c4b4cd2 7236static struct type *
a121b7c1 7237ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
dda83cd7 7238 int noerr)
14f9c5c9 7239{
14f9c5c9
AS
7240 if (name == NULL)
7241 goto BadName;
7242
76a01679 7243 if (refok && type != NULL)
4c4b4cd2
PH
7244 while (1)
7245 {
dda83cd7
SM
7246 type = ada_check_typedef (type);
7247 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7248 break;
27710edb 7249 type = type->target_type ();
4c4b4cd2 7250 }
14f9c5c9 7251
76a01679 7252 if (type == NULL
78134374
SM
7253 || (type->code () != TYPE_CODE_STRUCT
7254 && type->code () != TYPE_CODE_UNION))
14f9c5c9 7255 {
4c4b4cd2 7256 if (noerr)
dda83cd7 7257 return NULL;
99bbb428 7258
3b4de39c
PA
7259 error (_("Type %s is not a structure or union type"),
7260 type != NULL ? type_as_string (type).c_str () : _("(null)"));
14f9c5c9
AS
7261 }
7262
7263 type = to_static_fixed_type (type);
7264
f0874f41
TT
7265 struct type *result;
7266 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7267 nullptr);
7268 if (result != nullptr)
7269 return result;
828d5846 7270
14f9c5c9 7271BadName:
d2e4a39e 7272 if (!noerr)
14f9c5c9 7273 {
2b2798cc 7274 const char *name_str = name != NULL ? name : _("<null>");
99bbb428
PA
7275
7276 error (_("Type %s has no component named %s"),
3b4de39c 7277 type_as_string (type).c_str (), name_str);
14f9c5c9
AS
7278 }
7279
7280 return NULL;
7281}
7282
b1f33ddd
JB
7283/* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7284 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7285 represents an unchecked union (that is, the variant part of a
0963b4bd 7286 record that is named in an Unchecked_Union pragma). */
b1f33ddd
JB
7287
7288static int
7289is_unchecked_variant (struct type *var_type, struct type *outer_type)
7290{
a121b7c1 7291 const char *discrim_name = ada_variant_discrim_name (var_type);
5b4ee69b 7292
988f6b3d 7293 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
b1f33ddd
JB
7294}
7295
7296
14f9c5c9 7297/* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
d8af9068 7298 within OUTER, determine which variant clause (field number in VAR_TYPE,
4c4b4cd2 7299 numbering from 0) is applicable. Returns -1 if none are. */
14f9c5c9 7300
d2e4a39e 7301int
d8af9068 7302ada_which_variant_applies (struct type *var_type, struct value *outer)
14f9c5c9
AS
7303{
7304 int others_clause;
7305 int i;
a121b7c1 7306 const char *discrim_name = ada_variant_discrim_name (var_type);
0c281816 7307 struct value *discrim;
14f9c5c9
AS
7308 LONGEST discrim_val;
7309
012370f6
TT
7310 /* Using plain value_from_contents_and_address here causes problems
7311 because we will end up trying to resolve a type that is currently
7312 being constructed. */
0c281816
JB
7313 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7314 if (discrim == NULL)
14f9c5c9 7315 return -1;
0c281816 7316 discrim_val = value_as_long (discrim);
14f9c5c9
AS
7317
7318 others_clause = -1;
1f704f76 7319 for (i = 0; i < var_type->num_fields (); i += 1)
14f9c5c9
AS
7320 {
7321 if (ada_is_others_clause (var_type, i))
dda83cd7 7322 others_clause = i;
14f9c5c9 7323 else if (ada_in_variant (discrim_val, var_type, i))
dda83cd7 7324 return i;
14f9c5c9
AS
7325 }
7326
7327 return others_clause;
7328}
d2e4a39e 7329\f
14f9c5c9
AS
7330
7331
dda83cd7 7332 /* Dynamic-Sized Records */
14f9c5c9
AS
7333
7334/* Strategy: The type ostensibly attached to a value with dynamic size
7335 (i.e., a size that is not statically recorded in the debugging
7336 data) does not accurately reflect the size or layout of the value.
7337 Our strategy is to convert these values to values with accurate,
4c4b4cd2 7338 conventional types that are constructed on the fly. */
14f9c5c9
AS
7339
7340/* There is a subtle and tricky problem here. In general, we cannot
7341 determine the size of dynamic records without its data. However,
7342 the 'struct value' data structure, which GDB uses to represent
7343 quantities in the inferior process (the target), requires the size
7344 of the type at the time of its allocation in order to reserve space
7345 for GDB's internal copy of the data. That's why the
7346 'to_fixed_xxx_type' routines take (target) addresses as parameters,
4c4b4cd2 7347 rather than struct value*s.
14f9c5c9
AS
7348
7349 However, GDB's internal history variables ($1, $2, etc.) are
7350 struct value*s containing internal copies of the data that are not, in
7351 general, the same as the data at their corresponding addresses in
7352 the target. Fortunately, the types we give to these values are all
7353 conventional, fixed-size types (as per the strategy described
7354 above), so that we don't usually have to perform the
7355 'to_fixed_xxx_type' conversions to look at their values.
7356 Unfortunately, there is one exception: if one of the internal
7357 history variables is an array whose elements are unconstrained
7358 records, then we will need to create distinct fixed types for each
7359 element selected. */
7360
7361/* The upshot of all of this is that many routines take a (type, host
7362 address, target address) triple as arguments to represent a value.
7363 The host address, if non-null, is supposed to contain an internal
7364 copy of the relevant data; otherwise, the program is to consult the
4c4b4cd2 7365 target at the target address. */
14f9c5c9
AS
7366
7367/* Assuming that VAL0 represents a pointer value, the result of
7368 dereferencing it. Differs from value_ind in its treatment of
4c4b4cd2 7369 dynamic-sized types. */
14f9c5c9 7370
d2e4a39e
AS
7371struct value *
7372ada_value_ind (struct value *val0)
14f9c5c9 7373{
c48db5ca 7374 struct value *val = value_ind (val0);
5b4ee69b 7375
d0c97917 7376 if (ada_is_tagged_type (val->type (), 0))
b50d69b5
JG
7377 val = ada_tag_value_at_base_address (val);
7378
4c4b4cd2 7379 return ada_to_fixed_value (val);
14f9c5c9
AS
7380}
7381
7382/* The value resulting from dereferencing any "reference to"
4c4b4cd2
PH
7383 qualifiers on VAL0. */
7384
d2e4a39e
AS
7385static struct value *
7386ada_coerce_ref (struct value *val0)
7387{
d0c97917 7388 if (val0->type ()->code () == TYPE_CODE_REF)
d2e4a39e
AS
7389 {
7390 struct value *val = val0;
5b4ee69b 7391
994b9211 7392 val = coerce_ref (val);
b50d69b5 7393
d0c97917 7394 if (ada_is_tagged_type (val->type (), 0))
b50d69b5
JG
7395 val = ada_tag_value_at_base_address (val);
7396
4c4b4cd2 7397 return ada_to_fixed_value (val);
d2e4a39e
AS
7398 }
7399 else
14f9c5c9
AS
7400 return val0;
7401}
7402
4c4b4cd2 7403/* Return the bit alignment required for field #F of template type TYPE. */
14f9c5c9
AS
7404
7405static unsigned int
ebf56fd3 7406field_alignment (struct type *type, int f)
14f9c5c9 7407{
33d16dd9 7408 const char *name = type->field (f).name ();
64a1bf19 7409 int len;
14f9c5c9
AS
7410 int align_offset;
7411
64a1bf19
JB
7412 /* The field name should never be null, unless the debugging information
7413 is somehow malformed. In this case, we assume the field does not
7414 require any alignment. */
7415 if (name == NULL)
7416 return 1;
7417
7418 len = strlen (name);
7419
4c4b4cd2
PH
7420 if (!isdigit (name[len - 1]))
7421 return 1;
14f9c5c9 7422
d2e4a39e 7423 if (isdigit (name[len - 2]))
14f9c5c9
AS
7424 align_offset = len - 2;
7425 else
7426 align_offset = len - 1;
7427
61012eef 7428 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
14f9c5c9
AS
7429 return TARGET_CHAR_BIT;
7430
4c4b4cd2
PH
7431 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7432}
7433
852dff6c 7434/* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
4c4b4cd2 7435
852dff6c
JB
7436static struct symbol *
7437ada_find_any_type_symbol (const char *name)
4c4b4cd2 7438{
54d186cf
TT
7439 return standard_lookup (name, get_selected_block (nullptr),
7440 SEARCH_TYPE_DOMAIN);
14f9c5c9
AS
7441}
7442
dddfab26
UW
7443/* Find a type named NAME. Ignores ambiguity. This routine will look
7444 solely for types defined by debug info, it will not search the GDB
7445 primitive types. */
4c4b4cd2 7446
852dff6c 7447static struct type *
ebf56fd3 7448ada_find_any_type (const char *name)
14f9c5c9 7449{
852dff6c 7450 struct symbol *sym = ada_find_any_type_symbol (name);
14f9c5c9 7451
14f9c5c9 7452 if (sym != NULL)
5f9c5a63 7453 return sym->type ();
14f9c5c9 7454
dddfab26 7455 return NULL;
14f9c5c9
AS
7456}
7457
739593e0
JB
7458/* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7459 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7460 symbol, in which case it is returned. Otherwise, this looks for
7461 symbols whose name is that of NAME_SYM suffixed with "___XR".
7462 Return symbol if found, and NULL otherwise. */
4c4b4cd2 7463
c0e70c62
TT
7464static bool
7465ada_is_renaming_symbol (struct symbol *name_sym)
aeb5907d 7466{
987012b8 7467 const char *name = name_sym->linkage_name ();
c0e70c62 7468 return strstr (name, "___XR") != NULL;
4c4b4cd2
PH
7469}
7470
14f9c5c9 7471/* Because of GNAT encoding conventions, several GDB symbols may match a
4c4b4cd2 7472 given type name. If the type denoted by TYPE0 is to be preferred to
14f9c5c9 7473 that of TYPE1 for purposes of type printing, return non-zero;
4c4b4cd2
PH
7474 otherwise return 0. */
7475
14f9c5c9 7476int
d2e4a39e 7477ada_prefer_type (struct type *type0, struct type *type1)
14f9c5c9
AS
7478{
7479 if (type1 == NULL)
7480 return 1;
7481 else if (type0 == NULL)
7482 return 0;
78134374 7483 else if (type1->code () == TYPE_CODE_VOID)
14f9c5c9 7484 return 1;
78134374 7485 else if (type0->code () == TYPE_CODE_VOID)
14f9c5c9 7486 return 0;
7d93a1e0 7487 else if (type1->name () == NULL && type0->name () != NULL)
4c4b4cd2 7488 return 1;
ad82864c 7489 else if (ada_is_constrained_packed_array_type (type0))
14f9c5c9 7490 return 1;
4c4b4cd2 7491 else if (ada_is_array_descriptor_type (type0)
dda83cd7 7492 && !ada_is_array_descriptor_type (type1))
14f9c5c9 7493 return 1;
aeb5907d
JB
7494 else
7495 {
7d93a1e0
SM
7496 const char *type0_name = type0->name ();
7497 const char *type1_name = type1->name ();
aeb5907d
JB
7498
7499 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7500 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7501 return 1;
7502 }
14f9c5c9
AS
7503 return 0;
7504}
7505
e86ca25f
TT
7506/* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7507 null. */
4c4b4cd2 7508
0d5cff50 7509const char *
d2e4a39e 7510ada_type_name (struct type *type)
14f9c5c9 7511{
d2e4a39e 7512 if (type == NULL)
14f9c5c9 7513 return NULL;
7d93a1e0 7514 return type->name ();
14f9c5c9
AS
7515}
7516
b4ba55a1
JB
7517/* Search the list of "descriptive" types associated to TYPE for a type
7518 whose name is NAME. */
7519
7520static struct type *
7521find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7522{
931e5bc3 7523 struct type *result, *tmp;
b4ba55a1 7524
c6044dd1
JB
7525 if (ada_ignore_descriptive_types_p)
7526 return NULL;
7527
b4ba55a1
JB
7528 /* If there no descriptive-type info, then there is no parallel type
7529 to be found. */
7530 if (!HAVE_GNAT_AUX_INFO (type))
7531 return NULL;
7532
7533 result = TYPE_DESCRIPTIVE_TYPE (type);
7534 while (result != NULL)
7535 {
0d5cff50 7536 const char *result_name = ada_type_name (result);
b4ba55a1
JB
7537
7538 if (result_name == NULL)
dda83cd7
SM
7539 {
7540 warning (_("unexpected null name on descriptive type"));
7541 return NULL;
7542 }
b4ba55a1
JB
7543
7544 /* If the names match, stop. */
7545 if (strcmp (result_name, name) == 0)
7546 break;
7547
7548 /* Otherwise, look at the next item on the list, if any. */
7549 if (HAVE_GNAT_AUX_INFO (result))
931e5bc3
JG
7550 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7551 else
7552 tmp = NULL;
7553
7554 /* If not found either, try after having resolved the typedef. */
7555 if (tmp != NULL)
7556 result = tmp;
b4ba55a1 7557 else
931e5bc3 7558 {
f168693b 7559 result = check_typedef (result);
931e5bc3
JG
7560 if (HAVE_GNAT_AUX_INFO (result))
7561 result = TYPE_DESCRIPTIVE_TYPE (result);
7562 else
7563 result = NULL;
7564 }
b4ba55a1
JB
7565 }
7566
7567 /* If we didn't find a match, see whether this is a packed array. With
7568 older compilers, the descriptive type information is either absent or
7569 irrelevant when it comes to packed arrays so the above lookup fails.
7570 Fall back to using a parallel lookup by name in this case. */
12ab9e09 7571 if (result == NULL && ada_is_constrained_packed_array_type (type))
b4ba55a1
JB
7572 return ada_find_any_type (name);
7573
7574 return result;
7575}
7576
7577/* Find a parallel type to TYPE with the specified NAME, using the
7578 descriptive type taken from the debugging information, if available,
7579 and otherwise using the (slower) name-based method. */
7580
7581static struct type *
7582ada_find_parallel_type_with_name (struct type *type, const char *name)
7583{
7584 struct type *result = NULL;
7585
7586 if (HAVE_GNAT_AUX_INFO (type))
7587 result = find_parallel_type_by_descriptive_type (type, name);
7588 else
7589 result = ada_find_any_type (name);
7590
7591 return result;
7592}
7593
7594/* Same as above, but specify the name of the parallel type by appending
4c4b4cd2 7595 SUFFIX to the name of TYPE. */
14f9c5c9 7596
d2e4a39e 7597struct type *
ebf56fd3 7598ada_find_parallel_type (struct type *type, const char *suffix)
14f9c5c9 7599{
0d5cff50 7600 char *name;
fe978cb0 7601 const char *type_name = ada_type_name (type);
14f9c5c9 7602 int len;
d2e4a39e 7603
fe978cb0 7604 if (type_name == NULL)
14f9c5c9
AS
7605 return NULL;
7606
fe978cb0 7607 len = strlen (type_name);
14f9c5c9 7608
b4ba55a1 7609 name = (char *) alloca (len + strlen (suffix) + 1);
14f9c5c9 7610
fe978cb0 7611 strcpy (name, type_name);
14f9c5c9
AS
7612 strcpy (name + len, suffix);
7613
b4ba55a1 7614 return ada_find_parallel_type_with_name (type, name);
14f9c5c9
AS
7615}
7616
14f9c5c9 7617/* If TYPE is a variable-size record type, return the corresponding template
4c4b4cd2 7618 type describing its fields. Otherwise, return NULL. */
14f9c5c9 7619
d2e4a39e
AS
7620static struct type *
7621dynamic_template_type (struct type *type)
14f9c5c9 7622{
61ee279c 7623 type = ada_check_typedef (type);
14f9c5c9 7624
78134374 7625 if (type == NULL || type->code () != TYPE_CODE_STRUCT
d2e4a39e 7626 || ada_type_name (type) == NULL)
14f9c5c9 7627 return NULL;
d2e4a39e 7628 else
14f9c5c9
AS
7629 {
7630 int len = strlen (ada_type_name (type));
5b4ee69b 7631
4c4b4cd2 7632 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
dda83cd7 7633 return type;
14f9c5c9 7634 else
dda83cd7 7635 return ada_find_parallel_type (type, "___XVE");
14f9c5c9
AS
7636 }
7637}
7638
7639/* Assuming that TEMPL_TYPE is a union or struct type, returns
4c4b4cd2 7640 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
14f9c5c9 7641
d2e4a39e
AS
7642static int
7643is_dynamic_field (struct type *templ_type, int field_num)
14f9c5c9 7644{
33d16dd9 7645 const char *name = templ_type->field (field_num).name ();
5b4ee69b 7646
d2e4a39e 7647 return name != NULL
940da03e 7648 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
14f9c5c9
AS
7649 && strstr (name, "___XVL") != NULL;
7650}
7651
4c4b4cd2
PH
7652/* The index of the variant field of TYPE, or -1 if TYPE does not
7653 represent a variant record type. */
14f9c5c9 7654
d2e4a39e 7655static int
4c4b4cd2 7656variant_field_index (struct type *type)
14f9c5c9
AS
7657{
7658 int f;
7659
78134374 7660 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
4c4b4cd2
PH
7661 return -1;
7662
1f704f76 7663 for (f = 0; f < type->num_fields (); f += 1)
4c4b4cd2
PH
7664 {
7665 if (ada_is_variant_part (type, f))
dda83cd7 7666 return f;
4c4b4cd2
PH
7667 }
7668 return -1;
14f9c5c9
AS
7669}
7670
4c4b4cd2
PH
7671/* A record type with no fields. */
7672
d2e4a39e 7673static struct type *
fe978cb0 7674empty_record (struct type *templ)
14f9c5c9 7675{
9fa83a7a 7676 struct type *type = type_allocator (templ).new_type ();
5b4ee69b 7677
67607e24 7678 type->set_code (TYPE_CODE_STRUCT);
8ecb59f8 7679 INIT_NONE_SPECIFIC (type);
d0e39ea2 7680 type->set_name ("<empty>");
b6cdbc9a 7681 type->set_length (0);
14f9c5c9
AS
7682 return type;
7683}
7684
7685/* An ordinary record type (with fixed-length fields) that describes
4c4b4cd2
PH
7686 the value of type TYPE at VALADDR or ADDRESS (see comments at
7687 the beginning of this section) VAL according to GNAT conventions.
7688 DVAL0 should describe the (portion of a) record that contains any
d0c97917 7689 necessary discriminants. It should be NULL if VAL->type () is
14f9c5c9
AS
7690 an outer-level type (i.e., as opposed to a branch of a variant.) A
7691 variant field (unless unchecked) is replaced by a particular branch
4c4b4cd2 7692 of the variant.
14f9c5c9 7693
4c4b4cd2
PH
7694 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7695 length are not statically known are discarded. As a consequence,
7696 VALADDR, ADDRESS and DVAL0 are ignored.
7697
7698 NOTE: Limitations: For now, we assume that dynamic fields and
7699 variants occupy whole numbers of bytes. However, they need not be
7700 byte-aligned. */
7701
7702struct type *
10a2c479 7703ada_template_to_fixed_record_type_1 (struct type *type,
fc1a4b47 7704 const gdb_byte *valaddr,
dda83cd7
SM
7705 CORE_ADDR address, struct value *dval0,
7706 int keep_dynamic_fields)
14f9c5c9 7707{
d2e4a39e
AS
7708 struct value *dval;
7709 struct type *rtype;
14f9c5c9 7710 int nfields, bit_len;
4c4b4cd2 7711 int variant_field;
14f9c5c9 7712 long off;
d94e4f4f 7713 int fld_bit_len;
14f9c5c9
AS
7714 int f;
7715
65558ca5
TT
7716 scoped_value_mark mark;
7717
4c4b4cd2
PH
7718 /* Compute the number of fields in this record type that are going
7719 to be processed: unless keep_dynamic_fields, this includes only
7720 fields whose position and length are static will be processed. */
7721 if (keep_dynamic_fields)
1f704f76 7722 nfields = type->num_fields ();
4c4b4cd2
PH
7723 else
7724 {
7725 nfields = 0;
1f704f76 7726 while (nfields < type->num_fields ()
dda83cd7
SM
7727 && !ada_is_variant_part (type, nfields)
7728 && !is_dynamic_field (type, nfields))
7729 nfields++;
4c4b4cd2
PH
7730 }
7731
9fa83a7a 7732 rtype = type_allocator (type).new_type ();
67607e24 7733 rtype->set_code (TYPE_CODE_STRUCT);
8ecb59f8 7734 INIT_NONE_SPECIFIC (rtype);
2774f2da 7735 rtype->alloc_fields (nfields);
d0e39ea2 7736 rtype->set_name (ada_type_name (type));
9cdd0d12 7737 rtype->set_is_fixed_instance (true);
14f9c5c9 7738
d2e4a39e
AS
7739 off = 0;
7740 bit_len = 0;
4c4b4cd2
PH
7741 variant_field = -1;
7742
14f9c5c9
AS
7743 for (f = 0; f < nfields; f += 1)
7744 {
a89febbd 7745 off = align_up (off, field_alignment (type, f))
b610c045 7746 + type->field (f).loc_bitpos ();
cd3f655c 7747 rtype->field (f).set_loc_bitpos (off);
886176b8 7748 rtype->field (f).set_bitsize (0);
14f9c5c9 7749
d2e4a39e 7750 if (ada_is_variant_part (type, f))
dda83cd7
SM
7751 {
7752 variant_field = f;
7753 fld_bit_len = 0;
7754 }
14f9c5c9 7755 else if (is_dynamic_field (type, f))
dda83cd7 7756 {
284614f0
JB
7757 const gdb_byte *field_valaddr = valaddr;
7758 CORE_ADDR field_address = address;
27710edb 7759 struct type *field_type = type->field (f).type ()->target_type ();
284614f0 7760
dda83cd7 7761 if (dval0 == NULL)
b5304971 7762 {
012370f6
TT
7763 /* Using plain value_from_contents_and_address here
7764 causes problems because we will end up trying to
7765 resolve a type that is currently being
7766 constructed. */
7767 dval = value_from_contents_and_address_unresolved (rtype,
7768 valaddr,
7769 address);
d0c97917 7770 rtype = dval->type ();
b5304971 7771 }
dda83cd7
SM
7772 else
7773 dval = dval0;
4c4b4cd2 7774
284614f0
JB
7775 /* If the type referenced by this field is an aligner type, we need
7776 to unwrap that aligner type, because its size might not be set.
7777 Keeping the aligner type would cause us to compute the wrong
7778 size for this field, impacting the offset of the all the fields
7779 that follow this one. */
7780 if (ada_is_aligner_type (field_type))
7781 {
b610c045 7782 long field_offset = type->field (f).loc_bitpos ();
284614f0
JB
7783
7784 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7785 field_address = cond_offset_target (field_address, field_offset);
7786 field_type = ada_aligned_type (field_type);
7787 }
7788
7789 field_valaddr = cond_offset_host (field_valaddr,
7790 off / TARGET_CHAR_BIT);
7791 field_address = cond_offset_target (field_address,
7792 off / TARGET_CHAR_BIT);
7793
7794 /* Get the fixed type of the field. Note that, in this case,
7795 we do not want to get the real type out of the tag: if
7796 the current field is the parent part of a tagged record,
7797 we will get the tag of the object. Clearly wrong: the real
7798 type of the parent is not the real type of the child. We
7799 would end up in an infinite loop. */
7800 field_type = ada_get_base_type (field_type);
7801 field_type = ada_to_fixed_type (field_type, field_valaddr,
7802 field_address, dval, 0);
7803
5d14b6e5 7804 rtype->field (f).set_type (field_type);
33d16dd9 7805 rtype->field (f).set_name (type->field (f).name ());
27f2a97b
JB
7806 /* The multiplication can potentially overflow. But because
7807 the field length has been size-checked just above, and
7808 assuming that the maximum size is a reasonable value,
7809 an overflow should not happen in practice. So rather than
7810 adding overflow recovery code to this already complex code,
7811 we just assume that it's not going to happen. */
df86565b 7812 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
dda83cd7 7813 }
14f9c5c9 7814 else
dda83cd7 7815 {
5ded5331
JB
7816 /* Note: If this field's type is a typedef, it is important
7817 to preserve the typedef layer.
7818
7819 Otherwise, we might be transforming a typedef to a fat
7820 pointer (encoding a pointer to an unconstrained array),
7821 into a basic fat pointer (encoding an unconstrained
7822 array). As both types are implemented using the same
7823 structure, the typedef is the only clue which allows us
7824 to distinguish between the two options. Stripping it
7825 would prevent us from printing this field appropriately. */
dda83cd7 7826 rtype->field (f).set_type (type->field (f).type ());
33d16dd9 7827 rtype->field (f).set_name (type->field (f).name ());
3757d2d4 7828 if (type->field (f).bitsize () > 0)
886176b8 7829 {
3757d2d4 7830 fld_bit_len = type->field (f).bitsize ();
886176b8
SM
7831 rtype->field (f).set_bitsize (fld_bit_len);
7832 }
dda83cd7 7833 else
5ded5331 7834 {
940da03e 7835 struct type *field_type = type->field (f).type ();
5ded5331
JB
7836
7837 /* We need to be careful of typedefs when computing
7838 the length of our field. If this is a typedef,
7839 get the length of the target type, not the length
7840 of the typedef. */
78134374 7841 if (field_type->code () == TYPE_CODE_TYPEDEF)
5ded5331
JB
7842 field_type = ada_typedef_target_type (field_type);
7843
dda83cd7 7844 fld_bit_len =
df86565b 7845 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
5ded5331 7846 }
dda83cd7 7847 }
14f9c5c9 7848 if (off + fld_bit_len > bit_len)
dda83cd7 7849 bit_len = off + fld_bit_len;
d94e4f4f 7850 off += fld_bit_len;
b6cdbc9a 7851 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
14f9c5c9 7852 }
4c4b4cd2
PH
7853
7854 /* We handle the variant part, if any, at the end because of certain
b1f33ddd 7855 odd cases in which it is re-ordered so as NOT to be the last field of
4c4b4cd2
PH
7856 the record. This can happen in the presence of representation
7857 clauses. */
7858 if (variant_field >= 0)
7859 {
7860 struct type *branch_type;
7861
b610c045 7862 off = rtype->field (variant_field).loc_bitpos ();
4c4b4cd2
PH
7863
7864 if (dval0 == NULL)
9f1f738a 7865 {
012370f6
TT
7866 /* Using plain value_from_contents_and_address here causes
7867 problems because we will end up trying to resolve a type
7868 that is currently being constructed. */
7869 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7870 address);
d0c97917 7871 rtype = dval->type ();
9f1f738a 7872 }
4c4b4cd2 7873 else
dda83cd7 7874 dval = dval0;
4c4b4cd2
PH
7875
7876 branch_type =
dda83cd7
SM
7877 to_fixed_variant_branch_type
7878 (type->field (variant_field).type (),
7879 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7880 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
4c4b4cd2 7881 if (branch_type == NULL)
dda83cd7
SM
7882 {
7883 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7884 rtype->field (f - 1) = rtype->field (f);
5e33d5f4 7885 rtype->set_num_fields (rtype->num_fields () - 1);
dda83cd7 7886 }
4c4b4cd2 7887 else
dda83cd7
SM
7888 {
7889 rtype->field (variant_field).set_type (branch_type);
d3fd12df 7890 rtype->field (variant_field).set_name ("S");
dda83cd7 7891 fld_bit_len =
df86565b 7892 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
dda83cd7
SM
7893 if (off + fld_bit_len > bit_len)
7894 bit_len = off + fld_bit_len;
b6cdbc9a
SM
7895
7896 rtype->set_length
7897 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
dda83cd7 7898 }
4c4b4cd2
PH
7899 }
7900
714e53ab
PH
7901 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7902 should contain the alignment of that record, which should be a strictly
7903 positive value. If null or negative, then something is wrong, most
7904 probably in the debug info. In that case, we don't round up the size
0963b4bd 7905 of the resulting type. If this record is not part of another structure,
714e53ab 7906 the current RTYPE length might be good enough for our purposes. */
df86565b 7907 if (type->length () <= 0)
714e53ab 7908 {
7d93a1e0 7909 if (rtype->name ())
cc1defb1 7910 warning (_("Invalid type size for `%s' detected: %s."),
df86565b 7911 rtype->name (), pulongest (type->length ()));
323e0a4a 7912 else
cc1defb1 7913 warning (_("Invalid type size for <unnamed> detected: %s."),
df86565b 7914 pulongest (type->length ()));
714e53ab
PH
7915 }
7916 else
df86565b 7917 rtype->set_length (align_up (rtype->length (), type->length ()));
14f9c5c9 7918
14f9c5c9
AS
7919 return rtype;
7920}
7921
4c4b4cd2
PH
7922/* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7923 of 1. */
14f9c5c9 7924
d2e4a39e 7925static struct type *
fc1a4b47 7926template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
dda83cd7 7927 CORE_ADDR address, struct value *dval0)
4c4b4cd2
PH
7928{
7929 return ada_template_to_fixed_record_type_1 (type, valaddr,
dda83cd7 7930 address, dval0, 1);
4c4b4cd2
PH
7931}
7932
7933/* An ordinary record type in which ___XVL-convention fields and
7934 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
7935 static approximations, containing all possible fields. Uses
7936 no runtime values. Useless for use in values, but that's OK,
7937 since the results are used only for type determinations. Works on both
7938 structs and unions. Representation note: to save space, we memorize
27710edb 7939 the result of this function in the type::target_type of the
4c4b4cd2
PH
7940 template type. */
7941
7942static struct type *
7943template_to_static_fixed_type (struct type *type0)
14f9c5c9
AS
7944{
7945 struct type *type;
7946 int nfields;
7947 int f;
7948
9e195661 7949 /* No need no do anything if the input type is already fixed. */
22c4c60c 7950 if (type0->is_fixed_instance ())
9e195661
PMR
7951 return type0;
7952
7953 /* Likewise if we already have computed the static approximation. */
27710edb
SM
7954 if (type0->target_type () != NULL)
7955 return type0->target_type ();
4c4b4cd2 7956
9e195661 7957 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
4c4b4cd2 7958 type = type0;
1f704f76 7959 nfields = type0->num_fields ();
9e195661
PMR
7960
7961 /* Whether or not we cloned TYPE0, cache the result so that we don't do
7962 recompute all over next time. */
8a50fdce 7963 type0->set_target_type (type);
14f9c5c9
AS
7964
7965 for (f = 0; f < nfields; f += 1)
7966 {
940da03e 7967 struct type *field_type = type0->field (f).type ();
4c4b4cd2 7968 struct type *new_type;
14f9c5c9 7969
4c4b4cd2 7970 if (is_dynamic_field (type0, f))
460efde1
JB
7971 {
7972 field_type = ada_check_typedef (field_type);
27710edb 7973 new_type = to_static_fixed_type (field_type->target_type ());
460efde1 7974 }
14f9c5c9 7975 else
dda83cd7 7976 new_type = static_unwrap_type (field_type);
9e195661
PMR
7977
7978 if (new_type != field_type)
7979 {
7980 /* Clone TYPE0 only the first time we get a new field type. */
7981 if (type == type0)
7982 {
9fa83a7a 7983 type = type_allocator (type0).new_type ();
8a50fdce 7984 type0->set_target_type (type);
78134374 7985 type->set_code (type0->code ());
8ecb59f8 7986 INIT_NONE_SPECIFIC (type);
3cabb6b0 7987
2774f2da 7988 type->copy_fields (type0);
3cabb6b0 7989
d0e39ea2 7990 type->set_name (ada_type_name (type0));
9cdd0d12 7991 type->set_is_fixed_instance (true);
b6cdbc9a 7992 type->set_length (0);
9e195661 7993 }
5d14b6e5 7994 type->field (f).set_type (new_type);
33d16dd9 7995 type->field (f).set_name (type0->field (f).name ());
9e195661 7996 }
14f9c5c9 7997 }
9e195661 7998
14f9c5c9
AS
7999 return type;
8000}
8001
4c4b4cd2 8002/* Given an object of type TYPE whose contents are at VALADDR and
5823c3ef
JB
8003 whose address in memory is ADDRESS, returns a revision of TYPE,
8004 which should be a non-dynamic-sized record, in which the variant
8005 part, if any, is replaced with the appropriate branch. Looks
4c4b4cd2
PH
8006 for discriminant values in DVAL0, which can be NULL if the record
8007 contains the necessary discriminant values. */
8008
d2e4a39e 8009static struct type *
fc1a4b47 8010to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
dda83cd7 8011 CORE_ADDR address, struct value *dval0)
14f9c5c9 8012{
4c4b4cd2 8013 struct value *dval;
d2e4a39e 8014 struct type *rtype;
14f9c5c9 8015 struct type *branch_type;
1f704f76 8016 int nfields = type->num_fields ();
4c4b4cd2 8017 int variant_field = variant_field_index (type);
14f9c5c9 8018
4c4b4cd2 8019 if (variant_field == -1)
14f9c5c9
AS
8020 return type;
8021
65558ca5 8022 scoped_value_mark mark;
4c4b4cd2 8023 if (dval0 == NULL)
9f1f738a
SA
8024 {
8025 dval = value_from_contents_and_address (type, valaddr, address);
d0c97917 8026 type = dval->type ();
9f1f738a 8027 }
4c4b4cd2
PH
8028 else
8029 dval = dval0;
8030
9fa83a7a 8031 rtype = type_allocator (type).new_type ();
67607e24 8032 rtype->set_code (TYPE_CODE_STRUCT);
8ecb59f8 8033 INIT_NONE_SPECIFIC (rtype);
2774f2da 8034 rtype->copy_fields (type);
3cabb6b0 8035
d0e39ea2 8036 rtype->set_name (ada_type_name (type));
9cdd0d12 8037 rtype->set_is_fixed_instance (true);
df86565b 8038 rtype->set_length (type->length ());
14f9c5c9 8039
4c4b4cd2 8040 branch_type = to_fixed_variant_branch_type
940da03e 8041 (type->field (variant_field).type (),
d2e4a39e 8042 cond_offset_host (valaddr,
b610c045 8043 type->field (variant_field).loc_bitpos ()
dda83cd7 8044 / TARGET_CHAR_BIT),
d2e4a39e 8045 cond_offset_target (address,
b610c045 8046 type->field (variant_field).loc_bitpos ()
dda83cd7 8047 / TARGET_CHAR_BIT), dval);
d2e4a39e 8048 if (branch_type == NULL)
14f9c5c9 8049 {
4c4b4cd2 8050 int f;
5b4ee69b 8051
4c4b4cd2 8052 for (f = variant_field + 1; f < nfields; f += 1)
dda83cd7 8053 rtype->field (f - 1) = rtype->field (f);
5e33d5f4 8054 rtype->set_num_fields (rtype->num_fields () - 1);
14f9c5c9
AS
8055 }
8056 else
8057 {
5d14b6e5 8058 rtype->field (variant_field).set_type (branch_type);
d3fd12df 8059 rtype->field (variant_field).set_name ("S");
886176b8 8060 rtype->field (variant_field).set_bitsize (0);
df86565b 8061 rtype->set_length (rtype->length () + branch_type->length ());
14f9c5c9 8062 }
b6cdbc9a 8063
df86565b
SM
8064 rtype->set_length (rtype->length ()
8065 - type->field (variant_field).type ()->length ());
d2e4a39e 8066
14f9c5c9
AS
8067 return rtype;
8068}
8069
8070/* An ordinary record type (with fixed-length fields) that describes
8071 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8072 beginning of this section]. Any necessary discriminants' values
4c4b4cd2
PH
8073 should be in DVAL, a record value; it may be NULL if the object
8074 at ADDR itself contains any necessary discriminant values.
8075 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8076 values from the record are needed. Except in the case that DVAL,
8077 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8078 unchecked) is replaced by a particular branch of the variant.
8079
8080 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8081 is questionable and may be removed. It can arise during the
8082 processing of an unconstrained-array-of-record type where all the
8083 variant branches have exactly the same size. This is because in
8084 such cases, the compiler does not bother to use the XVS convention
8085 when encoding the record. I am currently dubious of this
8086 shortcut and suspect the compiler should be altered. FIXME. */
14f9c5c9 8087
d2e4a39e 8088static struct type *
fc1a4b47 8089to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
dda83cd7 8090 CORE_ADDR address, struct value *dval)
14f9c5c9 8091{
d2e4a39e 8092 struct type *templ_type;
14f9c5c9 8093
22c4c60c 8094 if (type0->is_fixed_instance ())
4c4b4cd2
PH
8095 return type0;
8096
d2e4a39e 8097 templ_type = dynamic_template_type (type0);
14f9c5c9
AS
8098
8099 if (templ_type != NULL)
8100 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
4c4b4cd2
PH
8101 else if (variant_field_index (type0) >= 0)
8102 {
8103 if (dval == NULL && valaddr == NULL && address == 0)
dda83cd7 8104 return type0;
4c4b4cd2 8105 return to_record_with_fixed_variant_part (type0, valaddr, address,
dda83cd7 8106 dval);
4c4b4cd2 8107 }
14f9c5c9
AS
8108 else
8109 {
9cdd0d12 8110 type0->set_is_fixed_instance (true);
14f9c5c9
AS
8111 return type0;
8112 }
8113
8114}
8115
8116/* An ordinary record type (with fixed-length fields) that describes
8117 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8118 union type. Any necessary discriminants' values should be in DVAL,
8119 a record value. That is, this routine selects the appropriate
8120 branch of the union at ADDR according to the discriminant value
b1f33ddd 8121 indicated in the union's type name. Returns VAR_TYPE0 itself if
0963b4bd 8122 it represents a variant subject to a pragma Unchecked_Union. */
14f9c5c9 8123
d2e4a39e 8124static struct type *
fc1a4b47 8125to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
dda83cd7 8126 CORE_ADDR address, struct value *dval)
14f9c5c9
AS
8127{
8128 int which;
d2e4a39e
AS
8129 struct type *templ_type;
8130 struct type *var_type;
14f9c5c9 8131
78134374 8132 if (var_type0->code () == TYPE_CODE_PTR)
27710edb 8133 var_type = var_type0->target_type ();
d2e4a39e 8134 else
14f9c5c9
AS
8135 var_type = var_type0;
8136
8137 templ_type = ada_find_parallel_type (var_type, "___XVU");
8138
8139 if (templ_type != NULL)
8140 var_type = templ_type;
8141
d0c97917 8142 if (is_unchecked_variant (var_type, dval->type ()))
b1f33ddd 8143 return var_type0;
d8af9068 8144 which = ada_which_variant_applies (var_type, dval);
14f9c5c9
AS
8145
8146 if (which < 0)
e9bb382b 8147 return empty_record (var_type);
14f9c5c9 8148 else if (is_dynamic_field (var_type, which))
4c4b4cd2 8149 return to_fixed_record_type
27710edb 8150 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
940da03e 8151 else if (variant_field_index (var_type->field (which).type ()) >= 0)
d2e4a39e
AS
8152 return
8153 to_fixed_record_type
940da03e 8154 (var_type->field (which).type (), valaddr, address, dval);
14f9c5c9 8155 else
940da03e 8156 return var_type->field (which).type ();
14f9c5c9
AS
8157}
8158
8908fca5
JB
8159/* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8160 ENCODING_TYPE, a type following the GNAT conventions for discrete
8161 type encodings, only carries redundant information. */
8162
8163static int
8164ada_is_redundant_range_encoding (struct type *range_type,
8165 struct type *encoding_type)
8166{
108d56a4 8167 const char *bounds_str;
8908fca5
JB
8168 int n;
8169 LONGEST lo, hi;
8170
78134374 8171 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8908fca5 8172
78134374
SM
8173 if (get_base_type (range_type)->code ()
8174 != get_base_type (encoding_type)->code ())
005e2509
JB
8175 {
8176 /* The compiler probably used a simple base type to describe
8177 the range type instead of the range's actual base type,
8178 expecting us to get the real base type from the encoding
8179 anyway. In this situation, the encoding cannot be ignored
8180 as redundant. */
8181 return 0;
8182 }
8183
8908fca5
JB
8184 if (is_dynamic_type (range_type))
8185 return 0;
8186
7d93a1e0 8187 if (encoding_type->name () == NULL)
8908fca5
JB
8188 return 0;
8189
7d93a1e0 8190 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8908fca5
JB
8191 if (bounds_str == NULL)
8192 return 0;
8193
8194 n = 8; /* Skip "___XDLU_". */
8195 if (!ada_scan_number (bounds_str, n, &lo, &n))
8196 return 0;
5537ddd0 8197 if (range_type->bounds ()->low.const_val () != lo)
8908fca5
JB
8198 return 0;
8199
8200 n += 2; /* Skip the "__" separator between the two bounds. */
8201 if (!ada_scan_number (bounds_str, n, &hi, &n))
8202 return 0;
5537ddd0 8203 if (range_type->bounds ()->high.const_val () != hi)
8908fca5
JB
8204 return 0;
8205
8206 return 1;
8207}
8208
8209/* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8210 a type following the GNAT encoding for describing array type
8211 indices, only carries redundant information. */
8212
8213static int
8214ada_is_redundant_index_type_desc (struct type *array_type,
8215 struct type *desc_type)
8216{
8217 struct type *this_layer = check_typedef (array_type);
8218 int i;
8219
1f704f76 8220 for (i = 0; i < desc_type->num_fields (); i++)
8908fca5 8221 {
3d967001 8222 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
940da03e 8223 desc_type->field (i).type ()))
8908fca5 8224 return 0;
27710edb 8225 this_layer = check_typedef (this_layer->target_type ());
8908fca5
JB
8226 }
8227
8228 return 1;
8229}
8230
14f9c5c9
AS
8231/* Assuming that TYPE0 is an array type describing the type of a value
8232 at ADDR, and that DVAL describes a record containing any
8233 discriminants used in TYPE0, returns a type for the value that
8234 contains no dynamic components (that is, no components whose sizes
8235 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8236 true, gives an error message if the resulting type's size is over
4c4b4cd2 8237 varsize_limit. */
14f9c5c9 8238
d2e4a39e
AS
8239static struct type *
8240to_fixed_array_type (struct type *type0, struct value *dval,
dda83cd7 8241 int ignore_too_big)
14f9c5c9 8242{
d2e4a39e
AS
8243 struct type *index_type_desc;
8244 struct type *result;
ad82864c 8245 int constrained_packed_array_p;
931e5bc3 8246 static const char *xa_suffix = "___XA";
14f9c5c9 8247
b0dd7688 8248 type0 = ada_check_typedef (type0);
22c4c60c 8249 if (type0->is_fixed_instance ())
4c4b4cd2 8250 return type0;
14f9c5c9 8251
ad82864c
JB
8252 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8253 if (constrained_packed_array_p)
75fd6a26
TT
8254 {
8255 type0 = decode_constrained_packed_array_type (type0);
8256 if (type0 == nullptr)
8257 error (_("could not decode constrained packed array type"));
8258 }
284614f0 8259
931e5bc3
JG
8260 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8261
8262 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8263 encoding suffixed with 'P' may still be generated. If so,
8264 it should be used to find the XA type. */
8265
8266 if (index_type_desc == NULL)
8267 {
1da0522e 8268 const char *type_name = ada_type_name (type0);
931e5bc3 8269
1da0522e 8270 if (type_name != NULL)
931e5bc3 8271 {
1da0522e 8272 const int len = strlen (type_name);
931e5bc3
JG
8273 char *name = (char *) alloca (len + strlen (xa_suffix));
8274
1da0522e 8275 if (type_name[len - 1] == 'P')
931e5bc3 8276 {
1da0522e 8277 strcpy (name, type_name);
931e5bc3
JG
8278 strcpy (name + len - 1, xa_suffix);
8279 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8280 }
8281 }
8282 }
8283
28c85d6c 8284 ada_fixup_array_indexes_type (index_type_desc);
8908fca5
JB
8285 if (index_type_desc != NULL
8286 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8287 {
8288 /* Ignore this ___XA parallel type, as it does not bring any
8289 useful information. This allows us to avoid creating fixed
8290 versions of the array's index types, which would be identical
8291 to the original ones. This, in turn, can also help avoid
8292 the creation of fixed versions of the array itself. */
8293 index_type_desc = NULL;
8294 }
8295
14f9c5c9
AS
8296 if (index_type_desc == NULL)
8297 {
27710edb 8298 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
5b4ee69b 8299
14f9c5c9 8300 /* NOTE: elt_type---the fixed version of elt_type0---should never
dda83cd7
SM
8301 depend on the contents of the array in properly constructed
8302 debugging data. */
529cad9c 8303 /* Create a fixed version of the array element type.
dda83cd7
SM
8304 We're not providing the address of an element here,
8305 and thus the actual object value cannot be inspected to do
8306 the conversion. This should not be a problem, since arrays of
8307 unconstrained objects are not allowed. In particular, all
8308 the elements of an array of a tagged type should all be of
8309 the same type specified in the debugging info. No need to
8310 consult the object tag. */
1ed6ede0 8311 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
14f9c5c9 8312
284614f0
JB
8313 /* Make sure we always create a new array type when dealing with
8314 packed array types, since we're going to fix-up the array
8315 type length and element bitsize a little further down. */
ad82864c 8316 if (elt_type0 == elt_type && !constrained_packed_array_p)
dda83cd7 8317 result = type0;
14f9c5c9 8318 else
9e76b17a
TT
8319 {
8320 type_allocator alloc (type0);
8321 result = create_array_type (alloc, elt_type, type0->index_type ());
8322 }
14f9c5c9
AS
8323 }
8324 else
8325 {
8326 int i;
8327 struct type *elt_type0;
8328
8329 elt_type0 = type0;
1f704f76 8330 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
27710edb 8331 elt_type0 = elt_type0->target_type ();
14f9c5c9
AS
8332
8333 /* NOTE: result---the fixed version of elt_type0---should never
dda83cd7
SM
8334 depend on the contents of the array in properly constructed
8335 debugging data. */
529cad9c 8336 /* Create a fixed version of the array element type.
dda83cd7
SM
8337 We're not providing the address of an element here,
8338 and thus the actual object value cannot be inspected to do
8339 the conversion. This should not be a problem, since arrays of
8340 unconstrained objects are not allowed. In particular, all
8341 the elements of an array of a tagged type should all be of
8342 the same type specified in the debugging info. No need to
8343 consult the object tag. */
1ed6ede0 8344 result =
dda83cd7 8345 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
1ce677a4
UW
8346
8347 elt_type0 = type0;
1f704f76 8348 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
dda83cd7
SM
8349 {
8350 struct type *range_type =
8351 to_fixed_range_type (index_type_desc->field (i).type (), dval);
5b4ee69b 8352
9e76b17a
TT
8353 type_allocator alloc (elt_type0);
8354 result = create_array_type (alloc, result, range_type);
27710edb 8355 elt_type0 = elt_type0->target_type ();
dda83cd7 8356 }
14f9c5c9
AS
8357 }
8358
2e6fda7d
JB
8359 /* We want to preserve the type name. This can be useful when
8360 trying to get the type name of a value that has already been
8361 printed (for instance, if the user did "print VAR; whatis $". */
7d93a1e0 8362 result->set_name (type0->name ());
2e6fda7d 8363
ad82864c 8364 if (constrained_packed_array_p)
284614f0
JB
8365 {
8366 /* So far, the resulting type has been created as if the original
8367 type was a regular (non-packed) array type. As a result, the
8368 bitsize of the array elements needs to be set again, and the array
8369 length needs to be recomputed based on that bitsize. */
df86565b 8370 int len = result->length () / result->target_type ()->length ();
3757d2d4 8371 int elt_bitsize = type0->field (0).bitsize ();
284614f0 8372
3757d2d4 8373 result->field (0).set_bitsize (elt_bitsize);
b6cdbc9a 8374 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
df86565b
SM
8375 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8376 result->set_length (result->length () + 1);
284614f0
JB
8377 }
8378
9cdd0d12 8379 result->set_is_fixed_instance (true);
14f9c5c9 8380 return result;
d2e4a39e 8381}
14f9c5c9
AS
8382
8383
8384/* A standard type (containing no dynamically sized components)
8385 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8386 DVAL describes a record containing any discriminants used in TYPE0,
4c4b4cd2 8387 and may be NULL if there are none, or if the object of type TYPE at
529cad9c
PH
8388 ADDRESS or in VALADDR contains these discriminants.
8389
1ed6ede0
JB
8390 If CHECK_TAG is not null, in the case of tagged types, this function
8391 attempts to locate the object's tag and use it to compute the actual
8392 type. However, when ADDRESS is null, we cannot use it to determine the
8393 location of the tag, and therefore compute the tagged type's actual type.
8394 So we return the tagged type without consulting the tag. */
529cad9c 8395
f192137b
JB
8396static struct type *
8397ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
dda83cd7 8398 CORE_ADDR address, struct value *dval, int check_tag)
14f9c5c9 8399{
61ee279c 8400 type = ada_check_typedef (type);
8ecb59f8
TT
8401
8402 /* Only un-fixed types need to be handled here. */
8403 if (!HAVE_GNAT_AUX_INFO (type))
8404 return type;
8405
78134374 8406 switch (type->code ())
d2e4a39e
AS
8407 {
8408 default:
14f9c5c9 8409 return type;
d2e4a39e 8410 case TYPE_CODE_STRUCT:
4c4b4cd2 8411 {
dda83cd7
SM
8412 struct type *static_type = to_static_fixed_type (type);
8413 struct type *fixed_record_type =
8414 to_fixed_record_type (type, valaddr, address, NULL);
8415
8416 /* If STATIC_TYPE is a tagged type and we know the object's address,
8417 then we can determine its tag, and compute the object's actual
8418 type from there. Note that we have to use the fixed record
8419 type (the parent part of the record may have dynamic fields
8420 and the way the location of _tag is expressed may depend on
8421 them). */
8422
8423 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8424 {
b50d69b5
JG
8425 struct value *tag =
8426 value_tag_from_contents_and_address
8427 (fixed_record_type,
8428 valaddr,
8429 address);
8430 struct type *real_type = type_from_tag (tag);
8431 struct value *obj =
8432 value_from_contents_and_address (fixed_record_type,
8433 valaddr,
8434 address);
d0c97917 8435 fixed_record_type = obj->type ();
dda83cd7
SM
8436 if (real_type != NULL)
8437 return to_fixed_record_type
b50d69b5 8438 (real_type, NULL,
9feb2d07 8439 ada_tag_value_at_base_address (obj)->address (), NULL);
dda83cd7
SM
8440 }
8441
8442 /* Check to see if there is a parallel ___XVZ variable.
8443 If there is, then it provides the actual size of our type. */
8444 else if (ada_type_name (fixed_record_type) != NULL)
8445 {
8446 const char *name = ada_type_name (fixed_record_type);
8447 char *xvz_name
224c3ddb 8448 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
eccab96d 8449 bool xvz_found = false;
dda83cd7 8450 LONGEST size;
4af88198 8451
dda83cd7 8452 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
a70b8144 8453 try
eccab96d
JB
8454 {
8455 xvz_found = get_int_var_value (xvz_name, size);
8456 }
230d2906 8457 catch (const gdb_exception_error &except)
eccab96d
JB
8458 {
8459 /* We found the variable, but somehow failed to read
8460 its value. Rethrow the same error, but with a little
8461 bit more information, to help the user understand
8462 what went wrong (Eg: the variable might have been
8463 optimized out). */
8464 throw_error (except.error,
8465 _("unable to read value of %s (%s)"),
3d6e9d23 8466 xvz_name, except.what ());
eccab96d 8467 }
eccab96d 8468
df86565b 8469 if (xvz_found && fixed_record_type->length () != size)
dda83cd7
SM
8470 {
8471 fixed_record_type = copy_type (fixed_record_type);
b6cdbc9a 8472 fixed_record_type->set_length (size);
dda83cd7
SM
8473
8474 /* The FIXED_RECORD_TYPE may have be a stub. We have
8475 observed this when the debugging info is STABS, and
8476 apparently it is something that is hard to fix.
8477
8478 In practice, we don't need the actual type definition
8479 at all, because the presence of the XVZ variable allows us
8480 to assume that there must be a XVS type as well, which we
8481 should be able to use later, when we need the actual type
8482 definition.
8483
8484 In the meantime, pretend that the "fixed" type we are
8485 returning is NOT a stub, because this can cause trouble
8486 when using this type to create new types targeting it.
8487 Indeed, the associated creation routines often check
8488 whether the target type is a stub and will try to replace
8489 it, thus using a type with the wrong size. This, in turn,
8490 might cause the new type to have the wrong size too.
8491 Consider the case of an array, for instance, where the size
8492 of the array is computed from the number of elements in
8493 our array multiplied by the size of its element. */
b4b73759 8494 fixed_record_type->set_is_stub (false);
dda83cd7
SM
8495 }
8496 }
8497 return fixed_record_type;
4c4b4cd2 8498 }
d2e4a39e 8499 case TYPE_CODE_ARRAY:
4c4b4cd2 8500 return to_fixed_array_type (type, dval, 1);
d2e4a39e
AS
8501 case TYPE_CODE_UNION:
8502 if (dval == NULL)
dda83cd7 8503 return type;
d2e4a39e 8504 else
dda83cd7 8505 return to_fixed_variant_branch_type (type, valaddr, address, dval);
d2e4a39e 8506 }
14f9c5c9
AS
8507}
8508
f192137b
JB
8509/* The same as ada_to_fixed_type_1, except that it preserves the type
8510 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
96dbd2c1
JB
8511
8512 The typedef layer needs be preserved in order to differentiate between
8513 arrays and array pointers when both types are implemented using the same
8514 fat pointer. In the array pointer case, the pointer is encoded as
8515 a typedef of the pointer type. For instance, considering:
8516
8517 type String_Access is access String;
8518 S1 : String_Access := null;
8519
8520 To the debugger, S1 is defined as a typedef of type String. But
8521 to the user, it is a pointer. So if the user tries to print S1,
8522 we should not dereference the array, but print the array address
8523 instead.
8524
8525 If we didn't preserve the typedef layer, we would lose the fact that
8526 the type is to be presented as a pointer (needs de-reference before
8527 being printed). And we would also use the source-level type name. */
f192137b
JB
8528
8529struct type *
8530ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
dda83cd7 8531 CORE_ADDR address, struct value *dval, int check_tag)
f192137b
JB
8532
8533{
8534 struct type *fixed_type =
8535 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8536
96dbd2c1
JB
8537 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8538 then preserve the typedef layer.
8539
8540 Implementation note: We can only check the main-type portion of
8541 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8542 from TYPE now returns a type that has the same instance flags
8543 as TYPE. For instance, if TYPE is a "typedef const", and its
8544 target type is a "struct", then the typedef elimination will return
8545 a "const" version of the target type. See check_typedef for more
8546 details about how the typedef layer elimination is done.
8547
8548 brobecker/2010-11-19: It seems to me that the only case where it is
8549 useful to preserve the typedef layer is when dealing with fat pointers.
8550 Perhaps, we could add a check for that and preserve the typedef layer
85102364 8551 only in that situation. But this seems unnecessary so far, probably
96dbd2c1
JB
8552 because we call check_typedef/ada_check_typedef pretty much everywhere.
8553 */
78134374 8554 if (type->code () == TYPE_CODE_TYPEDEF
720d1a40 8555 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
96dbd2c1 8556 == TYPE_MAIN_TYPE (fixed_type)))
f192137b
JB
8557 return type;
8558
8559 return fixed_type;
8560}
8561
14f9c5c9 8562/* A standard (static-sized) type corresponding as well as possible to
4c4b4cd2 8563 TYPE0, but based on no runtime data. */
14f9c5c9 8564
d2e4a39e
AS
8565static struct type *
8566to_static_fixed_type (struct type *type0)
14f9c5c9 8567{
d2e4a39e 8568 struct type *type;
14f9c5c9
AS
8569
8570 if (type0 == NULL)
8571 return NULL;
8572
22c4c60c 8573 if (type0->is_fixed_instance ())
4c4b4cd2
PH
8574 return type0;
8575
61ee279c 8576 type0 = ada_check_typedef (type0);
d2e4a39e 8577
78134374 8578 switch (type0->code ())
14f9c5c9
AS
8579 {
8580 default:
8581 return type0;
8582 case TYPE_CODE_STRUCT:
8583 type = dynamic_template_type (type0);
d2e4a39e 8584 if (type != NULL)
dda83cd7 8585 return template_to_static_fixed_type (type);
4c4b4cd2 8586 else
dda83cd7 8587 return template_to_static_fixed_type (type0);
14f9c5c9
AS
8588 case TYPE_CODE_UNION:
8589 type = ada_find_parallel_type (type0, "___XVU");
8590 if (type != NULL)
dda83cd7 8591 return template_to_static_fixed_type (type);
4c4b4cd2 8592 else
dda83cd7 8593 return template_to_static_fixed_type (type0);
14f9c5c9
AS
8594 }
8595}
8596
4c4b4cd2
PH
8597/* A static approximation of TYPE with all type wrappers removed. */
8598
d2e4a39e
AS
8599static struct type *
8600static_unwrap_type (struct type *type)
14f9c5c9
AS
8601{
8602 if (ada_is_aligner_type (type))
8603 {
940da03e 8604 struct type *type1 = ada_check_typedef (type)->field (0).type ();
14f9c5c9 8605 if (ada_type_name (type1) == NULL)
d0e39ea2 8606 type1->set_name (ada_type_name (type));
14f9c5c9
AS
8607
8608 return static_unwrap_type (type1);
8609 }
d2e4a39e 8610 else
14f9c5c9 8611 {
d2e4a39e 8612 struct type *raw_real_type = ada_get_base_type (type);
5b4ee69b 8613
d2e4a39e 8614 if (raw_real_type == type)
dda83cd7 8615 return type;
14f9c5c9 8616 else
dda83cd7 8617 return to_static_fixed_type (raw_real_type);
14f9c5c9
AS
8618 }
8619}
8620
8621/* In some cases, incomplete and private types require
4c4b4cd2 8622 cross-references that are not resolved as records (for example,
14f9c5c9
AS
8623 type Foo;
8624 type FooP is access Foo;
8625 V: FooP;
8626 type Foo is array ...;
4c4b4cd2 8627 ). In these cases, since there is no mechanism for producing
14f9c5c9
AS
8628 cross-references to such types, we instead substitute for FooP a
8629 stub enumeration type that is nowhere resolved, and whose tag is
4c4b4cd2 8630 the name of the actual type. Call these types "non-record stubs". */
14f9c5c9
AS
8631
8632/* A type equivalent to TYPE that is not a non-record stub, if one
4c4b4cd2
PH
8633 exists, otherwise TYPE. */
8634
d2e4a39e 8635struct type *
61ee279c 8636ada_check_typedef (struct type *type)
14f9c5c9 8637{
727e3d2e
JB
8638 if (type == NULL)
8639 return NULL;
8640
736ade86
XR
8641 /* If our type is an access to an unconstrained array, which is encoded
8642 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
720d1a40
JB
8643 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8644 what allows us to distinguish between fat pointers that represent
8645 array types, and fat pointers that represent array access types
8646 (in both cases, the compiler implements them as fat pointers). */
736ade86 8647 if (ada_is_access_to_unconstrained_array (type))
720d1a40
JB
8648 return type;
8649
f168693b 8650 type = check_typedef (type);
78134374 8651 if (type == NULL || type->code () != TYPE_CODE_ENUM
e46d3488 8652 || !type->is_stub ()
7d93a1e0 8653 || type->name () == NULL)
14f9c5c9 8654 return type;
d2e4a39e 8655 else
14f9c5c9 8656 {
7d93a1e0 8657 const char *name = type->name ();
d2e4a39e 8658 struct type *type1 = ada_find_any_type (name);
5b4ee69b 8659
05e522ef 8660 if (type1 == NULL)
dda83cd7 8661 return type;
05e522ef
JB
8662
8663 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8664 stubs pointing to arrays, as we don't create symbols for array
3a867c22
JB
8665 types, only for the typedef-to-array types). If that's the case,
8666 strip the typedef layer. */
78134374 8667 if (type1->code () == TYPE_CODE_TYPEDEF)
3a867c22
JB
8668 type1 = ada_check_typedef (type1);
8669
8670 return type1;
14f9c5c9
AS
8671 }
8672}
8673
8674/* A value representing the data at VALADDR/ADDRESS as described by
8675 type TYPE0, but with a standard (static-sized) type that correctly
8676 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8677 type, then return VAL0 [this feature is simply to avoid redundant
4c4b4cd2 8678 creation of struct values]. */
14f9c5c9 8679
4c4b4cd2
PH
8680static struct value *
8681ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
dda83cd7 8682 struct value *val0)
14f9c5c9 8683{
1ed6ede0 8684 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
5b4ee69b 8685
14f9c5c9
AS
8686 if (type == type0 && val0 != NULL)
8687 return val0;
cc0e770c 8688
736355f2 8689 if (val0->lval () != lval_memory)
cc0e770c
JB
8690 {
8691 /* Our value does not live in memory; it could be a convenience
8692 variable, for instance. Create a not_lval value using val0's
8693 contents. */
efaf1ae0 8694 return value_from_contents (type, val0->contents ().data ());
cc0e770c
JB
8695 }
8696
8697 return value_from_contents_and_address (type, 0, address);
4c4b4cd2
PH
8698}
8699
8700/* A value representing VAL, but with a standard (static-sized) type
8701 that correctly describes it. Does not necessarily create a new
8702 value. */
8703
0c3acc09 8704struct value *
4c4b4cd2
PH
8705ada_to_fixed_value (struct value *val)
8706{
c48db5ca 8707 val = unwrap_value (val);
9feb2d07 8708 val = ada_to_fixed_value_create (val->type (), val->address (), val);
c48db5ca 8709 return val;
14f9c5c9 8710}
d2e4a39e 8711\f
14f9c5c9 8712
14f9c5c9
AS
8713/* Attributes */
8714
4c4b4cd2 8715/* Evaluate the 'POS attribute applied to ARG. */
14f9c5c9 8716
4c4b4cd2
PH
8717static LONGEST
8718pos_atr (struct value *arg)
14f9c5c9 8719{
24209737 8720 struct value *val = coerce_ref (arg);
d0c97917 8721 struct type *type = val->type ();
14f9c5c9 8722
d2e4a39e 8723 if (!discrete_type_p (type))
323e0a4a 8724 error (_("'POS only defined on discrete types"));
14f9c5c9 8725
6b09f134 8726 std::optional<LONGEST> result = discrete_position (type, value_as_long (val));
6244c119 8727 if (!result.has_value ())
aa715135 8728 error (_("enumeration value is invalid: can't find 'POS"));
14f9c5c9 8729
6244c119 8730 return *result;
4c4b4cd2
PH
8731}
8732
7631cf6c 8733struct value *
7992accc
TT
8734ada_pos_atr (struct type *expect_type,
8735 struct expression *exp,
8736 enum noside noside, enum exp_opcode op,
8737 struct value *arg)
4c4b4cd2 8738{
7992accc
TT
8739 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8740 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 8741 return value::zero (type, not_lval);
3cb382c9 8742 return value_from_longest (type, pos_atr (arg));
14f9c5c9
AS
8743}
8744
4c4b4cd2 8745/* Evaluate the TYPE'VAL attribute applied to ARG. */
14f9c5c9 8746
d2e4a39e 8747static struct value *
53a47a3e 8748val_atr (struct type *type, LONGEST val)
14f9c5c9 8749{
53a47a3e 8750 gdb_assert (discrete_type_p (type));
0bc2354b 8751 if (type->code () == TYPE_CODE_RANGE)
27710edb 8752 type = type->target_type ();
78134374 8753 if (type->code () == TYPE_CODE_ENUM)
14f9c5c9 8754 {
53a47a3e 8755 if (val < 0 || val >= type->num_fields ())
dda83cd7 8756 error (_("argument to 'VAL out of range"));
970db518 8757 val = type->field (val).loc_enumval ();
14f9c5c9 8758 }
53a47a3e
TT
8759 return value_from_longest (type, val);
8760}
8761
9e99f48f 8762struct value *
22f6f797
TT
8763ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8764 struct value *arg)
53a47a3e 8765{
3848abd6 8766 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 8767 return value::zero (type, not_lval);
3848abd6 8768
53a47a3e
TT
8769 if (!discrete_type_p (type))
8770 error (_("'VAL only defined on discrete types"));
d0c97917 8771 if (!integer_type_p (arg->type ()))
53a47a3e
TT
8772 error (_("'VAL requires integral argument"));
8773
8774 return val_atr (type, value_as_long (arg));
14f9c5c9 8775}
22f6f797
TT
8776
8777/* Implementation of the enum_rep attribute. */
8778struct value *
8779ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8780 struct value *arg)
8781{
8782 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8783 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8784 return value::zero (inttype, not_lval);
8785
8786 if (type->code () == TYPE_CODE_RANGE)
8787 type = type->target_type ();
8788 if (type->code () != TYPE_CODE_ENUM)
8789 error (_("'Enum_Rep only defined on enum types"));
8790 if (!types_equal (type, arg->type ()))
8791 error (_("'Enum_Rep requires argument to have same type as enum"));
8792
8793 return value_cast (inttype, arg);
8794}
8795
8796/* Implementation of the enum_val attribute. */
8797struct value *
8798ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8799 struct value *arg)
8800{
8801 struct type *original_type = type;
8802 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8803 return value::zero (original_type, not_lval);
8804
8805 if (type->code () == TYPE_CODE_RANGE)
8806 type = type->target_type ();
8807 if (type->code () != TYPE_CODE_ENUM)
8808 error (_("'Enum_Val only defined on enum types"));
8809 if (!integer_type_p (arg->type ()))
8810 error (_("'Enum_Val requires integral argument"));
8811
8812 LONGEST value = value_as_long (arg);
8813 for (int i = 0; i < type->num_fields (); ++i)
8814 {
8815 if (type->field (i).loc_enumval () == value)
8816 return value_from_longest (original_type, value);
8817 }
8818
8819 error (_("value %s not found in enum"), plongest (value));
8820}
8821
14f9c5c9 8822\f
d2e4a39e 8823
dda83cd7 8824 /* Evaluation */
14f9c5c9 8825
4c4b4cd2
PH
8826/* True if TYPE appears to be an Ada character type.
8827 [At the moment, this is true only for Character and Wide_Character;
8828 It is a heuristic test that could stand improvement]. */
14f9c5c9 8829
fc913e53 8830bool
d2e4a39e 8831ada_is_character_type (struct type *type)
14f9c5c9 8832{
7b9f71f2
JB
8833 const char *name;
8834
8835 /* If the type code says it's a character, then assume it really is,
8836 and don't check any further. */
78134374 8837 if (type->code () == TYPE_CODE_CHAR)
fc913e53 8838 return true;
7b9f71f2
JB
8839
8840 /* Otherwise, assume it's a character type iff it is a discrete type
8841 with a known character type name. */
8842 name = ada_type_name (type);
8843 return (name != NULL
dda83cd7
SM
8844 && (type->code () == TYPE_CODE_INT
8845 || type->code () == TYPE_CODE_RANGE)
8846 && (strcmp (name, "character") == 0
8847 || strcmp (name, "wide_character") == 0
8848 || strcmp (name, "wide_wide_character") == 0
8849 || strcmp (name, "unsigned char") == 0));
14f9c5c9
AS
8850}
8851
4c4b4cd2 8852/* True if TYPE appears to be an Ada string type. */
14f9c5c9 8853
fc913e53 8854bool
ebf56fd3 8855ada_is_string_type (struct type *type)
14f9c5c9 8856{
61ee279c 8857 type = ada_check_typedef (type);
d2e4a39e 8858 if (type != NULL
78134374 8859 && type->code () != TYPE_CODE_PTR
76a01679 8860 && (ada_is_simple_array_type (type)
dda83cd7 8861 || ada_is_array_descriptor_type (type))
14f9c5c9
AS
8862 && ada_array_arity (type) == 1)
8863 {
8864 struct type *elttype = ada_array_element_type (type, 1);
8865
8866 return ada_is_character_type (elttype);
8867 }
d2e4a39e 8868 else
fc913e53 8869 return false;
14f9c5c9
AS
8870}
8871
5bf03f13
JB
8872/* The compiler sometimes provides a parallel XVS type for a given
8873 PAD type. Normally, it is safe to follow the PAD type directly,
8874 but older versions of the compiler have a bug that causes the offset
8875 of its "F" field to be wrong. Following that field in that case
8876 would lead to incorrect results, but this can be worked around
8877 by ignoring the PAD type and using the associated XVS type instead.
8878
8879 Set to True if the debugger should trust the contents of PAD types.
8880 Otherwise, ignore the PAD type if there is a parallel XVS type. */
491144b5 8881static bool trust_pad_over_xvs = true;
14f9c5c9
AS
8882
8883/* True if TYPE is a struct type introduced by the compiler to force the
8884 alignment of a value. Such types have a single field with a
4c4b4cd2 8885 distinctive name. */
14f9c5c9
AS
8886
8887int
ebf56fd3 8888ada_is_aligner_type (struct type *type)
14f9c5c9 8889{
61ee279c 8890 type = ada_check_typedef (type);
714e53ab 8891
5bf03f13 8892 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
714e53ab
PH
8893 return 0;
8894
78134374 8895 return (type->code () == TYPE_CODE_STRUCT
dda83cd7 8896 && type->num_fields () == 1
33d16dd9 8897 && strcmp (type->field (0).name (), "F") == 0);
14f9c5c9
AS
8898}
8899
8900/* If there is an ___XVS-convention type parallel to SUBTYPE, return
4c4b4cd2 8901 the parallel type. */
14f9c5c9 8902
d2e4a39e
AS
8903struct type *
8904ada_get_base_type (struct type *raw_type)
14f9c5c9 8905{
d2e4a39e
AS
8906 struct type *real_type_namer;
8907 struct type *raw_real_type;
14f9c5c9 8908
78134374 8909 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
14f9c5c9
AS
8910 return raw_type;
8911
284614f0
JB
8912 if (ada_is_aligner_type (raw_type))
8913 /* The encoding specifies that we should always use the aligner type.
8914 So, even if this aligner type has an associated XVS type, we should
8915 simply ignore it.
8916
8917 According to the compiler gurus, an XVS type parallel to an aligner
8918 type may exist because of a stabs limitation. In stabs, aligner
8919 types are empty because the field has a variable-sized type, and
8920 thus cannot actually be used as an aligner type. As a result,
8921 we need the associated parallel XVS type to decode the type.
8922 Since the policy in the compiler is to not change the internal
8923 representation based on the debugging info format, we sometimes
8924 end up having a redundant XVS type parallel to the aligner type. */
8925 return raw_type;
8926
14f9c5c9 8927 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
d2e4a39e 8928 if (real_type_namer == NULL
78134374 8929 || real_type_namer->code () != TYPE_CODE_STRUCT
1f704f76 8930 || real_type_namer->num_fields () != 1)
14f9c5c9
AS
8931 return raw_type;
8932
940da03e 8933 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
f80d3ff2
JB
8934 {
8935 /* This is an older encoding form where the base type needs to be
85102364 8936 looked up by name. We prefer the newer encoding because it is
f80d3ff2 8937 more efficient. */
33d16dd9 8938 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
f80d3ff2
JB
8939 if (raw_real_type == NULL)
8940 return raw_type;
8941 else
8942 return raw_real_type;
8943 }
8944
8945 /* The field in our XVS type is a reference to the base type. */
27710edb 8946 return real_type_namer->field (0).type ()->target_type ();
d2e4a39e 8947}
14f9c5c9 8948
4c4b4cd2 8949/* The type of value designated by TYPE, with all aligners removed. */
14f9c5c9 8950
d2e4a39e
AS
8951struct type *
8952ada_aligned_type (struct type *type)
14f9c5c9
AS
8953{
8954 if (ada_is_aligner_type (type))
940da03e 8955 return ada_aligned_type (type->field (0).type ());
14f9c5c9
AS
8956 else
8957 return ada_get_base_type (type);
8958}
8959
8960
8961/* The address of the aligned value in an object at address VALADDR
4c4b4cd2 8962 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
14f9c5c9 8963
fc1a4b47
AC
8964const gdb_byte *
8965ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
14f9c5c9 8966{
d2e4a39e 8967 if (ada_is_aligner_type (type))
b610c045
SM
8968 return ada_aligned_value_addr
8969 (type->field (0).type (),
8970 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
14f9c5c9
AS
8971 else
8972 return valaddr;
8973}
8974
4c4b4cd2
PH
8975
8976
14f9c5c9 8977/* The printed representation of an enumeration literal with encoded
4c4b4cd2 8978 name NAME. The value is good to the next call of ada_enum_name. */
d2e4a39e
AS
8979const char *
8980ada_enum_name (const char *name)
14f9c5c9 8981{
5f9febe0 8982 static std::string storage;
e6a959d6 8983 const char *tmp;
14f9c5c9 8984
4c4b4cd2
PH
8985 /* First, unqualify the enumeration name:
8986 1. Search for the last '.' character. If we find one, then skip
177b42fe 8987 all the preceding characters, the unqualified name starts
76a01679 8988 right after that dot.
4c4b4cd2 8989 2. Otherwise, we may be debugging on a target where the compiler
76a01679
JB
8990 translates dots into "__". Search forward for double underscores,
8991 but stop searching when we hit an overloading suffix, which is
8992 of the form "__" followed by digits. */
4c4b4cd2 8993
c3e5cd34
PH
8994 tmp = strrchr (name, '.');
8995 if (tmp != NULL)
4c4b4cd2
PH
8996 name = tmp + 1;
8997 else
14f9c5c9 8998 {
4c4b4cd2 8999 while ((tmp = strstr (name, "__")) != NULL)
dda83cd7
SM
9000 {
9001 if (isdigit (tmp[2]))
9002 break;
9003 else
9004 name = tmp + 2;
9005 }
14f9c5c9
AS
9006 }
9007
9008 if (name[0] == 'Q')
9009 {
14f9c5c9 9010 int v;
5b4ee69b 9011
14f9c5c9 9012 if (name[1] == 'U' || name[1] == 'W')
dda83cd7 9013 {
a7041de8
TT
9014 int offset = 2;
9015 if (name[1] == 'W' && name[2] == 'W')
9016 {
9017 /* Also handle the QWW case. */
9018 ++offset;
9019 }
9020 if (sscanf (name + offset, "%x", &v) != 1)
dda83cd7
SM
9021 return name;
9022 }
272560b5
TT
9023 else if (((name[1] >= '0' && name[1] <= '9')
9024 || (name[1] >= 'a' && name[1] <= 'z'))
9025 && name[2] == '\0')
9026 {
5f9febe0
TT
9027 storage = string_printf ("'%c'", name[1]);
9028 return storage.c_str ();
272560b5 9029 }
14f9c5c9 9030 else
dda83cd7 9031 return name;
14f9c5c9
AS
9032
9033 if (isascii (v) && isprint (v))
5f9febe0 9034 storage = string_printf ("'%c'", v);
14f9c5c9 9035 else if (name[1] == 'U')
a7041de8
TT
9036 storage = string_printf ("'[\"%02x\"]'", v);
9037 else if (name[2] != 'W')
9038 storage = string_printf ("'[\"%04x\"]'", v);
14f9c5c9 9039 else
a7041de8 9040 storage = string_printf ("'[\"%06x\"]'", v);
14f9c5c9 9041
5f9febe0 9042 return storage.c_str ();
14f9c5c9 9043 }
d2e4a39e 9044 else
4c4b4cd2 9045 {
c3e5cd34
PH
9046 tmp = strstr (name, "__");
9047 if (tmp == NULL)
9048 tmp = strstr (name, "$");
9049 if (tmp != NULL)
dda83cd7 9050 {
5f9febe0
TT
9051 storage = std::string (name, tmp - name);
9052 return storage.c_str ();
dda83cd7 9053 }
4c4b4cd2
PH
9054
9055 return name;
9056 }
14f9c5c9
AS
9057}
9058
013a623f
TT
9059/* If TYPE is a dynamic type, return the base type. Otherwise, if
9060 there is no parallel type, return nullptr. */
9061
9062static struct type *
9063find_base_type (struct type *type)
9064{
9065 struct type *raw_real_type
9066 = ada_check_typedef (ada_get_base_type (type));
9067
9068 /* No parallel XVS or XVE type. */
9069 if (type == raw_real_type
9070 && ada_find_parallel_type (type, "___XVE") == nullptr)
9071 return nullptr;
9072
9073 return raw_real_type;
9074}
9075
14f9c5c9 9076/* If VAL is wrapped in an aligner or subtype wrapper, return the
4c4b4cd2 9077 value it wraps. */
14f9c5c9 9078
d2e4a39e
AS
9079static struct value *
9080unwrap_value (struct value *val)
14f9c5c9 9081{
d0c97917 9082 struct type *type = ada_check_typedef (val->type ());
5b4ee69b 9083
14f9c5c9
AS
9084 if (ada_is_aligner_type (type))
9085 {
de4d072f 9086 struct value *v = ada_value_struct_elt (val, "F", 0);
d0c97917 9087 struct type *val_type = ada_check_typedef (v->type ());
5b4ee69b 9088
14f9c5c9 9089 if (ada_type_name (val_type) == NULL)
d0e39ea2 9090 val_type->set_name (ada_type_name (type));
14f9c5c9
AS
9091
9092 return unwrap_value (v);
9093 }
d2e4a39e 9094 else
14f9c5c9 9095 {
013a623f
TT
9096 struct type *raw_real_type = find_base_type (type);
9097 if (raw_real_type == nullptr)
5bf03f13 9098 return val;
14f9c5c9 9099
d2e4a39e 9100 return
dda83cd7
SM
9101 coerce_unspec_val_to_type
9102 (val, ada_to_fixed_type (raw_real_type, 0,
9feb2d07 9103 val->address (),
dda83cd7 9104 NULL, 1));
14f9c5c9
AS
9105 }
9106}
d2e4a39e 9107
d99dcf51
JB
9108/* Given two array types T1 and T2, return nonzero iff both arrays
9109 contain the same number of elements. */
9110
9111static int
9112ada_same_array_size_p (struct type *t1, struct type *t2)
9113{
9114 LONGEST lo1, hi1, lo2, hi2;
9115
9116 /* Get the array bounds in order to verify that the size of
9117 the two arrays match. */
9118 if (!get_array_bounds (t1, &lo1, &hi1)
9119 || !get_array_bounds (t2, &lo2, &hi2))
9120 error (_("unable to determine array bounds"));
9121
9122 /* To make things easier for size comparison, normalize a bit
9123 the case of empty arrays by making sure that the difference
9124 between upper bound and lower bound is always -1. */
9125 if (lo1 > hi1)
9126 hi1 = lo1 - 1;
9127 if (lo2 > hi2)
9128 hi2 = lo2 - 1;
9129
9130 return (hi1 - lo1 == hi2 - lo2);
9131}
9132
9133/* Assuming that VAL is an array of integrals, and TYPE represents
9134 an array with the same number of elements, but with wider integral
9135 elements, return an array "casted" to TYPE. In practice, this
9136 means that the returned array is built by casting each element
9137 of the original array into TYPE's (wider) element type. */
9138
9139static struct value *
9140ada_promote_array_of_integrals (struct type *type, struct value *val)
9141{
27710edb 9142 struct type *elt_type = type->target_type ();
d99dcf51 9143 LONGEST lo, hi;
d99dcf51
JB
9144 LONGEST i;
9145
9146 /* Verify that both val and type are arrays of scalars, and
9147 that the size of val's elements is smaller than the size
9148 of type's element. */
78134374 9149 gdb_assert (type->code () == TYPE_CODE_ARRAY);
27710edb 9150 gdb_assert (is_integral_type (type->target_type ()));
d0c97917
TT
9151 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9152 gdb_assert (is_integral_type (val->type ()->target_type ()));
df86565b 9153 gdb_assert (type->target_type ()->length ()
d0c97917 9154 > val->type ()->target_type ()->length ());
d99dcf51
JB
9155
9156 if (!get_array_bounds (type, &lo, &hi))
9157 error (_("unable to determine array bounds"));
9158
317c3ed9 9159 value *res = value::allocate (type);
bbe912ba 9160 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
d99dcf51
JB
9161
9162 /* Promote each array element. */
9163 for (i = 0; i < hi - lo + 1; i++)
9164 {
9165 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
df86565b 9166 int elt_len = elt_type->length ();
d99dcf51 9167
efaf1ae0 9168 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
d99dcf51
JB
9169 }
9170
9171 return res;
9172}
9173
4c4b4cd2
PH
9174/* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9175 return the converted value. */
9176
d2e4a39e
AS
9177static struct value *
9178coerce_for_assign (struct type *type, struct value *val)
14f9c5c9 9179{
d0c97917 9180 struct type *type2 = val->type ();
5b4ee69b 9181
14f9c5c9
AS
9182 if (type == type2)
9183 return val;
9184
61ee279c
PH
9185 type2 = ada_check_typedef (type2);
9186 type = ada_check_typedef (type);
14f9c5c9 9187
78134374
SM
9188 if (type2->code () == TYPE_CODE_PTR
9189 && type->code () == TYPE_CODE_ARRAY)
14f9c5c9
AS
9190 {
9191 val = ada_value_ind (val);
d0c97917 9192 type2 = val->type ();
14f9c5c9
AS
9193 }
9194
78134374
SM
9195 if (type2->code () == TYPE_CODE_ARRAY
9196 && type->code () == TYPE_CODE_ARRAY)
14f9c5c9 9197 {
d99dcf51
JB
9198 if (!ada_same_array_size_p (type, type2))
9199 error (_("cannot assign arrays of different length"));
9200
27710edb
SM
9201 if (is_integral_type (type->target_type ())
9202 && is_integral_type (type2->target_type ())
df86565b 9203 && type2->target_type ()->length () < type->target_type ()->length ())
d99dcf51
JB
9204 {
9205 /* Allow implicit promotion of the array elements to
9206 a wider type. */
9207 return ada_promote_array_of_integrals (type, val);
9208 }
9209
df86565b 9210 if (type2->target_type ()->length () != type->target_type ()->length ())
dda83cd7 9211 error (_("Incompatible types in assignment"));
81ae560c 9212 val->deprecated_set_type (type);
14f9c5c9 9213 }
d2e4a39e 9214 return val;
14f9c5c9
AS
9215}
9216
4c4b4cd2
PH
9217static struct value *
9218ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9219{
4c4b4cd2 9220 struct type *type1, *type2;
4c4b4cd2 9221
994b9211
AC
9222 arg1 = coerce_ref (arg1);
9223 arg2 = coerce_ref (arg2);
d0c97917
TT
9224 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9225 type2 = get_base_type (ada_check_typedef (arg2->type ()));
4c4b4cd2 9226
78134374
SM
9227 if (type1->code () != TYPE_CODE_INT
9228 || type2->code () != TYPE_CODE_INT)
4c4b4cd2
PH
9229 return value_binop (arg1, arg2, op);
9230
76a01679 9231 switch (op)
4c4b4cd2
PH
9232 {
9233 case BINOP_MOD:
9234 case BINOP_DIV:
9235 case BINOP_REM:
9236 break;
9237 default:
9238 return value_binop (arg1, arg2, op);
9239 }
9240
70050808
TT
9241 gdb_mpz v2 = value_as_mpz (arg2);
9242 if (v2.sgn () == 0)
b0f9164c
TT
9243 {
9244 const char *name;
9245 if (op == BINOP_MOD)
9246 name = "mod";
9247 else if (op == BINOP_DIV)
9248 name = "/";
9249 else
9250 {
9251 gdb_assert (op == BINOP_REM);
9252 name = "rem";
9253 }
9254
9255 error (_("second operand of %s must not be zero."), name);
9256 }
4c4b4cd2 9257
c6d940a9 9258 if (type1->is_unsigned () || op == BINOP_MOD)
4c4b4cd2
PH
9259 return value_binop (arg1, arg2, op);
9260
70050808
TT
9261 gdb_mpz v1 = value_as_mpz (arg1);
9262 gdb_mpz v;
4c4b4cd2
PH
9263 switch (op)
9264 {
9265 case BINOP_DIV:
9266 v = v1 / v2;
4c4b4cd2
PH
9267 break;
9268 case BINOP_REM:
9269 v = v1 % v2;
76a01679 9270 if (v * v1 < 0)
dda83cd7 9271 v -= v2;
4c4b4cd2
PH
9272 break;
9273 default:
9274 /* Should not reach this point. */
70050808 9275 gdb_assert_not_reached ("invalid operator");
4c4b4cd2
PH
9276 }
9277
70050808 9278 return value_from_mpz (type1, v);
4c4b4cd2
PH
9279}
9280
9281static int
9282ada_value_equal (struct value *arg1, struct value *arg2)
9283{
d0c97917
TT
9284 if (ada_is_direct_array_type (arg1->type ())
9285 || ada_is_direct_array_type (arg2->type ()))
4c4b4cd2 9286 {
79e8fcaa
JB
9287 struct type *arg1_type, *arg2_type;
9288
f58b38bf 9289 /* Automatically dereference any array reference before
dda83cd7 9290 we attempt to perform the comparison. */
f58b38bf
JB
9291 arg1 = ada_coerce_ref (arg1);
9292 arg2 = ada_coerce_ref (arg2);
79e8fcaa 9293
4c4b4cd2
PH
9294 arg1 = ada_coerce_to_simple_array (arg1);
9295 arg2 = ada_coerce_to_simple_array (arg2);
79e8fcaa 9296
d0c97917
TT
9297 arg1_type = ada_check_typedef (arg1->type ());
9298 arg2_type = ada_check_typedef (arg2->type ());
79e8fcaa 9299
78134374 9300 if (arg1_type->code () != TYPE_CODE_ARRAY
dda83cd7
SM
9301 || arg2_type->code () != TYPE_CODE_ARRAY)
9302 error (_("Attempt to compare array with non-array"));
4c4b4cd2 9303 /* FIXME: The following works only for types whose
dda83cd7
SM
9304 representations use all bits (no padding or undefined bits)
9305 and do not have user-defined equality. */
df86565b 9306 return (arg1_type->length () == arg2_type->length ()
efaf1ae0
TT
9307 && memcmp (arg1->contents ().data (),
9308 arg2->contents ().data (),
df86565b 9309 arg1_type->length ()) == 0);
4c4b4cd2
PH
9310 }
9311 return value_equal (arg1, arg2);
9312}
9313
d3c54a1c
TT
9314namespace expr
9315{
9316
9317bool
9318check_objfile (const std::unique_ptr<ada_component> &comp,
9319 struct objfile *objfile)
9320{
9321 return comp->uses_objfile (objfile);
9322}
9323
d9d782dd 9324/* See ada-exp.h. */
52ce6436 9325
d9d782dd
TT
9326void
9327aggregate_assigner::assign (LONGEST index, operation_up &arg)
52ce6436 9328{
d3c54a1c
TT
9329 scoped_value_mark mark;
9330
52ce6436 9331 struct value *elt;
d0c97917 9332 struct type *lhs_type = check_typedef (lhs->type ());
5b4ee69b 9333
78134374 9334 if (lhs_type->code () == TYPE_CODE_ARRAY)
52ce6436 9335 {
22601c15
UW
9336 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9337 struct value *index_val = value_from_longest (index_type, index);
5b4ee69b 9338
52ce6436
PH
9339 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9340 }
9341 else
9342 {
d0c97917 9343 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
c48db5ca 9344 elt = ada_to_fixed_value (elt);
52ce6436
PH
9345 }
9346
542ea7fe
TT
9347 scoped_restore save_index = make_scoped_restore (&m_current_index, index);
9348
d3c54a1c
TT
9349 ada_aggregate_operation *ag_op
9350 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9351 if (ag_op != nullptr)
9352 ag_op->assign_aggregate (container, elt, exp);
52ce6436 9353 else
d3c54a1c
TT
9354 value_assign_to_component (container, elt,
9355 arg->evaluate (nullptr, exp,
9356 EVAL_NORMAL));
9357}
52ce6436 9358
542ea7fe
TT
9359/* See ada-exp.h. */
9360
9361value *
9362aggregate_assigner::current_value () const
9363{
9364 /* Note that using an integer type here is incorrect -- the type
9365 should be the array's index type. Unfortunately, though, this
9366 isn't currently available during parsing and type resolution. */
9367 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9368 return value_from_longest (index_type, m_current_index);
9369}
9370
d3c54a1c
TT
9371bool
9372ada_aggregate_component::uses_objfile (struct objfile *objfile)
9373{
7e949f08
TT
9374 if (m_base != nullptr && m_base->uses_objfile (objfile))
9375 return true;
d3c54a1c
TT
9376 for (const auto &item : m_components)
9377 if (item->uses_objfile (objfile))
9378 return true;
9379 return false;
9380}
9381
9382void
9383ada_aggregate_component::dump (ui_file *stream, int depth)
9384{
6cb06a8c 9385 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
7e949f08
TT
9386 if (m_base != nullptr)
9387 {
9388 gdb_printf (stream, _("%*swith delta\n"), depth + 1, "");
9389 m_base->dump (stream, depth + 2);
9390 }
d3c54a1c
TT
9391 for (const auto &item : m_components)
9392 item->dump (stream, depth + 1);
9393}
9394
9395void
d9d782dd 9396ada_aggregate_component::assign (aggregate_assigner &assigner)
d3c54a1c 9397{
7e949f08
TT
9398 if (m_base != nullptr)
9399 {
d9d782dd 9400 value *base = m_base->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
7e949f08
TT
9401 if (ada_is_direct_array_type (base->type ()))
9402 base = ada_coerce_to_simple_array (base);
d9d782dd 9403 if (!types_deeply_equal (assigner.container->type (), base->type ()))
7e949f08 9404 error (_("Type mismatch in delta aggregate"));
d9d782dd
TT
9405 value_assign_to_component (assigner.container, assigner.container,
9406 base);
7e949f08
TT
9407 }
9408
d3c54a1c 9409 for (auto &item : m_components)
d9d782dd 9410 item->assign (assigner);
52ce6436
PH
9411}
9412
207582c0 9413/* See ada-exp.h. */
52ce6436 9414
7e949f08
TT
9415ada_aggregate_component::ada_aggregate_component
9416 (operation_up &&base, std::vector<ada_component_up> &&components)
9417 : m_base (std::move (base)),
9418 m_components (std::move (components))
9419{
9420 for (const auto &component : m_components)
9421 if (dynamic_cast<const ada_others_component *> (component.get ())
9422 != nullptr)
9423 {
9424 /* It's invalid and nonsensical to have 'others => ...' with a
9425 delta aggregate. It was simpler to enforce this
9426 restriction here as opposed to in the parser. */
9427 error (_("'others' invalid in delta aggregate"));
9428 }
9429}
9430
9431/* See ada-exp.h. */
9432
207582c0 9433value *
d3c54a1c
TT
9434ada_aggregate_operation::assign_aggregate (struct value *container,
9435 struct value *lhs,
9436 struct expression *exp)
52ce6436
PH
9437{
9438 struct type *lhs_type;
d9d782dd 9439 aggregate_assigner assigner;
52ce6436
PH
9440
9441 container = ada_coerce_ref (container);
d0c97917 9442 if (ada_is_direct_array_type (container->type ()))
52ce6436
PH
9443 container = ada_coerce_to_simple_array (container);
9444 lhs = ada_coerce_ref (lhs);
4b53ca88 9445 if (!lhs->deprecated_modifiable ())
52ce6436
PH
9446 error (_("Left operand of assignment is not a modifiable lvalue."));
9447
d0c97917 9448 lhs_type = check_typedef (lhs->type ());
52ce6436
PH
9449 if (ada_is_direct_array_type (lhs_type))
9450 {
9451 lhs = ada_coerce_to_simple_array (lhs);
d0c97917 9452 lhs_type = check_typedef (lhs->type ());
d9d782dd
TT
9453 assigner.low = lhs_type->bounds ()->low.const_val ();
9454 assigner.high = lhs_type->bounds ()->high.const_val ();
52ce6436 9455 }
78134374 9456 else if (lhs_type->code () == TYPE_CODE_STRUCT)
52ce6436 9457 {
d9d782dd
TT
9458 assigner.low = 0;
9459 assigner.high = num_visible_fields (lhs_type) - 1;
52ce6436
PH
9460 }
9461 else
9462 error (_("Left-hand side must be array or record."));
9463
d9d782dd
TT
9464 assigner.indices.push_back (assigner.low - 1);
9465 assigner.indices.push_back (assigner.low - 1);
9466 assigner.indices.push_back (assigner.high + 1);
9467 assigner.indices.push_back (assigner.high + 1);
9468
9469 assigner.container = container;
9470 assigner.lhs = lhs;
9471 assigner.exp = exp;
52ce6436 9472
d9d782dd 9473 std::get<0> (m_storage)->assign (assigner);
207582c0
TT
9474
9475 return container;
d3c54a1c
TT
9476}
9477
9478bool
9479ada_positional_component::uses_objfile (struct objfile *objfile)
9480{
9481 return m_op->uses_objfile (objfile);
9482}
52ce6436 9483
d3c54a1c
TT
9484void
9485ada_positional_component::dump (ui_file *stream, int depth)
9486{
6cb06a8c
TT
9487 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9488 depth, "", m_index);
d3c54a1c 9489 m_op->dump (stream, depth + 1);
52ce6436 9490}
d3c54a1c 9491
52ce6436 9492/* Assign into the component of LHS indexed by the OP_POSITIONAL
d3c54a1c
TT
9493 construct, given that the positions are relative to lower bound
9494 LOW, where HIGH is the upper bound. Record the position in
9495 INDICES. CONTAINER is as for assign_aggregate. */
9496void
d9d782dd 9497ada_positional_component::assign (aggregate_assigner &assigner)
52ce6436 9498{
d9d782dd 9499 LONGEST ind = m_index + assigner.low;
d3c54a1c 9500
d9d782dd 9501 if (ind - 1 == assigner.high)
e1d5a0d2 9502 warning (_("Extra components in aggregate ignored."));
d9d782dd 9503 if (ind <= assigner.high)
52ce6436 9504 {
d9d782dd
TT
9505 assigner.add_interval (ind, ind);
9506 assigner.assign (ind, m_op);
52ce6436 9507 }
52ce6436
PH
9508}
9509
d3c54a1c
TT
9510bool
9511ada_discrete_range_association::uses_objfile (struct objfile *objfile)
a88c4354
TT
9512{
9513 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9514}
9515
9516void
9517ada_discrete_range_association::dump (ui_file *stream, int depth)
9518{
6cb06a8c 9519 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
a88c4354
TT
9520 m_low->dump (stream, depth + 1);
9521 m_high->dump (stream, depth + 1);
9522}
9523
9524void
d9d782dd 9525ada_discrete_range_association::assign (aggregate_assigner &assigner,
a88c4354
TT
9526 operation_up &op)
9527{
d9d782dd
TT
9528 LONGEST lower = value_as_long (m_low->evaluate (nullptr, assigner.exp,
9529 EVAL_NORMAL));
9530 LONGEST upper = value_as_long (m_high->evaluate (nullptr, assigner.exp,
9531 EVAL_NORMAL));
a88c4354 9532
d9d782dd 9533 if (lower <= upper && (lower < assigner.low || upper > assigner.high))
a88c4354
TT
9534 error (_("Index in component association out of bounds."));
9535
d9d782dd 9536 assigner.add_interval (lower, upper);
a88c4354
TT
9537 while (lower <= upper)
9538 {
d9d782dd 9539 assigner.assign (lower, op);
a88c4354
TT
9540 lower += 1;
9541 }
9542}
9543
9544bool
9545ada_name_association::uses_objfile (struct objfile *objfile)
9546{
9547 return m_val->uses_objfile (objfile);
9548}
9549
9550void
9551ada_name_association::dump (ui_file *stream, int depth)
9552{
6cb06a8c 9553 gdb_printf (stream, _("%*sName:\n"), depth, "");
a88c4354
TT
9554 m_val->dump (stream, depth + 1);
9555}
9556
9557void
d9d782dd 9558ada_name_association::assign (aggregate_assigner &assigner,
a88c4354
TT
9559 operation_up &op)
9560{
9561 int index;
9562
d9d782dd
TT
9563 if (ada_is_direct_array_type (assigner.lhs->type ()))
9564 {
9565 value *tem = m_val->evaluate (nullptr, assigner.exp, EVAL_NORMAL);
9566 index = longest_to_int (value_as_long (tem));
9567 }
a88c4354
TT
9568 else
9569 {
9570 ada_string_operation *strop
9571 = dynamic_cast<ada_string_operation *> (m_val.get ());
9572
9573 const char *name;
9574 if (strop != nullptr)
9575 name = strop->get_name ();
9576 else
9577 {
9578 ada_var_value_operation *vvo
9579 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
94c5098e 9580 if (vvo == nullptr)
a88c4354
TT
9581 error (_("Invalid record component association."));
9582 name = vvo->get_symbol ()->natural_name ();
94c5098e
TT
9583 /* In this scenario, the user wrote (name => expr), but
9584 write_name_assoc found some fully-qualified name and
9585 substituted it. This happens because, at parse time, the
9586 meaning of the expression isn't known; but here we know
9587 that just the base name was supplied and it refers to the
9588 name of a field. */
9589 name = ada_unqualified_name (name);
a88c4354
TT
9590 }
9591
9592 index = 0;
d9d782dd 9593 if (! find_struct_field (name, assigner.lhs->type (), 0,
a88c4354
TT
9594 NULL, NULL, NULL, NULL, &index))
9595 error (_("Unknown component name: %s."), name);
9596 }
9597
d9d782dd
TT
9598 assigner.add_interval (index, index);
9599 assigner.assign (index, op);
a88c4354
TT
9600}
9601
9602bool
9603ada_choices_component::uses_objfile (struct objfile *objfile)
9604{
9605 if (m_op->uses_objfile (objfile))
9606 return true;
9607 for (const auto &item : m_assocs)
9608 if (item->uses_objfile (objfile))
9609 return true;
9610 return false;
9611}
9612
9613void
9614ada_choices_component::dump (ui_file *stream, int depth)
9615{
542ea7fe
TT
9616 if (m_name.empty ())
9617 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
9618 else
9619 {
9620 gdb_printf (stream, _("%*sIterated choices:\n"), depth, "");
9621 gdb_printf (stream, _("%*sName: %s\n"), depth + 1, "", m_name.c_str ());
9622 }
a88c4354 9623 m_op->dump (stream, depth + 1);
542ea7fe 9624
a88c4354
TT
9625 for (const auto &item : m_assocs)
9626 item->dump (stream, depth + 1);
9627}
9628
9629/* Assign into the components of LHS indexed by the OP_CHOICES
9630 construct at *POS, updating *POS past the construct, given that
9631 the allowable indices are LOW..HIGH. Record the indices assigned
9632 to in INDICES. CONTAINER is as for assign_aggregate. */
9633void
d9d782dd 9634ada_choices_component::assign (aggregate_assigner &assigner)
a88c4354 9635{
542ea7fe 9636 scoped_restore save_index = make_scoped_restore (&m_assigner, &assigner);
a88c4354 9637 for (auto &item : m_assocs)
d9d782dd 9638 item->assign (assigner, m_op);
a88c4354
TT
9639}
9640
542ea7fe
TT
9641void
9642ada_index_var_operation::dump (struct ui_file *stream, int depth) const
9643{
9644 gdb_printf (stream, _("%*sIndex variable: %s\n"), depth, "",
9645 m_var->name ().c_str ());
9646}
9647
9648value *
9649ada_index_var_operation::evaluate (struct type *expect_type,
9650 struct expression *exp,
9651 enum noside noside)
9652{
9653 if (noside == EVAL_AVOID_SIDE_EFFECTS)
9654 {
9655 /* Note that using an integer type here is incorrect -- the type
9656 should be the array's index type. Unfortunately, though,
9657 this isn't currently available during parsing and type
9658 resolution. */
9659 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9660 return value::zero (index_type, not_lval);
9661 }
9662
9663 return m_var->current_value ();
9664}
9665
a88c4354
TT
9666bool
9667ada_others_component::uses_objfile (struct objfile *objfile)
9668{
9669 return m_op->uses_objfile (objfile);
9670}
9671
9672void
9673ada_others_component::dump (ui_file *stream, int depth)
9674{
6cb06a8c 9675 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
a88c4354
TT
9676 m_op->dump (stream, depth + 1);
9677}
9678
9679/* Assign the value of the expression in the OP_OTHERS construct in
9680 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9681 have not been previously assigned. The index intervals already assigned
9682 are in INDICES. CONTAINER is as for assign_aggregate. */
9683void
d9d782dd 9684ada_others_component::assign (aggregate_assigner &assigner)
a88c4354 9685{
d9d782dd 9686 int num_indices = assigner.indices.size ();
a88c4354
TT
9687 for (int i = 0; i < num_indices - 2; i += 2)
9688 {
d9d782dd
TT
9689 for (LONGEST ind = assigner.indices[i + 1] + 1;
9690 ind < assigner.indices[i + 2];
9691 ind += 1)
9692 assigner.assign (ind, m_op);
a88c4354
TT
9693 }
9694}
9695
9696struct value *
9697ada_assign_operation::evaluate (struct type *expect_type,
9698 struct expression *exp,
9699 enum noside noside)
9700{
9701 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
b3a27d2f 9702 scoped_restore save_lhs = make_scoped_restore (&m_current, arg1);
a88c4354
TT
9703
9704 ada_aggregate_operation *ag_op
9705 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9706 if (ag_op != nullptr)
9707 {
9708 if (noside != EVAL_NORMAL)
9709 return arg1;
9710
207582c0 9711 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
a88c4354
TT
9712 return ada_value_assign (arg1, arg1);
9713 }
9714 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9715 except if the lhs of our assignment is a convenience variable.
9716 In the case of assigning to a convenience variable, the lhs
9717 should be exactly the result of the evaluation of the rhs. */
d0c97917 9718 struct type *type = arg1->type ();
736355f2 9719 if (arg1->lval () == lval_internalvar)
a88c4354
TT
9720 type = NULL;
9721 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
0b2b0b82 9722 if (noside == EVAL_AVOID_SIDE_EFFECTS)
a88c4354 9723 return arg1;
736355f2 9724 if (arg1->lval () == lval_internalvar)
a88c4354
TT
9725 {
9726 /* Nothing. */
9727 }
9728 else
d0c97917 9729 arg2 = coerce_for_assign (arg1->type (), arg2);
a88c4354
TT
9730 return ada_value_assign (arg1, arg2);
9731}
9732
d9d782dd 9733/* See ada-exp.h. */
a88c4354 9734
d9d782dd
TT
9735void
9736aggregate_assigner::add_interval (LONGEST from, LONGEST to)
52ce6436
PH
9737{
9738 int i, j;
5b4ee69b 9739
cf608cc4
TT
9740 int size = indices.size ();
9741 for (i = 0; i < size; i += 2) {
d9d782dd 9742 if (to >= indices[i] && from <= indices[i + 1])
52ce6436
PH
9743 {
9744 int kh;
5b4ee69b 9745
cf608cc4 9746 for (kh = i + 2; kh < size; kh += 2)
d9d782dd 9747 if (to < indices[kh])
52ce6436 9748 break;
d9d782dd
TT
9749 if (from < indices[i])
9750 indices[i] = from;
52ce6436 9751 indices[i + 1] = indices[kh - 1];
d9d782dd
TT
9752 if (to > indices[i + 1])
9753 indices[i + 1] = to;
cf608cc4
TT
9754 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9755 indices.resize (kh - i - 2);
52ce6436
PH
9756 return;
9757 }
d9d782dd 9758 else if (to < indices[i])
52ce6436
PH
9759 break;
9760 }
9761
cf608cc4 9762 indices.resize (indices.size () + 2);
d4813f10 9763 for (j = indices.size () - 1; j >= i + 2; j -= 1)
52ce6436 9764 indices[j] = indices[j - 2];
d9d782dd
TT
9765 indices[i] = from;
9766 indices[i + 1] = to;
52ce6436
PH
9767}
9768
d9d782dd
TT
9769} /* namespace expr */
9770
6e48bd2c
JB
9771/* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9772 is different. */
9773
9774static struct value *
b7e22850 9775ada_value_cast (struct type *type, struct value *arg2)
6e48bd2c 9776{
d0c97917 9777 if (type == ada_check_typedef (arg2->type ()))
6e48bd2c
JB
9778 return arg2;
9779
6e48bd2c
JB
9780 return value_cast (type, arg2);
9781}
9782
284614f0
JB
9783/* Evaluating Ada expressions, and printing their result.
9784 ------------------------------------------------------
9785
21649b50
JB
9786 1. Introduction:
9787 ----------------
9788
284614f0
JB
9789 We usually evaluate an Ada expression in order to print its value.
9790 We also evaluate an expression in order to print its type, which
9791 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9792 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9793 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9794 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9795 similar.
9796
9797 Evaluating expressions is a little more complicated for Ada entities
9798 than it is for entities in languages such as C. The main reason for
9799 this is that Ada provides types whose definition might be dynamic.
9800 One example of such types is variant records. Or another example
9801 would be an array whose bounds can only be known at run time.
9802
9803 The following description is a general guide as to what should be
9804 done (and what should NOT be done) in order to evaluate an expression
9805 involving such types, and when. This does not cover how the semantic
9806 information is encoded by GNAT as this is covered separatly. For the
9807 document used as the reference for the GNAT encoding, see exp_dbug.ads
9808 in the GNAT sources.
9809
9810 Ideally, we should embed each part of this description next to its
9811 associated code. Unfortunately, the amount of code is so vast right
9812 now that it's hard to see whether the code handling a particular
9813 situation might be duplicated or not. One day, when the code is
9814 cleaned up, this guide might become redundant with the comments
9815 inserted in the code, and we might want to remove it.
9816
21649b50
JB
9817 2. ``Fixing'' an Entity, the Simple Case:
9818 -----------------------------------------
9819
284614f0
JB
9820 When evaluating Ada expressions, the tricky issue is that they may
9821 reference entities whose type contents and size are not statically
9822 known. Consider for instance a variant record:
9823
9824 type Rec (Empty : Boolean := True) is record
dda83cd7
SM
9825 case Empty is
9826 when True => null;
9827 when False => Value : Integer;
9828 end case;
284614f0
JB
9829 end record;
9830 Yes : Rec := (Empty => False, Value => 1);
9831 No : Rec := (empty => True);
9832
9833 The size and contents of that record depends on the value of the
33b5899f 9834 discriminant (Rec.Empty). At this point, neither the debugging
284614f0
JB
9835 information nor the associated type structure in GDB are able to
9836 express such dynamic types. So what the debugger does is to create
9837 "fixed" versions of the type that applies to the specific object.
30baf67b 9838 We also informally refer to this operation as "fixing" an object,
284614f0
JB
9839 which means creating its associated fixed type.
9840
9841 Example: when printing the value of variable "Yes" above, its fixed
9842 type would look like this:
9843
9844 type Rec is record
dda83cd7
SM
9845 Empty : Boolean;
9846 Value : Integer;
284614f0
JB
9847 end record;
9848
9849 On the other hand, if we printed the value of "No", its fixed type
9850 would become:
9851
9852 type Rec is record
dda83cd7 9853 Empty : Boolean;
284614f0
JB
9854 end record;
9855
9856 Things become a little more complicated when trying to fix an entity
9857 with a dynamic type that directly contains another dynamic type,
9858 such as an array of variant records, for instance. There are
9859 two possible cases: Arrays, and records.
9860
21649b50
JB
9861 3. ``Fixing'' Arrays:
9862 ---------------------
9863
9864 The type structure in GDB describes an array in terms of its bounds,
9865 and the type of its elements. By design, all elements in the array
9866 have the same type and we cannot represent an array of variant elements
9867 using the current type structure in GDB. When fixing an array,
9868 we cannot fix the array element, as we would potentially need one
9869 fixed type per element of the array. As a result, the best we can do
9870 when fixing an array is to produce an array whose bounds and size
9871 are correct (allowing us to read it from memory), but without having
9872 touched its element type. Fixing each element will be done later,
9873 when (if) necessary.
9874
9875 Arrays are a little simpler to handle than records, because the same
9876 amount of memory is allocated for each element of the array, even if
1b536f04 9877 the amount of space actually used by each element differs from element
21649b50 9878 to element. Consider for instance the following array of type Rec:
284614f0
JB
9879
9880 type Rec_Array is array (1 .. 2) of Rec;
9881
1b536f04
JB
9882 The actual amount of memory occupied by each element might be different
9883 from element to element, depending on the value of their discriminant.
21649b50 9884 But the amount of space reserved for each element in the array remains
1b536f04 9885 fixed regardless. So we simply need to compute that size using
21649b50
JB
9886 the debugging information available, from which we can then determine
9887 the array size (we multiply the number of elements of the array by
9888 the size of each element).
9889
9890 The simplest case is when we have an array of a constrained element
9891 type. For instance, consider the following type declarations:
9892
dda83cd7
SM
9893 type Bounded_String (Max_Size : Integer) is
9894 Length : Integer;
9895 Buffer : String (1 .. Max_Size);
9896 end record;
9897 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
21649b50
JB
9898
9899 In this case, the compiler describes the array as an array of
9900 variable-size elements (identified by its XVS suffix) for which
9901 the size can be read in the parallel XVZ variable.
9902
9903 In the case of an array of an unconstrained element type, the compiler
9904 wraps the array element inside a private PAD type. This type should not
9905 be shown to the user, and must be "unwrap"'ed before printing. Note
284614f0
JB
9906 that we also use the adjective "aligner" in our code to designate
9907 these wrapper types.
9908
1b536f04 9909 In some cases, the size allocated for each element is statically
21649b50
JB
9910 known. In that case, the PAD type already has the correct size,
9911 and the array element should remain unfixed.
9912
9913 But there are cases when this size is not statically known.
9914 For instance, assuming that "Five" is an integer variable:
284614f0 9915
dda83cd7
SM
9916 type Dynamic is array (1 .. Five) of Integer;
9917 type Wrapper (Has_Length : Boolean := False) is record
9918 Data : Dynamic;
9919 case Has_Length is
9920 when True => Length : Integer;
9921 when False => null;
9922 end case;
9923 end record;
9924 type Wrapper_Array is array (1 .. 2) of Wrapper;
284614f0 9925
dda83cd7
SM
9926 Hello : Wrapper_Array := (others => (Has_Length => True,
9927 Data => (others => 17),
9928 Length => 1));
284614f0
JB
9929
9930
9931 The debugging info would describe variable Hello as being an
9932 array of a PAD type. The size of that PAD type is not statically
9933 known, but can be determined using a parallel XVZ variable.
9934 In that case, a copy of the PAD type with the correct size should
9935 be used for the fixed array.
9936
21649b50
JB
9937 3. ``Fixing'' record type objects:
9938 ----------------------------------
9939
9940 Things are slightly different from arrays in the case of dynamic
284614f0
JB
9941 record types. In this case, in order to compute the associated
9942 fixed type, we need to determine the size and offset of each of
9943 its components. This, in turn, requires us to compute the fixed
9944 type of each of these components.
9945
9946 Consider for instance the example:
9947
dda83cd7
SM
9948 type Bounded_String (Max_Size : Natural) is record
9949 Str : String (1 .. Max_Size);
9950 Length : Natural;
9951 end record;
9952 My_String : Bounded_String (Max_Size => 10);
284614f0
JB
9953
9954 In that case, the position of field "Length" depends on the size
9955 of field Str, which itself depends on the value of the Max_Size
21649b50 9956 discriminant. In order to fix the type of variable My_String,
284614f0
JB
9957 we need to fix the type of field Str. Therefore, fixing a variant
9958 record requires us to fix each of its components.
9959
9960 However, if a component does not have a dynamic size, the component
9961 should not be fixed. In particular, fields that use a PAD type
9962 should not fixed. Here is an example where this might happen
9963 (assuming type Rec above):
9964
9965 type Container (Big : Boolean) is record
dda83cd7
SM
9966 First : Rec;
9967 After : Integer;
9968 case Big is
9969 when True => Another : Integer;
9970 when False => null;
9971 end case;
284614f0
JB
9972 end record;
9973 My_Container : Container := (Big => False,
dda83cd7
SM
9974 First => (Empty => True),
9975 After => 42);
284614f0
JB
9976
9977 In that example, the compiler creates a PAD type for component First,
9978 whose size is constant, and then positions the component After just
9979 right after it. The offset of component After is therefore constant
9980 in this case.
9981
9982 The debugger computes the position of each field based on an algorithm
9983 that uses, among other things, the actual position and size of the field
21649b50
JB
9984 preceding it. Let's now imagine that the user is trying to print
9985 the value of My_Container. If the type fixing was recursive, we would
284614f0
JB
9986 end up computing the offset of field After based on the size of the
9987 fixed version of field First. And since in our example First has
9988 only one actual field, the size of the fixed type is actually smaller
9989 than the amount of space allocated to that field, and thus we would
9990 compute the wrong offset of field After.
9991
21649b50
JB
9992 To make things more complicated, we need to watch out for dynamic
9993 components of variant records (identified by the ___XVL suffix in
9994 the component name). Even if the target type is a PAD type, the size
9995 of that type might not be statically known. So the PAD type needs
9996 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9997 we might end up with the wrong size for our component. This can be
9998 observed with the following type declarations:
284614f0 9999
dda83cd7
SM
10000 type Octal is new Integer range 0 .. 7;
10001 type Octal_Array is array (Positive range <>) of Octal;
10002 pragma Pack (Octal_Array);
284614f0 10003
dda83cd7
SM
10004 type Octal_Buffer (Size : Positive) is record
10005 Buffer : Octal_Array (1 .. Size);
10006 Length : Integer;
10007 end record;
284614f0
JB
10008
10009 In that case, Buffer is a PAD type whose size is unset and needs
10010 to be computed by fixing the unwrapped type.
10011
21649b50
JB
10012 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10013 ----------------------------------------------------------
10014
10015 Lastly, when should the sub-elements of an entity that remained unfixed
284614f0
JB
10016 thus far, be actually fixed?
10017
10018 The answer is: Only when referencing that element. For instance
10019 when selecting one component of a record, this specific component
10020 should be fixed at that point in time. Or when printing the value
10021 of a record, each component should be fixed before its value gets
10022 printed. Similarly for arrays, the element of the array should be
10023 fixed when printing each element of the array, or when extracting
10024 one element out of that array. On the other hand, fixing should
10025 not be performed on the elements when taking a slice of an array!
10026
31432a67 10027 Note that one of the side effects of miscomputing the offset and
284614f0
JB
10028 size of each field is that we end up also miscomputing the size
10029 of the containing type. This can have adverse results when computing
10030 the value of an entity. GDB fetches the value of an entity based
10031 on the size of its type, and thus a wrong size causes GDB to fetch
10032 the wrong amount of memory. In the case where the computed size is
10033 too small, GDB fetches too little data to print the value of our
31432a67 10034 entity. Results in this case are unpredictable, as we usually read
284614f0
JB
10035 past the buffer containing the data =:-o. */
10036
62d4bd94
TT
10037/* A helper function for TERNOP_IN_RANGE. */
10038
10039static value *
10040eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10041 enum noside noside,
10042 value *arg1, value *arg2, value *arg3)
10043{
62d4bd94
TT
10044 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10045 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10046 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10047 return
10048 value_from_longest (type,
10049 (value_less (arg1, arg3)
10050 || value_equal (arg1, arg3))
10051 && (value_less (arg2, arg1)
10052 || value_equal (arg2, arg1)));
10053}
10054
82390ab8
TT
10055/* A helper function for UNOP_NEG. */
10056
7c15d377 10057value *
82390ab8
TT
10058ada_unop_neg (struct type *expect_type,
10059 struct expression *exp,
10060 enum noside noside, enum exp_opcode op,
10061 struct value *arg1)
10062{
82390ab8
TT
10063 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10064 return value_neg (arg1);
10065}
10066
7efc87ff
TT
10067/* A helper function for UNOP_IN_RANGE. */
10068
95d49dfb 10069value *
7efc87ff
TT
10070ada_unop_in_range (struct type *expect_type,
10071 struct expression *exp,
10072 enum noside noside, enum exp_opcode op,
10073 struct value *arg1, struct type *type)
10074{
7efc87ff
TT
10075 struct value *arg2, *arg3;
10076 switch (type->code ())
10077 {
10078 default:
10079 lim_warning (_("Membership test incompletely implemented; "
10080 "always returns true"));
10081 type = language_bool_type (exp->language_defn, exp->gdbarch);
66cf9350 10082 return value_from_longest (type, 1);
7efc87ff
TT
10083
10084 case TYPE_CODE_RANGE:
10085 arg2 = value_from_longest (type,
10086 type->bounds ()->low.const_val ());
10087 arg3 = value_from_longest (type,
10088 type->bounds ()->high.const_val ());
10089 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10090 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10091 type = language_bool_type (exp->language_defn, exp->gdbarch);
10092 return
10093 value_from_longest (type,
10094 (value_less (arg1, arg3)
10095 || value_equal (arg1, arg3))
10096 && (value_less (arg2, arg1)
10097 || value_equal (arg2, arg1)));
10098 }
10099}
10100
020dbabe
TT
10101/* A helper function for OP_ATR_TAG. */
10102
7c15d377 10103value *
020dbabe
TT
10104ada_atr_tag (struct type *expect_type,
10105 struct expression *exp,
10106 enum noside noside, enum exp_opcode op,
10107 struct value *arg1)
10108{
10109 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10110 return value::zero (ada_tag_type (arg1), not_lval);
020dbabe
TT
10111
10112 return ada_value_tag (arg1);
10113}
10114
68c75735
TT
10115/* A helper function for OP_ATR_SIZE. */
10116
7c15d377 10117value *
68c75735
TT
10118ada_atr_size (struct type *expect_type,
10119 struct expression *exp,
10120 enum noside noside, enum exp_opcode op,
10121 struct value *arg1)
10122{
d0c97917 10123 struct type *type = arg1->type ();
68c75735
TT
10124
10125 /* If the argument is a reference, then dereference its type, since
10126 the user is really asking for the size of the actual object,
10127 not the size of the pointer. */
10128 if (type->code () == TYPE_CODE_REF)
27710edb 10129 type = type->target_type ();
68c75735 10130
0b2b0b82 10131 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10132 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
68c75735
TT
10133 else
10134 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
df86565b 10135 TARGET_CHAR_BIT * type->length ());
68c75735
TT
10136}
10137
d05e24e6
TT
10138/* A helper function for UNOP_ABS. */
10139
7c15d377 10140value *
d05e24e6
TT
10141ada_abs (struct type *expect_type,
10142 struct expression *exp,
10143 enum noside noside, enum exp_opcode op,
10144 struct value *arg1)
10145{
10146 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
ee7bb294 10147 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
d05e24e6
TT
10148 return value_neg (arg1);
10149 else
10150 return arg1;
10151}
10152
faa1dfd7
TT
10153/* A helper function for BINOP_MUL. */
10154
d9e7db06 10155value *
faa1dfd7
TT
10156ada_mult_binop (struct type *expect_type,
10157 struct expression *exp,
10158 enum noside noside, enum exp_opcode op,
10159 struct value *arg1, struct value *arg2)
10160{
10161 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10162 {
10163 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
ee7bb294 10164 return value::zero (arg1->type (), not_lval);
faa1dfd7
TT
10165 }
10166 else
10167 {
10168 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10169 return ada_value_binop (arg1, arg2, op);
10170 }
10171}
10172
214b13ac
TT
10173/* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10174
6e8fb7b7 10175value *
214b13ac
TT
10176ada_equal_binop (struct type *expect_type,
10177 struct expression *exp,
10178 enum noside noside, enum exp_opcode op,
10179 struct value *arg1, struct value *arg2)
10180{
10181 int tem;
10182 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10183 tem = 0;
10184 else
10185 {
10186 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10187 tem = ada_value_equal (arg1, arg2);
10188 }
10189 if (op == BINOP_NOTEQUAL)
10190 tem = !tem;
10191 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
66cf9350 10192 return value_from_longest (type, tem);
214b13ac
TT
10193}
10194
5ce19db8
TT
10195/* A helper function for TERNOP_SLICE. */
10196
1b1ebfab 10197value *
5ce19db8
TT
10198ada_ternop_slice (struct expression *exp,
10199 enum noside noside,
10200 struct value *array, struct value *low_bound_val,
10201 struct value *high_bound_val)
10202{
10203 LONGEST low_bound;
10204 LONGEST high_bound;
10205
10206 low_bound_val = coerce_ref (low_bound_val);
10207 high_bound_val = coerce_ref (high_bound_val);
10208 low_bound = value_as_long (low_bound_val);
10209 high_bound = value_as_long (high_bound_val);
10210
10211 /* If this is a reference to an aligner type, then remove all
10212 the aligners. */
d0c97917
TT
10213 if (array->type ()->code () == TYPE_CODE_REF
10214 && ada_is_aligner_type (array->type ()->target_type ()))
10215 array->type ()->set_target_type
10216 (ada_aligned_type (array->type ()->target_type ()));
5ce19db8 10217
d0c97917 10218 if (ada_is_any_packed_array_type (array->type ()))
5ce19db8
TT
10219 error (_("cannot slice a packed array"));
10220
10221 /* If this is a reference to an array or an array lvalue,
10222 convert to a pointer. */
d0c97917
TT
10223 if (array->type ()->code () == TYPE_CODE_REF
10224 || (array->type ()->code () == TYPE_CODE_ARRAY
736355f2 10225 && array->lval () == lval_memory))
5ce19db8
TT
10226 array = value_addr (array);
10227
10228 if (noside == EVAL_AVOID_SIDE_EFFECTS
10229 && ada_is_array_descriptor_type (ada_check_typedef
d0c97917 10230 (array->type ())))
5ce19db8
TT
10231 return empty_array (ada_type_of_array (array, 0), low_bound,
10232 high_bound);
10233
10234 array = ada_coerce_to_simple_array_ptr (array);
10235
10236 /* If we have more than one level of pointer indirection,
10237 dereference the value until we get only one level. */
d0c97917
TT
10238 while (array->type ()->code () == TYPE_CODE_PTR
10239 && (array->type ()->target_type ()->code ()
5ce19db8
TT
10240 == TYPE_CODE_PTR))
10241 array = value_ind (array);
10242
10243 /* Make sure we really do have an array type before going further,
10244 to avoid a SEGV when trying to get the index type or the target
10245 type later down the road if the debug info generated by
10246 the compiler is incorrect or incomplete. */
d0c97917 10247 if (!ada_is_simple_array_type (array->type ()))
5ce19db8
TT
10248 error (_("cannot take slice of non-array"));
10249
d0c97917 10250 if (ada_check_typedef (array->type ())->code ()
5ce19db8
TT
10251 == TYPE_CODE_PTR)
10252 {
d0c97917 10253 struct type *type0 = ada_check_typedef (array->type ());
5ce19db8
TT
10254
10255 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
27710edb 10256 return empty_array (type0->target_type (), low_bound, high_bound);
5ce19db8
TT
10257 else
10258 {
10259 struct type *arr_type0 =
27710edb 10260 to_fixed_array_type (type0->target_type (), NULL, 1);
5ce19db8
TT
10261
10262 return ada_value_slice_from_ptr (array, arr_type0,
10263 longest_to_int (low_bound),
10264 longest_to_int (high_bound));
10265 }
10266 }
10267 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10268 return array;
10269 else if (high_bound < low_bound)
d0c97917 10270 return empty_array (array->type (), low_bound, high_bound);
5ce19db8
TT
10271 else
10272 return ada_value_slice (array, longest_to_int (low_bound),
10273 longest_to_int (high_bound));
10274}
10275
b467efaa
TT
10276/* A helper function for BINOP_IN_BOUNDS. */
10277
82c3886e 10278value *
b467efaa
TT
10279ada_binop_in_bounds (struct expression *exp, enum noside noside,
10280 struct value *arg1, struct value *arg2, int n)
10281{
10282 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10283 {
10284 struct type *type = language_bool_type (exp->language_defn,
10285 exp->gdbarch);
ee7bb294 10286 return value::zero (type, not_lval);
b467efaa
TT
10287 }
10288
d0c97917 10289 struct type *type = ada_index_type (arg2->type (), n, "range");
b467efaa 10290 if (!type)
d0c97917 10291 type = arg1->type ();
b467efaa
TT
10292
10293 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10294 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10295
10296 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10297 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10298 type = language_bool_type (exp->language_defn, exp->gdbarch);
10299 return value_from_longest (type,
10300 (value_less (arg1, arg3)
10301 || value_equal (arg1, arg3))
10302 && (value_less (arg2, arg1)
10303 || value_equal (arg2, arg1)));
10304}
10305
b84564fc
TT
10306/* A helper function for some attribute operations. */
10307
10308static value *
10309ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10310 struct value *arg1, struct type *type_arg, int tem)
10311{
1e5ae3d1
TT
10312 const char *attr_name = nullptr;
10313 if (op == OP_ATR_FIRST)
10314 attr_name = "first";
10315 else if (op == OP_ATR_LAST)
10316 attr_name = "last";
10317
b84564fc
TT
10318 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10319 {
10320 if (type_arg == NULL)
d0c97917 10321 type_arg = arg1->type ();
b84564fc
TT
10322
10323 if (ada_is_constrained_packed_array_type (type_arg))
10324 type_arg = decode_constrained_packed_array_type (type_arg);
10325
10326 if (!discrete_type_p (type_arg))
10327 {
10328 switch (op)
10329 {
10330 default: /* Should never happen. */
10331 error (_("unexpected attribute encountered"));
10332 case OP_ATR_FIRST:
10333 case OP_ATR_LAST:
10334 type_arg = ada_index_type (type_arg, tem,
1e5ae3d1 10335 attr_name);
b84564fc
TT
10336 break;
10337 case OP_ATR_LENGTH:
10338 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10339 break;
10340 }
10341 }
10342
ee7bb294 10343 return value::zero (type_arg, not_lval);
b84564fc
TT
10344 }
10345 else if (type_arg == NULL)
10346 {
10347 arg1 = ada_coerce_ref (arg1);
10348
d0c97917 10349 if (ada_is_constrained_packed_array_type (arg1->type ()))
b84564fc
TT
10350 arg1 = ada_coerce_to_simple_array (arg1);
10351
10352 struct type *type;
10353 if (op == OP_ATR_LENGTH)
10354 type = builtin_type (exp->gdbarch)->builtin_int;
10355 else
10356 {
d0c97917 10357 type = ada_index_type (arg1->type (), tem,
1e5ae3d1 10358 attr_name);
b84564fc
TT
10359 if (type == NULL)
10360 type = builtin_type (exp->gdbarch)->builtin_int;
10361 }
10362
10363 switch (op)
10364 {
10365 default: /* Should never happen. */
10366 error (_("unexpected attribute encountered"));
10367 case OP_ATR_FIRST:
10368 return value_from_longest
10369 (type, ada_array_bound (arg1, tem, 0));
10370 case OP_ATR_LAST:
10371 return value_from_longest
10372 (type, ada_array_bound (arg1, tem, 1));
10373 case OP_ATR_LENGTH:
10374 return value_from_longest
10375 (type, ada_array_length (arg1, tem));
10376 }
10377 }
10378 else if (discrete_type_p (type_arg))
10379 {
10380 struct type *range_type;
10381 const char *name = ada_type_name (type_arg);
10382
10383 range_type = NULL;
10384 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10385 range_type = to_fixed_range_type (type_arg, NULL);
10386 if (range_type == NULL)
10387 range_type = type_arg;
10388 switch (op)
10389 {
10390 default:
10391 error (_("unexpected attribute encountered"));
10392 case OP_ATR_FIRST:
10393 return value_from_longest
10394 (range_type, ada_discrete_type_low_bound (range_type));
10395 case OP_ATR_LAST:
10396 return value_from_longest
10397 (range_type, ada_discrete_type_high_bound (range_type));
10398 case OP_ATR_LENGTH:
10399 error (_("the 'length attribute applies only to array types"));
10400 }
10401 }
10402 else if (type_arg->code () == TYPE_CODE_FLT)
10403 error (_("unimplemented type attribute"));
10404 else
10405 {
10406 LONGEST low, high;
10407
10408 if (ada_is_constrained_packed_array_type (type_arg))
10409 type_arg = decode_constrained_packed_array_type (type_arg);
10410
10411 struct type *type;
10412 if (op == OP_ATR_LENGTH)
10413 type = builtin_type (exp->gdbarch)->builtin_int;
10414 else
10415 {
1e5ae3d1 10416 type = ada_index_type (type_arg, tem, attr_name);
b84564fc
TT
10417 if (type == NULL)
10418 type = builtin_type (exp->gdbarch)->builtin_int;
10419 }
10420
10421 switch (op)
10422 {
10423 default:
10424 error (_("unexpected attribute encountered"));
10425 case OP_ATR_FIRST:
10426 low = ada_array_bound_from_type (type_arg, tem, 0);
10427 return value_from_longest (type, low);
10428 case OP_ATR_LAST:
10429 high = ada_array_bound_from_type (type_arg, tem, 1);
10430 return value_from_longest (type, high);
10431 case OP_ATR_LENGTH:
10432 low = ada_array_bound_from_type (type_arg, tem, 0);
10433 high = ada_array_bound_from_type (type_arg, tem, 1);
10434 return value_from_longest (type, high - low + 1);
10435 }
10436 }
10437}
10438
38dc70cf
TT
10439/* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10440
6ad3b8bf 10441struct value *
38dc70cf
TT
10442ada_binop_minmax (struct type *expect_type,
10443 struct expression *exp,
10444 enum noside noside, enum exp_opcode op,
10445 struct value *arg1, struct value *arg2)
10446{
10447 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10448 return value::zero (arg1->type (), not_lval);
38dc70cf
TT
10449 else
10450 {
10451 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
0922dc84 10452 return value_binop (arg1, arg2, op);
38dc70cf
TT
10453 }
10454}
10455
dd5fd283
TT
10456/* A helper function for BINOP_EXP. */
10457
065ec826 10458struct value *
dd5fd283
TT
10459ada_binop_exp (struct type *expect_type,
10460 struct expression *exp,
10461 enum noside noside, enum exp_opcode op,
10462 struct value *arg1, struct value *arg2)
10463{
10464 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10465 return value::zero (arg1->type (), not_lval);
dd5fd283
TT
10466 else
10467 {
10468 /* For integer exponentiation operations,
10469 only promote the first argument. */
d0c97917 10470 if (is_integral_type (arg2->type ()))
dd5fd283
TT
10471 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10472 else
10473 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10474
10475 return value_binop (arg1, arg2, op);
10476 }
10477}
10478
03070ee9
TT
10479namespace expr
10480{
10481
8b12db26
TT
10482/* See ada-exp.h. */
10483
10484operation_up
10485ada_resolvable::replace (operation_up &&owner,
10486 struct expression *exp,
10487 bool deprocedure_p,
10488 bool parse_completion,
10489 innermost_block_tracker *tracker,
10490 struct type *context_type)
10491{
10492 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10493 return (make_operation<ada_funcall_operation>
10494 (std::move (owner),
10495 std::vector<operation_up> ()));
10496 return std::move (owner);
10497}
10498
c9f66f00 10499/* Convert the character literal whose value would be VAL to the
03adb248
TT
10500 appropriate value of type TYPE, if there is a translation.
10501 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10502 the literal 'A' (VAL == 65), returns 0. */
10503
10504static LONGEST
10505convert_char_literal (struct type *type, LONGEST val)
10506{
c9f66f00 10507 char name[12];
03adb248
TT
10508 int f;
10509
10510 if (type == NULL)
10511 return val;
10512 type = check_typedef (type);
10513 if (type->code () != TYPE_CODE_ENUM)
10514 return val;
10515
10516 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10517 xsnprintf (name, sizeof (name), "Q%c", (int) val);
c9f66f00
TT
10518 else if (val >= 0 && val < 256)
10519 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10520 else if (val >= 0 && val < 0x10000)
10521 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
03adb248 10522 else
c9f66f00 10523 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
03adb248
TT
10524 size_t len = strlen (name);
10525 for (f = 0; f < type->num_fields (); f += 1)
10526 {
10527 /* Check the suffix because an enum constant in a package will
10528 have a name like "pkg__QUxx". This is safe enough because we
10529 already have the correct type, and because mangling means
10530 there can't be clashes. */
33d16dd9 10531 const char *ename = type->field (f).name ();
03adb248
TT
10532 size_t elen = strlen (ename);
10533
10534 if (elen >= len && strcmp (name, ename + elen - len) == 0)
970db518 10535 return type->field (f).loc_enumval ();
03adb248
TT
10536 }
10537 return val;
10538}
10539
b1b9c411
TT
10540value *
10541ada_char_operation::evaluate (struct type *expect_type,
10542 struct expression *exp,
10543 enum noside noside)
10544{
10545 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10546 if (expect_type != nullptr)
10547 result = ada_value_cast (expect_type, result);
10548 return result;
10549}
10550
03adb248
TT
10551/* See ada-exp.h. */
10552
10553operation_up
10554ada_char_operation::replace (operation_up &&owner,
10555 struct expression *exp,
10556 bool deprocedure_p,
10557 bool parse_completion,
10558 innermost_block_tracker *tracker,
10559 struct type *context_type)
10560{
10561 operation_up result = std::move (owner);
10562
10563 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10564 {
5309ce2f 10565 LONGEST val = as_longest ();
03adb248
TT
10566 gdb_assert (result.get () == this);
10567 std::get<0> (m_storage) = context_type;
5309ce2f 10568 std::get<1> (m_storage) = convert_char_literal (context_type, val);
03adb248
TT
10569 }
10570
b1b9c411 10571 return result;
03adb248
TT
10572}
10573
03070ee9
TT
10574value *
10575ada_wrapped_operation::evaluate (struct type *expect_type,
10576 struct expression *exp,
10577 enum noside noside)
10578{
10579 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10580 if (noside == EVAL_NORMAL)
10581 result = unwrap_value (result);
10582
10583 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10584 then we need to perform the conversion manually, because
10585 evaluate_subexp_standard doesn't do it. This conversion is
10586 necessary in Ada because the different kinds of float/fixed
10587 types in Ada have different representations.
10588
10589 Similarly, we need to perform the conversion from OP_LONG
10590 ourselves. */
10591 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10592 result = ada_value_cast (expect_type, result);
10593
10594 return result;
10595}
10596
013a623f
TT
10597void
10598ada_wrapped_operation::do_generate_ax (struct expression *exp,
10599 struct agent_expr *ax,
10600 struct axs_value *value,
10601 struct type *cast_type)
10602{
10603 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10604
10605 struct type *type = value->type;
10606 if (ada_is_aligner_type (type))
10607 error (_("Aligner types cannot be handled in agent expressions"));
10608 else if (find_base_type (type) != nullptr)
10609 error (_("Dynamic types cannot be handled in agent expressions"));
10610}
10611
42fecb61
TT
10612value *
10613ada_string_operation::evaluate (struct type *expect_type,
10614 struct expression *exp,
10615 enum noside noside)
10616{
fc18a21b
TT
10617 struct type *char_type;
10618 if (expect_type != nullptr && ada_is_string_type (expect_type))
10619 char_type = ada_array_element_type (expect_type, 1);
10620 else
10621 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10622
10623 const std::string &str = std::get<0> (m_storage);
10624 const char *encoding;
df86565b 10625 switch (char_type->length ())
fc18a21b
TT
10626 {
10627 case 1:
10628 {
10629 /* Simply copy over the data -- this isn't perhaps strictly
10630 correct according to the encodings, but it is gdb's
10631 historical behavior. */
10632 struct type *stringtype
10633 = lookup_array_range_type (char_type, 1, str.length ());
317c3ed9 10634 struct value *val = value::allocate (stringtype);
bbe912ba 10635 memcpy (val->contents_raw ().data (), str.c_str (),
fc18a21b
TT
10636 str.length ());
10637 return val;
10638 }
10639
10640 case 2:
10641 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10642 encoding = "UTF-16BE";
10643 else
10644 encoding = "UTF-16LE";
10645 break;
10646
10647 case 4:
10648 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10649 encoding = "UTF-32BE";
10650 else
10651 encoding = "UTF-32LE";
10652 break;
10653
10654 default:
10655 error (_("unexpected character type size %s"),
df86565b 10656 pulongest (char_type->length ()));
fc18a21b
TT
10657 }
10658
10659 auto_obstack converted;
10660 convert_between_encodings (host_charset (), encoding,
10661 (const gdb_byte *) str.c_str (),
10662 str.length (), 1,
10663 &converted, translit_none);
10664
10665 struct type *stringtype
10666 = lookup_array_range_type (char_type, 1,
10667 obstack_object_size (&converted)
df86565b 10668 / char_type->length ());
317c3ed9 10669 struct value *val = value::allocate (stringtype);
bbe912ba 10670 memcpy (val->contents_raw ().data (),
fc18a21b
TT
10671 obstack_base (&converted),
10672 obstack_object_size (&converted));
10673 return val;
42fecb61
TT
10674}
10675
b1b9c411
TT
10676value *
10677ada_concat_operation::evaluate (struct type *expect_type,
10678 struct expression *exp,
10679 enum noside noside)
10680{
10681 /* If one side is a literal, evaluate the other side first so that
10682 the expected type can be set properly. */
10683 const operation_up &lhs_expr = std::get<0> (m_storage);
10684 const operation_up &rhs_expr = std::get<1> (m_storage);
10685
10686 value *lhs, *rhs;
10687 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10688 {
10689 rhs = rhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10690 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
b1b9c411
TT
10691 }
10692 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10693 {
10694 rhs = rhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10695 struct type *rhs_type = check_typedef (rhs->type ());
b1b9c411
TT
10696 struct type *elt_type = nullptr;
10697 if (rhs_type->code () == TYPE_CODE_ARRAY)
27710edb 10698 elt_type = rhs_type->target_type ();
b1b9c411
TT
10699 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10700 }
10701 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10702 {
10703 lhs = lhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10704 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
b1b9c411
TT
10705 }
10706 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10707 {
10708 lhs = lhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10709 struct type *lhs_type = check_typedef (lhs->type ());
b1b9c411
TT
10710 struct type *elt_type = nullptr;
10711 if (lhs_type->code () == TYPE_CODE_ARRAY)
27710edb 10712 elt_type = lhs_type->target_type ();
b1b9c411
TT
10713 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10714 }
10715 else
10716 return concat_operation::evaluate (expect_type, exp, noside);
10717
10718 return value_concat (lhs, rhs);
10719}
10720
cc6bd32e
TT
10721value *
10722ada_qual_operation::evaluate (struct type *expect_type,
10723 struct expression *exp,
10724 enum noside noside)
10725{
10726 struct type *type = std::get<1> (m_storage);
10727 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10728}
10729
fc715eb2
TT
10730value *
10731ada_ternop_range_operation::evaluate (struct type *expect_type,
10732 struct expression *exp,
10733 enum noside noside)
10734{
10735 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10736 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10737 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10738 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10739}
10740
73796c73
TT
10741value *
10742ada_binop_addsub_operation::evaluate (struct type *expect_type,
10743 struct expression *exp,
10744 enum noside noside)
10745{
10746 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10747 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10748
5bd5fecd 10749 auto do_op = [this] (LONGEST x, LONGEST y)
73796c73
TT
10750 {
10751 if (std::get<0> (m_storage) == BINOP_ADD)
10752 return x + y;
10753 return x - y;
10754 };
10755
d0c97917 10756 if (arg1->type ()->code () == TYPE_CODE_PTR)
73796c73 10757 return (value_from_longest
d0c97917 10758 (arg1->type (),
73796c73 10759 do_op (value_as_long (arg1), value_as_long (arg2))));
d0c97917 10760 if (arg2->type ()->code () == TYPE_CODE_PTR)
73796c73 10761 return (value_from_longest
d0c97917 10762 (arg2->type (),
73796c73
TT
10763 do_op (value_as_long (arg1), value_as_long (arg2))));
10764 /* Preserve the original type for use by the range case below.
10765 We cannot cast the result to a reference type, so if ARG1 is
10766 a reference type, find its underlying type. */
d0c97917 10767 struct type *type = arg1->type ();
73796c73 10768 while (type->code () == TYPE_CODE_REF)
27710edb 10769 type = type->target_type ();
73796c73
TT
10770 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10771 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10772 /* We need to special-case the result with a range.
10773 This is done for the benefit of "ptype". gdb's Ada support
10774 historically used the LHS to set the result type here, so
10775 preserve this behavior. */
10776 if (type->code () == TYPE_CODE_RANGE)
10777 arg1 = value_cast (type, arg1);
10778 return arg1;
10779}
10780
60fa02ca
TT
10781value *
10782ada_unop_atr_operation::evaluate (struct type *expect_type,
10783 struct expression *exp,
10784 enum noside noside)
10785{
10786 struct type *type_arg = nullptr;
10787 value *val = nullptr;
10788
10789 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10790 {
10791 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10792 EVAL_AVOID_SIDE_EFFECTS);
d0c97917 10793 type_arg = tem->type ();
60fa02ca
TT
10794 }
10795 else
10796 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10797
10798 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10799 val, type_arg, std::get<2> (m_storage));
10800}
10801
3f4a0053
TT
10802value *
10803ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10804 struct expression *exp,
10805 enum noside noside)
10806{
10807 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10808 return value::zero (expect_type, not_lval);
3f4a0053 10809
9c79936b
TT
10810 const bound_minimal_symbol &b = std::get<0> (m_storage);
10811 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
3f4a0053
TT
10812
10813 val = ada_value_cast (expect_type, val);
10814
10815 /* Follow the Ada language semantics that do not allow taking
10816 an address of the result of a cast (view conversion in Ada). */
736355f2 10817 if (val->lval () == lval_memory)
3f4a0053 10818 {
3ee3b270 10819 if (val->lazy ())
78259c36 10820 val->fetch_lazy ();
6f9c9d71 10821 val->set_lval (not_lval);
3f4a0053
TT
10822 }
10823 return val;
10824}
10825
99a3b1e7
TT
10826value *
10827ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10828 struct expression *exp,
10829 enum noside noside)
10830{
10831 value *val = evaluate_var_value (noside,
9e5e03df
TT
10832 std::get<0> (m_storage).block,
10833 std::get<0> (m_storage).symbol);
99a3b1e7
TT
10834
10835 val = ada_value_cast (expect_type, val);
10836
10837 /* Follow the Ada language semantics that do not allow taking
10838 an address of the result of a cast (view conversion in Ada). */
736355f2 10839 if (val->lval () == lval_memory)
99a3b1e7 10840 {
3ee3b270 10841 if (val->lazy ())
78259c36 10842 val->fetch_lazy ();
6f9c9d71 10843 val->set_lval (not_lval);
99a3b1e7
TT
10844 }
10845 return val;
10846}
10847
10848value *
10849ada_var_value_operation::evaluate (struct type *expect_type,
10850 struct expression *exp,
10851 enum noside noside)
10852{
9e5e03df 10853 symbol *sym = std::get<0> (m_storage).symbol;
99a3b1e7 10854
6c9c307c 10855 if (sym->domain () == UNDEF_DOMAIN)
99a3b1e7
TT
10856 /* Only encountered when an unresolved symbol occurs in a
10857 context other than a function call, in which case, it is
10858 invalid. */
10859 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10860 sym->print_name ());
10861
10862 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10863 {
5f9c5a63 10864 struct type *type = static_unwrap_type (sym->type ());
99a3b1e7
TT
10865 /* Check to see if this is a tagged type. We also need to handle
10866 the case where the type is a reference to a tagged type, but
10867 we have to be careful to exclude pointers to tagged types.
10868 The latter should be shown as usual (as a pointer), whereas
10869 a reference should mostly be transparent to the user. */
10870 if (ada_is_tagged_type (type, 0)
10871 || (type->code () == TYPE_CODE_REF
27710edb 10872 && ada_is_tagged_type (type->target_type (), 0)))
99a3b1e7
TT
10873 {
10874 /* Tagged types are a little special in the fact that the real
10875 type is dynamic and can only be determined by inspecting the
10876 object's tag. This means that we need to get the object's
10877 value first (EVAL_NORMAL) and then extract the actual object
10878 type from its tag.
10879
10880 Note that we cannot skip the final step where we extract
10881 the object type from its tag, because the EVAL_NORMAL phase
10882 results in dynamic components being resolved into fixed ones.
10883 This can cause problems when trying to print the type
10884 description of tagged types whose parent has a dynamic size:
10885 We use the type name of the "_parent" component in order
10886 to print the name of the ancestor type in the type description.
10887 If that component had a dynamic size, the resolution into
10888 a fixed type would result in the loss of that type name,
10889 thus preventing us from printing the name of the ancestor
10890 type in the type description. */
9863c3b5 10891 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
99a3b1e7
TT
10892
10893 if (type->code () != TYPE_CODE_REF)
10894 {
10895 struct type *actual_type;
10896
10897 actual_type = type_from_tag (ada_value_tag (arg1));
10898 if (actual_type == NULL)
10899 /* If, for some reason, we were unable to determine
10900 the actual type from the tag, then use the static
10901 approximation that we just computed as a fallback.
10902 This can happen if the debugging information is
10903 incomplete, for instance. */
10904 actual_type = type;
ee7bb294 10905 return value::zero (actual_type, not_lval);
99a3b1e7
TT
10906 }
10907 else
10908 {
10909 /* In the case of a ref, ada_coerce_ref takes care
10910 of determining the actual type. But the evaluation
10911 should return a ref as it should be valid to ask
10912 for its address; so rebuild a ref after coerce. */
10913 arg1 = ada_coerce_ref (arg1);
10914 return value_ref (arg1, TYPE_CODE_REF);
10915 }
10916 }
10917
10918 /* Records and unions for which GNAT encodings have been
10919 generated need to be statically fixed as well.
10920 Otherwise, non-static fixing produces a type where
10921 all dynamic properties are removed, which prevents "ptype"
10922 from being able to completely describe the type.
10923 For instance, a case statement in a variant record would be
10924 replaced by the relevant components based on the actual
10925 value of the discriminants. */
10926 if ((type->code () == TYPE_CODE_STRUCT
10927 && dynamic_template_type (type) != NULL)
10928 || (type->code () == TYPE_CODE_UNION
10929 && ada_find_parallel_type (type, "___XVU") != NULL))
ee7bb294 10930 return value::zero (to_static_fixed_type (type), not_lval);
99a3b1e7
TT
10931 }
10932
10933 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10934 return ada_to_fixed_value (arg1);
10935}
10936
d8a4ed8a
TT
10937bool
10938ada_var_value_operation::resolve (struct expression *exp,
10939 bool deprocedure_p,
10940 bool parse_completion,
10941 innermost_block_tracker *tracker,
10942 struct type *context_type)
10943{
9e5e03df 10944 symbol *sym = std::get<0> (m_storage).symbol;
6c9c307c 10945 if (sym->domain () == UNDEF_DOMAIN)
d8a4ed8a
TT
10946 {
10947 block_symbol resolved
9e5e03df 10948 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
d8a4ed8a
TT
10949 context_type, parse_completion,
10950 deprocedure_p, tracker);
9e5e03df 10951 std::get<0> (m_storage) = resolved;
d8a4ed8a
TT
10952 }
10953
10954 if (deprocedure_p
5f9c5a63 10955 && (std::get<0> (m_storage).symbol->type ()->code ()
9e5e03df 10956 == TYPE_CODE_FUNC))
d8a4ed8a
TT
10957 return true;
10958
10959 return false;
10960}
10961
013a623f
TT
10962void
10963ada_var_value_operation::do_generate_ax (struct expression *exp,
10964 struct agent_expr *ax,
10965 struct axs_value *value,
10966 struct type *cast_type)
10967{
10968 symbol *sym = std::get<0> (m_storage).symbol;
10969
10970 if (sym->domain () == UNDEF_DOMAIN)
10971 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10972 sym->print_name ());
10973
10974 struct type *type = static_unwrap_type (sym->type ());
10975 if (ada_is_tagged_type (type, 0)
10976 || (type->code () == TYPE_CODE_REF
10977 && ada_is_tagged_type (type->target_type (), 0)))
10978 error (_("Tagged types cannot be handled in agent expressions"));
10979
10980 if ((type->code () == TYPE_CODE_STRUCT
10981 && dynamic_template_type (type) != NULL)
10982 || (type->code () == TYPE_CODE_UNION
10983 && ada_find_parallel_type (type, "___XVU") != NULL))
10984 error (_("Dynamic types cannot be handled in agent expressions"));
10985
10986 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10987}
10988
e8c33fa1
TT
10989value *
10990ada_unop_ind_operation::evaluate (struct type *expect_type,
10991 struct expression *exp,
10992 enum noside noside)
10993{
10994 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10995
d0c97917 10996 struct type *type = ada_check_typedef (arg1->type ());
e8c33fa1
TT
10997 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10998 {
10999 if (ada_is_array_descriptor_type (type))
e8c33fa1 11000 {
1dd09e7f
TT
11001 /* GDB allows dereferencing GNAT array descriptors.
11002 However, for 'ptype' we don't want to try to
11003 "dereference" a thick pointer here -- that will end up
11004 giving us an array with (1 .. 0) for bounds, which is
11005 less clear than (<>). */
e8c33fa1
TT
11006 struct type *arrType = ada_type_of_array (arg1, 0);
11007
11008 if (arrType == NULL)
11009 error (_("Attempt to dereference null array pointer."));
1dd09e7f
TT
11010 if (is_thick_pntr (type))
11011 return arg1;
e8c33fa1
TT
11012 return value_at_lazy (arrType, 0);
11013 }
11014 else if (type->code () == TYPE_CODE_PTR
11015 || type->code () == TYPE_CODE_REF
11016 /* In C you can dereference an array to get the 1st elt. */
11017 || type->code () == TYPE_CODE_ARRAY)
11018 {
11019 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11020 only be determined by inspecting the object's tag.
11021 This means that we need to evaluate completely the
11022 expression in order to get its type. */
11023
11024 if ((type->code () == TYPE_CODE_REF
11025 || type->code () == TYPE_CODE_PTR)
27710edb 11026 && ada_is_tagged_type (type->target_type (), 0))
e8c33fa1
TT
11027 {
11028 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11029 EVAL_NORMAL);
d0c97917 11030 type = ada_value_ind (arg1)->type ();
e8c33fa1
TT
11031 }
11032 else
11033 {
11034 type = to_static_fixed_type
11035 (ada_aligned_type
27710edb 11036 (ada_check_typedef (type->target_type ())));
e8c33fa1 11037 }
ee7bb294 11038 return value::zero (type, lval_memory);
e8c33fa1
TT
11039 }
11040 else if (type->code () == TYPE_CODE_INT)
11041 {
11042 /* GDB allows dereferencing an int. */
11043 if (expect_type == NULL)
ee7bb294 11044 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
e8c33fa1
TT
11045 lval_memory);
11046 else
11047 {
11048 expect_type =
11049 to_static_fixed_type (ada_aligned_type (expect_type));
ee7bb294 11050 return value::zero (expect_type, lval_memory);
e8c33fa1
TT
11051 }
11052 }
11053 else
11054 error (_("Attempt to take contents of a non-pointer value."));
11055 }
11056 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
d0c97917 11057 type = ada_check_typedef (arg1->type ());
e8c33fa1
TT
11058
11059 if (type->code () == TYPE_CODE_INT)
11060 /* GDB allows dereferencing an int. If we were given
11061 the expect_type, then use that as the target type.
11062 Otherwise, assume that the target type is an int. */
11063 {
11064 if (expect_type != NULL)
11065 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11066 arg1));
11067 else
11068 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
4c3b59d5 11069 value_as_address (arg1));
e8c33fa1
TT
11070 }
11071
11072 if (ada_is_array_descriptor_type (type))
11073 /* GDB allows dereferencing GNAT array descriptors. */
11074 return ada_coerce_to_simple_array (arg1);
11075 else
11076 return ada_value_ind (arg1);
11077}
11078
ebc06ad8
TT
11079value *
11080ada_structop_operation::evaluate (struct type *expect_type,
11081 struct expression *exp,
11082 enum noside noside)
11083{
11084 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11085 const char *str = std::get<1> (m_storage).c_str ();
11086 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11087 {
11088 struct type *type;
d0c97917 11089 struct type *type1 = arg1->type ();
ebc06ad8
TT
11090
11091 if (ada_is_tagged_type (type1, 1))
11092 {
11093 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11094
11095 /* If the field is not found, check if it exists in the
11096 extension of this object's type. This means that we
11097 need to evaluate completely the expression. */
11098
11099 if (type == NULL)
11100 {
11101 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11102 EVAL_NORMAL);
11103 arg1 = ada_value_struct_elt (arg1, str, 0);
11104 arg1 = unwrap_value (arg1);
d0c97917 11105 type = ada_to_fixed_value (arg1)->type ();
ebc06ad8
TT
11106 }
11107 }
11108 else
11109 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11110
ee7bb294 11111 return value::zero (ada_aligned_type (type), lval_memory);
ebc06ad8
TT
11112 }
11113 else
11114 {
11115 arg1 = ada_value_struct_elt (arg1, str, 0);
11116 arg1 = unwrap_value (arg1);
11117 return ada_to_fixed_value (arg1);
11118 }
11119}
11120
efe3af2f
TT
11121value *
11122ada_funcall_operation::evaluate (struct type *expect_type,
11123 struct expression *exp,
11124 enum noside noside)
11125{
11126 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11127 int nargs = args_up.size ();
11128 std::vector<value *> argvec (nargs);
11129 operation_up &callee_op = std::get<0> (m_storage);
11130
11131 ada_var_value_operation *avv
11132 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11133 if (avv != nullptr
6c9c307c 11134 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
efe3af2f
TT
11135 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11136 avv->get_symbol ()->print_name ());
11137
11138 value *callee = callee_op->evaluate (nullptr, exp, noside);
11139 for (int i = 0; i < args_up.size (); ++i)
11140 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11141
11142 if (ada_is_constrained_packed_array_type
d0c97917 11143 (desc_base_type (callee->type ())))
efe3af2f 11144 callee = ada_coerce_to_simple_array (callee);
d0c97917 11145 else if (callee->type ()->code () == TYPE_CODE_ARRAY
3757d2d4 11146 && callee->type ()->field (0).bitsize () != 0)
efe3af2f
TT
11147 /* This is a packed array that has already been fixed, and
11148 therefore already coerced to a simple array. Nothing further
11149 to do. */
11150 ;
d0c97917 11151 else if (callee->type ()->code () == TYPE_CODE_REF)
efe3af2f
TT
11152 {
11153 /* Make sure we dereference references so that all the code below
11154 feels like it's really handling the referenced value. Wrapping
11155 types (for alignment) may be there, so make sure we strip them as
11156 well. */
11157 callee = ada_to_fixed_value (coerce_ref (callee));
11158 }
d0c97917 11159 else if (callee->type ()->code () == TYPE_CODE_ARRAY
736355f2 11160 && callee->lval () == lval_memory)
efe3af2f
TT
11161 callee = value_addr (callee);
11162
d0c97917 11163 struct type *type = ada_check_typedef (callee->type ());
efe3af2f
TT
11164
11165 /* Ada allows us to implicitly dereference arrays when subscripting
11166 them. So, if this is an array typedef (encoding use for array
11167 access types encoded as fat pointers), strip it now. */
11168 if (type->code () == TYPE_CODE_TYPEDEF)
11169 type = ada_typedef_target_type (type);
11170
11171 if (type->code () == TYPE_CODE_PTR)
11172 {
27710edb 11173 switch (ada_check_typedef (type->target_type ())->code ())
efe3af2f
TT
11174 {
11175 case TYPE_CODE_FUNC:
27710edb 11176 type = ada_check_typedef (type->target_type ());
efe3af2f
TT
11177 break;
11178 case TYPE_CODE_ARRAY:
11179 break;
11180 case TYPE_CODE_STRUCT:
11181 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11182 callee = ada_value_ind (callee);
27710edb 11183 type = ada_check_typedef (type->target_type ());
efe3af2f
TT
11184 break;
11185 default:
11186 error (_("cannot subscript or call something of type `%s'"),
d0c97917 11187 ada_type_name (callee->type ()));
efe3af2f
TT
11188 break;
11189 }
11190 }
11191
11192 switch (type->code ())
11193 {
11194 case TYPE_CODE_FUNC:
11195 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11196 {
27710edb 11197 if (type->target_type () == NULL)
efe3af2f 11198 error_call_unknown_return_type (NULL);
317c3ed9 11199 return value::allocate (type->target_type ());
efe3af2f 11200 }
61f9fb1e 11201 return call_function_by_hand (callee, expect_type, argvec);
efe3af2f
TT
11202 case TYPE_CODE_INTERNAL_FUNCTION:
11203 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11204 /* We don't know anything about what the internal
11205 function might return, but we have to return
11206 something. */
ee7bb294 11207 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
efe3af2f
TT
11208 not_lval);
11209 else
11210 return call_internal_function (exp->gdbarch, exp->language_defn,
11211 callee, nargs,
11212 argvec.data ());
11213
d3c54a1c
TT
11214 case TYPE_CODE_STRUCT:
11215 {
11216 int arity;
4c4b4cd2 11217
d3c54a1c
TT
11218 arity = ada_array_arity (type);
11219 type = ada_array_element_type (type, nargs);
11220 if (type == NULL)
11221 error (_("cannot subscript or call a record"));
11222 if (arity != nargs)
11223 error (_("wrong number of subscripts; expecting %d"), arity);
11224 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 11225 return value::zero (ada_aligned_type (type), lval_memory);
d3c54a1c
TT
11226 return
11227 unwrap_value (ada_value_subscript
11228 (callee, nargs, argvec.data ()));
11229 }
11230 case TYPE_CODE_ARRAY:
14f9c5c9 11231 if (noside == EVAL_AVOID_SIDE_EFFECTS)
dda83cd7 11232 {
d3c54a1c
TT
11233 type = ada_array_element_type (type, nargs);
11234 if (type == NULL)
11235 error (_("element type of array unknown"));
dda83cd7 11236 else
ee7bb294 11237 return value::zero (ada_aligned_type (type), lval_memory);
dda83cd7 11238 }
d3c54a1c
TT
11239 return
11240 unwrap_value (ada_value_subscript
11241 (ada_coerce_to_simple_array (callee),
11242 nargs, argvec.data ()));
11243 case TYPE_CODE_PTR: /* Pointer to array */
11244 if (noside == EVAL_AVOID_SIDE_EFFECTS)
dda83cd7 11245 {
27710edb 11246 type = to_fixed_array_type (type->target_type (), NULL, 1);
d3c54a1c
TT
11247 type = ada_array_element_type (type, nargs);
11248 if (type == NULL)
11249 error (_("element type of array unknown"));
96967637 11250 else
ee7bb294 11251 return value::zero (ada_aligned_type (type), lval_memory);
dda83cd7 11252 }
d3c54a1c
TT
11253 return
11254 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11255 argvec.data ()));
6b0d7253 11256
d3c54a1c
TT
11257 default:
11258 error (_("Attempt to index or call something other than an "
11259 "array or function"));
11260 }
11261}
5b4ee69b 11262
d3c54a1c
TT
11263bool
11264ada_funcall_operation::resolve (struct expression *exp,
11265 bool deprocedure_p,
11266 bool parse_completion,
11267 innermost_block_tracker *tracker,
11268 struct type *context_type)
11269{
11270 operation_up &callee_op = std::get<0> (m_storage);
5ec18f2b 11271
d3c54a1c
TT
11272 ada_var_value_operation *avv
11273 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11274 if (avv == nullptr)
11275 return false;
5ec18f2b 11276
d3c54a1c 11277 symbol *sym = avv->get_symbol ();
6c9c307c 11278 if (sym->domain () != UNDEF_DOMAIN)
d3c54a1c 11279 return false;
dda83cd7 11280
d3c54a1c
TT
11281 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11282 int nargs = args_up.size ();
11283 std::vector<value *> argvec (nargs);
284614f0 11284
d3c54a1c
TT
11285 for (int i = 0; i < args_up.size (); ++i)
11286 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
52ce6436 11287
d3c54a1c
TT
11288 const block *block = avv->get_block ();
11289 block_symbol resolved
11290 = ada_resolve_funcall (sym, block,
11291 context_type, parse_completion,
11292 nargs, argvec.data (),
11293 tracker);
11294
11295 std::get<0> (m_storage)
9e5e03df 11296 = make_operation<ada_var_value_operation> (resolved);
d3c54a1c
TT
11297 return false;
11298}
11299
11300bool
11301ada_ternop_slice_operation::resolve (struct expression *exp,
11302 bool deprocedure_p,
11303 bool parse_completion,
11304 innermost_block_tracker *tracker,
11305 struct type *context_type)
11306{
11307 /* Historically this check was done during resolution, so we
11308 continue that here. */
11309 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11310 EVAL_AVOID_SIDE_EFFECTS);
d0c97917 11311 if (ada_is_any_packed_array_type (v->type ()))
d3c54a1c
TT
11312 error (_("cannot slice a packed array"));
11313 return false;
11314}
14f9c5c9 11315
14f9c5c9 11316}
d3c54a1c 11317
14f9c5c9 11318\f
d2e4a39e 11319
4c4b4cd2
PH
11320/* Return non-zero iff TYPE represents a System.Address type. */
11321
11322int
11323ada_is_system_address_type (struct type *type)
11324{
7d93a1e0 11325 return (type->name () && strcmp (type->name (), "system__address") == 0);
4c4b4cd2
PH
11326}
11327
14f9c5c9 11328\f
d2e4a39e 11329
dda83cd7 11330 /* Range types */
14f9c5c9
AS
11331
11332/* Scan STR beginning at position K for a discriminant name, and
11333 return the value of that discriminant field of DVAL in *PX. If
11334 PNEW_K is not null, put the position of the character beyond the
11335 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
4c4b4cd2 11336 not alter *PX and *PNEW_K if unsuccessful. */
14f9c5c9
AS
11337
11338static int
108d56a4 11339scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
dda83cd7 11340 int *pnew_k)
14f9c5c9 11341{
5f9febe0 11342 static std::string storage;
5da1a4d3 11343 const char *pstart, *pend, *bound;
d2e4a39e 11344 struct value *bound_val;
14f9c5c9
AS
11345
11346 if (dval == NULL || str == NULL || str[k] == '\0')
11347 return 0;
11348
5da1a4d3
SM
11349 pstart = str + k;
11350 pend = strstr (pstart, "__");
14f9c5c9
AS
11351 if (pend == NULL)
11352 {
5da1a4d3 11353 bound = pstart;
14f9c5c9
AS
11354 k += strlen (bound);
11355 }
d2e4a39e 11356 else
14f9c5c9 11357 {
5da1a4d3
SM
11358 int len = pend - pstart;
11359
11360 /* Strip __ and beyond. */
5f9febe0
TT
11361 storage = std::string (pstart, len);
11362 bound = storage.c_str ();
d2e4a39e 11363 k = pend - str;
14f9c5c9 11364 }
d2e4a39e 11365
d0c97917 11366 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
14f9c5c9
AS
11367 if (bound_val == NULL)
11368 return 0;
11369
11370 *px = value_as_long (bound_val);
11371 if (pnew_k != NULL)
11372 *pnew_k = k;
11373 return 1;
11374}
11375
25a1127b
TT
11376/* Value of variable named NAME. Only exact matches are considered.
11377 If no such variable found, then if ERR_MSG is null, returns 0, and
4c4b4cd2
PH
11378 otherwise causes an error with message ERR_MSG. */
11379
d2e4a39e 11380static struct value *
edb0c9cb 11381get_var_value (const char *name, const char *err_msg)
14f9c5c9 11382{
25a1127b
TT
11383 std::string quoted_name = add_angle_brackets (name);
11384
11385 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
14f9c5c9 11386
d1183b06
TT
11387 std::vector<struct block_symbol> syms
11388 = ada_lookup_symbol_list_worker (lookup_name,
11389 get_selected_block (0),
6c015214 11390 SEARCH_VFT, 1);
14f9c5c9 11391
d1183b06 11392 if (syms.size () != 1)
14f9c5c9
AS
11393 {
11394 if (err_msg == NULL)
dda83cd7 11395 return 0;
14f9c5c9 11396 else
dda83cd7 11397 error (("%s"), err_msg);
14f9c5c9
AS
11398 }
11399
54d343a2 11400 return value_of_variable (syms[0].symbol, syms[0].block);
14f9c5c9 11401}
d2e4a39e 11402
edb0c9cb
PA
11403/* Value of integer variable named NAME in the current environment.
11404 If no such variable is found, returns false. Otherwise, sets VALUE
11405 to the variable's value and returns true. */
4c4b4cd2 11406
edb0c9cb
PA
11407bool
11408get_int_var_value (const char *name, LONGEST &value)
14f9c5c9 11409{
4c4b4cd2 11410 struct value *var_val = get_var_value (name, 0);
d2e4a39e 11411
14f9c5c9 11412 if (var_val == 0)
edb0c9cb
PA
11413 return false;
11414
11415 value = value_as_long (var_val);
11416 return true;
14f9c5c9 11417}
d2e4a39e 11418
14f9c5c9
AS
11419
11420/* Return a range type whose base type is that of the range type named
11421 NAME in the current environment, and whose bounds are calculated
4c4b4cd2 11422 from NAME according to the GNAT range encoding conventions.
1ce677a4
UW
11423 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11424 corresponding range type from debug information; fall back to using it
11425 if symbol lookup fails. If a new type must be created, allocate it
11426 like ORIG_TYPE was. The bounds information, in general, is encoded
11427 in NAME, the base type given in the named range type. */
14f9c5c9 11428
d2e4a39e 11429static struct type *
28c85d6c 11430to_fixed_range_type (struct type *raw_type, struct value *dval)
14f9c5c9 11431{
0d5cff50 11432 const char *name;
14f9c5c9 11433 struct type *base_type;
108d56a4 11434 const char *subtype_info;
14f9c5c9 11435
28c85d6c 11436 gdb_assert (raw_type != NULL);
7d93a1e0 11437 gdb_assert (raw_type->name () != NULL);
dddfab26 11438
78134374 11439 if (raw_type->code () == TYPE_CODE_RANGE)
27710edb 11440 base_type = raw_type->target_type ();
14f9c5c9
AS
11441 else
11442 base_type = raw_type;
11443
7d93a1e0 11444 name = raw_type->name ();
14f9c5c9
AS
11445 subtype_info = strstr (name, "___XD");
11446 if (subtype_info == NULL)
690cc4eb 11447 {
43bbcdc2
PH
11448 LONGEST L = ada_discrete_type_low_bound (raw_type);
11449 LONGEST U = ada_discrete_type_high_bound (raw_type);
5b4ee69b 11450
690cc4eb
PH
11451 if (L < INT_MIN || U > INT_MAX)
11452 return raw_type;
11453 else
e727c536
TT
11454 {
11455 type_allocator alloc (raw_type);
11456 return create_static_range_type (alloc, raw_type, L, U);
11457 }
690cc4eb 11458 }
14f9c5c9
AS
11459 else
11460 {
14f9c5c9
AS
11461 int prefix_len = subtype_info - name;
11462 LONGEST L, U;
11463 struct type *type;
108d56a4 11464 const char *bounds_str;
14f9c5c9
AS
11465 int n;
11466
14f9c5c9
AS
11467 subtype_info += 5;
11468 bounds_str = strchr (subtype_info, '_');
11469 n = 1;
11470
d2e4a39e 11471 if (*subtype_info == 'L')
dda83cd7
SM
11472 {
11473 if (!ada_scan_number (bounds_str, n, &L, &n)
11474 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11475 return raw_type;
11476 if (bounds_str[n] == '_')
11477 n += 2;
11478 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11479 n += 1;
11480 subtype_info += 1;
11481 }
d2e4a39e 11482 else
dda83cd7 11483 {
5f9febe0
TT
11484 std::string name_buf = std::string (name, prefix_len) + "___L";
11485 if (!get_int_var_value (name_buf.c_str (), L))
dda83cd7
SM
11486 {
11487 lim_warning (_("Unknown lower bound, using 1."));
11488 L = 1;
11489 }
11490 }
14f9c5c9 11491
d2e4a39e 11492 if (*subtype_info == 'U')
dda83cd7
SM
11493 {
11494 if (!ada_scan_number (bounds_str, n, &U, &n)
11495 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11496 return raw_type;
11497 }
d2e4a39e 11498 else
dda83cd7 11499 {
5f9febe0
TT
11500 std::string name_buf = std::string (name, prefix_len) + "___U";
11501 if (!get_int_var_value (name_buf.c_str (), U))
dda83cd7
SM
11502 {
11503 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11504 U = L;
11505 }
11506 }
14f9c5c9 11507
e727c536
TT
11508 type_allocator alloc (raw_type);
11509 type = create_static_range_type (alloc, base_type, L, U);
f5a91472 11510 /* create_static_range_type alters the resulting type's length
dda83cd7
SM
11511 to match the size of the base_type, which is not what we want.
11512 Set it back to the original range type's length. */
df86565b 11513 type->set_length (raw_type->length ());
d0e39ea2 11514 type->set_name (name);
14f9c5c9
AS
11515 return type;
11516 }
11517}
11518
4c4b4cd2
PH
11519/* True iff NAME is the name of a range type. */
11520
14f9c5c9 11521int
d2e4a39e 11522ada_is_range_type_name (const char *name)
14f9c5c9
AS
11523{
11524 return (name != NULL && strstr (name, "___XD"));
d2e4a39e 11525}
14f9c5c9 11526\f
d2e4a39e 11527
dda83cd7 11528 /* Modular types */
4c4b4cd2
PH
11529
11530/* True iff TYPE is an Ada modular type. */
14f9c5c9 11531
14f9c5c9 11532int
d2e4a39e 11533ada_is_modular_type (struct type *type)
14f9c5c9 11534{
18af8284 11535 struct type *subranged_type = get_base_type (type);
14f9c5c9 11536
78134374 11537 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
dda83cd7
SM
11538 && subranged_type->code () == TYPE_CODE_INT
11539 && subranged_type->is_unsigned ());
14f9c5c9
AS
11540}
11541
4c4b4cd2
PH
11542/* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11543
61ee279c 11544ULONGEST
0056e4d5 11545ada_modulus (struct type *type)
14f9c5c9 11546{
5e500d33
SM
11547 const dynamic_prop &high = type->bounds ()->high;
11548
9c0fb734 11549 if (high.is_constant ())
5e500d33
SM
11550 return (ULONGEST) high.const_val () + 1;
11551
11552 /* If TYPE is unresolved, the high bound might be a location list. Return
11553 0, for lack of a better value to return. */
11554 return 0;
14f9c5c9 11555}
d2e4a39e 11556\f
f7f9143b
JB
11557
11558/* Ada exception catchpoint support:
11559 ---------------------------------
11560
11561 We support 3 kinds of exception catchpoints:
11562 . catchpoints on Ada exceptions
11563 . catchpoints on unhandled Ada exceptions
11564 . catchpoints on failed assertions
11565
11566 Exceptions raised during failed assertions, or unhandled exceptions
11567 could perfectly be caught with the general catchpoint on Ada exceptions.
11568 However, we can easily differentiate these two special cases, and having
11569 the option to distinguish these two cases from the rest can be useful
11570 to zero-in on certain situations.
11571
11572 Exception catchpoints are a specialized form of breakpoint,
11573 since they rely on inserting breakpoints inside known routines
11574 of the GNAT runtime. The implementation therefore uses a standard
11575 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11576 of breakpoint_ops.
11577
0259addd
JB
11578 Support in the runtime for exception catchpoints have been changed
11579 a few times already, and these changes affect the implementation
11580 of these catchpoints. In order to be able to support several
11581 variants of the runtime, we use a sniffer that will determine
28010a5d 11582 the runtime variant used by the program being debugged. */
f7f9143b 11583
82eacd52
JB
11584/* Ada's standard exceptions.
11585
11586 The Ada 83 standard also defined Numeric_Error. But there so many
11587 situations where it was unclear from the Ada 83 Reference Manual
11588 (RM) whether Constraint_Error or Numeric_Error should be raised,
11589 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11590 Interpretation saying that anytime the RM says that Numeric_Error
11591 should be raised, the implementation may raise Constraint_Error.
11592 Ada 95 went one step further and pretty much removed Numeric_Error
11593 from the list of standard exceptions (it made it a renaming of
11594 Constraint_Error, to help preserve compatibility when compiling
11595 an Ada83 compiler). As such, we do not include Numeric_Error from
11596 this list of standard exceptions. */
3d0b0fa3 11597
27087b7f 11598static const char * const standard_exc[] = {
3d0b0fa3
JB
11599 "constraint_error",
11600 "program_error",
11601 "storage_error",
11602 "tasking_error"
11603};
11604
0259addd
JB
11605typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11606
11607/* A structure that describes how to support exception catchpoints
11608 for a given executable. */
11609
11610struct exception_support_info
11611{
11612 /* The name of the symbol to break on in order to insert
11613 a catchpoint on exceptions. */
11614 const char *catch_exception_sym;
11615
11616 /* The name of the symbol to break on in order to insert
11617 a catchpoint on unhandled exceptions. */
11618 const char *catch_exception_unhandled_sym;
11619
11620 /* The name of the symbol to break on in order to insert
11621 a catchpoint on failed assertions. */
11622 const char *catch_assert_sym;
11623
9f757bf7
XR
11624 /* The name of the symbol to break on in order to insert
11625 a catchpoint on exception handling. */
11626 const char *catch_handlers_sym;
11627
0259addd
JB
11628 /* Assuming that the inferior just triggered an unhandled exception
11629 catchpoint, this function is responsible for returning the address
11630 in inferior memory where the name of that exception is stored.
11631 Return zero if the address could not be computed. */
11632 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11633};
11634
11635static CORE_ADDR ada_unhandled_exception_name_addr (void);
11636static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11637
11638/* The following exception support info structure describes how to
11639 implement exception catchpoints with the latest version of the
ca683e3a 11640 Ada runtime (as of 2019-08-??). */
0259addd
JB
11641
11642static const struct exception_support_info default_exception_support_info =
ca683e3a
AO
11643{
11644 "__gnat_debug_raise_exception", /* catch_exception_sym */
11645 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11646 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11647 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11648 ada_unhandled_exception_name_addr
11649};
11650
11651/* The following exception support info structure describes how to
11652 implement exception catchpoints with an earlier version of the
11653 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11654
11655static const struct exception_support_info exception_support_info_v0 =
0259addd
JB
11656{
11657 "__gnat_debug_raise_exception", /* catch_exception_sym */
11658 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11659 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
9f757bf7 11660 "__gnat_begin_handler", /* catch_handlers_sym */
0259addd
JB
11661 ada_unhandled_exception_name_addr
11662};
11663
11664/* The following exception support info structure describes how to
11665 implement exception catchpoints with a slightly older version
11666 of the Ada runtime. */
11667
11668static const struct exception_support_info exception_support_info_fallback =
11669{
11670 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11671 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11672 "system__assertions__raise_assert_failure", /* catch_assert_sym */
9f757bf7 11673 "__gnat_begin_handler", /* catch_handlers_sym */
0259addd
JB
11674 ada_unhandled_exception_name_addr_from_raise
11675};
11676
f17011e0
JB
11677/* Return nonzero if we can detect the exception support routines
11678 described in EINFO.
11679
11680 This function errors out if an abnormal situation is detected
11681 (for instance, if we find the exception support routines, but
11682 that support is found to be incomplete). */
11683
11684static int
11685ada_has_this_exception_support (const struct exception_support_info *einfo)
11686{
11687 struct symbol *sym;
11688
11689 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11690 that should be compiled with debugging information. As a result, we
11691 expect to find that symbol in the symtabs. */
11692
6c015214 11693 sym = standard_lookup (einfo->catch_exception_sym, NULL, SEARCH_VFT);
f17011e0 11694 if (sym == NULL)
a6af7abe
JB
11695 {
11696 /* Perhaps we did not find our symbol because the Ada runtime was
11697 compiled without debugging info, or simply stripped of it.
11698 It happens on some GNU/Linux distributions for instance, where
11699 users have to install a separate debug package in order to get
11700 the runtime's debugging info. In that situation, let the user
11701 know why we cannot insert an Ada exception catchpoint.
11702
11703 Note: Just for the purpose of inserting our Ada exception
11704 catchpoint, we could rely purely on the associated minimal symbol.
11705 But we would be operating in degraded mode anyway, since we are
11706 still lacking the debugging info needed later on to extract
11707 the name of the exception being raised (this name is printed in
11708 the catchpoint message, and is also used when trying to catch
11709 a specific exception). We do not handle this case for now. */
3b7344d5 11710 struct bound_minimal_symbol msym
1c8e84b0
JB
11711 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11712
60f62e2b 11713 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
a6af7abe
JB
11714 error (_("Your Ada runtime appears to be missing some debugging "
11715 "information.\nCannot insert Ada exception catchpoint "
11716 "in this configuration."));
11717
11718 return 0;
11719 }
f17011e0
JB
11720
11721 /* Make sure that the symbol we found corresponds to a function. */
11722
66d7f48f 11723 if (sym->aclass () != LOC_BLOCK)
fe043185
TT
11724 error (_("Symbol \"%s\" is not a function (class = %d)"),
11725 sym->linkage_name (), sym->aclass ());
ca683e3a 11726
6c015214 11727 sym = standard_lookup (einfo->catch_handlers_sym, NULL, SEARCH_VFT);
ca683e3a
AO
11728 if (sym == NULL)
11729 {
11730 struct bound_minimal_symbol msym
11731 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11732
60f62e2b 11733 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
ca683e3a
AO
11734 error (_("Your Ada runtime appears to be missing some debugging "
11735 "information.\nCannot insert Ada exception catchpoint "
11736 "in this configuration."));
11737
11738 return 0;
11739 }
11740
11741 /* Make sure that the symbol we found corresponds to a function. */
11742
66d7f48f 11743 if (sym->aclass () != LOC_BLOCK)
fe043185
TT
11744 error (_("Symbol \"%s\" is not a function (class = %d)"),
11745 sym->linkage_name (), sym->aclass ());
f17011e0
JB
11746
11747 return 1;
11748}
11749
0259addd
JB
11750/* Inspect the Ada runtime and determine which exception info structure
11751 should be used to provide support for exception catchpoints.
11752
3eecfa55
JB
11753 This function will always set the per-inferior exception_info,
11754 or raise an error. */
0259addd
JB
11755
11756static void
11757ada_exception_support_info_sniffer (void)
11758{
3eecfa55 11759 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
0259addd
JB
11760
11761 /* If the exception info is already known, then no need to recompute it. */
3eecfa55 11762 if (data->exception_info != NULL)
0259addd
JB
11763 return;
11764
11765 /* Check the latest (default) exception support info. */
f17011e0 11766 if (ada_has_this_exception_support (&default_exception_support_info))
0259addd 11767 {
3eecfa55 11768 data->exception_info = &default_exception_support_info;
0259addd
JB
11769 return;
11770 }
11771
ca683e3a
AO
11772 /* Try the v0 exception suport info. */
11773 if (ada_has_this_exception_support (&exception_support_info_v0))
11774 {
11775 data->exception_info = &exception_support_info_v0;
11776 return;
11777 }
11778
0259addd 11779 /* Try our fallback exception suport info. */
f17011e0 11780 if (ada_has_this_exception_support (&exception_support_info_fallback))
0259addd 11781 {
3eecfa55 11782 data->exception_info = &exception_support_info_fallback;
0259addd
JB
11783 return;
11784 }
11785
2c4c710f
TT
11786 throw_error (NOT_FOUND_ERROR,
11787 _("Could not find Ada runtime exception support"));
0259addd
JB
11788}
11789
f7f9143b
JB
11790/* True iff FRAME is very likely to be that of a function that is
11791 part of the runtime system. This is all very heuristic, but is
11792 intended to be used as advice as to what frames are uninteresting
11793 to most users. */
11794
11795static int
8480a37e 11796is_known_support_routine (const frame_info_ptr &frame)
f7f9143b 11797{
692465f1 11798 enum language func_lang;
f7f9143b 11799 int i;
f35a17b5 11800 const char *fullname;
f7f9143b 11801
4ed6b5be
JB
11802 /* If this code does not have any debugging information (no symtab),
11803 This cannot be any user code. */
f7f9143b 11804
51abb421 11805 symtab_and_line sal = find_frame_sal (frame);
f7f9143b
JB
11806 if (sal.symtab == NULL)
11807 return 1;
11808
4ed6b5be
JB
11809 /* If there is a symtab, but the associated source file cannot be
11810 located, then assume this is not user code: Selecting a frame
11811 for which we cannot display the code would not be very helpful
11812 for the user. This should also take care of case such as VxWorks
11813 where the kernel has some debugging info provided for a few units. */
f7f9143b 11814
f35a17b5
JK
11815 fullname = symtab_to_fullname (sal.symtab);
11816 if (access (fullname, R_OK) != 0)
f7f9143b
JB
11817 return 1;
11818
85102364 11819 /* Check the unit filename against the Ada runtime file naming.
4ed6b5be
JB
11820 We also check the name of the objfile against the name of some
11821 known system libraries that sometimes come with debugging info
11822 too. */
11823
f7f9143b
JB
11824 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11825 {
11826 re_comp (known_runtime_file_name_patterns[i]);
f69c91ad 11827 if (re_exec (lbasename (sal.symtab->filename)))
dda83cd7 11828 return 1;
3c86fae3
SM
11829 if (sal.symtab->compunit ()->objfile () != NULL
11830 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
dda83cd7 11831 return 1;
f7f9143b
JB
11832 }
11833
4ed6b5be 11834 /* Check whether the function is a GNAT-generated entity. */
f7f9143b 11835
c6dc63a1
TT
11836 gdb::unique_xmalloc_ptr<char> func_name
11837 = find_frame_funname (frame, &func_lang, NULL);
f7f9143b
JB
11838 if (func_name == NULL)
11839 return 1;
11840
11841 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11842 {
11843 re_comp (known_auxiliary_function_name_patterns[i]);
c6dc63a1
TT
11844 if (re_exec (func_name.get ()))
11845 return 1;
f7f9143b
JB
11846 }
11847
11848 return 0;
11849}
11850
11851/* Find the first frame that contains debugging information and that is not
11852 part of the Ada run-time, starting from FI and moving upward. */
11853
0ef643c8 11854void
8480a37e 11855ada_find_printable_frame (const frame_info_ptr &initial_fi)
f7f9143b 11856{
8480a37e 11857 for (frame_info_ptr fi = initial_fi; fi != nullptr; fi = get_prev_frame (fi))
f7f9143b
JB
11858 {
11859 if (!is_known_support_routine (fi))
dda83cd7
SM
11860 {
11861 select_frame (fi);
11862 break;
11863 }
f7f9143b
JB
11864 }
11865
11866}
11867
11868/* Assuming that the inferior just triggered an unhandled exception
11869 catchpoint, return the address in inferior memory where the name
11870 of the exception is stored.
11871
11872 Return zero if the address could not be computed. */
11873
11874static CORE_ADDR
11875ada_unhandled_exception_name_addr (void)
0259addd
JB
11876{
11877 return parse_and_eval_address ("e.full_name");
11878}
11879
11880/* Same as ada_unhandled_exception_name_addr, except that this function
11881 should be used when the inferior uses an older version of the runtime,
11882 where the exception name needs to be extracted from a specific frame
11883 several frames up in the callstack. */
11884
11885static CORE_ADDR
11886ada_unhandled_exception_name_addr_from_raise (void)
f7f9143b
JB
11887{
11888 int frame_level;
bd2b40ac 11889 frame_info_ptr fi;
3eecfa55 11890 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
f7f9143b
JB
11891
11892 /* To determine the name of this exception, we need to select
11893 the frame corresponding to RAISE_SYM_NAME. This frame is
11894 at least 3 levels up, so we simply skip the first 3 frames
11895 without checking the name of their associated function. */
11896 fi = get_current_frame ();
11897 for (frame_level = 0; frame_level < 3; frame_level += 1)
11898 if (fi != NULL)
11899 fi = get_prev_frame (fi);
11900
11901 while (fi != NULL)
11902 {
692465f1
JB
11903 enum language func_lang;
11904
c6dc63a1
TT
11905 gdb::unique_xmalloc_ptr<char> func_name
11906 = find_frame_funname (fi, &func_lang, NULL);
55b87a52
KS
11907 if (func_name != NULL)
11908 {
dda83cd7 11909 if (strcmp (func_name.get (),
55b87a52
KS
11910 data->exception_info->catch_exception_sym) == 0)
11911 break; /* We found the frame we were looking for... */
55b87a52 11912 }
fb44b1a7 11913 fi = get_prev_frame (fi);
f7f9143b
JB
11914 }
11915
11916 if (fi == NULL)
11917 return 0;
11918
11919 select_frame (fi);
11920 return parse_and_eval_address ("id.full_name");
11921}
11922
11923/* Assuming the inferior just triggered an Ada exception catchpoint
11924 (of any type), return the address in inferior memory where the name
11925 of the exception is stored, if applicable.
11926
45db7c09
PA
11927 Assumes the selected frame is the current frame.
11928
f7f9143b
JB
11929 Return zero if the address could not be computed, or if not relevant. */
11930
11931static CORE_ADDR
7bd86313 11932ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
f7f9143b 11933{
3eecfa55
JB
11934 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11935
f7f9143b
JB
11936 switch (ex)
11937 {
761269c8 11938 case ada_catch_exception:
dda83cd7
SM
11939 return (parse_and_eval_address ("e.full_name"));
11940 break;
f7f9143b 11941
761269c8 11942 case ada_catch_exception_unhandled:
dda83cd7
SM
11943 return data->exception_info->unhandled_exception_name_addr ();
11944 break;
9f757bf7
XR
11945
11946 case ada_catch_handlers:
dda83cd7 11947 return 0; /* The runtimes does not provide access to the exception
9f757bf7 11948 name. */
dda83cd7 11949 break;
9f757bf7 11950
761269c8 11951 case ada_catch_assert:
dda83cd7
SM
11952 return 0; /* Exception name is not relevant in this case. */
11953 break;
f7f9143b
JB
11954
11955 default:
f34652de 11956 internal_error (_("unexpected catchpoint type"));
dda83cd7 11957 break;
f7f9143b
JB
11958 }
11959
11960 return 0; /* Should never be reached. */
11961}
11962
e547c119
JB
11963/* Assuming the inferior is stopped at an exception catchpoint,
11964 return the message which was associated to the exception, if
11965 available. Return NULL if the message could not be retrieved.
11966
e547c119
JB
11967 Note: The exception message can be associated to an exception
11968 either through the use of the Raise_Exception function, or
11969 more simply (Ada 2005 and later), via:
11970
11971 raise Exception_Name with "exception message";
11972
11973 */
11974
6f46ac85 11975static gdb::unique_xmalloc_ptr<char>
e547c119
JB
11976ada_exception_message_1 (void)
11977{
11978 struct value *e_msg_val;
e547c119 11979 int e_msg_len;
e547c119
JB
11980
11981 /* For runtimes that support this feature, the exception message
11982 is passed as an unbounded string argument called "message". */
11983 e_msg_val = parse_and_eval ("message");
11984 if (e_msg_val == NULL)
11985 return NULL; /* Exception message not supported. */
11986
11987 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11988 gdb_assert (e_msg_val != NULL);
d0c97917 11989 e_msg_len = e_msg_val->type ()->length ();
e547c119
JB
11990
11991 /* If the message string is empty, then treat it as if there was
11992 no exception message. */
11993 if (e_msg_len <= 0)
11994 return NULL;
11995
15f3b077 11996 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
9feb2d07 11997 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
15f3b077
TT
11998 e_msg_len);
11999 e_msg.get ()[e_msg_len] = '\0';
12000
12001 return e_msg;
e547c119
JB
12002}
12003
12004/* Same as ada_exception_message_1, except that all exceptions are
12005 contained here (returning NULL instead). */
12006
6f46ac85 12007static gdb::unique_xmalloc_ptr<char>
e547c119
JB
12008ada_exception_message (void)
12009{
6f46ac85 12010 gdb::unique_xmalloc_ptr<char> e_msg;
e547c119 12011
a70b8144 12012 try
e547c119
JB
12013 {
12014 e_msg = ada_exception_message_1 ();
12015 }
230d2906 12016 catch (const gdb_exception_error &e)
e547c119 12017 {
6f46ac85 12018 e_msg.reset (nullptr);
e547c119 12019 }
e547c119
JB
12020
12021 return e_msg;
12022}
12023
f7f9143b
JB
12024/* Same as ada_exception_name_addr_1, except that it intercepts and contains
12025 any error that ada_exception_name_addr_1 might cause to be thrown.
12026 When an error is intercepted, a warning with the error message is printed,
12027 and zero is returned. */
12028
12029static CORE_ADDR
7bd86313 12030ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
f7f9143b 12031{
f7f9143b
JB
12032 CORE_ADDR result = 0;
12033
a70b8144 12034 try
f7f9143b 12035 {
7bd86313 12036 result = ada_exception_name_addr_1 (ex);
f7f9143b
JB
12037 }
12038
230d2906 12039 catch (const gdb_exception_error &e)
f7f9143b 12040 {
3d6e9d23 12041 warning (_("failed to get exception name: %s"), e.what ());
f7f9143b
JB
12042 return 0;
12043 }
12044
12045 return result;
12046}
12047
cb7de75e 12048static std::string ada_exception_catchpoint_cond_string
9f757bf7
XR
12049 (const char *excep_string,
12050 enum ada_exception_catchpoint_kind ex);
28010a5d
PA
12051
12052/* Ada catchpoints.
12053
12054 In the case of catchpoints on Ada exceptions, the catchpoint will
12055 stop the target on every exception the program throws. When a user
12056 specifies the name of a specific exception, we translate this
12057 request into a condition expression (in text form), and then parse
12058 it into an expression stored in each of the catchpoint's locations.
12059 We then use this condition to check whether the exception that was
12060 raised is the one the user is interested in. If not, then the
12061 target is resumed again. We store the name of the requested
12062 exception, in order to be able to re-set the condition expression
12063 when symbols change. */
12064
c1fc2657 12065/* An instance of this type is used to represent an Ada catchpoint. */
28010a5d 12066
74421c0b 12067struct ada_catchpoint : public code_breakpoint
28010a5d 12068{
73063f51 12069 ada_catchpoint (struct gdbarch *gdbarch_,
bd21b6c9 12070 enum ada_exception_catchpoint_kind kind,
2c4c710f 12071 const char *cond_string,
bd21b6c9
PA
12072 bool tempflag,
12073 bool enabled,
898db0f7
TT
12074 bool from_tty,
12075 std::string &&excep_string_)
2c4c710f 12076 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
03f531ea 12077 m_excep_string (std::move (excep_string_)),
73063f51 12078 m_kind (kind)
37f6a7f4 12079 {
74421c0b 12080 /* Unlike most code_breakpoint types, Ada catchpoints are
bd21b6c9 12081 pspace-specific. */
2c4c710f 12082 pspace = current_program_space;
bd21b6c9 12083 enable_state = enabled ? bp_enabled : bp_disabled;
bd21b6c9 12084 language = language_ada;
95f2fe27
TT
12085
12086 re_set ();
37f6a7f4
TT
12087 }
12088
ae72050b
TT
12089 struct bp_location *allocate_location () override;
12090 void re_set () override;
12091 void check_status (struct bpstat *bs) override;
7bd86313 12092 enum print_stop_action print_it (const bpstat *bs) const override;
5e632eca 12093 bool print_one (const bp_location **) const override;
b713485d 12094 void print_mention () const override;
4d1ae558 12095 void print_recreate (struct ui_file *fp) const override;
ae72050b 12096
03f531ea
TT
12097private:
12098
971149cb
TT
12099 /* A helper function for check_status. Returns true if we should
12100 stop for this breakpoint hit. If the user specified a specific
12101 exception, we only want to cause a stop if the program thrown
12102 that exception. */
12103 bool should_stop_exception (const struct bp_location *bl) const;
12104
28010a5d 12105 /* The name of the specific exception the user specified. */
03f531ea 12106 std::string m_excep_string;
37f6a7f4
TT
12107
12108 /* What kind of catchpoint this is. */
12109 enum ada_exception_catchpoint_kind m_kind;
28010a5d
PA
12110};
12111
8cd0bf5e
PA
12112/* An instance of this type is used to represent an Ada catchpoint
12113 breakpoint location. */
12114
12115class ada_catchpoint_location : public bp_location
12116{
12117public:
12118 explicit ada_catchpoint_location (ada_catchpoint *owner)
12119 : bp_location (owner, bp_loc_software_breakpoint)
12120 {}
12121
12122 /* The condition that checks whether the exception that was raised
12123 is the specific exception the user specified on catchpoint
12124 creation. */
12125 expression_up excep_cond_expr;
12126};
12127
2c4c710f
TT
12128static struct symtab_and_line ada_exception_sal
12129 (enum ada_exception_catchpoint_kind ex);
12130
95f2fe27
TT
12131/* Implement the RE_SET method in the structure for all exception
12132 catchpoint kinds. */
28010a5d 12133
95f2fe27
TT
12134void
12135ada_catchpoint::re_set ()
28010a5d 12136{
2c4c710f
TT
12137 std::vector<symtab_and_line> sals;
12138 try
12139 {
12140 struct symtab_and_line sal = ada_exception_sal (m_kind);
12141 sals.push_back (sal);
12142 }
12143 catch (const gdb_exception_error &ex)
12144 {
12145 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12146 if (ex.error != NOT_FOUND_ERROR)
12147 throw;
12148 }
12149
12150 update_breakpoint_locations (this, pspace, sals, {});
95f2fe27
TT
12151
12152 /* Reparse the exception conditional expressions. One for each
12153 location. */
12154
28010a5d 12155 /* Nothing to do if there's no specific exception to catch. */
03f531ea 12156 if (m_excep_string.empty ())
28010a5d
PA
12157 return;
12158
12159 /* Same if there are no locations... */
95f2fe27 12160 if (!has_locations ())
28010a5d
PA
12161 return;
12162
fccf9de1 12163 /* Compute the condition expression in text form, from the specific
33b5899f 12164 exception we want to catch. */
fccf9de1 12165 std::string cond_string
03f531ea 12166 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
28010a5d 12167
fccf9de1
TT
12168 /* Iterate over all the catchpoint's locations, and parse an
12169 expression for each. */
95f2fe27 12170 for (bp_location &bl : locations ())
28010a5d 12171 {
b00b30b2
SM
12172 ada_catchpoint_location &ada_loc
12173 = static_cast<ada_catchpoint_location &> (bl);
4d01a485 12174 expression_up exp;
28010a5d 12175
b00b30b2 12176 if (!bl.shlib_disabled)
28010a5d 12177 {
bbc13ae3 12178 const char *s;
28010a5d 12179
cb7de75e 12180 s = cond_string.c_str ();
a70b8144 12181 try
28010a5d 12182 {
b00b30b2 12183 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
28010a5d 12184 }
230d2906 12185 catch (const gdb_exception_error &e)
849f2b52
JB
12186 {
12187 warning (_("failed to reevaluate internal exception condition "
12188 "for catchpoint %d: %s"),
95f2fe27 12189 number, e.what ());
849f2b52 12190 }
28010a5d
PA
12191 }
12192
b00b30b2 12193 ada_loc.excep_cond_expr = std::move (exp);
28010a5d 12194 }
28010a5d
PA
12195}
12196
ae72050b
TT
12197/* Implement the ALLOCATE_LOCATION method in the structure for all
12198 exception catchpoint kinds. */
28010a5d 12199
ae72050b
TT
12200struct bp_location *
12201ada_catchpoint::allocate_location ()
28010a5d 12202{
ae72050b 12203 return new ada_catchpoint_location (this);
28010a5d
PA
12204}
12205
971149cb 12206/* See declaration. */
28010a5d 12207
971149cb
TT
12208bool
12209ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
28010a5d 12210{
8e032233 12211 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
28010a5d
PA
12212 const struct ada_catchpoint_location *ada_loc
12213 = (const struct ada_catchpoint_location *) bl;
7ebaa5f7 12214 bool stop;
28010a5d 12215
37f6a7f4
TT
12216 struct internalvar *var = lookup_internalvar ("_ada_exception");
12217 if (c->m_kind == ada_catch_assert)
12218 clear_internalvar (var);
12219 else
12220 {
12221 try
12222 {
12223 const char *expr;
12224
12225 if (c->m_kind == ada_catch_handlers)
12226 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12227 ".all.occurrence.id");
12228 else
12229 expr = "e";
12230
12231 struct value *exc = parse_and_eval (expr);
12232 set_internalvar (var, exc);
12233 }
12234 catch (const gdb_exception_error &ex)
12235 {
12236 clear_internalvar (var);
12237 }
12238 }
12239
28010a5d 12240 /* With no specific exception, should always stop. */
03f531ea 12241 if (c->m_excep_string.empty ())
7ebaa5f7 12242 return true;
28010a5d
PA
12243
12244 if (ada_loc->excep_cond_expr == NULL)
12245 {
12246 /* We will have a NULL expression if back when we were creating
12247 the expressions, this location's had failed to parse. */
7ebaa5f7 12248 return true;
28010a5d
PA
12249 }
12250
7ebaa5f7 12251 stop = true;
a70b8144 12252 try
28010a5d 12253 {
65558ca5 12254 scoped_value_mark mark;
43048e46 12255 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
28010a5d 12256 }
b1ffd112 12257 catch (const gdb_exception_error &ex)
492d29ea
PA
12258 {
12259 exception_fprintf (gdb_stderr, ex,
12260 _("Error in testing exception condition:\n"));
12261 }
492d29ea 12262
28010a5d
PA
12263 return stop;
12264}
12265
ae72050b
TT
12266/* Implement the CHECK_STATUS method in the structure for all
12267 exception catchpoint kinds. */
28010a5d 12268
ae72050b
TT
12269void
12270ada_catchpoint::check_status (bpstat *bs)
28010a5d 12271{
b6433ede 12272 bs->stop = should_stop_exception (bs->bp_location_at.get ());
28010a5d
PA
12273}
12274
ae72050b
TT
12275/* Implement the PRINT_IT method in the structure for all exception
12276 catchpoint kinds. */
f7f9143b 12277
ae72050b 12278enum print_stop_action
7bd86313 12279ada_catchpoint::print_it (const bpstat *bs) const
f7f9143b 12280{
79a45e25 12281 struct ui_out *uiout = current_uiout;
348d480f 12282
ae72050b 12283 annotate_catchpoint (number);
f7f9143b 12284
112e8700 12285 if (uiout->is_mi_like_p ())
f7f9143b 12286 {
112e8700 12287 uiout->field_string ("reason",
956a9fb9 12288 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
ae72050b 12289 uiout->field_string ("disp", bpdisp_text (disposition));
f7f9143b
JB
12290 }
12291
ae72050b 12292 uiout->text (disposition == disp_del
112e8700 12293 ? "\nTemporary catchpoint " : "\nCatchpoint ");
78805ff8 12294 print_num_locno (bs, uiout);
112e8700 12295 uiout->text (", ");
f7f9143b 12296
45db7c09
PA
12297 /* ada_exception_name_addr relies on the selected frame being the
12298 current frame. Need to do this here because this function may be
12299 called more than once when printing a stop, and below, we'll
12300 select the first frame past the Ada run-time (see
12301 ada_find_printable_frame). */
12302 select_frame (get_current_frame ());
12303
ae72050b 12304 switch (m_kind)
f7f9143b 12305 {
761269c8
JB
12306 case ada_catch_exception:
12307 case ada_catch_exception_unhandled:
9f757bf7 12308 case ada_catch_handlers:
956a9fb9 12309 {
7bd86313 12310 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
956a9fb9
JB
12311 char exception_name[256];
12312
12313 if (addr != 0)
12314 {
c714b426
PA
12315 read_memory (addr, (gdb_byte *) exception_name,
12316 sizeof (exception_name) - 1);
956a9fb9
JB
12317 exception_name [sizeof (exception_name) - 1] = '\0';
12318 }
12319 else
12320 {
12321 /* For some reason, we were unable to read the exception
12322 name. This could happen if the Runtime was compiled
12323 without debugging info, for instance. In that case,
12324 just replace the exception name by the generic string
12325 "exception" - it will read as "an exception" in the
12326 notification we are about to print. */
967cff16 12327 memcpy (exception_name, "exception", sizeof ("exception"));
956a9fb9
JB
12328 }
12329 /* In the case of unhandled exception breakpoints, we print
12330 the exception name as "unhandled EXCEPTION_NAME", to make
12331 it clearer to the user which kind of catchpoint just got
12332 hit. We used ui_out_text to make sure that this extra
12333 info does not pollute the exception name in the MI case. */
ae72050b 12334 if (m_kind == ada_catch_exception_unhandled)
112e8700
SM
12335 uiout->text ("unhandled ");
12336 uiout->field_string ("exception-name", exception_name);
956a9fb9
JB
12337 }
12338 break;
761269c8 12339 case ada_catch_assert:
956a9fb9
JB
12340 /* In this case, the name of the exception is not really
12341 important. Just print "failed assertion" to make it clearer
12342 that his program just hit an assertion-failure catchpoint.
12343 We used ui_out_text because this info does not belong in
12344 the MI output. */
112e8700 12345 uiout->text ("failed assertion");
956a9fb9 12346 break;
f7f9143b 12347 }
e547c119 12348
6f46ac85 12349 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
e547c119
JB
12350 if (exception_message != NULL)
12351 {
e547c119 12352 uiout->text (" (");
6f46ac85 12353 uiout->field_string ("exception-message", exception_message.get ());
e547c119 12354 uiout->text (")");
e547c119
JB
12355 }
12356
112e8700 12357 uiout->text (" at ");
956a9fb9 12358 ada_find_printable_frame (get_current_frame ());
f7f9143b
JB
12359
12360 return PRINT_SRC_AND_LOC;
12361}
12362
ae72050b
TT
12363/* Implement the PRINT_ONE method in the structure for all exception
12364 catchpoint kinds. */
f7f9143b 12365
ae72050b 12366bool
5e632eca 12367ada_catchpoint::print_one (const bp_location **last_loc) const
f7f9143b 12368{
79a45e25 12369 struct ui_out *uiout = current_uiout;
79a45b7d
TT
12370 struct value_print_options opts;
12371
12372 get_user_print_options (&opts);
f06f1252 12373
79a45b7d 12374 if (opts.addressprint)
f06f1252 12375 uiout->field_skip ("addr");
f7f9143b
JB
12376
12377 annotate_field (5);
ae72050b 12378 switch (m_kind)
f7f9143b 12379 {
761269c8 12380 case ada_catch_exception:
03f531ea 12381 if (!m_excep_string.empty ())
dda83cd7 12382 {
bc18fbb5 12383 std::string msg = string_printf (_("`%s' Ada exception"),
03f531ea 12384 m_excep_string.c_str ());
28010a5d 12385
dda83cd7
SM
12386 uiout->field_string ("what", msg);
12387 }
12388 else
12389 uiout->field_string ("what", "all Ada exceptions");
12390
12391 break;
f7f9143b 12392
761269c8 12393 case ada_catch_exception_unhandled:
dda83cd7
SM
12394 uiout->field_string ("what", "unhandled Ada exceptions");
12395 break;
f7f9143b 12396
9f757bf7 12397 case ada_catch_handlers:
03f531ea 12398 if (!m_excep_string.empty ())
dda83cd7 12399 {
9f757bf7
XR
12400 uiout->field_fmt ("what",
12401 _("`%s' Ada exception handlers"),
03f531ea 12402 m_excep_string.c_str ());
dda83cd7
SM
12403 }
12404 else
9f757bf7 12405 uiout->field_string ("what", "all Ada exceptions handlers");
dda83cd7 12406 break;
9f757bf7 12407
761269c8 12408 case ada_catch_assert:
dda83cd7
SM
12409 uiout->field_string ("what", "failed Ada assertions");
12410 break;
f7f9143b
JB
12411
12412 default:
f34652de 12413 internal_error (_("unexpected catchpoint type"));
dda83cd7 12414 break;
f7f9143b 12415 }
c01e038b
TT
12416
12417 return true;
f7f9143b
JB
12418}
12419
12420/* Implement the PRINT_MENTION method in the breakpoint_ops structure
12421 for all exception catchpoint kinds. */
12422
ae72050b 12423void
b713485d 12424ada_catchpoint::print_mention () const
f7f9143b 12425{
79a45e25 12426 struct ui_out *uiout = current_uiout;
28010a5d 12427
ae72050b 12428 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
dda83cd7 12429 : _("Catchpoint "));
ae72050b 12430 uiout->field_signed ("bkptno", number);
112e8700 12431 uiout->text (": ");
00eb2c4a 12432
ae72050b 12433 switch (m_kind)
f7f9143b 12434 {
761269c8 12435 case ada_catch_exception:
03f531ea 12436 if (!m_excep_string.empty ())
00eb2c4a 12437 {
862d101a 12438 std::string info = string_printf (_("`%s' Ada exception"),
03f531ea 12439 m_excep_string.c_str ());
4915bfdc 12440 uiout->text (info);
00eb2c4a 12441 }
dda83cd7
SM
12442 else
12443 uiout->text (_("all Ada exceptions"));
12444 break;
f7f9143b 12445
761269c8 12446 case ada_catch_exception_unhandled:
dda83cd7
SM
12447 uiout->text (_("unhandled Ada exceptions"));
12448 break;
9f757bf7
XR
12449
12450 case ada_catch_handlers:
03f531ea 12451 if (!m_excep_string.empty ())
9f757bf7
XR
12452 {
12453 std::string info
12454 = string_printf (_("`%s' Ada exception handlers"),
03f531ea 12455 m_excep_string.c_str ());
4915bfdc 12456 uiout->text (info);
9f757bf7 12457 }
dda83cd7
SM
12458 else
12459 uiout->text (_("all Ada exceptions handlers"));
12460 break;
9f757bf7 12461
761269c8 12462 case ada_catch_assert:
dda83cd7
SM
12463 uiout->text (_("failed Ada assertions"));
12464 break;
f7f9143b
JB
12465
12466 default:
f34652de 12467 internal_error (_("unexpected catchpoint type"));
dda83cd7 12468 break;
f7f9143b
JB
12469 }
12470}
12471
ae72050b
TT
12472/* Implement the PRINT_RECREATE method in the structure for all
12473 exception catchpoint kinds. */
6149aea9 12474
ae72050b 12475void
4d1ae558 12476ada_catchpoint::print_recreate (struct ui_file *fp) const
6149aea9 12477{
ae72050b 12478 switch (m_kind)
6149aea9 12479 {
761269c8 12480 case ada_catch_exception:
6cb06a8c 12481 gdb_printf (fp, "catch exception");
03f531ea
TT
12482 if (!m_excep_string.empty ())
12483 gdb_printf (fp, " %s", m_excep_string.c_str ());
6149aea9
PA
12484 break;
12485
761269c8 12486 case ada_catch_exception_unhandled:
6cb06a8c 12487 gdb_printf (fp, "catch exception unhandled");
6149aea9
PA
12488 break;
12489
9f757bf7 12490 case ada_catch_handlers:
6cb06a8c 12491 gdb_printf (fp, "catch handlers");
9f757bf7
XR
12492 break;
12493
761269c8 12494 case ada_catch_assert:
6cb06a8c 12495 gdb_printf (fp, "catch assert");
6149aea9
PA
12496 break;
12497
12498 default:
f34652de 12499 internal_error (_("unexpected catchpoint type"));
6149aea9 12500 }
04d0163c 12501 print_recreate_thread (fp);
6149aea9
PA
12502}
12503
f06f1252
TT
12504/* See ada-lang.h. */
12505
12506bool
12507is_ada_exception_catchpoint (breakpoint *bp)
12508{
ae72050b 12509 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
f06f1252
TT
12510}
12511
f7f9143b
JB
12512/* Split the arguments specified in a "catch exception" command.
12513 Set EX to the appropriate catchpoint type.
28010a5d 12514 Set EXCEP_STRING to the name of the specific exception if
5845583d 12515 specified by the user.
9f757bf7
XR
12516 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12517 "catch handlers" command. False otherwise.
5845583d
JB
12518 If a condition is found at the end of the arguments, the condition
12519 expression is stored in COND_STRING (memory must be deallocated
12520 after use). Otherwise COND_STRING is set to NULL. */
f7f9143b
JB
12521
12522static void
a121b7c1 12523catch_ada_exception_command_split (const char *args,
9f757bf7 12524 bool is_catch_handlers_cmd,
dda83cd7 12525 enum ada_exception_catchpoint_kind *ex,
bc18fbb5
TT
12526 std::string *excep_string,
12527 std::string *cond_string)
f7f9143b 12528{
bc18fbb5 12529 std::string exception_name;
f7f9143b 12530
bc18fbb5
TT
12531 exception_name = extract_arg (&args);
12532 if (exception_name == "if")
5845583d
JB
12533 {
12534 /* This is not an exception name; this is the start of a condition
12535 expression for a catchpoint on all exceptions. So, "un-get"
12536 this token, and set exception_name to NULL. */
bc18fbb5 12537 exception_name.clear ();
5845583d
JB
12538 args -= 2;
12539 }
f7f9143b 12540
5845583d 12541 /* Check to see if we have a condition. */
f7f9143b 12542
f1735a53 12543 args = skip_spaces (args);
61012eef 12544 if (startswith (args, "if")
5845583d
JB
12545 && (isspace (args[2]) || args[2] == '\0'))
12546 {
12547 args += 2;
f1735a53 12548 args = skip_spaces (args);
5845583d
JB
12549
12550 if (args[0] == '\0')
dda83cd7 12551 error (_("Condition missing after `if' keyword"));
bc18fbb5 12552 *cond_string = args;
5845583d
JB
12553
12554 args += strlen (args);
12555 }
12556
12557 /* Check that we do not have any more arguments. Anything else
12558 is unexpected. */
f7f9143b
JB
12559
12560 if (args[0] != '\0')
12561 error (_("Junk at end of expression"));
12562
9f757bf7
XR
12563 if (is_catch_handlers_cmd)
12564 {
12565 /* Catch handling of exceptions. */
12566 *ex = ada_catch_handlers;
12567 *excep_string = exception_name;
12568 }
bc18fbb5 12569 else if (exception_name.empty ())
f7f9143b
JB
12570 {
12571 /* Catch all exceptions. */
761269c8 12572 *ex = ada_catch_exception;
bc18fbb5 12573 excep_string->clear ();
f7f9143b 12574 }
bc18fbb5 12575 else if (exception_name == "unhandled")
f7f9143b
JB
12576 {
12577 /* Catch unhandled exceptions. */
761269c8 12578 *ex = ada_catch_exception_unhandled;
bc18fbb5 12579 excep_string->clear ();
f7f9143b
JB
12580 }
12581 else
12582 {
12583 /* Catch a specific exception. */
761269c8 12584 *ex = ada_catch_exception;
28010a5d 12585 *excep_string = exception_name;
f7f9143b
JB
12586 }
12587}
12588
12589/* Return the name of the symbol on which we should break in order to
12590 implement a catchpoint of the EX kind. */
12591
12592static const char *
761269c8 12593ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
f7f9143b 12594{
3eecfa55
JB
12595 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12596
12597 gdb_assert (data->exception_info != NULL);
0259addd 12598
f7f9143b
JB
12599 switch (ex)
12600 {
761269c8 12601 case ada_catch_exception:
dda83cd7
SM
12602 return (data->exception_info->catch_exception_sym);
12603 break;
761269c8 12604 case ada_catch_exception_unhandled:
dda83cd7
SM
12605 return (data->exception_info->catch_exception_unhandled_sym);
12606 break;
761269c8 12607 case ada_catch_assert:
dda83cd7
SM
12608 return (data->exception_info->catch_assert_sym);
12609 break;
9f757bf7 12610 case ada_catch_handlers:
dda83cd7
SM
12611 return (data->exception_info->catch_handlers_sym);
12612 break;
f7f9143b 12613 default:
f34652de 12614 internal_error (_("unexpected catchpoint kind (%d)"), ex);
f7f9143b
JB
12615 }
12616}
12617
f7f9143b
JB
12618/* Return the condition that will be used to match the current exception
12619 being raised with the exception that the user wants to catch. This
12620 assumes that this condition is used when the inferior just triggered
12621 an exception catchpoint.
cb7de75e 12622 EX: the type of catchpoints used for catching Ada exceptions. */
f7f9143b 12623
cb7de75e 12624static std::string
9f757bf7 12625ada_exception_catchpoint_cond_string (const char *excep_string,
dda83cd7 12626 enum ada_exception_catchpoint_kind ex)
f7f9143b 12627{
fccf9de1 12628 bool is_standard_exc = false;
cb7de75e 12629 std::string result;
9f757bf7
XR
12630
12631 if (ex == ada_catch_handlers)
12632 {
12633 /* For exception handlers catchpoints, the condition string does
dda83cd7 12634 not use the same parameter as for the other exceptions. */
fccf9de1
TT
12635 result = ("long_integer (GNAT_GCC_exception_Access"
12636 "(gcc_exception).all.occurrence.id)");
9f757bf7
XR
12637 }
12638 else
fccf9de1 12639 result = "long_integer (e)";
3d0b0fa3 12640
0963b4bd 12641 /* The standard exceptions are a special case. They are defined in
3d0b0fa3 12642 runtime units that have been compiled without debugging info; if
28010a5d 12643 EXCEP_STRING is the not-fully-qualified name of a standard
3d0b0fa3
JB
12644 exception (e.g. "constraint_error") then, during the evaluation
12645 of the condition expression, the symbol lookup on this name would
0963b4bd 12646 *not* return this standard exception. The catchpoint condition
3d0b0fa3
JB
12647 may then be set only on user-defined exceptions which have the
12648 same not-fully-qualified name (e.g. my_package.constraint_error).
12649
12650 To avoid this unexcepted behavior, these standard exceptions are
0963b4bd 12651 systematically prefixed by "standard". This means that "catch
3d0b0fa3
JB
12652 exception constraint_error" is rewritten into "catch exception
12653 standard.constraint_error".
12654
85102364 12655 If an exception named constraint_error is defined in another package of
3d0b0fa3
JB
12656 the inferior program, then the only way to specify this exception as a
12657 breakpoint condition is to use its fully-qualified named:
fccf9de1 12658 e.g. my_package.constraint_error. */
3d0b0fa3 12659
696d6f4d 12660 for (const char *name : standard_exc)
3d0b0fa3 12661 {
696d6f4d 12662 if (strcmp (name, excep_string) == 0)
3d0b0fa3 12663 {
fccf9de1 12664 is_standard_exc = true;
9f757bf7 12665 break;
3d0b0fa3
JB
12666 }
12667 }
9f757bf7 12668
fccf9de1
TT
12669 result += " = ";
12670
12671 if (is_standard_exc)
12672 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12673 else
12674 string_appendf (result, "long_integer (&%s)", excep_string);
9f757bf7 12675
9f757bf7 12676 return result;
f7f9143b
JB
12677}
12678
2c4c710f
TT
12679/* Return the symtab_and_line that should be used to insert an
12680 exception catchpoint of the TYPE kind. */
f7f9143b
JB
12681
12682static struct symtab_and_line
2c4c710f 12683ada_exception_sal (enum ada_exception_catchpoint_kind ex)
f7f9143b
JB
12684{
12685 const char *sym_name;
12686 struct symbol *sym;
f7f9143b 12687
0259addd
JB
12688 /* First, find out which exception support info to use. */
12689 ada_exception_support_info_sniffer ();
12690
12691 /* Then lookup the function on which we will break in order to catch
f7f9143b 12692 the Ada exceptions requested by the user. */
f7f9143b 12693 sym_name = ada_exception_sym_name (ex);
6c015214 12694 sym = standard_lookup (sym_name, NULL, SEARCH_VFT);
f7f9143b 12695
57aff202 12696 if (sym == NULL)
2c4c710f
TT
12697 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12698 sym_name);
57aff202 12699
66d7f48f 12700 if (sym->aclass () != LOC_BLOCK)
57aff202 12701 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
f7f9143b 12702
f17011e0 12703 return find_function_start_sal (sym, 1);
f7f9143b
JB
12704}
12705
b4a5b78b 12706/* Create an Ada exception catchpoint.
f7f9143b 12707
b4a5b78b 12708 EX_KIND is the kind of exception catchpoint to be created.
5845583d 12709
bc18fbb5 12710 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
2df4d1d5 12711 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
bc18fbb5 12712 of the exception to which this catchpoint applies.
2df4d1d5 12713
bc18fbb5 12714 COND_STRING, if not empty, is the catchpoint condition.
f7f9143b 12715
b4a5b78b
JB
12716 TEMPFLAG, if nonzero, means that the underlying breakpoint
12717 should be temporary.
28010a5d 12718
b4a5b78b 12719 FROM_TTY is the usual argument passed to all commands implementations. */
28010a5d 12720
349774ef 12721void
28010a5d 12722create_ada_exception_catchpoint (struct gdbarch *gdbarch,
761269c8 12723 enum ada_exception_catchpoint_kind ex_kind,
898db0f7 12724 std::string &&excep_string,
56ecd069 12725 const std::string &cond_string,
28010a5d 12726 int tempflag,
12d67b37 12727 int enabled,
28010a5d
PA
12728 int from_tty)
12729{
bd21b6c9 12730 std::unique_ptr<ada_catchpoint> c
2c4c710f
TT
12731 (new ada_catchpoint (gdbarch, ex_kind,
12732 cond_string.empty () ? nullptr : cond_string.c_str (),
898db0f7
TT
12733 tempflag, enabled, from_tty,
12734 std::move (excep_string)));
b270e6f9 12735 install_breakpoint (0, std::move (c), 1);
f7f9143b
JB
12736}
12737
9ac4176b
PA
12738/* Implement the "catch exception" command. */
12739
12740static void
eb4c3f4a 12741catch_ada_exception_command (const char *arg_entry, int from_tty,
9ac4176b
PA
12742 struct cmd_list_element *command)
12743{
a121b7c1 12744 const char *arg = arg_entry;
9ac4176b
PA
12745 struct gdbarch *gdbarch = get_current_arch ();
12746 int tempflag;
761269c8 12747 enum ada_exception_catchpoint_kind ex_kind;
bc18fbb5 12748 std::string excep_string;
56ecd069 12749 std::string cond_string;
9ac4176b 12750
0f8e2034 12751 tempflag = command->context () == CATCH_TEMPORARY;
9ac4176b
PA
12752
12753 if (!arg)
12754 arg = "";
9f757bf7 12755 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
bc18fbb5 12756 &cond_string);
9f757bf7 12757 create_ada_exception_catchpoint (gdbarch, ex_kind,
898db0f7 12758 std::move (excep_string), cond_string,
9f757bf7
XR
12759 tempflag, 1 /* enabled */,
12760 from_tty);
12761}
12762
12763/* Implement the "catch handlers" command. */
12764
12765static void
12766catch_ada_handlers_command (const char *arg_entry, int from_tty,
12767 struct cmd_list_element *command)
12768{
12769 const char *arg = arg_entry;
12770 struct gdbarch *gdbarch = get_current_arch ();
12771 int tempflag;
12772 enum ada_exception_catchpoint_kind ex_kind;
bc18fbb5 12773 std::string excep_string;
56ecd069 12774 std::string cond_string;
9f757bf7 12775
0f8e2034 12776 tempflag = command->context () == CATCH_TEMPORARY;
9f757bf7
XR
12777
12778 if (!arg)
12779 arg = "";
12780 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
bc18fbb5 12781 &cond_string);
b4a5b78b 12782 create_ada_exception_catchpoint (gdbarch, ex_kind,
898db0f7 12783 std::move (excep_string), cond_string,
349774ef
JB
12784 tempflag, 1 /* enabled */,
12785 from_tty);
9ac4176b
PA
12786}
12787
71bed2db
TT
12788/* Completion function for the Ada "catch" commands. */
12789
12790static void
12791catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12792 const char *text, const char *word)
12793{
12794 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12795
12796 for (const ada_exc_info &info : exceptions)
12797 {
12798 if (startswith (info.name, word))
b02f78f9 12799 tracker.add_completion (make_unique_xstrdup (info.name));
71bed2db
TT
12800 }
12801}
12802
b4a5b78b 12803/* Split the arguments specified in a "catch assert" command.
5845583d 12804
b4a5b78b
JB
12805 ARGS contains the command's arguments (or the empty string if
12806 no arguments were passed).
5845583d
JB
12807
12808 If ARGS contains a condition, set COND_STRING to that condition
b4a5b78b 12809 (the memory needs to be deallocated after use). */
5845583d 12810
b4a5b78b 12811static void
56ecd069 12812catch_ada_assert_command_split (const char *args, std::string &cond_string)
f7f9143b 12813{
f1735a53 12814 args = skip_spaces (args);
f7f9143b 12815
5845583d 12816 /* Check whether a condition was provided. */
61012eef 12817 if (startswith (args, "if")
5845583d 12818 && (isspace (args[2]) || args[2] == '\0'))
f7f9143b 12819 {
5845583d 12820 args += 2;
f1735a53 12821 args = skip_spaces (args);
5845583d 12822 if (args[0] == '\0')
dda83cd7 12823 error (_("condition missing after `if' keyword"));
56ecd069 12824 cond_string.assign (args);
f7f9143b
JB
12825 }
12826
5845583d
JB
12827 /* Otherwise, there should be no other argument at the end of
12828 the command. */
12829 else if (args[0] != '\0')
12830 error (_("Junk at end of arguments."));
f7f9143b
JB
12831}
12832
9ac4176b
PA
12833/* Implement the "catch assert" command. */
12834
12835static void
eb4c3f4a 12836catch_assert_command (const char *arg_entry, int from_tty,
9ac4176b
PA
12837 struct cmd_list_element *command)
12838{
a121b7c1 12839 const char *arg = arg_entry;
9ac4176b
PA
12840 struct gdbarch *gdbarch = get_current_arch ();
12841 int tempflag;
56ecd069 12842 std::string cond_string;
9ac4176b 12843
0f8e2034 12844 tempflag = command->context () == CATCH_TEMPORARY;
9ac4176b
PA
12845
12846 if (!arg)
12847 arg = "";
56ecd069 12848 catch_ada_assert_command_split (arg, cond_string);
761269c8 12849 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
898db0f7 12850 {}, cond_string,
349774ef
JB
12851 tempflag, 1 /* enabled */,
12852 from_tty);
9ac4176b 12853}
778865d3
JB
12854
12855/* Return non-zero if the symbol SYM is an Ada exception object. */
12856
12857static int
12858ada_is_exception_sym (struct symbol *sym)
12859{
5f9c5a63 12860 const char *type_name = sym->type ()->name ();
778865d3 12861
66d7f48f
SM
12862 return (sym->aclass () != LOC_TYPEDEF
12863 && sym->aclass () != LOC_BLOCK
12864 && sym->aclass () != LOC_CONST
12865 && sym->aclass () != LOC_UNRESOLVED
dda83cd7 12866 && type_name != NULL && strcmp (type_name, "exception") == 0);
778865d3
JB
12867}
12868
12869/* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12870 Ada exception object. This matches all exceptions except the ones
12871 defined by the Ada language. */
12872
12873static int
12874ada_is_non_standard_exception_sym (struct symbol *sym)
12875{
778865d3
JB
12876 if (!ada_is_exception_sym (sym))
12877 return 0;
12878
696d6f4d
TT
12879 for (const char *name : standard_exc)
12880 if (strcmp (sym->linkage_name (), name) == 0)
778865d3
JB
12881 return 0; /* A standard exception. */
12882
12883 /* Numeric_Error is also a standard exception, so exclude it.
12884 See the STANDARD_EXC description for more details as to why
12885 this exception is not listed in that array. */
987012b8 12886 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
778865d3
JB
12887 return 0;
12888
12889 return 1;
12890}
12891
ab816a27 12892/* A helper function for std::sort, comparing two struct ada_exc_info
778865d3
JB
12893 objects.
12894
12895 The comparison is determined first by exception name, and then
12896 by exception address. */
12897
ab816a27 12898bool
cc536b21 12899ada_exc_info::operator< (const ada_exc_info &other) const
778865d3 12900{
778865d3
JB
12901 int result;
12902
ab816a27
TT
12903 result = strcmp (name, other.name);
12904 if (result < 0)
12905 return true;
12906 if (result == 0 && addr < other.addr)
12907 return true;
12908 return false;
12909}
778865d3 12910
ab816a27 12911bool
cc536b21 12912ada_exc_info::operator== (const ada_exc_info &other) const
ab816a27
TT
12913{
12914 return addr == other.addr && strcmp (name, other.name) == 0;
778865d3
JB
12915}
12916
12917/* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12918 routine, but keeping the first SKIP elements untouched.
12919
12920 All duplicates are also removed. */
12921
12922static void
ab816a27 12923sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
778865d3
JB
12924 int skip)
12925{
ab816a27
TT
12926 std::sort (exceptions->begin () + skip, exceptions->end ());
12927 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12928 exceptions->end ());
778865d3
JB
12929}
12930
778865d3
JB
12931/* Add all exceptions defined by the Ada standard whose name match
12932 a regular expression.
12933
12934 If PREG is not NULL, then this regexp_t object is used to
12935 perform the symbol name matching. Otherwise, no name-based
12936 filtering is performed.
12937
12938 EXCEPTIONS is a vector of exceptions to which matching exceptions
12939 gets pushed. */
12940
12941static void
2d7cc5c7 12942ada_add_standard_exceptions (compiled_regex *preg,
ab816a27 12943 std::vector<ada_exc_info> *exceptions)
778865d3 12944{
696d6f4d 12945 for (const char *name : standard_exc)
778865d3 12946 {
696d6f4d 12947 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
778865d3 12948 {
4326580d
MM
12949 symbol_name_match_type match_type = name_match_type_from_name (name);
12950 lookup_name_info lookup_name (name, match_type);
778865d3 12951
4326580d
MM
12952 symbol_name_matcher_ftype *match_name
12953 = ada_get_symbol_name_matcher (lookup_name);
778865d3 12954
4326580d
MM
12955 /* Iterate over all objfiles irrespective of scope or linker
12956 namespaces so we get all exceptions anywhere in the
12957 progspace. */
12958 for (objfile *objfile : current_program_space->objfiles ())
12959 {
12960 for (minimal_symbol *msymbol : objfile->msymbols ())
12961 {
12962 if (match_name (msymbol->linkage_name (), lookup_name,
12963 nullptr)
12964 && msymbol->type () != mst_solib_trampoline)
12965 {
12966 ada_exc_info info
12967 = {name, msymbol->value_address (objfile)};
12968
12969 exceptions->push_back (info);
12970 }
12971 }
778865d3
JB
12972 }
12973 }
12974 }
12975}
12976
12977/* Add all Ada exceptions defined locally and accessible from the given
12978 FRAME.
12979
12980 If PREG is not NULL, then this regexp_t object is used to
12981 perform the symbol name matching. Otherwise, no name-based
12982 filtering is performed.
12983
12984 EXCEPTIONS is a vector of exceptions to which matching exceptions
12985 gets pushed. */
12986
12987static void
2d7cc5c7 12988ada_add_exceptions_from_frame (compiled_regex *preg,
8480a37e 12989 const frame_info_ptr &frame,
ab816a27 12990 std::vector<ada_exc_info> *exceptions)
778865d3 12991{
3977b71f 12992 const struct block *block = get_frame_block (frame, 0);
778865d3
JB
12993
12994 while (block != 0)
12995 {
548a89df 12996 for (struct symbol *sym : block_iterator_range (block))
778865d3 12997 {
66d7f48f 12998 switch (sym->aclass ())
778865d3
JB
12999 {
13000 case LOC_TYPEDEF:
13001 case LOC_BLOCK:
13002 case LOC_CONST:
13003 break;
13004 default:
13005 if (ada_is_exception_sym (sym))
13006 {
987012b8 13007 struct ada_exc_info info = {sym->print_name (),
4aeddc50 13008 sym->value_address ()};
778865d3 13009
ab816a27 13010 exceptions->push_back (info);
778865d3
JB
13011 }
13012 }
13013 }
6c00f721 13014 if (block->function () != NULL)
778865d3 13015 break;
f135fe72 13016 block = block->superblock ();
778865d3
JB
13017 }
13018}
13019
14bc53a8
PA
13020/* Return true if NAME matches PREG or if PREG is NULL. */
13021
13022static bool
2d7cc5c7 13023name_matches_regex (const char *name, compiled_regex *preg)
14bc53a8
PA
13024{
13025 return (preg == NULL
f945dedf 13026 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
14bc53a8
PA
13027}
13028
778865d3
JB
13029/* Add all exceptions defined globally whose name name match
13030 a regular expression, excluding standard exceptions.
13031
13032 The reason we exclude standard exceptions is that they need
13033 to be handled separately: Standard exceptions are defined inside
13034 a runtime unit which is normally not compiled with debugging info,
13035 and thus usually do not show up in our symbol search. However,
13036 if the unit was in fact built with debugging info, we need to
13037 exclude them because they would duplicate the entry we found
13038 during the special loop that specifically searches for those
13039 standard exceptions.
13040
13041 If PREG is not NULL, then this regexp_t object is used to
13042 perform the symbol name matching. Otherwise, no name-based
13043 filtering is performed.
13044
13045 EXCEPTIONS is a vector of exceptions to which matching exceptions
13046 gets pushed. */
13047
13048static void
2d7cc5c7 13049ada_add_global_exceptions (compiled_regex *preg,
ab816a27 13050 std::vector<ada_exc_info> *exceptions)
778865d3 13051{
14bc53a8
PA
13052 /* In Ada, the symbol "search name" is a linkage name, whereas the
13053 regular expression used to do the matching refers to the natural
13054 name. So match against the decoded name. */
13055 expand_symtabs_matching (NULL,
b5ec771e 13056 lookup_name_info::match_any (),
14bc53a8
PA
13057 [&] (const char *search_name)
13058 {
f945dedf
CB
13059 std::string decoded = ada_decode (search_name);
13060 return name_matches_regex (decoded.c_str (), preg);
14bc53a8
PA
13061 },
13062 NULL,
03a8ea51 13063 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
c92d4de1 13064 SEARCH_VAR_DOMAIN);
778865d3 13065
4326580d
MM
13066 /* Iterate over all objfiles irrespective of scope or linker namespaces
13067 so we get all exceptions anywhere in the progspace. */
2030c079 13068 for (objfile *objfile : current_program_space->objfiles ())
778865d3 13069 {
b669c953 13070 for (compunit_symtab *s : objfile->compunits ())
778865d3 13071 {
af39c5c8 13072 const struct blockvector *bv = s->blockvector ();
d8aeb77f 13073 int i;
778865d3 13074
d8aeb77f
TT
13075 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13076 {
63d609de 13077 const struct block *b = bv->block (i);
778865d3 13078
548a89df 13079 for (struct symbol *sym : block_iterator_range (b))
d8aeb77f 13080 if (ada_is_non_standard_exception_sym (sym)
987012b8 13081 && name_matches_regex (sym->natural_name (), preg))
d8aeb77f
TT
13082 {
13083 struct ada_exc_info info
4aeddc50 13084 = {sym->print_name (), sym->value_address ()};
d8aeb77f
TT
13085
13086 exceptions->push_back (info);
13087 }
13088 }
778865d3
JB
13089 }
13090 }
13091}
13092
13093/* Implements ada_exceptions_list with the regular expression passed
13094 as a regex_t, rather than a string.
13095
13096 If not NULL, PREG is used to filter out exceptions whose names
13097 do not match. Otherwise, all exceptions are listed. */
13098
ab816a27 13099static std::vector<ada_exc_info>
2d7cc5c7 13100ada_exceptions_list_1 (compiled_regex *preg)
778865d3 13101{
ab816a27 13102 std::vector<ada_exc_info> result;
778865d3
JB
13103 int prev_len;
13104
13105 /* First, list the known standard exceptions. These exceptions
13106 need to be handled separately, as they are usually defined in
13107 runtime units that have been compiled without debugging info. */
13108
13109 ada_add_standard_exceptions (preg, &result);
13110
13111 /* Next, find all exceptions whose scope is local and accessible
13112 from the currently selected frame. */
13113
13114 if (has_stack_frames ())
13115 {
ab816a27 13116 prev_len = result.size ();
778865d3
JB
13117 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13118 &result);
ab816a27 13119 if (result.size () > prev_len)
778865d3
JB
13120 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13121 }
13122
13123 /* Add all exceptions whose scope is global. */
13124
ab816a27 13125 prev_len = result.size ();
778865d3 13126 ada_add_global_exceptions (preg, &result);
ab816a27 13127 if (result.size () > prev_len)
778865d3
JB
13128 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13129
778865d3
JB
13130 return result;
13131}
13132
13133/* Return a vector of ada_exc_info.
13134
13135 If REGEXP is NULL, all exceptions are included in the result.
13136 Otherwise, it should contain a valid regular expression,
13137 and only the exceptions whose names match that regular expression
13138 are included in the result.
13139
13140 The exceptions are sorted in the following order:
13141 - Standard exceptions (defined by the Ada language), in
13142 alphabetical order;
13143 - Exceptions only visible from the current frame, in
13144 alphabetical order;
13145 - Exceptions whose scope is global, in alphabetical order. */
13146
ab816a27 13147std::vector<ada_exc_info>
778865d3
JB
13148ada_exceptions_list (const char *regexp)
13149{
2d7cc5c7
PA
13150 if (regexp == NULL)
13151 return ada_exceptions_list_1 (NULL);
778865d3 13152
2d7cc5c7
PA
13153 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13154 return ada_exceptions_list_1 (&reg);
778865d3
JB
13155}
13156
13157/* Implement the "info exceptions" command. */
13158
13159static void
1d12d88f 13160info_exceptions_command (const char *regexp, int from_tty)
778865d3 13161{
778865d3 13162 struct gdbarch *gdbarch = get_current_arch ();
778865d3 13163
ab816a27 13164 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
778865d3
JB
13165
13166 if (regexp != NULL)
6cb06a8c 13167 gdb_printf
778865d3
JB
13168 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13169 else
6cb06a8c 13170 gdb_printf (_("All defined Ada exceptions:\n"));
778865d3 13171
ab816a27 13172 for (const ada_exc_info &info : exceptions)
6cb06a8c 13173 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
778865d3
JB
13174}
13175
6c038f32
PH
13176\f
13177 /* Language vector */
13178
b5ec771e
PA
13179/* symbol_name_matcher_ftype adapter for wild_match. */
13180
13181static bool
13182do_wild_match (const char *symbol_search_name,
13183 const lookup_name_info &lookup_name,
a207cff2 13184 completion_match_result *comp_match_res)
b5ec771e
PA
13185{
13186 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13187}
13188
13189/* symbol_name_matcher_ftype adapter for full_match. */
13190
13191static bool
13192do_full_match (const char *symbol_search_name,
13193 const lookup_name_info &lookup_name,
a207cff2 13194 completion_match_result *comp_match_res)
b5ec771e 13195{
959d6a67
TT
13196 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13197
13198 /* If both symbols start with "_ada_", just let the loop below
13199 handle the comparison. However, if only the symbol name starts
13200 with "_ada_", skip the prefix and let the match proceed as
13201 usual. */
13202 if (startswith (symbol_search_name, "_ada_")
13203 && !startswith (lname, "_ada"))
86b44259 13204 symbol_search_name += 5;
81eaa506
TT
13205 /* Likewise for ghost entities. */
13206 if (startswith (symbol_search_name, "___ghost_")
13207 && !startswith (lname, "___ghost_"))
13208 symbol_search_name += 9;
86b44259 13209
86b44259
TT
13210 int uscore_count = 0;
13211 while (*lname != '\0')
13212 {
13213 if (*symbol_search_name != *lname)
13214 {
13215 if (*symbol_search_name == 'B' && uscore_count == 2
13216 && symbol_search_name[1] == '_')
13217 {
13218 symbol_search_name += 2;
13219 while (isdigit (*symbol_search_name))
13220 ++symbol_search_name;
13221 if (symbol_search_name[0] == '_'
13222 && symbol_search_name[1] == '_')
13223 {
13224 symbol_search_name += 2;
13225 continue;
13226 }
13227 }
13228 return false;
13229 }
13230
13231 if (*symbol_search_name == '_')
13232 ++uscore_count;
13233 else
13234 uscore_count = 0;
13235
13236 ++symbol_search_name;
13237 ++lname;
13238 }
13239
13240 return is_name_suffix (symbol_search_name);
b5ec771e
PA
13241}
13242
a2cd4f14
JB
13243/* symbol_name_matcher_ftype for exact (verbatim) matches. */
13244
13245static bool
13246do_exact_match (const char *symbol_search_name,
13247 const lookup_name_info &lookup_name,
13248 completion_match_result *comp_match_res)
13249{
13250 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13251}
13252
b5ec771e
PA
13253/* Build the Ada lookup name for LOOKUP_NAME. */
13254
13255ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13256{
8082468f 13257 std::string_view user_name = lookup_name.name ();
b5ec771e 13258
6a780b67 13259 if (!user_name.empty () && user_name[0] == '<')
b5ec771e
PA
13260 {
13261 if (user_name.back () == '>')
882b0505 13262 m_encoded_name = user_name.substr (1, user_name.size () - 2);
b5ec771e 13263 else
882b0505 13264 m_encoded_name = user_name.substr (1, user_name.size () - 1);
b5ec771e
PA
13265 m_encoded_p = true;
13266 m_verbatim_p = true;
13267 m_wild_match_p = false;
13268 m_standard_p = false;
13269 }
13270 else
13271 {
13272 m_verbatim_p = false;
13273
8082468f 13274 m_encoded_p = user_name.find ("__") != std::string_view::npos;
b5ec771e
PA
13275
13276 if (!m_encoded_p)
13277 {
e0802d59 13278 const char *folded = ada_fold_name (user_name);
5c4258f4
TT
13279 m_encoded_name = ada_encode_1 (folded, false);
13280 if (m_encoded_name.empty ())
882b0505 13281 m_encoded_name = user_name;
b5ec771e
PA
13282 }
13283 else
882b0505 13284 m_encoded_name = user_name;
b5ec771e
PA
13285
13286 /* Handle the 'package Standard' special case. See description
13287 of m_standard_p. */
13288 if (startswith (m_encoded_name.c_str (), "standard__"))
13289 {
13290 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13291 m_standard_p = true;
13292 }
13293 else
13294 m_standard_p = false;
74ccd7f5 13295
957ce537
TT
13296 m_decoded_name = ada_decode (m_encoded_name.c_str (), true, false, false);
13297
b5ec771e
PA
13298 /* If the name contains a ".", then the user is entering a fully
13299 qualified entity name, and the match must not be done in wild
13300 mode. Similarly, if the user wants to complete what looks
13301 like an encoded name, the match must not be done in wild
13302 mode. Also, in the standard__ special case always do
13303 non-wild matching. */
13304 m_wild_match_p
13305 = (lookup_name.match_type () != symbol_name_match_type::FULL
13306 && !m_encoded_p
13307 && !m_standard_p
13308 && user_name.find ('.') == std::string::npos);
13309 }
13310}
13311
13312/* symbol_name_matcher_ftype method for Ada. This only handles
13313 completion mode. */
13314
13315static bool
13316ada_symbol_name_matches (const char *symbol_search_name,
13317 const lookup_name_info &lookup_name,
a207cff2 13318 completion_match_result *comp_match_res)
74ccd7f5 13319{
b5ec771e
PA
13320 return lookup_name.ada ().matches (symbol_search_name,
13321 lookup_name.match_type (),
a207cff2 13322 comp_match_res);
b5ec771e
PA
13323}
13324
de63c46b
PA
13325/* A name matcher that matches the symbol name exactly, with
13326 strcmp. */
13327
13328static bool
13329literal_symbol_name_matcher (const char *symbol_search_name,
13330 const lookup_name_info &lookup_name,
13331 completion_match_result *comp_match_res)
13332{
8082468f 13333 std::string_view name_view = lookup_name.name ();
de63c46b 13334
e0802d59
TT
13335 if (lookup_name.completion_mode ()
13336 ? (strncmp (symbol_search_name, name_view.data (),
13337 name_view.size ()) == 0)
13338 : symbol_search_name == name_view)
de63c46b
PA
13339 {
13340 if (comp_match_res != NULL)
13341 comp_match_res->set_match (symbol_search_name);
13342 return true;
13343 }
13344 else
13345 return false;
13346}
13347
c9debfb9 13348/* Implement the "get_symbol_name_matcher" language_defn method for
b5ec771e
PA
13349 Ada. */
13350
13351static symbol_name_matcher_ftype *
13352ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13353{
de63c46b
PA
13354 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13355 return literal_symbol_name_matcher;
13356
b5ec771e
PA
13357 if (lookup_name.completion_mode ())
13358 return ada_symbol_name_matches;
74ccd7f5 13359 else
b5ec771e
PA
13360 {
13361 if (lookup_name.ada ().wild_match_p ())
13362 return do_wild_match;
a2cd4f14
JB
13363 else if (lookup_name.ada ().verbatim_p ())
13364 return do_exact_match;
b5ec771e
PA
13365 else
13366 return do_full_match;
13367 }
74ccd7f5
JB
13368}
13369
0874fd07
AB
13370/* Class representing the Ada language. */
13371
13372class ada_language : public language_defn
13373{
13374public:
13375 ada_language ()
0e25e767 13376 : language_defn (language_ada)
0874fd07 13377 { /* Nothing. */ }
5bd40f2a 13378
6f7664a9
AB
13379 /* See language.h. */
13380
13381 const char *name () const override
13382 { return "ada"; }
13383
13384 /* See language.h. */
13385
13386 const char *natural_name () const override
13387 { return "Ada"; }
13388
e171d6f1
AB
13389 /* See language.h. */
13390
13391 const std::vector<const char *> &filename_extensions () const override
13392 {
13393 static const std::vector<const char *> extensions
13394 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13395 return extensions;
13396 }
13397
5bd40f2a
AB
13398 /* Print an array element index using the Ada syntax. */
13399
13400 void print_array_index (struct type *index_type,
13401 LONGEST index,
13402 struct ui_file *stream,
13403 const value_print_options *options) const override
13404 {
13405 struct value *index_value = val_atr (index_type, index);
13406
00c696a6 13407 value_print (index_value, stream, options);
6cb06a8c 13408 gdb_printf (stream, " => ");
5bd40f2a 13409 }
15e5fd35
AB
13410
13411 /* Implement the "read_var_value" language_defn method for Ada. */
13412
13413 struct value *read_var_value (struct symbol *var,
13414 const struct block *var_block,
8480a37e 13415 const frame_info_ptr &frame) const override
15e5fd35
AB
13416 {
13417 /* The only case where default_read_var_value is not sufficient
13418 is when VAR is a renaming... */
13419 if (frame != nullptr)
13420 {
13421 const struct block *frame_block = get_frame_block (frame, NULL);
13422 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13423 return ada_read_renaming_var_value (var, frame_block);
13424 }
13425
13426 /* This is a typical case where we expect the default_read_var_value
13427 function to work. */
13428 return language_defn::read_var_value (var, var_block, frame);
13429 }
1fb314aa 13430
2c71f639 13431 /* See language.h. */
496feb16 13432 bool symbol_printing_suppressed (struct symbol *symbol) const override
2c71f639 13433 {
496feb16 13434 return symbol->is_artificial ();
2c71f639
TV
13435 }
13436
baab3753
AB
13437 /* See language.h. */
13438 struct value *value_string (struct gdbarch *gdbarch,
13439 const char *ptr, ssize_t len) const override
13440 {
13441 struct type *type = language_string_char_type (this, gdbarch);
13442 value *val = ::value_string (ptr, len, type);
13443 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13444 strings that are arrays of characters, so fix the type now. */
13445 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13446 val->type ()->set_code (TYPE_CODE_ARRAY);
13447 return val;
13448 }
13449
1fb314aa
AB
13450 /* See language.h. */
13451 void language_arch_info (struct gdbarch *gdbarch,
13452 struct language_arch_info *lai) const override
13453 {
13454 const struct builtin_type *builtin = builtin_type (gdbarch);
13455
7bea47f0
AB
13456 /* Helper function to allow shorter lines below. */
13457 auto add = [&] (struct type *t)
13458 {
13459 lai->add_primitive_type (t);
13460 };
13461
cc495054 13462 type_allocator alloc (gdbarch);
2d39ccd3 13463 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0 13464 0, "integer"));
2d39ccd3 13465 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
7bea47f0 13466 0, "long_integer"));
2d39ccd3 13467 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
7bea47f0 13468 0, "short_integer"));
f50b437c 13469 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
c9f66f00 13470 1, "character");
7bea47f0
AB
13471 lai->set_string_char_type (char_type);
13472 add (char_type);
f50b437c
TT
13473 add (init_character_type (alloc, 16, 1, "wide_character"));
13474 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
77c5f496 13475 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
7bea47f0 13476 "float", gdbarch_float_format (gdbarch)));
77c5f496 13477 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
7bea47f0 13478 "long_float", gdbarch_double_format (gdbarch)));
2d39ccd3 13479 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
7bea47f0 13480 0, "long_long_integer"));
e49831ba
TT
13481 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13482 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
77c5f496 13483 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
7bea47f0
AB
13484 "long_long_float",
13485 gdbarch_long_double_format (gdbarch)));
2d39ccd3 13486 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0 13487 0, "natural"));
2d39ccd3 13488 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0
AB
13489 0, "positive"));
13490 add (builtin->builtin_void);
13491
13492 struct type *system_addr_ptr
cc495054
TT
13493 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13494 "void"));
7bea47f0
AB
13495 system_addr_ptr->set_name ("system__address");
13496 add (system_addr_ptr);
1fb314aa
AB
13497
13498 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13499 type. This is a signed integral type whose size is the same as
13500 the size of addresses. */
df86565b 13501 unsigned int addr_length = system_addr_ptr->length ();
2d39ccd3 13502 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
7bea47f0 13503 "storage_offset"));
1fb314aa 13504
7bea47f0 13505 lai->set_bool_type (builtin->builtin_bool);
1fb314aa 13506 }
4009ee92
AB
13507
13508 /* See language.h. */
13509
13510 bool iterate_over_symbols
13511 (const struct block *block, const lookup_name_info &name,
6c015214 13512 domain_search_flags domain,
4009ee92
AB
13513 gdb::function_view<symbol_found_callback_ftype> callback) const override
13514 {
d1183b06
TT
13515 std::vector<struct block_symbol> results
13516 = ada_lookup_symbol_list_worker (name, block, domain, 0);
4009ee92
AB
13517 for (block_symbol &sym : results)
13518 {
13519 if (!callback (&sym))
13520 return false;
13521 }
13522
13523 return true;
13524 }
6f827019
AB
13525
13526 /* See language.h. */
3456e70c
TT
13527 bool sniff_from_mangled_name
13528 (const char *mangled,
13529 gdb::unique_xmalloc_ptr<char> *out) const override
6f827019
AB
13530 {
13531 std::string demangled = ada_decode (mangled);
13532
13533 *out = NULL;
13534
13535 if (demangled != mangled && demangled[0] != '<')
13536 {
13537 /* Set the gsymbol language to Ada, but still return 0.
13538 Two reasons for that:
13539
13540 1. For Ada, we prefer computing the symbol's decoded name
13541 on the fly rather than pre-compute it, in order to save
13542 memory (Ada projects are typically very large).
13543
13544 2. There are some areas in the definition of the GNAT
13545 encoding where, with a bit of bad luck, we might be able
13546 to decode a non-Ada symbol, generating an incorrect
13547 demangled name (Eg: names ending with "TB" for instance
13548 are identified as task bodies and so stripped from
13549 the decoded name returned).
13550
13551 Returning true, here, but not setting *DEMANGLED, helps us get
13552 a little bit of the best of both worlds. Because we're last,
13553 we should not affect any of the other languages that were
13554 able to demangle the symbol before us; we get to correctly
13555 tag Ada symbols as such; and even if we incorrectly tagged a
13556 non-Ada symbol, which should be rare, any routing through the
13557 Ada language should be transparent (Ada tries to behave much
13558 like C/C++ with non-Ada symbols). */
13559 return true;
13560 }
13561
13562 return false;
13563 }
fbfb0a46
AB
13564
13565 /* See language.h. */
13566
3456e70c
TT
13567 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13568 int options) const override
0a50df5d 13569 {
3456e70c 13570 return make_unique_xstrdup (ada_decode (mangled).c_str ());
0a50df5d
AB
13571 }
13572
13573 /* See language.h. */
13574
fbfb0a46
AB
13575 void print_type (struct type *type, const char *varstring,
13576 struct ui_file *stream, int show, int level,
13577 const struct type_print_options *flags) const override
13578 {
13579 ada_print_type (type, varstring, stream, show, level, flags);
13580 }
c9debfb9 13581
53fc67f8
AB
13582 /* See language.h. */
13583
13584 const char *word_break_characters (void) const override
13585 {
13586 return ada_completer_word_break_characters;
13587 }
13588
7e56227d
AB
13589 /* See language.h. */
13590
13591 void collect_symbol_completion_matches (completion_tracker &tracker,
13592 complete_symbol_mode mode,
13593 symbol_name_match_type name_match_type,
13594 const char *text, const char *word,
13595 enum type_code code) const override
13596 {
7e56227d 13597 const struct block *b, *surrounding_static_block = 0;
7e56227d
AB
13598
13599 gdb_assert (code == TYPE_CODE_UNDEF);
13600
13601 lookup_name_info lookup_name (text, name_match_type, true);
13602
13603 /* First, look at the partial symtab symbols. */
13604 expand_symtabs_matching (NULL,
13605 lookup_name,
13606 NULL,
13607 NULL,
03a8ea51 13608 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
f214edce 13609 SEARCH_ALL_DOMAINS);
7e56227d
AB
13610
13611 /* At this point scan through the misc symbol vectors and add each
13612 symbol you find to the list. Eventually we want to ignore
13613 anything that isn't a text symbol (everything else will be
13614 handled by the psymtab code above). */
13615
13616 for (objfile *objfile : current_program_space->objfiles ())
13617 {
13618 for (minimal_symbol *msymbol : objfile->msymbols ())
13619 {
13620 QUIT;
13621
13622 if (completion_skip_symbol (mode, msymbol))
13623 continue;
13624
13625 language symbol_language = msymbol->language ();
13626
13627 /* Ada minimal symbols won't have their language set to Ada. If
13628 we let completion_list_add_name compare using the
13629 default/C-like matcher, then when completing e.g., symbols in a
13630 package named "pck", we'd match internal Ada symbols like
13631 "pckS", which are invalid in an Ada expression, unless you wrap
13632 them in '<' '>' to request a verbatim match.
13633
13634 Unfortunately, some Ada encoded names successfully demangle as
13635 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13636 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13637 with the wrong language set. Paper over that issue here. */
129bce36 13638 if (symbol_language == language_unknown
7e56227d
AB
13639 || symbol_language == language_cplus)
13640 symbol_language = language_ada;
13641
13642 completion_list_add_name (tracker,
13643 symbol_language,
13644 msymbol->linkage_name (),
13645 lookup_name, text, word);
13646 }
13647 }
13648
13649 /* Search upwards from currently selected frame (so that we can
13650 complete on local vars. */
13651
f135fe72 13652 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
7e56227d 13653 {
f135fe72 13654 if (!b->superblock ())
7e56227d
AB
13655 surrounding_static_block = b; /* For elmin of dups */
13656
548a89df 13657 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13658 {
13659 if (completion_skip_symbol (mode, sym))
13660 continue;
13661
13662 completion_list_add_name (tracker,
13663 sym->language (),
13664 sym->linkage_name (),
13665 lookup_name, text, word);
13666 }
13667 }
13668
13669 /* Go through the symtabs and check the externs and statics for
13670 symbols which match. */
13671
13672 for (objfile *objfile : current_program_space->objfiles ())
13673 {
13674 for (compunit_symtab *s : objfile->compunits ())
13675 {
13676 QUIT;
63d609de 13677 b = s->blockvector ()->global_block ();
548a89df 13678 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13679 {
13680 if (completion_skip_symbol (mode, sym))
13681 continue;
13682
13683 completion_list_add_name (tracker,
13684 sym->language (),
13685 sym->linkage_name (),
13686 lookup_name, text, word);
13687 }
13688 }
13689 }
13690
13691 for (objfile *objfile : current_program_space->objfiles ())
13692 {
13693 for (compunit_symtab *s : objfile->compunits ())
13694 {
13695 QUIT;
63d609de 13696 b = s->blockvector ()->static_block ();
7e56227d
AB
13697 /* Don't do this block twice. */
13698 if (b == surrounding_static_block)
13699 continue;
548a89df 13700 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13701 {
13702 if (completion_skip_symbol (mode, sym))
13703 continue;
13704
13705 completion_list_add_name (tracker,
13706 sym->language (),
13707 sym->linkage_name (),
13708 lookup_name, text, word);
13709 }
13710 }
13711 }
13712 }
13713
f16a9f57
AB
13714 /* See language.h. */
13715
13716 gdb::unique_xmalloc_ptr<char> watch_location_expression
13717 (struct type *type, CORE_ADDR addr) const override
13718 {
27710edb 13719 type = check_typedef (check_typedef (type)->target_type ());
f16a9f57 13720 std::string name = type_to_string (type);
8579fd13 13721 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
f16a9f57
AB
13722 }
13723
a1d1fa3e
AB
13724 /* See language.h. */
13725
13726 void value_print (struct value *val, struct ui_file *stream,
13727 const struct value_print_options *options) const override
13728 {
13729 return ada_value_print (val, stream, options);
13730 }
13731
ebe2334e
AB
13732 /* See language.h. */
13733
13734 void value_print_inner
13735 (struct value *val, struct ui_file *stream, int recurse,
13736 const struct value_print_options *options) const override
13737 {
13738 return ada_value_print_inner (val, stream, recurse, options);
13739 }
13740
a78a19b1
AB
13741 /* See language.h. */
13742
13743 struct block_symbol lookup_symbol_nonlocal
13744 (const char *name, const struct block *block,
ccf41c24 13745 const domain_search_flags domain) const override
a78a19b1
AB
13746 {
13747 struct block_symbol sym;
13748
78004096
TT
13749 sym = ada_lookup_symbol (name,
13750 (block == nullptr
13751 ? nullptr
d24e14a0 13752 : block->static_block ()),
ccf41c24 13753 domain);
a78a19b1
AB
13754 if (sym.symbol != NULL)
13755 return sym;
13756
13757 /* If we haven't found a match at this point, try the primitive
13758 types. In other languages, this search is performed before
13759 searching for global symbols in order to short-circuit that
13760 global-symbol search if it happens that the name corresponds
13761 to a primitive type. But we cannot do the same in Ada, because
13762 it is perfectly legitimate for a program to declare a type which
13763 has the same name as a standard type. If looking up a type in
13764 that situation, we have traditionally ignored the primitive type
13765 in favor of user-defined types. This is why, unlike most other
13766 languages, we search the primitive types this late and only after
13767 having searched the global symbols without success. */
13768
ccf41c24 13769 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
a78a19b1
AB
13770 {
13771 struct gdbarch *gdbarch;
13772
13773 if (block == NULL)
99d9c3b9 13774 gdbarch = current_inferior ()->arch ();
a78a19b1 13775 else
7f5937df 13776 gdbarch = block->gdbarch ();
a78a19b1
AB
13777 sym.symbol
13778 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13779 if (sym.symbol != NULL)
13780 return sym;
13781 }
13782
13783 return {};
13784 }
13785
87afa652
AB
13786 /* See language.h. */
13787
13788 int parser (struct parser_state *ps) const override
13789 {
13790 warnings_issued = 0;
13791 return ada_parse (ps);
13792 }
13793
ec8cec5b
AB
13794 /* See language.h. */
13795
13796 void emitchar (int ch, struct type *chtype,
13797 struct ui_file *stream, int quoter) const override
13798 {
13799 ada_emit_char (ch, chtype, stream, quoter, 1);
13800 }
13801
52b50f2c
AB
13802 /* See language.h. */
13803
13804 void printchar (int ch, struct type *chtype,
13805 struct ui_file *stream) const override
13806 {
13807 ada_printchar (ch, chtype, stream);
13808 }
13809
d711ee67
AB
13810 /* See language.h. */
13811
13812 void printstr (struct ui_file *stream, struct type *elttype,
13813 const gdb_byte *string, unsigned int length,
13814 const char *encoding, int force_ellipses,
13815 const struct value_print_options *options) const override
13816 {
13817 ada_printstr (stream, elttype, string, length, encoding,
13818 force_ellipses, options);
13819 }
13820
4ffc13fb
AB
13821 /* See language.h. */
13822
13823 void print_typedef (struct type *type, struct symbol *new_symbol,
13824 struct ui_file *stream) const override
13825 {
13826 ada_print_typedef (type, new_symbol, stream);
13827 }
13828
39e7ecca
AB
13829 /* See language.h. */
13830
13831 bool is_string_type_p (struct type *type) const override
13832 {
13833 return ada_is_string_type (type);
13834 }
13835
22e3f3ed
AB
13836 /* See language.h. */
13837
26733fc7
TT
13838 bool is_array_like (struct type *type) const override
13839 {
13840 return (ada_is_constrained_packed_array_type (type)
13841 || ada_is_array_descriptor_type (type));
13842 }
13843
13844 /* See language.h. */
13845
13846 struct value *to_array (struct value *val) const override
13847 { return ada_coerce_to_simple_array (val); }
13848
13849 /* See language.h. */
13850
22e3f3ed
AB
13851 const char *struct_too_deep_ellipsis () const override
13852 { return "(...)"; }
39e7ecca 13853
67bd3fd5
AB
13854 /* See language.h. */
13855
13856 bool c_style_arrays_p () const override
13857 { return false; }
13858
d3355e4d
AB
13859 /* See language.h. */
13860
13861 bool store_sym_names_in_linkage_form_p () const override
13862 { return true; }
13863
b63a3f3f
AB
13864 /* See language.h. */
13865
13866 const struct lang_varobj_ops *varobj_ops () const override
13867 { return &ada_varobj_ops; }
13868
c9debfb9
AB
13869protected:
13870 /* See language.h. */
13871
13872 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13873 (const lookup_name_info &lookup_name) const override
13874 {
13875 return ada_get_symbol_name_matcher (lookup_name);
13876 }
0874fd07
AB
13877};
13878
13879/* Single instance of the Ada language class. */
13880
13881static ada_language ada_language_defn;
13882
5bf03f13
JB
13883/* Command-list for the "set/show ada" prefix command. */
13884static struct cmd_list_element *set_ada_list;
13885static struct cmd_list_element *show_ada_list;
13886
3d9434b5
JB
13887/* This module's 'new_objfile' observer. */
13888
13889static void
13890ada_new_objfile_observer (struct objfile *objfile)
13891{
74daa597 13892 ada_clear_symbol_cache (objfile->pspace);
3d9434b5
JB
13893}
13894
13895/* This module's 'free_objfile' observer. */
13896
13897static void
13898ada_free_objfile_observer (struct objfile *objfile)
13899{
74daa597 13900 ada_clear_symbol_cache (objfile->pspace);
3d9434b5
JB
13901}
13902
315e4ebb
TT
13903/* Charsets known to GNAT. */
13904static const char * const gnat_source_charsets[] =
13905{
13906 /* Note that code below assumes that the default comes first.
13907 Latin-1 is the default here, because that is also GNAT's
13908 default. */
13909 "ISO-8859-1",
13910 "ISO-8859-2",
13911 "ISO-8859-3",
13912 "ISO-8859-4",
13913 "ISO-8859-5",
13914 "ISO-8859-15",
13915 "CP437",
13916 "CP850",
13917 /* Note that this value is special-cased in the encoder and
13918 decoder. */
13919 ada_utf8,
13920 nullptr
13921};
13922
6c265988 13923void _initialize_ada_language ();
d2e4a39e 13924void
6c265988 13925_initialize_ada_language ()
14f9c5c9 13926{
f54bdb6d
SM
13927 add_setshow_prefix_cmd
13928 ("ada", no_class,
13929 _("Prefix command for changing Ada-specific settings."),
13930 _("Generic command for showing Ada-specific settings."),
13931 &set_ada_list, &show_ada_list,
13932 &setlist, &showlist);
5bf03f13
JB
13933
13934 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
dda83cd7 13935 &trust_pad_over_xvs, _("\
590042fc
PW
13936Enable or disable an optimization trusting PAD types over XVS types."), _("\
13937Show whether an optimization trusting PAD types over XVS types is activated."),
dda83cd7 13938 _("\
5bf03f13
JB
13939This is related to the encoding used by the GNAT compiler. The debugger\n\
13940should normally trust the contents of PAD types, but certain older versions\n\
13941of GNAT have a bug that sometimes causes the information in the PAD type\n\
13942to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13943work around this bug. It is always safe to turn this option \"off\", but\n\
13944this incurs a slight performance penalty, so it is recommended to NOT change\n\
13945this option to \"off\" unless necessary."),
dda83cd7 13946 NULL, NULL, &set_ada_list, &show_ada_list);
5bf03f13 13947
d72413e6
PMR
13948 add_setshow_boolean_cmd ("print-signatures", class_vars,
13949 &print_signatures, _("\
13950Enable or disable the output of formal and return types for functions in the \
590042fc 13951overloads selection menu."), _("\
d72413e6 13952Show whether the output of formal and return types for functions in the \
590042fc 13953overloads selection menu is activated."),
d72413e6
PMR
13954 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13955
315e4ebb
TT
13956 ada_source_charset = gnat_source_charsets[0];
13957 add_setshow_enum_cmd ("source-charset", class_files,
13958 gnat_source_charsets,
13959 &ada_source_charset, _("\
13960Set the Ada source character set."), _("\
13961Show the Ada source character set."), _("\
13962The character set used for Ada source files.\n\
13963This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13964 nullptr, nullptr,
13965 &set_ada_list, &show_ada_list);
13966
9ac4176b
PA
13967 add_catch_command ("exception", _("\
13968Catch Ada exceptions, when raised.\n\
9bf7038b 13969Usage: catch exception [ARG] [if CONDITION]\n\
60a90376
JB
13970Without any argument, stop when any Ada exception is raised.\n\
13971If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13972being raised does not have a handler (and will therefore lead to the task's\n\
13973termination).\n\
13974Otherwise, the catchpoint only stops when the name of the exception being\n\
9bf7038b
TT
13975raised is the same as ARG.\n\
13976CONDITION is a boolean expression that is evaluated to see whether the\n\
13977exception should cause a stop."),
9ac4176b 13978 catch_ada_exception_command,
71bed2db 13979 catch_ada_completer,
9ac4176b
PA
13980 CATCH_PERMANENT,
13981 CATCH_TEMPORARY);
9f757bf7
XR
13982
13983 add_catch_command ("handlers", _("\
13984Catch Ada exceptions, when handled.\n\
9bf7038b
TT
13985Usage: catch handlers [ARG] [if CONDITION]\n\
13986Without any argument, stop when any Ada exception is handled.\n\
13987With an argument, catch only exceptions with the given name.\n\
13988CONDITION is a boolean expression that is evaluated to see whether the\n\
13989exception should cause a stop."),
9f757bf7 13990 catch_ada_handlers_command,
dda83cd7 13991 catch_ada_completer,
9f757bf7
XR
13992 CATCH_PERMANENT,
13993 CATCH_TEMPORARY);
9ac4176b
PA
13994 add_catch_command ("assert", _("\
13995Catch failed Ada assertions, when raised.\n\
9bf7038b
TT
13996Usage: catch assert [if CONDITION]\n\
13997CONDITION is a boolean expression that is evaluated to see whether the\n\
13998exception should cause a stop."),
9ac4176b 13999 catch_assert_command,
dda83cd7 14000 NULL,
9ac4176b
PA
14001 CATCH_PERMANENT,
14002 CATCH_TEMPORARY);
14003
778865d3
JB
14004 add_info ("exceptions", info_exceptions_command,
14005 _("\
14006List all Ada exception names.\n\
9bf7038b 14007Usage: info exceptions [REGEXP]\n\
778865d3
JB
14008If a regular expression is passed as an argument, only those matching\n\
14009the regular expression are listed."));
14010
f54bdb6d
SM
14011 add_setshow_prefix_cmd ("ada", class_maintenance,
14012 _("Set Ada maintenance-related variables."),
14013 _("Show Ada maintenance-related variables."),
14014 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14015 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
c6044dd1
JB
14016
14017 add_setshow_boolean_cmd
14018 ("ignore-descriptive-types", class_maintenance,
14019 &ada_ignore_descriptive_types_p,
14020 _("Set whether descriptive types generated by GNAT should be ignored."),
14021 _("Show whether descriptive types generated by GNAT should be ignored."),
14022 _("\
14023When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14024DWARF attribute."),
14025 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14026
2698f5ea
TT
14027 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14028 htab_eq_string,
459a2e4c 14029 NULL, xcalloc, xfree);
6b69afc4 14030
3d9434b5 14031 /* The ada-lang observers. */
c90e7d63 14032 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
74daa597
SM
14033 gdb::observers::all_objfiles_removed.attach (ada_clear_symbol_cache,
14034 "ada-lang");
c90e7d63
SM
14035 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14036 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
033bc52b
TT
14037
14038#ifdef GDB_SELF_TEST
14039 selftests::register_test ("ada-decode", ada_decode_tests);
14040#endif
14f9c5c9 14041}