]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/ada-lang.c
Finalized intl-update patches
[thirdparty/binutils-gdb.git] / gdb / ada-lang.c
CommitLineData
6e681866 1/* Ada language support routines for GDB, the GNU debugger.
10a2c479 2
213516ef 3 Copyright (C) 1992-2023 Free Software Foundation, Inc.
14f9c5c9 4
a9762ec7 5 This file is part of GDB.
14f9c5c9 6
a9762ec7
JB
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
14f9c5c9 11
a9762ec7
JB
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
14f9c5c9 16
a9762ec7
JB
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
14f9c5c9 19
96d887e8 20
4c4b4cd2 21#include "defs.h"
14f9c5c9 22#include <ctype.h>
d322d6d6 23#include "gdbsupport/gdb_regex.h"
4de283e4
TT
24#include "frame.h"
25#include "symtab.h"
26#include "gdbtypes.h"
14f9c5c9 27#include "gdbcmd.h"
4de283e4
TT
28#include "expression.h"
29#include "parser-defs.h"
30#include "language.h"
31#include "varobj.h"
4de283e4
TT
32#include "inferior.h"
33#include "symfile.h"
34#include "objfiles.h"
35#include "breakpoint.h"
14f9c5c9 36#include "gdbcore.h"
4c4b4cd2 37#include "hashtab.h"
bf31fd38 38#include "gdbsupport/gdb_obstack.h"
4de283e4
TT
39#include "ada-lang.h"
40#include "completer.h"
4de283e4
TT
41#include "ui-out.h"
42#include "block.h"
04714b91 43#include "infcall.h"
4de283e4
TT
44#include "annotate.h"
45#include "valprint.h"
d55e5aa6 46#include "source.h"
4de283e4 47#include "observable.h"
692465f1 48#include "stack.h"
79d43c61 49#include "typeprint.h"
4de283e4 50#include "namespace.h"
7f6aba03 51#include "cli/cli-style.h"
0f8e2034 52#include "cli/cli-decode.h"
4de283e4 53
40bc484c 54#include "value.h"
4de283e4
TT
55#include "mi/mi-common.h"
56#include "arch-utils.h"
57#include "cli/cli-utils.h"
268a13a5
TT
58#include "gdbsupport/function-view.h"
59#include "gdbsupport/byte-vector.h"
033bc52b 60#include "gdbsupport/selftest.h"
4de283e4 61#include <algorithm>
03070ee9 62#include "ada-exp.h"
315e4ebb 63#include "charset.h"
013a623f 64#include "ax-gdb.h"
ccefe4c4 65
d2e4a39e 66static struct type *desc_base_type (struct type *);
14f9c5c9 67
d2e4a39e 68static struct type *desc_bounds_type (struct type *);
14f9c5c9 69
d2e4a39e 70static struct value *desc_bounds (struct value *);
14f9c5c9 71
d2e4a39e 72static int fat_pntr_bounds_bitpos (struct type *);
14f9c5c9 73
d2e4a39e 74static int fat_pntr_bounds_bitsize (struct type *);
14f9c5c9 75
556bdfd4 76static struct type *desc_data_target_type (struct type *);
14f9c5c9 77
d2e4a39e 78static struct value *desc_data (struct value *);
14f9c5c9 79
d2e4a39e 80static int fat_pntr_data_bitpos (struct type *);
14f9c5c9 81
d2e4a39e 82static int fat_pntr_data_bitsize (struct type *);
14f9c5c9 83
d2e4a39e 84static struct value *desc_one_bound (struct value *, int, int);
14f9c5c9 85
d2e4a39e 86static int desc_bound_bitpos (struct type *, int, int);
14f9c5c9 87
d2e4a39e 88static int desc_bound_bitsize (struct type *, int, int);
14f9c5c9 89
d2e4a39e 90static struct type *desc_index_type (struct type *, int);
14f9c5c9 91
d2e4a39e 92static int desc_arity (struct type *);
14f9c5c9 93
d2e4a39e 94static int ada_args_match (struct symbol *, struct value **, int);
14f9c5c9 95
40bc484c 96static struct value *make_array_descriptor (struct type *, struct value *);
14f9c5c9 97
d1183b06 98static void ada_add_block_symbols (std::vector<struct block_symbol> &,
b5ec771e
PA
99 const struct block *,
100 const lookup_name_info &lookup_name,
101 domain_enum, struct objfile *);
14f9c5c9 102
d1183b06
TT
103static void ada_add_all_symbols (std::vector<struct block_symbol> &,
104 const struct block *,
b5ec771e
PA
105 const lookup_name_info &lookup_name,
106 domain_enum, int, int *);
22cee43f 107
d1183b06 108static int is_nonfunction (const std::vector<struct block_symbol> &);
14f9c5c9 109
d1183b06
TT
110static void add_defn_to_vec (std::vector<struct block_symbol> &,
111 struct symbol *,
dda83cd7 112 const struct block *);
14f9c5c9 113
d2e4a39e 114static int possible_user_operator_p (enum exp_opcode, struct value **);
14f9c5c9 115
4c4b4cd2 116static const char *ada_decoded_op_name (enum exp_opcode);
14f9c5c9 117
d2e4a39e 118static int numeric_type_p (struct type *);
14f9c5c9 119
d2e4a39e 120static int integer_type_p (struct type *);
14f9c5c9 121
d2e4a39e 122static int scalar_type_p (struct type *);
14f9c5c9 123
d2e4a39e 124static int discrete_type_p (struct type *);
14f9c5c9 125
a121b7c1 126static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
dda83cd7 127 int, int);
4c4b4cd2 128
b4ba55a1 129static struct type *ada_find_parallel_type_with_name (struct type *,
dda83cd7 130 const char *);
b4ba55a1 131
d2e4a39e 132static int is_dynamic_field (struct type *, int);
14f9c5c9 133
10a2c479 134static struct type *to_fixed_variant_branch_type (struct type *,
fc1a4b47 135 const gdb_byte *,
dda83cd7 136 CORE_ADDR, struct value *);
4c4b4cd2
PH
137
138static struct type *to_fixed_array_type (struct type *, struct value *, int);
14f9c5c9 139
28c85d6c 140static struct type *to_fixed_range_type (struct type *, struct value *);
14f9c5c9 141
d2e4a39e 142static struct type *to_static_fixed_type (struct type *);
f192137b 143static struct type *static_unwrap_type (struct type *type);
14f9c5c9 144
d2e4a39e 145static struct value *unwrap_value (struct value *);
14f9c5c9 146
ad82864c 147static struct type *constrained_packed_array_type (struct type *, long *);
14f9c5c9 148
ad82864c 149static struct type *decode_constrained_packed_array_type (struct type *);
14f9c5c9 150
ad82864c
JB
151static long decode_packed_array_bitsize (struct type *);
152
153static struct value *decode_constrained_packed_array (struct value *);
154
ad82864c 155static int ada_is_unconstrained_packed_array_type (struct type *);
14f9c5c9 156
d2e4a39e 157static struct value *value_subscript_packed (struct value *, int,
dda83cd7 158 struct value **);
14f9c5c9 159
4c4b4cd2 160static struct value *coerce_unspec_val_to_type (struct value *,
dda83cd7 161 struct type *);
14f9c5c9 162
d2e4a39e 163static int lesseq_defined_than (struct symbol *, struct symbol *);
14f9c5c9 164
d2e4a39e 165static int equiv_types (struct type *, struct type *);
14f9c5c9 166
d2e4a39e 167static int is_name_suffix (const char *);
14f9c5c9 168
59c8a30b 169static int advance_wild_match (const char **, const char *, char);
73589123 170
b5ec771e 171static bool wild_match (const char *name, const char *patn);
14f9c5c9 172
d2e4a39e 173static struct value *ada_coerce_ref (struct value *);
14f9c5c9 174
4c4b4cd2
PH
175static LONGEST pos_atr (struct value *);
176
53a47a3e
TT
177static struct value *val_atr (struct type *, LONGEST);
178
4c4b4cd2 179static struct symbol *standard_lookup (const char *, const struct block *,
dda83cd7 180 domain_enum);
14f9c5c9 181
108d56a4 182static struct value *ada_search_struct_field (const char *, struct value *, int,
dda83cd7 183 struct type *);
4c4b4cd2 184
0d5cff50 185static int find_struct_field (const char *, struct type *, int,
dda83cd7 186 struct type **, int *, int *, int *, int *);
4c4b4cd2 187
d1183b06 188static int ada_resolve_function (std::vector<struct block_symbol> &,
dda83cd7 189 struct value **, int, const char *,
7056f312 190 struct type *, bool);
4c4b4cd2 191
4c4b4cd2
PH
192static int ada_is_direct_array_type (struct type *);
193
52ce6436
PH
194static struct value *ada_index_struct_field (int, struct value *, int,
195 struct type *);
196
cf608cc4 197static void add_component_interval (LONGEST, LONGEST, std::vector<LONGEST> &);
52ce6436
PH
198
199
852dff6c 200static struct type *ada_find_any_type (const char *name);
b5ec771e
PA
201
202static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
203 (const lookup_name_info &lookup_name);
204
ef136c7f
TV
205static int symbols_are_identical_enums
206 (const std::vector<struct block_symbol> &syms);
74c36641
TV
207
208static int ada_identical_enum_types_p (struct type *type1, struct type *type2);
4c4b4cd2
PH
209\f
210
315e4ebb
TT
211/* The character set used for source files. */
212static const char *ada_source_charset;
213
214/* The string "UTF-8". This is here so we can check for the UTF-8
215 charset using == rather than strcmp. */
216static const char ada_utf8[] = "UTF-8";
217
218/* Each entry in the UTF-32 case-folding table is of this form. */
219struct utf8_entry
220{
221 /* The start and end, inclusive, of this range of codepoints. */
222 uint32_t start, end;
223 /* The delta to apply to get the upper-case form. 0 if this is
224 already upper-case. */
225 int upper_delta;
226 /* The delta to apply to get the lower-case form. 0 if this is
227 already lower-case. */
228 int lower_delta;
229
230 bool operator< (uint32_t val) const
231 {
232 return end < val;
233 }
234};
235
236static const utf8_entry ada_case_fold[] =
237{
238#include "ada-casefold.h"
239};
240
241\f
242
67cb5b2d 243static const char ada_completer_word_break_characters[] =
4c4b4cd2
PH
244#ifdef VMS
245 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
246#else
14f9c5c9 247 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
4c4b4cd2 248#endif
14f9c5c9 249
4c4b4cd2 250/* The name of the symbol to use to get the name of the main subprogram. */
76a01679 251static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
4c4b4cd2 252 = "__gnat_ada_main_program_name";
14f9c5c9 253
4c4b4cd2
PH
254/* Limit on the number of warnings to raise per expression evaluation. */
255static int warning_limit = 2;
256
257/* Number of warning messages issued; reset to 0 by cleanups after
258 expression evaluation. */
259static int warnings_issued = 0;
260
27087b7f 261static const char * const known_runtime_file_name_patterns[] = {
4c4b4cd2
PH
262 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
263};
264
27087b7f 265static const char * const known_auxiliary_function_name_patterns[] = {
4c4b4cd2
PH
266 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
267};
268
c6044dd1
JB
269/* Maintenance-related settings for this module. */
270
271static struct cmd_list_element *maint_set_ada_cmdlist;
272static struct cmd_list_element *maint_show_ada_cmdlist;
273
c6044dd1
JB
274/* The "maintenance ada set/show ignore-descriptive-type" value. */
275
491144b5 276static bool ada_ignore_descriptive_types_p = false;
c6044dd1 277
e802dbe0
JB
278 /* Inferior-specific data. */
279
280/* Per-inferior data for this module. */
281
282struct ada_inferior_data
283{
284 /* The ada__tags__type_specific_data type, which is used when decoding
285 tagged types. With older versions of GNAT, this type was directly
286 accessible through a component ("tsd") in the object tag. But this
287 is no longer the case, so we cache it for each inferior. */
f37b313d 288 struct type *tsd_type = nullptr;
3eecfa55
JB
289
290 /* The exception_support_info data. This data is used to determine
291 how to implement support for Ada exception catchpoints in a given
292 inferior. */
f37b313d 293 const struct exception_support_info *exception_info = nullptr;
e802dbe0
JB
294};
295
296/* Our key to this module's inferior data. */
08b8a139 297static const registry<inferior>::key<ada_inferior_data> ada_inferior_data;
e802dbe0
JB
298
299/* Return our inferior data for the given inferior (INF).
300
301 This function always returns a valid pointer to an allocated
302 ada_inferior_data structure. If INF's inferior data has not
303 been previously set, this functions creates a new one with all
304 fields set to zero, sets INF's inferior to it, and then returns
305 a pointer to that newly allocated ada_inferior_data. */
306
307static struct ada_inferior_data *
308get_ada_inferior_data (struct inferior *inf)
309{
310 struct ada_inferior_data *data;
311
f37b313d 312 data = ada_inferior_data.get (inf);
e802dbe0 313 if (data == NULL)
f37b313d 314 data = ada_inferior_data.emplace (inf);
e802dbe0
JB
315
316 return data;
317}
318
319/* Perform all necessary cleanups regarding our module's inferior data
320 that is required after the inferior INF just exited. */
321
322static void
323ada_inferior_exit (struct inferior *inf)
324{
f37b313d 325 ada_inferior_data.clear (inf);
e802dbe0
JB
326}
327
ee01b665
JB
328
329 /* program-space-specific data. */
330
9d1c303d
TT
331/* The result of a symbol lookup to be stored in our symbol cache. */
332
333struct cache_entry
ee01b665 334{
9d1c303d
TT
335 /* The name used to perform the lookup. */
336 std::string name;
337 /* The namespace used during the lookup. */
338 domain_enum domain = UNDEF_DOMAIN;
339 /* The symbol returned by the lookup, or NULL if no matching symbol
340 was found. */
341 struct symbol *sym = nullptr;
342 /* The block where the symbol was found, or NULL if no matching
343 symbol was found. */
344 const struct block *block = nullptr;
ee01b665
JB
345};
346
9d1c303d
TT
347/* The symbol cache uses this type when searching. */
348
349struct cache_entry_search
350{
351 const char *name;
352 domain_enum domain;
353
354 hashval_t hash () const
355 {
356 /* This must agree with hash_cache_entry, below. */
357 return htab_hash_string (name);
358 }
359};
360
361/* Hash function for cache_entry. */
362
363static hashval_t
364hash_cache_entry (const void *v)
365{
366 const cache_entry *entry = (const cache_entry *) v;
367 return htab_hash_string (entry->name.c_str ());
368}
369
370/* Equality function for cache_entry. */
371
372static int
373eq_cache_entry (const void *a, const void *b)
374{
375 const cache_entry *entrya = (const cache_entry *) a;
376 const cache_entry_search *entryb = (const cache_entry_search *) b;
377
378 return entrya->domain == entryb->domain && entrya->name == entryb->name;
379}
380
ee01b665 381/* Key to our per-program-space data. */
9d1c303d 382static const registry<program_space>::key<htab, htab_deleter>
08b8a139 383 ada_pspace_data_handle;
ee01b665
JB
384
385/* Return this module's data for the given program space (PSPACE).
386 If not is found, add a zero'ed one now.
387
388 This function always returns a valid object. */
389
9d1c303d 390static htab_t
ee01b665
JB
391get_ada_pspace_data (struct program_space *pspace)
392{
9d1c303d
TT
393 htab_t data = ada_pspace_data_handle.get (pspace);
394 if (data == nullptr)
395 {
396 data = htab_create_alloc (10, hash_cache_entry, eq_cache_entry,
397 htab_delete_entry<cache_entry>,
398 xcalloc, xfree);
399 ada_pspace_data_handle.set (pspace, data);
400 }
ee01b665
JB
401
402 return data;
403}
404
dda83cd7 405 /* Utilities */
4c4b4cd2 406
720d1a40 407/* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
eed9788b 408 all typedef layers have been peeled. Otherwise, return TYPE.
720d1a40
JB
409
410 Normally, we really expect a typedef type to only have 1 typedef layer.
411 In other words, we really expect the target type of a typedef type to be
412 a non-typedef type. This is particularly true for Ada units, because
413 the language does not have a typedef vs not-typedef distinction.
414 In that respect, the Ada compiler has been trying to eliminate as many
415 typedef definitions in the debugging information, since they generally
416 do not bring any extra information (we still use typedef under certain
417 circumstances related mostly to the GNAT encoding).
418
419 Unfortunately, we have seen situations where the debugging information
420 generated by the compiler leads to such multiple typedef layers. For
421 instance, consider the following example with stabs:
422
423 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
424 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
425
426 This is an error in the debugging information which causes type
427 pck__float_array___XUP to be defined twice, and the second time,
428 it is defined as a typedef of a typedef.
429
430 This is on the fringe of legality as far as debugging information is
431 concerned, and certainly unexpected. But it is easy to handle these
432 situations correctly, so we can afford to be lenient in this case. */
433
434static struct type *
435ada_typedef_target_type (struct type *type)
436{
78134374 437 while (type->code () == TYPE_CODE_TYPEDEF)
27710edb 438 type = type->target_type ();
720d1a40
JB
439 return type;
440}
441
41d27058
JB
442/* Given DECODED_NAME a string holding a symbol name in its
443 decoded form (ie using the Ada dotted notation), returns
444 its unqualified name. */
445
446static const char *
447ada_unqualified_name (const char *decoded_name)
448{
2b0f535a
JB
449 const char *result;
450
451 /* If the decoded name starts with '<', it means that the encoded
452 name does not follow standard naming conventions, and thus that
453 it is not your typical Ada symbol name. Trying to unqualify it
454 is therefore pointless and possibly erroneous. */
455 if (decoded_name[0] == '<')
456 return decoded_name;
457
458 result = strrchr (decoded_name, '.');
41d27058
JB
459 if (result != NULL)
460 result++; /* Skip the dot... */
461 else
462 result = decoded_name;
463
464 return result;
465}
466
39e7af3e 467/* Return a string starting with '<', followed by STR, and '>'. */
41d27058 468
39e7af3e 469static std::string
41d27058
JB
470add_angle_brackets (const char *str)
471{
39e7af3e 472 return string_printf ("<%s>", str);
41d27058 473}
96d887e8 474
14f9c5c9 475/* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
4c4b4cd2 476 suffix of FIELD_NAME beginning "___". */
14f9c5c9
AS
477
478static int
ebf56fd3 479field_name_match (const char *field_name, const char *target)
14f9c5c9
AS
480{
481 int len = strlen (target);
5b4ee69b 482
d2e4a39e 483 return
4c4b4cd2
PH
484 (strncmp (field_name, target, len) == 0
485 && (field_name[len] == '\0'
dda83cd7
SM
486 || (startswith (field_name + len, "___")
487 && strcmp (field_name + strlen (field_name) - 6,
488 "___XVN") != 0)));
14f9c5c9
AS
489}
490
491
872c8b51
JB
492/* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
493 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
494 and return its index. This function also handles fields whose name
495 have ___ suffixes because the compiler sometimes alters their name
496 by adding such a suffix to represent fields with certain constraints.
497 If the field could not be found, return a negative number if
498 MAYBE_MISSING is set. Otherwise raise an error. */
4c4b4cd2
PH
499
500int
501ada_get_field_index (const struct type *type, const char *field_name,
dda83cd7 502 int maybe_missing)
4c4b4cd2
PH
503{
504 int fieldno;
872c8b51
JB
505 struct type *struct_type = check_typedef ((struct type *) type);
506
1f704f76 507 for (fieldno = 0; fieldno < struct_type->num_fields (); fieldno++)
33d16dd9 508 if (field_name_match (struct_type->field (fieldno).name (), field_name))
4c4b4cd2
PH
509 return fieldno;
510
511 if (!maybe_missing)
323e0a4a 512 error (_("Unable to find field %s in struct %s. Aborting"),
dda83cd7 513 field_name, struct_type->name ());
4c4b4cd2
PH
514
515 return -1;
516}
517
518/* The length of the prefix of NAME prior to any "___" suffix. */
14f9c5c9
AS
519
520int
d2e4a39e 521ada_name_prefix_len (const char *name)
14f9c5c9
AS
522{
523 if (name == NULL)
524 return 0;
d2e4a39e 525 else
14f9c5c9 526 {
d2e4a39e 527 const char *p = strstr (name, "___");
5b4ee69b 528
14f9c5c9 529 if (p == NULL)
dda83cd7 530 return strlen (name);
14f9c5c9 531 else
dda83cd7 532 return p - name;
14f9c5c9
AS
533 }
534}
535
4c4b4cd2
PH
536/* Return non-zero if SUFFIX is a suffix of STR.
537 Return zero if STR is null. */
538
14f9c5c9 539static int
d2e4a39e 540is_suffix (const char *str, const char *suffix)
14f9c5c9
AS
541{
542 int len1, len2;
5b4ee69b 543
14f9c5c9
AS
544 if (str == NULL)
545 return 0;
546 len1 = strlen (str);
547 len2 = strlen (suffix);
4c4b4cd2 548 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
14f9c5c9
AS
549}
550
4c4b4cd2
PH
551/* The contents of value VAL, treated as a value of type TYPE. The
552 result is an lval in memory if VAL is. */
14f9c5c9 553
d2e4a39e 554static struct value *
4c4b4cd2 555coerce_unspec_val_to_type (struct value *val, struct type *type)
14f9c5c9 556{
61ee279c 557 type = ada_check_typedef (type);
d0c97917 558 if (val->type () == type)
4c4b4cd2 559 return val;
d2e4a39e 560 else
14f9c5c9 561 {
4c4b4cd2
PH
562 struct value *result;
563
d00664db 564 if (val->optimized_out ())
b27556e3 565 result = value::allocate_optimized_out (type);
3ee3b270 566 else if (val->lazy ()
f73e424f 567 /* Be careful not to make a lazy not_lval value. */
736355f2 568 || (val->lval () != not_lval
d0c97917 569 && type->length () > val->type ()->length ()))
cbe793af 570 result = value::allocate_lazy (type);
41e8491f
JK
571 else
572 {
317c3ed9 573 result = value::allocate (type);
6c49729e 574 val->contents_copy (result, 0, 0, type->length ());
41e8491f 575 }
8181b7b6 576 result->set_component_location (val);
f49d5fa2 577 result->set_bitsize (val->bitsize ());
5011c493 578 result->set_bitpos (val->bitpos ());
736355f2 579 if (result->lval () == lval_memory)
9feb2d07 580 result->set_address (val->address ());
14f9c5c9
AS
581 return result;
582 }
583}
584
fc1a4b47
AC
585static const gdb_byte *
586cond_offset_host (const gdb_byte *valaddr, long offset)
14f9c5c9
AS
587{
588 if (valaddr == NULL)
589 return NULL;
590 else
591 return valaddr + offset;
592}
593
594static CORE_ADDR
ebf56fd3 595cond_offset_target (CORE_ADDR address, long offset)
14f9c5c9
AS
596{
597 if (address == 0)
598 return 0;
d2e4a39e 599 else
14f9c5c9
AS
600 return address + offset;
601}
602
4c4b4cd2
PH
603/* Issue a warning (as for the definition of warning in utils.c, but
604 with exactly one argument rather than ...), unless the limit on the
605 number of warnings has passed during the evaluation of the current
606 expression. */
a2249542 607
77109804
AC
608/* FIXME: cagney/2004-10-10: This function is mimicking the behavior
609 provided by "complaint". */
a0b31db1 610static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
77109804 611
14f9c5c9 612static void
a2249542 613lim_warning (const char *format, ...)
14f9c5c9 614{
a2249542 615 va_list args;
a2249542 616
5b4ee69b 617 va_start (args, format);
4c4b4cd2
PH
618 warnings_issued += 1;
619 if (warnings_issued <= warning_limit)
a2249542
MK
620 vwarning (format, args);
621
622 va_end (args);
4c4b4cd2
PH
623}
624
0963b4bd 625/* Maximum value of a SIZE-byte signed integer type. */
4c4b4cd2 626static LONGEST
c3e5cd34 627max_of_size (int size)
4c4b4cd2 628{
76a01679 629 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
5b4ee69b 630
76a01679 631 return top_bit | (top_bit - 1);
4c4b4cd2
PH
632}
633
0963b4bd 634/* Minimum value of a SIZE-byte signed integer type. */
4c4b4cd2 635static LONGEST
c3e5cd34 636min_of_size (int size)
4c4b4cd2 637{
c3e5cd34 638 return -max_of_size (size) - 1;
4c4b4cd2
PH
639}
640
0963b4bd 641/* Maximum value of a SIZE-byte unsigned integer type. */
4c4b4cd2 642static ULONGEST
c3e5cd34 643umax_of_size (int size)
4c4b4cd2 644{
76a01679 645 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
5b4ee69b 646
76a01679 647 return top_bit | (top_bit - 1);
4c4b4cd2
PH
648}
649
0963b4bd 650/* Maximum value of integral type T, as a signed quantity. */
c3e5cd34
PH
651static LONGEST
652max_of_type (struct type *t)
4c4b4cd2 653{
c6d940a9 654 if (t->is_unsigned ())
df86565b 655 return (LONGEST) umax_of_size (t->length ());
c3e5cd34 656 else
df86565b 657 return max_of_size (t->length ());
c3e5cd34
PH
658}
659
0963b4bd 660/* Minimum value of integral type T, as a signed quantity. */
c3e5cd34
PH
661static LONGEST
662min_of_type (struct type *t)
663{
c6d940a9 664 if (t->is_unsigned ())
c3e5cd34
PH
665 return 0;
666 else
df86565b 667 return min_of_size (t->length ());
4c4b4cd2
PH
668}
669
670/* The largest value in the domain of TYPE, a discrete type, as an integer. */
43bbcdc2
PH
671LONGEST
672ada_discrete_type_high_bound (struct type *type)
4c4b4cd2 673{
b249d2c2 674 type = resolve_dynamic_type (type, {}, 0);
78134374 675 switch (type->code ())
4c4b4cd2
PH
676 {
677 case TYPE_CODE_RANGE:
d1fd641e
SM
678 {
679 const dynamic_prop &high = type->bounds ()->high;
680
9c0fb734 681 if (high.is_constant ())
d1fd641e
SM
682 return high.const_val ();
683 else
684 {
685 gdb_assert (high.kind () == PROP_UNDEFINED);
686
687 /* This happens when trying to evaluate a type's dynamic bound
688 without a live target. There is nothing relevant for us to
689 return here, so return 0. */
690 return 0;
691 }
692 }
4c4b4cd2 693 case TYPE_CODE_ENUM:
970db518 694 return type->field (type->num_fields () - 1).loc_enumval ();
690cc4eb
PH
695 case TYPE_CODE_BOOL:
696 return 1;
697 case TYPE_CODE_CHAR:
76a01679 698 case TYPE_CODE_INT:
690cc4eb 699 return max_of_type (type);
4c4b4cd2 700 default:
43bbcdc2 701 error (_("Unexpected type in ada_discrete_type_high_bound."));
4c4b4cd2
PH
702 }
703}
704
14e75d8e 705/* The smallest value in the domain of TYPE, a discrete type, as an integer. */
43bbcdc2
PH
706LONGEST
707ada_discrete_type_low_bound (struct type *type)
4c4b4cd2 708{
b249d2c2 709 type = resolve_dynamic_type (type, {}, 0);
78134374 710 switch (type->code ())
4c4b4cd2
PH
711 {
712 case TYPE_CODE_RANGE:
d1fd641e
SM
713 {
714 const dynamic_prop &low = type->bounds ()->low;
715
9c0fb734 716 if (low.is_constant ())
d1fd641e
SM
717 return low.const_val ();
718 else
719 {
720 gdb_assert (low.kind () == PROP_UNDEFINED);
721
722 /* This happens when trying to evaluate a type's dynamic bound
723 without a live target. There is nothing relevant for us to
724 return here, so return 0. */
725 return 0;
726 }
727 }
4c4b4cd2 728 case TYPE_CODE_ENUM:
970db518 729 return type->field (0).loc_enumval ();
690cc4eb
PH
730 case TYPE_CODE_BOOL:
731 return 0;
732 case TYPE_CODE_CHAR:
76a01679 733 case TYPE_CODE_INT:
690cc4eb 734 return min_of_type (type);
4c4b4cd2 735 default:
43bbcdc2 736 error (_("Unexpected type in ada_discrete_type_low_bound."));
4c4b4cd2
PH
737 }
738}
739
740/* The identity on non-range types. For range types, the underlying
76a01679 741 non-range scalar type. */
4c4b4cd2
PH
742
743static struct type *
18af8284 744get_base_type (struct type *type)
4c4b4cd2 745{
78134374 746 while (type != NULL && type->code () == TYPE_CODE_RANGE)
4c4b4cd2 747 {
27710edb 748 if (type == type->target_type () || type->target_type () == NULL)
dda83cd7 749 return type;
27710edb 750 type = type->target_type ();
4c4b4cd2
PH
751 }
752 return type;
14f9c5c9 753}
41246937
JB
754
755/* Return a decoded version of the given VALUE. This means returning
756 a value whose type is obtained by applying all the GNAT-specific
85102364 757 encodings, making the resulting type a static but standard description
41246937
JB
758 of the initial type. */
759
760struct value *
761ada_get_decoded_value (struct value *value)
762{
d0c97917 763 struct type *type = ada_check_typedef (value->type ());
41246937
JB
764
765 if (ada_is_array_descriptor_type (type)
766 || (ada_is_constrained_packed_array_type (type)
dda83cd7 767 && type->code () != TYPE_CODE_PTR))
41246937 768 {
78134374 769 if (type->code () == TYPE_CODE_TYPEDEF) /* array access type. */
dda83cd7 770 value = ada_coerce_to_simple_array_ptr (value);
41246937 771 else
dda83cd7 772 value = ada_coerce_to_simple_array (value);
41246937
JB
773 }
774 else
775 value = ada_to_fixed_value (value);
776
777 return value;
778}
779
780/* Same as ada_get_decoded_value, but with the given TYPE.
781 Because there is no associated actual value for this type,
782 the resulting type might be a best-effort approximation in
783 the case of dynamic types. */
784
785struct type *
786ada_get_decoded_type (struct type *type)
787{
788 type = to_static_fixed_type (type);
789 if (ada_is_constrained_packed_array_type (type))
790 type = ada_coerce_to_simple_array_type (type);
791 return type;
792}
793
4c4b4cd2 794\f
76a01679 795
dda83cd7 796 /* Language Selection */
14f9c5c9 797
96d887e8
PH
798/* If the main procedure is written in Ada, then return its name.
799 The result is good until the next call. Return NULL if the main
800 procedure doesn't appear to be in Ada. */
801
6f63b61d
TT
802const char *
803ada_main_name ()
96d887e8 804{
3b7344d5 805 struct bound_minimal_symbol msym;
e83e4e24 806 static gdb::unique_xmalloc_ptr<char> main_program_name;
6c038f32 807
96d887e8
PH
808 /* For Ada, the name of the main procedure is stored in a specific
809 string constant, generated by the binder. Look for that symbol,
810 extract its address, and then read that string. If we didn't find
811 that string, then most probably the main procedure is not written
812 in Ada. */
813 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
814
3b7344d5 815 if (msym.minsym != NULL)
96d887e8 816 {
4aeddc50 817 CORE_ADDR main_program_name_addr = msym.value_address ();
96d887e8 818 if (main_program_name_addr == 0)
dda83cd7 819 error (_("Invalid address for Ada main program name."));
96d887e8 820
358be6e7
TT
821 /* Force trust_readonly, because we always want to fetch this
822 string from the executable, not from inferior memory. If the
823 user changes the exec-file and invokes "start", we want to
824 pick the "main" from the new executable, not one that may
825 come from the still-live inferior. */
826 scoped_restore save_trust_readonly
827 = make_scoped_restore (&trust_readonly, true);
66920317 828 main_program_name = target_read_string (main_program_name_addr, 1024);
e83e4e24 829 return main_program_name.get ();
96d887e8
PH
830 }
831
832 /* The main procedure doesn't seem to be in Ada. */
833 return NULL;
834}
14f9c5c9 835\f
dda83cd7 836 /* Symbols */
d2e4a39e 837
4c4b4cd2
PH
838/* Table of Ada operators and their GNAT-encoded names. Last entry is pair
839 of NULLs. */
14f9c5c9 840
d2e4a39e
AS
841const struct ada_opname_map ada_opname_table[] = {
842 {"Oadd", "\"+\"", BINOP_ADD},
843 {"Osubtract", "\"-\"", BINOP_SUB},
844 {"Omultiply", "\"*\"", BINOP_MUL},
845 {"Odivide", "\"/\"", BINOP_DIV},
846 {"Omod", "\"mod\"", BINOP_MOD},
847 {"Orem", "\"rem\"", BINOP_REM},
848 {"Oexpon", "\"**\"", BINOP_EXP},
849 {"Olt", "\"<\"", BINOP_LESS},
850 {"Ole", "\"<=\"", BINOP_LEQ},
851 {"Ogt", "\">\"", BINOP_GTR},
852 {"Oge", "\">=\"", BINOP_GEQ},
853 {"Oeq", "\"=\"", BINOP_EQUAL},
854 {"One", "\"/=\"", BINOP_NOTEQUAL},
855 {"Oand", "\"and\"", BINOP_BITWISE_AND},
856 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
857 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
858 {"Oconcat", "\"&\"", BINOP_CONCAT},
859 {"Oabs", "\"abs\"", UNOP_ABS},
860 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
861 {"Oadd", "\"+\"", UNOP_PLUS},
862 {"Osubtract", "\"-\"", UNOP_NEG},
863 {NULL, NULL}
14f9c5c9
AS
864};
865
965bc1df
TT
866/* If STR is a decoded version of a compiler-provided suffix (like the
867 "[cold]" in "symbol[cold]"), return true. Otherwise, return
868 false. */
869
870static bool
871is_compiler_suffix (const char *str)
872{
873 gdb_assert (*str == '[');
874 ++str;
875 while (*str != '\0' && isalpha (*str))
876 ++str;
877 /* We accept a missing "]" in order to support completion. */
878 return *str == '\0' || (str[0] == ']' && str[1] == '\0');
879}
880
315e4ebb
TT
881/* Append a non-ASCII character to RESULT. */
882static void
883append_hex_encoded (std::string &result, uint32_t one_char)
884{
885 if (one_char <= 0xff)
886 {
887 result.append ("U");
888 result.append (phex (one_char, 1));
889 }
890 else if (one_char <= 0xffff)
891 {
892 result.append ("W");
893 result.append (phex (one_char, 2));
894 }
895 else
896 {
897 result.append ("WW");
898 result.append (phex (one_char, 4));
899 }
900}
901
902/* Return a string that is a copy of the data in STORAGE, with
903 non-ASCII characters replaced by the appropriate hex encoding. A
904 template is used because, for UTF-8, we actually want to work with
905 UTF-32 codepoints. */
906template<typename T>
907std::string
908copy_and_hex_encode (struct obstack *storage)
909{
910 const T *chars = (T *) obstack_base (storage);
911 int num_chars = obstack_object_size (storage) / sizeof (T);
912 std::string result;
913 for (int i = 0; i < num_chars; ++i)
914 {
915 if (chars[i] <= 0x7f)
916 {
917 /* The host character set has to be a superset of ASCII, as
918 are all the other character sets we can use. */
919 result.push_back (chars[i]);
920 }
921 else
922 append_hex_encoded (result, chars[i]);
923 }
924 return result;
925}
926
5c4258f4 927/* The "encoded" form of DECODED, according to GNAT conventions. If
b5ec771e 928 THROW_ERRORS, throw an error if invalid operator name is found.
5c4258f4 929 Otherwise, return the empty string in that case. */
4c4b4cd2 930
5c4258f4 931static std::string
b5ec771e 932ada_encode_1 (const char *decoded, bool throw_errors)
14f9c5c9 933{
4c4b4cd2 934 if (decoded == NULL)
5c4258f4 935 return {};
14f9c5c9 936
5c4258f4 937 std::string encoding_buffer;
315e4ebb 938 bool saw_non_ascii = false;
5c4258f4 939 for (const char *p = decoded; *p != '\0'; p += 1)
14f9c5c9 940 {
315e4ebb
TT
941 if ((*p & 0x80) != 0)
942 saw_non_ascii = true;
943
cdc7bb92 944 if (*p == '.')
5c4258f4 945 encoding_buffer.append ("__");
965bc1df
TT
946 else if (*p == '[' && is_compiler_suffix (p))
947 {
948 encoding_buffer = encoding_buffer + "." + (p + 1);
949 if (encoding_buffer.back () == ']')
950 encoding_buffer.pop_back ();
951 break;
952 }
14f9c5c9 953 else if (*p == '"')
dda83cd7
SM
954 {
955 const struct ada_opname_map *mapping;
956
957 for (mapping = ada_opname_table;
958 mapping->encoded != NULL
959 && !startswith (p, mapping->decoded); mapping += 1)
960 ;
961 if (mapping->encoded == NULL)
b5ec771e
PA
962 {
963 if (throw_errors)
964 error (_("invalid Ada operator name: %s"), p);
965 else
5c4258f4 966 return {};
b5ec771e 967 }
5c4258f4 968 encoding_buffer.append (mapping->encoded);
dda83cd7
SM
969 break;
970 }
d2e4a39e 971 else
5c4258f4 972 encoding_buffer.push_back (*p);
14f9c5c9
AS
973 }
974
315e4ebb
TT
975 /* If a non-ASCII character is seen, we must convert it to the
976 appropriate hex form. As this is more expensive, we keep track
977 of whether it is even necessary. */
978 if (saw_non_ascii)
979 {
980 auto_obstack storage;
981 bool is_utf8 = ada_source_charset == ada_utf8;
982 try
983 {
984 convert_between_encodings
985 (host_charset (),
986 is_utf8 ? HOST_UTF32 : ada_source_charset,
987 (const gdb_byte *) encoding_buffer.c_str (),
988 encoding_buffer.length (), 1,
989 &storage, translit_none);
990 }
991 catch (const gdb_exception &)
992 {
993 static bool warned = false;
994
995 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
996 might like to know why. */
997 if (!warned)
998 {
999 warned = true;
1000 warning (_("charset conversion failure for '%s'.\n"
1001 "You may have the wrong value for 'set ada source-charset'."),
1002 encoding_buffer.c_str ());
1003 }
1004
1005 /* We don't try to recover from errors. */
1006 return encoding_buffer;
1007 }
1008
1009 if (is_utf8)
1010 return copy_and_hex_encode<uint32_t> (&storage);
1011 return copy_and_hex_encode<gdb_byte> (&storage);
1012 }
1013
4c4b4cd2 1014 return encoding_buffer;
14f9c5c9
AS
1015}
1016
315e4ebb
TT
1017/* Find the entry for C in the case-folding table. Return nullptr if
1018 the entry does not cover C. */
1019static const utf8_entry *
1020find_case_fold_entry (uint32_t c)
b5ec771e 1021{
315e4ebb
TT
1022 auto iter = std::lower_bound (std::begin (ada_case_fold),
1023 std::end (ada_case_fold),
1024 c);
1025 if (iter == std::end (ada_case_fold)
1026 || c < iter->start
1027 || c > iter->end)
1028 return nullptr;
1029 return &*iter;
b5ec771e
PA
1030}
1031
14f9c5c9 1032/* Return NAME folded to lower case, or, if surrounded by single
315e4ebb
TT
1033 quotes, unfolded, but with the quotes stripped away. If
1034 THROW_ON_ERROR is true, encoding failures will throw an exception
1035 rather than emitting a warning. Result good to next call. */
4c4b4cd2 1036
5f9febe0 1037static const char *
315e4ebb 1038ada_fold_name (gdb::string_view name, bool throw_on_error = false)
14f9c5c9 1039{
5f9febe0 1040 static std::string fold_storage;
14f9c5c9 1041
6a780b67 1042 if (!name.empty () && name[0] == '\'')
01573d73 1043 fold_storage = gdb::to_string (name.substr (1, name.size () - 2));
14f9c5c9
AS
1044 else
1045 {
315e4ebb
TT
1046 /* Why convert to UTF-32 and implement our own case-folding,
1047 rather than convert to wchar_t and use the platform's
1048 functions? I'm glad you asked.
1049
1050 The main problem is that GNAT implements an unusual rule for
1051 case folding. For ASCII letters, letters in single-byte
1052 encodings (such as ISO-8859-*), and Unicode letters that fit
1053 in a single byte (i.e., code point is <= 0xff), the letter is
1054 folded to lower case. Other Unicode letters are folded to
1055 upper case.
1056
1057 This rule means that the code must be able to examine the
1058 value of the character. And, some hosts do not use Unicode
1059 for wchar_t, so examining the value of such characters is
1060 forbidden. */
1061 auto_obstack storage;
1062 try
1063 {
1064 convert_between_encodings
1065 (host_charset (), HOST_UTF32,
1066 (const gdb_byte *) name.data (),
1067 name.length (), 1,
1068 &storage, translit_none);
1069 }
1070 catch (const gdb_exception &)
1071 {
1072 if (throw_on_error)
1073 throw;
1074
1075 static bool warned = false;
1076
1077 /* Converting to UTF-32 shouldn't fail, so if it doesn't, we
1078 might like to know why. */
1079 if (!warned)
1080 {
1081 warned = true;
1082 warning (_("could not convert '%s' from the host encoding (%s) to UTF-32.\n"
1083 "This normally should not happen, please file a bug report."),
1084 gdb::to_string (name).c_str (), host_charset ());
1085 }
1086
1087 /* We don't try to recover from errors; just return the
1088 original string. */
1089 fold_storage = gdb::to_string (name);
1090 return fold_storage.c_str ();
1091 }
1092
1093 bool is_utf8 = ada_source_charset == ada_utf8;
1094 uint32_t *chars = (uint32_t *) obstack_base (&storage);
1095 int num_chars = obstack_object_size (&storage) / sizeof (uint32_t);
1096 for (int i = 0; i < num_chars; ++i)
1097 {
1098 const struct utf8_entry *entry = find_case_fold_entry (chars[i]);
1099 if (entry != nullptr)
1100 {
1101 uint32_t low = chars[i] + entry->lower_delta;
1102 if (!is_utf8 || low <= 0xff)
1103 chars[i] = low;
1104 else
1105 chars[i] = chars[i] + entry->upper_delta;
1106 }
1107 }
1108
1109 /* Now convert back to ordinary characters. */
1110 auto_obstack reconverted;
1111 try
1112 {
1113 convert_between_encodings (HOST_UTF32,
1114 host_charset (),
1115 (const gdb_byte *) chars,
1116 num_chars * sizeof (uint32_t),
1117 sizeof (uint32_t),
1118 &reconverted,
1119 translit_none);
1120 obstack_1grow (&reconverted, '\0');
1121 fold_storage = std::string ((const char *) obstack_base (&reconverted));
1122 }
1123 catch (const gdb_exception &)
1124 {
1125 if (throw_on_error)
1126 throw;
1127
1128 static bool warned = false;
1129
1130 /* Converting back from UTF-32 shouldn't normally fail, but
1131 there are some host encodings without upper/lower
1132 equivalence. */
1133 if (!warned)
1134 {
1135 warned = true;
1136 warning (_("could not convert the lower-cased variant of '%s'\n"
1137 "from UTF-32 to the host encoding (%s)."),
1138 gdb::to_string (name).c_str (), host_charset ());
1139 }
1140
1141 /* We don't try to recover from errors; just return the
1142 original string. */
1143 fold_storage = gdb::to_string (name);
1144 }
14f9c5c9
AS
1145 }
1146
5f9febe0 1147 return fold_storage.c_str ();
14f9c5c9
AS
1148}
1149
5fea9794
TT
1150/* The "encoded" form of DECODED, according to GNAT conventions. If
1151 FOLD is true (the default), case-fold any ordinary symbol. Symbols
1152 with <...> quoting are not folded in any case. */
315e4ebb
TT
1153
1154std::string
5fea9794 1155ada_encode (const char *decoded, bool fold)
315e4ebb 1156{
5fea9794 1157 if (fold && decoded[0] != '<')
315e4ebb
TT
1158 decoded = ada_fold_name (decoded);
1159 return ada_encode_1 (decoded, true);
1160}
1161
529cad9c
PH
1162/* Return nonzero if C is either a digit or a lowercase alphabet character. */
1163
1164static int
1165is_lower_alphanum (const char c)
1166{
1167 return (isdigit (c) || (isalpha (c) && islower (c)));
1168}
1169
c90092fe
JB
1170/* ENCODED is the linkage name of a symbol and LEN contains its length.
1171 This function saves in LEN the length of that same symbol name but
1172 without either of these suffixes:
29480c32
JB
1173 . .{DIGIT}+
1174 . ${DIGIT}+
1175 . ___{DIGIT}+
1176 . __{DIGIT}+.
c90092fe 1177
29480c32
JB
1178 These are suffixes introduced by the compiler for entities such as
1179 nested subprogram for instance, in order to avoid name clashes.
1180 They do not serve any purpose for the debugger. */
1181
1182static void
1183ada_remove_trailing_digits (const char *encoded, int *len)
1184{
1185 if (*len > 1 && isdigit (encoded[*len - 1]))
1186 {
1187 int i = *len - 2;
5b4ee69b 1188
29480c32 1189 while (i > 0 && isdigit (encoded[i]))
dda83cd7 1190 i--;
29480c32 1191 if (i >= 0 && encoded[i] == '.')
dda83cd7 1192 *len = i;
29480c32 1193 else if (i >= 0 && encoded[i] == '$')
dda83cd7 1194 *len = i;
61012eef 1195 else if (i >= 2 && startswith (encoded + i - 2, "___"))
dda83cd7 1196 *len = i - 2;
61012eef 1197 else if (i >= 1 && startswith (encoded + i - 1, "__"))
dda83cd7 1198 *len = i - 1;
29480c32
JB
1199 }
1200}
1201
1202/* Remove the suffix introduced by the compiler for protected object
1203 subprograms. */
1204
1205static void
1206ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1207{
1208 /* Remove trailing N. */
1209
1210 /* Protected entry subprograms are broken into two
1211 separate subprograms: The first one is unprotected, and has
1212 a 'N' suffix; the second is the protected version, and has
0963b4bd 1213 the 'P' suffix. The second calls the first one after handling
29480c32
JB
1214 the protection. Since the P subprograms are internally generated,
1215 we leave these names undecoded, giving the user a clue that this
1216 entity is internal. */
1217
1218 if (*len > 1
1219 && encoded[*len - 1] == 'N'
1220 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1221 *len = *len - 1;
1222}
1223
965bc1df
TT
1224/* If ENCODED ends with a compiler-provided suffix (like ".cold"),
1225 then update *LEN to remove the suffix and return the offset of the
1226 character just past the ".". Otherwise, return -1. */
1227
1228static int
1229remove_compiler_suffix (const char *encoded, int *len)
1230{
1231 int offset = *len - 1;
1232 while (offset > 0 && isalpha (encoded[offset]))
1233 --offset;
1234 if (offset > 0 && encoded[offset] == '.')
1235 {
1236 *len = offset;
1237 return offset + 1;
1238 }
1239 return -1;
1240}
1241
315e4ebb
TT
1242/* Convert an ASCII hex string to a number. Reads exactly N
1243 characters from STR. Returns true on success, false if one of the
1244 digits was not a hex digit. */
1245static bool
1246convert_hex (const char *str, int n, uint32_t *out)
1247{
1248 uint32_t result = 0;
1249
1250 for (int i = 0; i < n; ++i)
1251 {
1252 if (!isxdigit (str[i]))
1253 return false;
1254 result <<= 4;
1255 result |= fromhex (str[i]);
1256 }
1257
1258 *out = result;
1259 return true;
1260}
1261
1262/* Convert a wide character from its ASCII hex representation in STR
1263 (consisting of exactly N characters) to the host encoding,
1264 appending the resulting bytes to OUT. If N==2 and the Ada source
1265 charset is not UTF-8, then hex refers to an encoding in the
1266 ADA_SOURCE_CHARSET; otherwise, use UTF-32. Return true on success.
1267 Return false and do not modify OUT on conversion failure. */
1268static bool
1269convert_from_hex_encoded (std::string &out, const char *str, int n)
1270{
1271 uint32_t value;
1272
1273 if (!convert_hex (str, n, &value))
1274 return false;
1275 try
1276 {
1277 auto_obstack bytes;
1278 /* In the 'U' case, the hex digits encode the character in the
1279 Ada source charset. However, if the source charset is UTF-8,
1280 this really means it is a single-byte UTF-32 character. */
1281 if (n == 2 && ada_source_charset != ada_utf8)
1282 {
1283 gdb_byte one_char = (gdb_byte) value;
1284
1285 convert_between_encodings (ada_source_charset, host_charset (),
1286 &one_char,
1287 sizeof (one_char), sizeof (one_char),
1288 &bytes, translit_none);
1289 }
1290 else
1291 convert_between_encodings (HOST_UTF32, host_charset (),
1292 (const gdb_byte *) &value,
1293 sizeof (value), sizeof (value),
1294 &bytes, translit_none);
1295 obstack_1grow (&bytes, '\0');
1296 out.append ((const char *) obstack_base (&bytes));
1297 }
1298 catch (const gdb_exception &)
1299 {
1300 /* On failure, the caller will just let the encoded form
1301 through, which seems basically reasonable. */
1302 return false;
1303 }
1304
1305 return true;
1306}
1307
8a3df5ac 1308/* See ada-lang.h. */
14f9c5c9 1309
f945dedf 1310std::string
5c94f938 1311ada_decode (const char *encoded, bool wrap, bool operators)
14f9c5c9 1312{
36f5ca53 1313 int i;
14f9c5c9 1314 int len0;
d2e4a39e 1315 const char *p;
14f9c5c9 1316 int at_start_name;
f945dedf 1317 std::string decoded;
965bc1df 1318 int suffix = -1;
d2e4a39e 1319
0d81f350
JG
1320 /* With function descriptors on PPC64, the value of a symbol named
1321 ".FN", if it exists, is the entry point of the function "FN". */
1322 if (encoded[0] == '.')
1323 encoded += 1;
1324
29480c32
JB
1325 /* The name of the Ada main procedure starts with "_ada_".
1326 This prefix is not part of the decoded name, so skip this part
1327 if we see this prefix. */
61012eef 1328 if (startswith (encoded, "_ada_"))
4c4b4cd2 1329 encoded += 5;
81eaa506
TT
1330 /* The "___ghost_" prefix is used for ghost entities. Normally
1331 these aren't preserved but when they are, it's useful to see
1332 them. */
1333 if (startswith (encoded, "___ghost_"))
1334 encoded += 9;
14f9c5c9 1335
29480c32
JB
1336 /* If the name starts with '_', then it is not a properly encoded
1337 name, so do not attempt to decode it. Similarly, if the name
1338 starts with '<', the name should not be decoded. */
4c4b4cd2 1339 if (encoded[0] == '_' || encoded[0] == '<')
14f9c5c9
AS
1340 goto Suppress;
1341
4c4b4cd2 1342 len0 = strlen (encoded);
4c4b4cd2 1343
965bc1df
TT
1344 suffix = remove_compiler_suffix (encoded, &len0);
1345
29480c32
JB
1346 ada_remove_trailing_digits (encoded, &len0);
1347 ada_remove_po_subprogram_suffix (encoded, &len0);
529cad9c 1348
4c4b4cd2
PH
1349 /* Remove the ___X.* suffix if present. Do not forget to verify that
1350 the suffix is located before the current "end" of ENCODED. We want
1351 to avoid re-matching parts of ENCODED that have previously been
1352 marked as discarded (by decrementing LEN0). */
1353 p = strstr (encoded, "___");
1354 if (p != NULL && p - encoded < len0 - 3)
14f9c5c9
AS
1355 {
1356 if (p[3] == 'X')
dda83cd7 1357 len0 = p - encoded;
14f9c5c9 1358 else
dda83cd7 1359 goto Suppress;
14f9c5c9 1360 }
4c4b4cd2 1361
29480c32
JB
1362 /* Remove any trailing TKB suffix. It tells us that this symbol
1363 is for the body of a task, but that information does not actually
1364 appear in the decoded name. */
1365
61012eef 1366 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
14f9c5c9 1367 len0 -= 3;
76a01679 1368
a10967fa
JB
1369 /* Remove any trailing TB suffix. The TB suffix is slightly different
1370 from the TKB suffix because it is used for non-anonymous task
1371 bodies. */
1372
61012eef 1373 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
a10967fa
JB
1374 len0 -= 2;
1375
29480c32
JB
1376 /* Remove trailing "B" suffixes. */
1377 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1378
61012eef 1379 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
14f9c5c9
AS
1380 len0 -= 1;
1381
29480c32
JB
1382 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1383
4c4b4cd2 1384 if (len0 > 1 && isdigit (encoded[len0 - 1]))
d2e4a39e 1385 {
4c4b4cd2
PH
1386 i = len0 - 2;
1387 while ((i >= 0 && isdigit (encoded[i]))
dda83cd7
SM
1388 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1389 i -= 1;
4c4b4cd2 1390 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
dda83cd7 1391 len0 = i - 1;
033bc52b 1392 else if (i >= 0 && encoded[i] == '$')
dda83cd7 1393 len0 = i;
d2e4a39e 1394 }
14f9c5c9 1395
29480c32
JB
1396 /* The first few characters that are not alphabetic are not part
1397 of any encoding we use, so we can copy them over verbatim. */
1398
36f5ca53
TT
1399 for (i = 0; i < len0 && !isalpha (encoded[i]); i += 1)
1400 decoded.push_back (encoded[i]);
14f9c5c9
AS
1401
1402 at_start_name = 1;
1403 while (i < len0)
1404 {
29480c32 1405 /* Is this a symbol function? */
5c94f938 1406 if (operators && at_start_name && encoded[i] == 'O')
dda83cd7
SM
1407 {
1408 int k;
1409
1410 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1411 {
1412 int op_len = strlen (ada_opname_table[k].encoded);
1413 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1414 op_len - 1) == 0)
1415 && !isalnum (encoded[i + op_len]))
1416 {
36f5ca53 1417 decoded.append (ada_opname_table[k].decoded);
dda83cd7
SM
1418 at_start_name = 0;
1419 i += op_len;
dda83cd7
SM
1420 break;
1421 }
1422 }
1423 if (ada_opname_table[k].encoded != NULL)
1424 continue;
1425 }
14f9c5c9
AS
1426 at_start_name = 0;
1427
529cad9c 1428 /* Replace "TK__" with "__", which will eventually be translated
dda83cd7 1429 into "." (just below). */
529cad9c 1430
61012eef 1431 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
dda83cd7 1432 i += 2;
529cad9c 1433
29480c32 1434 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
dda83cd7
SM
1435 be translated into "." (just below). These are internal names
1436 generated for anonymous blocks inside which our symbol is nested. */
29480c32
JB
1437
1438 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
dda83cd7
SM
1439 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1440 && isdigit (encoded [i+4]))
1441 {
1442 int k = i + 5;
1443
1444 while (k < len0 && isdigit (encoded[k]))
1445 k++; /* Skip any extra digit. */
1446
1447 /* Double-check that the "__B_{DIGITS}+" sequence we found
1448 is indeed followed by "__". */
1449 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1450 i = k;
1451 }
29480c32 1452
529cad9c
PH
1453 /* Remove _E{DIGITS}+[sb] */
1454
1455 /* Just as for protected object subprograms, there are 2 categories
dda83cd7
SM
1456 of subprograms created by the compiler for each entry. The first
1457 one implements the actual entry code, and has a suffix following
1458 the convention above; the second one implements the barrier and
1459 uses the same convention as above, except that the 'E' is replaced
1460 by a 'B'.
529cad9c 1461
dda83cd7
SM
1462 Just as above, we do not decode the name of barrier functions
1463 to give the user a clue that the code he is debugging has been
1464 internally generated. */
529cad9c
PH
1465
1466 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
dda83cd7
SM
1467 && isdigit (encoded[i+2]))
1468 {
1469 int k = i + 3;
1470
1471 while (k < len0 && isdigit (encoded[k]))
1472 k++;
1473
1474 if (k < len0
1475 && (encoded[k] == 'b' || encoded[k] == 's'))
1476 {
1477 k++;
1478 /* Just as an extra precaution, make sure that if this
1479 suffix is followed by anything else, it is a '_'.
1480 Otherwise, we matched this sequence by accident. */
1481 if (k == len0
1482 || (k < len0 && encoded[k] == '_'))
1483 i = k;
1484 }
1485 }
529cad9c
PH
1486
1487 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
dda83cd7 1488 the GNAT front-end in protected object subprograms. */
529cad9c
PH
1489
1490 if (i < len0 + 3
dda83cd7
SM
1491 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1492 {
1493 /* Backtrack a bit up until we reach either the begining of
1494 the encoded name, or "__". Make sure that we only find
1495 digits or lowercase characters. */
1496 const char *ptr = encoded + i - 1;
1497
1498 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1499 ptr--;
1500 if (ptr < encoded
1501 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1502 i++;
1503 }
529cad9c 1504
315e4ebb
TT
1505 if (i < len0 + 3 && encoded[i] == 'U' && isxdigit (encoded[i + 1]))
1506 {
1507 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 2))
1508 {
1509 i += 3;
1510 continue;
1511 }
1512 }
1513 else if (i < len0 + 5 && encoded[i] == 'W' && isxdigit (encoded[i + 1]))
1514 {
1515 if (convert_from_hex_encoded (decoded, &encoded[i + 1], 4))
1516 {
1517 i += 5;
1518 continue;
1519 }
1520 }
1521 else if (i < len0 + 10 && encoded[i] == 'W' && encoded[i + 1] == 'W'
1522 && isxdigit (encoded[i + 2]))
1523 {
1524 if (convert_from_hex_encoded (decoded, &encoded[i + 2], 8))
1525 {
1526 i += 10;
1527 continue;
1528 }
1529 }
1530
4c4b4cd2 1531 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
dda83cd7
SM
1532 {
1533 /* This is a X[bn]* sequence not separated from the previous
1534 part of the name with a non-alpha-numeric character (in other
1535 words, immediately following an alpha-numeric character), then
1536 verify that it is placed at the end of the encoded name. If
1537 not, then the encoding is not valid and we should abort the
1538 decoding. Otherwise, just skip it, it is used in body-nested
1539 package names. */
1540 do
1541 i += 1;
1542 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1543 if (i < len0)
1544 goto Suppress;
1545 }
cdc7bb92 1546 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
dda83cd7
SM
1547 {
1548 /* Replace '__' by '.'. */
36f5ca53 1549 decoded.push_back ('.');
dda83cd7
SM
1550 at_start_name = 1;
1551 i += 2;
dda83cd7 1552 }
14f9c5c9 1553 else
dda83cd7
SM
1554 {
1555 /* It's a character part of the decoded name, so just copy it
1556 over. */
36f5ca53 1557 decoded.push_back (encoded[i]);
dda83cd7 1558 i += 1;
dda83cd7 1559 }
14f9c5c9 1560 }
14f9c5c9 1561
29480c32
JB
1562 /* Decoded names should never contain any uppercase character.
1563 Double-check this, and abort the decoding if we find one. */
1564
5c94f938
TT
1565 if (operators)
1566 {
1567 for (i = 0; i < decoded.length(); ++i)
1568 if (isupper (decoded[i]) || decoded[i] == ' ')
1569 goto Suppress;
1570 }
14f9c5c9 1571
965bc1df
TT
1572 /* If the compiler added a suffix, append it now. */
1573 if (suffix >= 0)
1574 decoded = decoded + "[" + &encoded[suffix] + "]";
1575
f945dedf 1576 return decoded;
14f9c5c9
AS
1577
1578Suppress:
8a3df5ac
TT
1579 if (!wrap)
1580 return {};
1581
4c4b4cd2 1582 if (encoded[0] == '<')
f945dedf 1583 decoded = encoded;
14f9c5c9 1584 else
f945dedf 1585 decoded = '<' + std::string(encoded) + '>';
4c4b4cd2 1586 return decoded;
4c4b4cd2
PH
1587}
1588
033bc52b
TT
1589#ifdef GDB_SELF_TEST
1590
1591static void
1592ada_decode_tests ()
1593{
1594 /* This isn't valid, but used to cause a crash. PR gdb/30639. The
1595 result does not really matter very much. */
1596 SELF_CHECK (ada_decode ("44") == "44");
1597}
1598
1599#endif
1600
4c4b4cd2
PH
1601/* Table for keeping permanent unique copies of decoded names. Once
1602 allocated, names in this table are never released. While this is a
1603 storage leak, it should not be significant unless there are massive
1604 changes in the set of decoded names in successive versions of a
1605 symbol table loaded during a single session. */
1606static struct htab *decoded_names_store;
1607
1608/* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1609 in the language-specific part of GSYMBOL, if it has not been
1610 previously computed. Tries to save the decoded name in the same
1611 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1612 in any case, the decoded symbol has a lifetime at least that of
0963b4bd 1613 GSYMBOL).
4c4b4cd2
PH
1614 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1615 const, but nevertheless modified to a semantically equivalent form
0963b4bd 1616 when a decoded name is cached in it. */
4c4b4cd2 1617
45e6c716 1618const char *
f85f34ed 1619ada_decode_symbol (const struct general_symbol_info *arg)
4c4b4cd2 1620{
f85f34ed
TT
1621 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1622 const char **resultp =
615b3f62 1623 &gsymbol->language_specific.demangled_name;
5b4ee69b 1624
f85f34ed 1625 if (!gsymbol->ada_mangled)
4c4b4cd2 1626 {
4d4eaa30 1627 std::string decoded = ada_decode (gsymbol->linkage_name ());
f85f34ed 1628 struct obstack *obstack = gsymbol->language_specific.obstack;
5b4ee69b 1629
f85f34ed 1630 gsymbol->ada_mangled = 1;
5b4ee69b 1631
f85f34ed 1632 if (obstack != NULL)
f945dedf 1633 *resultp = obstack_strdup (obstack, decoded.c_str ());
f85f34ed 1634 else
dda83cd7 1635 {
f85f34ed
TT
1636 /* Sometimes, we can't find a corresponding objfile, in
1637 which case, we put the result on the heap. Since we only
1638 decode when needed, we hope this usually does not cause a
1639 significant memory leak (FIXME). */
1640
dda83cd7
SM
1641 char **slot = (char **) htab_find_slot (decoded_names_store,
1642 decoded.c_str (), INSERT);
5b4ee69b 1643
dda83cd7
SM
1644 if (*slot == NULL)
1645 *slot = xstrdup (decoded.c_str ());
1646 *resultp = *slot;
1647 }
4c4b4cd2 1648 }
14f9c5c9 1649
4c4b4cd2
PH
1650 return *resultp;
1651}
76a01679 1652
14f9c5c9 1653\f
d2e4a39e 1654
dda83cd7 1655 /* Arrays */
14f9c5c9 1656
28c85d6c
JB
1657/* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1658 generated by the GNAT compiler to describe the index type used
1659 for each dimension of an array, check whether it follows the latest
1660 known encoding. If not, fix it up to conform to the latest encoding.
1661 Otherwise, do nothing. This function also does nothing if
1662 INDEX_DESC_TYPE is NULL.
1663
85102364 1664 The GNAT encoding used to describe the array index type evolved a bit.
28c85d6c
JB
1665 Initially, the information would be provided through the name of each
1666 field of the structure type only, while the type of these fields was
1667 described as unspecified and irrelevant. The debugger was then expected
1668 to perform a global type lookup using the name of that field in order
1669 to get access to the full index type description. Because these global
1670 lookups can be very expensive, the encoding was later enhanced to make
1671 the global lookup unnecessary by defining the field type as being
1672 the full index type description.
1673
1674 The purpose of this routine is to allow us to support older versions
1675 of the compiler by detecting the use of the older encoding, and by
1676 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1677 we essentially replace each field's meaningless type by the associated
1678 index subtype). */
1679
1680void
1681ada_fixup_array_indexes_type (struct type *index_desc_type)
1682{
1683 int i;
1684
1685 if (index_desc_type == NULL)
1686 return;
1f704f76 1687 gdb_assert (index_desc_type->num_fields () > 0);
28c85d6c
JB
1688
1689 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1690 to check one field only, no need to check them all). If not, return
1691 now.
1692
1693 If our INDEX_DESC_TYPE was generated using the older encoding,
1694 the field type should be a meaningless integer type whose name
1695 is not equal to the field name. */
940da03e
SM
1696 if (index_desc_type->field (0).type ()->name () != NULL
1697 && strcmp (index_desc_type->field (0).type ()->name (),
33d16dd9 1698 index_desc_type->field (0).name ()) == 0)
28c85d6c
JB
1699 return;
1700
1701 /* Fixup each field of INDEX_DESC_TYPE. */
1f704f76 1702 for (i = 0; i < index_desc_type->num_fields (); i++)
28c85d6c 1703 {
33d16dd9 1704 const char *name = index_desc_type->field (i).name ();
28c85d6c
JB
1705 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1706
1707 if (raw_type)
5d14b6e5 1708 index_desc_type->field (i).set_type (raw_type);
28c85d6c
JB
1709 }
1710}
1711
4c4b4cd2
PH
1712/* The desc_* routines return primitive portions of array descriptors
1713 (fat pointers). */
14f9c5c9
AS
1714
1715/* The descriptor or array type, if any, indicated by TYPE; removes
4c4b4cd2
PH
1716 level of indirection, if needed. */
1717
d2e4a39e
AS
1718static struct type *
1719desc_base_type (struct type *type)
14f9c5c9
AS
1720{
1721 if (type == NULL)
1722 return NULL;
61ee279c 1723 type = ada_check_typedef (type);
78134374 1724 if (type->code () == TYPE_CODE_TYPEDEF)
720d1a40
JB
1725 type = ada_typedef_target_type (type);
1726
1265e4aa 1727 if (type != NULL
78134374 1728 && (type->code () == TYPE_CODE_PTR
dda83cd7 1729 || type->code () == TYPE_CODE_REF))
27710edb 1730 return ada_check_typedef (type->target_type ());
14f9c5c9
AS
1731 else
1732 return type;
1733}
1734
4c4b4cd2
PH
1735/* True iff TYPE indicates a "thin" array pointer type. */
1736
14f9c5c9 1737static int
d2e4a39e 1738is_thin_pntr (struct type *type)
14f9c5c9 1739{
d2e4a39e 1740 return
14f9c5c9
AS
1741 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1742 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1743}
1744
4c4b4cd2
PH
1745/* The descriptor type for thin pointer type TYPE. */
1746
d2e4a39e
AS
1747static struct type *
1748thin_descriptor_type (struct type *type)
14f9c5c9 1749{
d2e4a39e 1750 struct type *base_type = desc_base_type (type);
5b4ee69b 1751
14f9c5c9
AS
1752 if (base_type == NULL)
1753 return NULL;
1754 if (is_suffix (ada_type_name (base_type), "___XVE"))
1755 return base_type;
d2e4a39e 1756 else
14f9c5c9 1757 {
d2e4a39e 1758 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
5b4ee69b 1759
14f9c5c9 1760 if (alt_type == NULL)
dda83cd7 1761 return base_type;
14f9c5c9 1762 else
dda83cd7 1763 return alt_type;
14f9c5c9
AS
1764 }
1765}
1766
4c4b4cd2
PH
1767/* A pointer to the array data for thin-pointer value VAL. */
1768
d2e4a39e
AS
1769static struct value *
1770thin_data_pntr (struct value *val)
14f9c5c9 1771{
d0c97917 1772 struct type *type = ada_check_typedef (val->type ());
556bdfd4 1773 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
5b4ee69b 1774
556bdfd4
UW
1775 data_type = lookup_pointer_type (data_type);
1776
78134374 1777 if (type->code () == TYPE_CODE_PTR)
cda03344 1778 return value_cast (data_type, val->copy ());
d2e4a39e 1779 else
9feb2d07 1780 return value_from_longest (data_type, val->address ());
14f9c5c9
AS
1781}
1782
4c4b4cd2
PH
1783/* True iff TYPE indicates a "thick" array pointer type. */
1784
14f9c5c9 1785static int
d2e4a39e 1786is_thick_pntr (struct type *type)
14f9c5c9
AS
1787{
1788 type = desc_base_type (type);
78134374 1789 return (type != NULL && type->code () == TYPE_CODE_STRUCT
dda83cd7 1790 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
14f9c5c9
AS
1791}
1792
4c4b4cd2
PH
1793/* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1794 pointer to one, the type of its bounds data; otherwise, NULL. */
76a01679 1795
d2e4a39e
AS
1796static struct type *
1797desc_bounds_type (struct type *type)
14f9c5c9 1798{
d2e4a39e 1799 struct type *r;
14f9c5c9
AS
1800
1801 type = desc_base_type (type);
1802
1803 if (type == NULL)
1804 return NULL;
1805 else if (is_thin_pntr (type))
1806 {
1807 type = thin_descriptor_type (type);
1808 if (type == NULL)
dda83cd7 1809 return NULL;
14f9c5c9
AS
1810 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1811 if (r != NULL)
dda83cd7 1812 return ada_check_typedef (r);
14f9c5c9 1813 }
78134374 1814 else if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9
AS
1815 {
1816 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1817 if (r != NULL)
27710edb 1818 return ada_check_typedef (ada_check_typedef (r)->target_type ());
14f9c5c9
AS
1819 }
1820 return NULL;
1821}
1822
1823/* If ARR is an array descriptor (fat or thin pointer), or pointer to
4c4b4cd2
PH
1824 one, a pointer to its bounds data. Otherwise NULL. */
1825
d2e4a39e
AS
1826static struct value *
1827desc_bounds (struct value *arr)
14f9c5c9 1828{
d0c97917 1829 struct type *type = ada_check_typedef (arr->type ());
5b4ee69b 1830
d2e4a39e 1831 if (is_thin_pntr (type))
14f9c5c9 1832 {
d2e4a39e 1833 struct type *bounds_type =
dda83cd7 1834 desc_bounds_type (thin_descriptor_type (type));
14f9c5c9
AS
1835 LONGEST addr;
1836
4cdfadb1 1837 if (bounds_type == NULL)
dda83cd7 1838 error (_("Bad GNAT array descriptor"));
14f9c5c9
AS
1839
1840 /* NOTE: The following calculation is not really kosher, but
dda83cd7
SM
1841 since desc_type is an XVE-encoded type (and shouldn't be),
1842 the correct calculation is a real pain. FIXME (and fix GCC). */
78134374 1843 if (type->code () == TYPE_CODE_PTR)
dda83cd7 1844 addr = value_as_long (arr);
d2e4a39e 1845 else
9feb2d07 1846 addr = arr->address ();
14f9c5c9 1847
d2e4a39e 1848 return
dda83cd7 1849 value_from_longest (lookup_pointer_type (bounds_type),
df86565b 1850 addr - bounds_type->length ());
14f9c5c9
AS
1851 }
1852
1853 else if (is_thick_pntr (type))
05e522ef 1854 {
158cc4fe 1855 struct value *p_bounds = value_struct_elt (&arr, {}, "P_BOUNDS", NULL,
05e522ef 1856 _("Bad GNAT array descriptor"));
d0c97917 1857 struct type *p_bounds_type = p_bounds->type ();
05e522ef
JB
1858
1859 if (p_bounds_type
78134374 1860 && p_bounds_type->code () == TYPE_CODE_PTR)
05e522ef 1861 {
27710edb 1862 struct type *target_type = p_bounds_type->target_type ();
05e522ef 1863
e46d3488 1864 if (target_type->is_stub ())
05e522ef
JB
1865 p_bounds = value_cast (lookup_pointer_type
1866 (ada_check_typedef (target_type)),
1867 p_bounds);
1868 }
1869 else
1870 error (_("Bad GNAT array descriptor"));
1871
1872 return p_bounds;
1873 }
14f9c5c9
AS
1874 else
1875 return NULL;
1876}
1877
4c4b4cd2
PH
1878/* If TYPE is the type of an array-descriptor (fat pointer), the bit
1879 position of the field containing the address of the bounds data. */
1880
14f9c5c9 1881static int
d2e4a39e 1882fat_pntr_bounds_bitpos (struct type *type)
14f9c5c9 1883{
b610c045 1884 return desc_base_type (type)->field (1).loc_bitpos ();
14f9c5c9
AS
1885}
1886
1887/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1888 size of the field containing the address of the bounds data. */
1889
14f9c5c9 1890static int
d2e4a39e 1891fat_pntr_bounds_bitsize (struct type *type)
14f9c5c9
AS
1892{
1893 type = desc_base_type (type);
1894
3757d2d4
SM
1895 if (type->field (1).bitsize () > 0)
1896 return type->field (1).bitsize ();
14f9c5c9 1897 else
df86565b 1898 return 8 * ada_check_typedef (type->field (1).type ())->length ();
14f9c5c9
AS
1899}
1900
4c4b4cd2 1901/* If TYPE is the type of an array descriptor (fat or thin pointer) or a
556bdfd4
UW
1902 pointer to one, the type of its array data (a array-with-no-bounds type);
1903 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1904 data. */
4c4b4cd2 1905
d2e4a39e 1906static struct type *
556bdfd4 1907desc_data_target_type (struct type *type)
14f9c5c9
AS
1908{
1909 type = desc_base_type (type);
1910
4c4b4cd2 1911 /* NOTE: The following is bogus; see comment in desc_bounds. */
14f9c5c9 1912 if (is_thin_pntr (type))
940da03e 1913 return desc_base_type (thin_descriptor_type (type)->field (1).type ());
14f9c5c9 1914 else if (is_thick_pntr (type))
556bdfd4
UW
1915 {
1916 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1917
1918 if (data_type
78134374 1919 && ada_check_typedef (data_type)->code () == TYPE_CODE_PTR)
27710edb 1920 return ada_check_typedef (data_type->target_type ());
556bdfd4
UW
1921 }
1922
1923 return NULL;
14f9c5c9
AS
1924}
1925
1926/* If ARR is an array descriptor (fat or thin pointer), a pointer to
1927 its array data. */
4c4b4cd2 1928
d2e4a39e
AS
1929static struct value *
1930desc_data (struct value *arr)
14f9c5c9 1931{
d0c97917 1932 struct type *type = arr->type ();
5b4ee69b 1933
14f9c5c9
AS
1934 if (is_thin_pntr (type))
1935 return thin_data_pntr (arr);
1936 else if (is_thick_pntr (type))
158cc4fe 1937 return value_struct_elt (&arr, {}, "P_ARRAY", NULL,
dda83cd7 1938 _("Bad GNAT array descriptor"));
14f9c5c9
AS
1939 else
1940 return NULL;
1941}
1942
1943
1944/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1945 position of the field containing the address of the data. */
1946
14f9c5c9 1947static int
d2e4a39e 1948fat_pntr_data_bitpos (struct type *type)
14f9c5c9 1949{
b610c045 1950 return desc_base_type (type)->field (0).loc_bitpos ();
14f9c5c9
AS
1951}
1952
1953/* If TYPE is the type of an array-descriptor (fat pointer), the bit
4c4b4cd2
PH
1954 size of the field containing the address of the data. */
1955
14f9c5c9 1956static int
d2e4a39e 1957fat_pntr_data_bitsize (struct type *type)
14f9c5c9
AS
1958{
1959 type = desc_base_type (type);
1960
3757d2d4
SM
1961 if (type->field (0).bitsize () > 0)
1962 return type->field (0).bitsize ();
d2e4a39e 1963 else
df86565b 1964 return TARGET_CHAR_BIT * type->field (0).type ()->length ();
14f9c5c9
AS
1965}
1966
4c4b4cd2 1967/* If BOUNDS is an array-bounds structure (or pointer to one), return
14f9c5c9 1968 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1969 bound, if WHICH is 1. The first bound is I=1. */
1970
d2e4a39e
AS
1971static struct value *
1972desc_one_bound (struct value *bounds, int i, int which)
14f9c5c9 1973{
250106a7
TT
1974 char bound_name[20];
1975 xsnprintf (bound_name, sizeof (bound_name), "%cB%d",
1976 which ? 'U' : 'L', i - 1);
158cc4fe 1977 return value_struct_elt (&bounds, {}, bound_name, NULL,
dda83cd7 1978 _("Bad GNAT array descriptor bounds"));
14f9c5c9
AS
1979}
1980
1981/* If BOUNDS is an array-bounds structure type, return the bit position
1982 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1983 bound, if WHICH is 1. The first bound is I=1. */
1984
14f9c5c9 1985static int
d2e4a39e 1986desc_bound_bitpos (struct type *type, int i, int which)
14f9c5c9 1987{
b610c045 1988 return desc_base_type (type)->field (2 * i + which - 2).loc_bitpos ();
14f9c5c9
AS
1989}
1990
1991/* If BOUNDS is an array-bounds structure type, return the bit field size
1992 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
4c4b4cd2
PH
1993 bound, if WHICH is 1. The first bound is I=1. */
1994
76a01679 1995static int
d2e4a39e 1996desc_bound_bitsize (struct type *type, int i, int which)
14f9c5c9
AS
1997{
1998 type = desc_base_type (type);
1999
3757d2d4
SM
2000 if (type->field (2 * i + which - 2).bitsize () > 0)
2001 return type->field (2 * i + which - 2).bitsize ();
d2e4a39e 2002 else
df86565b 2003 return 8 * type->field (2 * i + which - 2).type ()->length ();
14f9c5c9
AS
2004}
2005
2006/* If TYPE is the type of an array-bounds structure, the type of its
4c4b4cd2
PH
2007 Ith bound (numbering from 1). Otherwise, NULL. */
2008
d2e4a39e
AS
2009static struct type *
2010desc_index_type (struct type *type, int i)
14f9c5c9
AS
2011{
2012 type = desc_base_type (type);
2013
78134374 2014 if (type->code () == TYPE_CODE_STRUCT)
250106a7
TT
2015 {
2016 char bound_name[20];
2017 xsnprintf (bound_name, sizeof (bound_name), "LB%d", i - 1);
2018 return lookup_struct_elt_type (type, bound_name, 1);
2019 }
d2e4a39e 2020 else
14f9c5c9
AS
2021 return NULL;
2022}
2023
4c4b4cd2
PH
2024/* The number of index positions in the array-bounds type TYPE.
2025 Return 0 if TYPE is NULL. */
2026
14f9c5c9 2027static int
d2e4a39e 2028desc_arity (struct type *type)
14f9c5c9
AS
2029{
2030 type = desc_base_type (type);
2031
2032 if (type != NULL)
1f704f76 2033 return type->num_fields () / 2;
14f9c5c9
AS
2034 return 0;
2035}
2036
4c4b4cd2
PH
2037/* Non-zero iff TYPE is a simple array type (not a pointer to one) or
2038 an array descriptor type (representing an unconstrained array
2039 type). */
2040
76a01679
JB
2041static int
2042ada_is_direct_array_type (struct type *type)
4c4b4cd2
PH
2043{
2044 if (type == NULL)
2045 return 0;
61ee279c 2046 type = ada_check_typedef (type);
78134374 2047 return (type->code () == TYPE_CODE_ARRAY
dda83cd7 2048 || ada_is_array_descriptor_type (type));
4c4b4cd2
PH
2049}
2050
52ce6436 2051/* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
0963b4bd 2052 * to one. */
52ce6436 2053
2c0b251b 2054static int
52ce6436
PH
2055ada_is_array_type (struct type *type)
2056{
78134374
SM
2057 while (type != NULL
2058 && (type->code () == TYPE_CODE_PTR
2059 || type->code () == TYPE_CODE_REF))
27710edb 2060 type = type->target_type ();
52ce6436
PH
2061 return ada_is_direct_array_type (type);
2062}
2063
4c4b4cd2 2064/* Non-zero iff TYPE is a simple array type or pointer to one. */
14f9c5c9 2065
14f9c5c9 2066int
4c4b4cd2 2067ada_is_simple_array_type (struct type *type)
14f9c5c9
AS
2068{
2069 if (type == NULL)
2070 return 0;
61ee279c 2071 type = ada_check_typedef (type);
78134374
SM
2072 return (type->code () == TYPE_CODE_ARRAY
2073 || (type->code () == TYPE_CODE_PTR
27710edb 2074 && (ada_check_typedef (type->target_type ())->code ()
78134374 2075 == TYPE_CODE_ARRAY)));
14f9c5c9
AS
2076}
2077
4c4b4cd2
PH
2078/* Non-zero iff TYPE belongs to a GNAT array descriptor. */
2079
14f9c5c9 2080int
4c4b4cd2 2081ada_is_array_descriptor_type (struct type *type)
14f9c5c9 2082{
556bdfd4 2083 struct type *data_type = desc_data_target_type (type);
14f9c5c9
AS
2084
2085 if (type == NULL)
2086 return 0;
61ee279c 2087 type = ada_check_typedef (type);
556bdfd4 2088 return (data_type != NULL
78134374 2089 && data_type->code () == TYPE_CODE_ARRAY
556bdfd4 2090 && desc_arity (desc_bounds_type (type)) > 0);
14f9c5c9
AS
2091}
2092
4c4b4cd2 2093/* If ARR has a record type in the form of a standard GNAT array descriptor,
14f9c5c9 2094 (fat pointer) returns the type of the array data described---specifically,
4c4b4cd2 2095 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
14f9c5c9 2096 in from the descriptor; otherwise, they are left unspecified. If
4c4b4cd2
PH
2097 the ARR denotes a null array descriptor and BOUNDS is non-zero,
2098 returns NULL. The result is simply the type of ARR if ARR is not
14f9c5c9 2099 a descriptor. */
de93309a
SM
2100
2101static struct type *
d2e4a39e 2102ada_type_of_array (struct value *arr, int bounds)
14f9c5c9 2103{
d0c97917
TT
2104 if (ada_is_constrained_packed_array_type (arr->type ()))
2105 return decode_constrained_packed_array_type (arr->type ());
14f9c5c9 2106
d0c97917
TT
2107 if (!ada_is_array_descriptor_type (arr->type ()))
2108 return arr->type ();
d2e4a39e
AS
2109
2110 if (!bounds)
ad82864c
JB
2111 {
2112 struct type *array_type =
d0c97917 2113 ada_check_typedef (desc_data_target_type (arr->type ()));
ad82864c 2114
d0c97917 2115 if (ada_is_unconstrained_packed_array_type (arr->type ()))
886176b8
SM
2116 array_type->field (0).set_bitsize
2117 (decode_packed_array_bitsize (arr->type ()));
2118
ad82864c
JB
2119 return array_type;
2120 }
14f9c5c9
AS
2121 else
2122 {
d2e4a39e 2123 struct type *elt_type;
14f9c5c9 2124 int arity;
d2e4a39e 2125 struct value *descriptor;
14f9c5c9 2126
d0c97917
TT
2127 elt_type = ada_array_element_type (arr->type (), -1);
2128 arity = ada_array_arity (arr->type ());
14f9c5c9 2129
d2e4a39e 2130 if (elt_type == NULL || arity == 0)
d0c97917 2131 return ada_check_typedef (arr->type ());
14f9c5c9
AS
2132
2133 descriptor = desc_bounds (arr);
d2e4a39e 2134 if (value_as_long (descriptor) == 0)
dda83cd7 2135 return NULL;
d2e4a39e 2136 while (arity > 0)
dda83cd7 2137 {
9fa83a7a 2138 type_allocator alloc (arr->type ());
dda83cd7
SM
2139 struct value *low = desc_one_bound (descriptor, arity, 0);
2140 struct value *high = desc_one_bound (descriptor, arity, 1);
2141
2142 arity -= 1;
e727c536
TT
2143 struct type *range_type
2144 = create_static_range_type (alloc, low->type (),
2145 longest_to_int (value_as_long (low)),
2146 longest_to_int (value_as_long (high)));
9e76b17a 2147 elt_type = create_array_type (alloc, elt_type, range_type);
cf1eca3c 2148 INIT_GNAT_SPECIFIC (elt_type);
ad82864c 2149
d0c97917 2150 if (ada_is_unconstrained_packed_array_type (arr->type ()))
e67ad678
JB
2151 {
2152 /* We need to store the element packed bitsize, as well as
dda83cd7 2153 recompute the array size, because it was previously
e67ad678
JB
2154 computed based on the unpacked element size. */
2155 LONGEST lo = value_as_long (low);
2156 LONGEST hi = value_as_long (high);
2157
886176b8
SM
2158 elt_type->field (0).set_bitsize
2159 (decode_packed_array_bitsize (arr->type ()));
2160
e67ad678 2161 /* If the array has no element, then the size is already
dda83cd7 2162 zero, and does not need to be recomputed. */
e67ad678
JB
2163 if (lo < hi)
2164 {
2165 int array_bitsize =
3757d2d4 2166 (hi - lo + 1) * elt_type->field (0).bitsize ();
e67ad678 2167
9e76b17a 2168 elt_type->set_length ((array_bitsize + 7) / 8);
e67ad678
JB
2169 }
2170 }
dda83cd7 2171 }
14f9c5c9
AS
2172
2173 return lookup_pointer_type (elt_type);
2174 }
2175}
2176
2177/* If ARR does not represent an array, returns ARR unchanged.
4c4b4cd2
PH
2178 Otherwise, returns either a standard GDB array with bounds set
2179 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2180 GDB array. Returns NULL if ARR is a null fat pointer. */
2181
d2e4a39e
AS
2182struct value *
2183ada_coerce_to_simple_array_ptr (struct value *arr)
14f9c5c9 2184{
d0c97917 2185 if (ada_is_array_descriptor_type (arr->type ()))
14f9c5c9 2186 {
d2e4a39e 2187 struct type *arrType = ada_type_of_array (arr, 1);
5b4ee69b 2188
14f9c5c9 2189 if (arrType == NULL)
dda83cd7 2190 return NULL;
cda03344 2191 return value_cast (arrType, desc_data (arr)->copy ());
14f9c5c9 2192 }
d0c97917 2193 else if (ada_is_constrained_packed_array_type (arr->type ()))
ad82864c 2194 return decode_constrained_packed_array (arr);
14f9c5c9
AS
2195 else
2196 return arr;
2197}
2198
2199/* If ARR does not represent an array, returns ARR unchanged.
2200 Otherwise, returns a standard GDB array describing ARR (which may
4c4b4cd2
PH
2201 be ARR itself if it already is in the proper form). */
2202
720d1a40 2203struct value *
d2e4a39e 2204ada_coerce_to_simple_array (struct value *arr)
14f9c5c9 2205{
d0c97917 2206 if (ada_is_array_descriptor_type (arr->type ()))
14f9c5c9 2207 {
d2e4a39e 2208 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
5b4ee69b 2209
14f9c5c9 2210 if (arrVal == NULL)
dda83cd7 2211 error (_("Bounds unavailable for null array pointer."));
14f9c5c9
AS
2212 return value_ind (arrVal);
2213 }
d0c97917 2214 else if (ada_is_constrained_packed_array_type (arr->type ()))
ad82864c 2215 return decode_constrained_packed_array (arr);
d2e4a39e 2216 else
14f9c5c9
AS
2217 return arr;
2218}
2219
2220/* If TYPE represents a GNAT array type, return it translated to an
2221 ordinary GDB array type (possibly with BITSIZE fields indicating
4c4b4cd2
PH
2222 packing). For other types, is the identity. */
2223
d2e4a39e
AS
2224struct type *
2225ada_coerce_to_simple_array_type (struct type *type)
14f9c5c9 2226{
ad82864c
JB
2227 if (ada_is_constrained_packed_array_type (type))
2228 return decode_constrained_packed_array_type (type);
17280b9f
UW
2229
2230 if (ada_is_array_descriptor_type (type))
556bdfd4 2231 return ada_check_typedef (desc_data_target_type (type));
17280b9f
UW
2232
2233 return type;
14f9c5c9
AS
2234}
2235
4c4b4cd2
PH
2236/* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2237
ad82864c 2238static int
57567375 2239ada_is_gnat_encoded_packed_array_type (struct type *type)
14f9c5c9
AS
2240{
2241 if (type == NULL)
2242 return 0;
4c4b4cd2 2243 type = desc_base_type (type);
61ee279c 2244 type = ada_check_typedef (type);
d2e4a39e 2245 return
14f9c5c9
AS
2246 ada_type_name (type) != NULL
2247 && strstr (ada_type_name (type), "___XP") != NULL;
2248}
2249
ad82864c
JB
2250/* Non-zero iff TYPE represents a standard GNAT constrained
2251 packed-array type. */
2252
2253int
2254ada_is_constrained_packed_array_type (struct type *type)
2255{
57567375 2256 return ada_is_gnat_encoded_packed_array_type (type)
ad82864c
JB
2257 && !ada_is_array_descriptor_type (type);
2258}
2259
2260/* Non-zero iff TYPE represents an array descriptor for a
2261 unconstrained packed-array type. */
2262
2263static int
2264ada_is_unconstrained_packed_array_type (struct type *type)
2265{
57567375
TT
2266 if (!ada_is_array_descriptor_type (type))
2267 return 0;
2268
2269 if (ada_is_gnat_encoded_packed_array_type (type))
2270 return 1;
2271
2272 /* If we saw GNAT encodings, then the above code is sufficient.
2273 However, with minimal encodings, we will just have a thick
2274 pointer instead. */
2275 if (is_thick_pntr (type))
2276 {
2277 type = desc_base_type (type);
2278 /* The structure's first field is a pointer to an array, so this
2279 fetches the array type. */
27710edb 2280 type = type->field (0).type ()->target_type ();
af5300fe
TV
2281 if (type->code () == TYPE_CODE_TYPEDEF)
2282 type = ada_typedef_target_type (type);
57567375 2283 /* Now we can see if the array elements are packed. */
3757d2d4 2284 return type->field (0).bitsize () > 0;
57567375
TT
2285 }
2286
2287 return 0;
ad82864c
JB
2288}
2289
c9a28cbe
TT
2290/* Return true if TYPE is a (Gnat-encoded) constrained packed array
2291 type, or if it is an ordinary (non-Gnat-encoded) packed array. */
2292
2293static bool
2294ada_is_any_packed_array_type (struct type *type)
2295{
2296 return (ada_is_constrained_packed_array_type (type)
2297 || (type->code () == TYPE_CODE_ARRAY
3757d2d4 2298 && type->field (0).bitsize () % 8 != 0));
c9a28cbe
TT
2299}
2300
ad82864c
JB
2301/* Given that TYPE encodes a packed array type (constrained or unconstrained),
2302 return the size of its elements in bits. */
2303
2304static long
2305decode_packed_array_bitsize (struct type *type)
2306{
0d5cff50
DE
2307 const char *raw_name;
2308 const char *tail;
ad82864c
JB
2309 long bits;
2310
720d1a40
JB
2311 /* Access to arrays implemented as fat pointers are encoded as a typedef
2312 of the fat pointer type. We need the name of the fat pointer type
2313 to do the decoding, so strip the typedef layer. */
78134374 2314 if (type->code () == TYPE_CODE_TYPEDEF)
720d1a40
JB
2315 type = ada_typedef_target_type (type);
2316
2317 raw_name = ada_type_name (ada_check_typedef (type));
ad82864c
JB
2318 if (!raw_name)
2319 raw_name = ada_type_name (desc_base_type (type));
2320
2321 if (!raw_name)
2322 return 0;
2323
2324 tail = strstr (raw_name, "___XP");
57567375
TT
2325 if (tail == nullptr)
2326 {
2327 gdb_assert (is_thick_pntr (type));
2328 /* The structure's first field is a pointer to an array, so this
2329 fetches the array type. */
27710edb 2330 type = type->field (0).type ()->target_type ();
57567375 2331 /* Now we can see if the array elements are packed. */
3757d2d4 2332 return type->field (0).bitsize ();
57567375 2333 }
ad82864c
JB
2334
2335 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2336 {
2337 lim_warning
2338 (_("could not understand bit size information on packed array"));
2339 return 0;
2340 }
2341
2342 return bits;
2343}
2344
14f9c5c9
AS
2345/* Given that TYPE is a standard GDB array type with all bounds filled
2346 in, and that the element size of its ultimate scalar constituents
2347 (that is, either its elements, or, if it is an array of arrays, its
2348 elements' elements, etc.) is *ELT_BITS, return an identical type,
2349 but with the bit sizes of its elements (and those of any
2350 constituent arrays) recorded in the BITSIZE components of its
4c4b4cd2 2351 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
4a46959e
JB
2352 in bits.
2353
2354 Note that, for arrays whose index type has an XA encoding where
2355 a bound references a record discriminant, getting that discriminant,
2356 and therefore the actual value of that bound, is not possible
2357 because none of the given parameters gives us access to the record.
2358 This function assumes that it is OK in the context where it is being
2359 used to return an array whose bounds are still dynamic and where
2360 the length is arbitrary. */
4c4b4cd2 2361
d2e4a39e 2362static struct type *
ad82864c 2363constrained_packed_array_type (struct type *type, long *elt_bits)
14f9c5c9 2364{
d2e4a39e
AS
2365 struct type *new_elt_type;
2366 struct type *new_type;
99b1c762
JB
2367 struct type *index_type_desc;
2368 struct type *index_type;
14f9c5c9
AS
2369 LONGEST low_bound, high_bound;
2370
61ee279c 2371 type = ada_check_typedef (type);
78134374 2372 if (type->code () != TYPE_CODE_ARRAY)
14f9c5c9
AS
2373 return type;
2374
99b1c762
JB
2375 index_type_desc = ada_find_parallel_type (type, "___XA");
2376 if (index_type_desc)
940da03e 2377 index_type = to_fixed_range_type (index_type_desc->field (0).type (),
99b1c762
JB
2378 NULL);
2379 else
3d967001 2380 index_type = type->index_type ();
99b1c762 2381
9e76b17a 2382 type_allocator alloc (type);
ad82864c 2383 new_elt_type =
27710edb 2384 constrained_packed_array_type (ada_check_typedef (type->target_type ()),
ad82864c 2385 elt_bits);
9e76b17a 2386 new_type = create_array_type (alloc, new_elt_type, index_type);
886176b8 2387 new_type->field (0).set_bitsize (*elt_bits);
d0e39ea2 2388 new_type->set_name (ada_type_name (type));
14f9c5c9 2389
78134374 2390 if ((check_typedef (index_type)->code () == TYPE_CODE_RANGE
4a46959e 2391 && is_dynamic_type (check_typedef (index_type)))
1f8d2881 2392 || !get_discrete_bounds (index_type, &low_bound, &high_bound))
14f9c5c9
AS
2393 low_bound = high_bound = 0;
2394 if (high_bound < low_bound)
b6cdbc9a
SM
2395 {
2396 *elt_bits = 0;
2397 new_type->set_length (0);
2398 }
d2e4a39e 2399 else
14f9c5c9
AS
2400 {
2401 *elt_bits *= (high_bound - low_bound + 1);
b6cdbc9a 2402 new_type->set_length ((*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT);
14f9c5c9
AS
2403 }
2404
9cdd0d12 2405 new_type->set_is_fixed_instance (true);
14f9c5c9
AS
2406 return new_type;
2407}
2408
ad82864c
JB
2409/* The array type encoded by TYPE, where
2410 ada_is_constrained_packed_array_type (TYPE). */
4c4b4cd2 2411
d2e4a39e 2412static struct type *
ad82864c 2413decode_constrained_packed_array_type (struct type *type)
d2e4a39e 2414{
0d5cff50 2415 const char *raw_name = ada_type_name (ada_check_typedef (type));
727e3d2e 2416 char *name;
0d5cff50 2417 const char *tail;
d2e4a39e 2418 struct type *shadow_type;
14f9c5c9 2419 long bits;
14f9c5c9 2420
727e3d2e
JB
2421 if (!raw_name)
2422 raw_name = ada_type_name (desc_base_type (type));
2423
2424 if (!raw_name)
2425 return NULL;
2426
2427 name = (char *) alloca (strlen (raw_name) + 1);
2428 tail = strstr (raw_name, "___XP");
4c4b4cd2
PH
2429 type = desc_base_type (type);
2430
14f9c5c9
AS
2431 memcpy (name, raw_name, tail - raw_name);
2432 name[tail - raw_name] = '\000';
2433
b4ba55a1
JB
2434 shadow_type = ada_find_parallel_type_with_name (type, name);
2435
2436 if (shadow_type == NULL)
14f9c5c9 2437 {
323e0a4a 2438 lim_warning (_("could not find bounds information on packed array"));
14f9c5c9
AS
2439 return NULL;
2440 }
f168693b 2441 shadow_type = check_typedef (shadow_type);
14f9c5c9 2442
78134374 2443 if (shadow_type->code () != TYPE_CODE_ARRAY)
14f9c5c9 2444 {
0963b4bd
MS
2445 lim_warning (_("could not understand bounds "
2446 "information on packed array"));
14f9c5c9
AS
2447 return NULL;
2448 }
d2e4a39e 2449
ad82864c
JB
2450 bits = decode_packed_array_bitsize (type);
2451 return constrained_packed_array_type (shadow_type, &bits);
14f9c5c9
AS
2452}
2453
a7400e44
TT
2454/* Helper function for decode_constrained_packed_array. Set the field
2455 bitsize on a series of packed arrays. Returns the number of
2456 elements in TYPE. */
2457
2458static LONGEST
2459recursively_update_array_bitsize (struct type *type)
2460{
2461 gdb_assert (type->code () == TYPE_CODE_ARRAY);
2462
2463 LONGEST low, high;
1f8d2881 2464 if (!get_discrete_bounds (type->index_type (), &low, &high)
a7400e44
TT
2465 || low > high)
2466 return 0;
2467 LONGEST our_len = high - low + 1;
2468
27710edb 2469 struct type *elt_type = type->target_type ();
a7400e44
TT
2470 if (elt_type->code () == TYPE_CODE_ARRAY)
2471 {
2472 LONGEST elt_len = recursively_update_array_bitsize (elt_type);
3757d2d4 2473 LONGEST elt_bitsize = elt_len * elt_type->field (0).bitsize ();
886176b8 2474 type->field (0).set_bitsize (elt_bitsize);
a7400e44 2475
b6cdbc9a
SM
2476 type->set_length (((our_len * elt_bitsize + HOST_CHAR_BIT - 1)
2477 / HOST_CHAR_BIT));
a7400e44
TT
2478 }
2479
2480 return our_len;
2481}
2482
ad82864c
JB
2483/* Given that ARR is a struct value *indicating a GNAT constrained packed
2484 array, returns a simple array that denotes that array. Its type is a
14f9c5c9
AS
2485 standard GDB array type except that the BITSIZEs of the array
2486 target types are set to the number of bits in each element, and the
4c4b4cd2 2487 type length is set appropriately. */
14f9c5c9 2488
d2e4a39e 2489static struct value *
ad82864c 2490decode_constrained_packed_array (struct value *arr)
14f9c5c9 2491{
4c4b4cd2 2492 struct type *type;
14f9c5c9 2493
11aa919a
PMR
2494 /* If our value is a pointer, then dereference it. Likewise if
2495 the value is a reference. Make sure that this operation does not
2496 cause the target type to be fixed, as this would indirectly cause
2497 this array to be decoded. The rest of the routine assumes that
2498 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2499 and "value_ind" routines to perform the dereferencing, as opposed
2500 to using "ada_coerce_ref" or "ada_value_ind". */
2501 arr = coerce_ref (arr);
d0c97917 2502 if (ada_check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
284614f0 2503 arr = value_ind (arr);
4c4b4cd2 2504
d0c97917 2505 type = decode_constrained_packed_array_type (arr->type ());
14f9c5c9
AS
2506 if (type == NULL)
2507 {
323e0a4a 2508 error (_("can't unpack array"));
14f9c5c9
AS
2509 return NULL;
2510 }
61ee279c 2511
a7400e44
TT
2512 /* Decoding the packed array type could not correctly set the field
2513 bitsizes for any dimension except the innermost, because the
2514 bounds may be variable and were not passed to that function. So,
2515 we further resolve the array bounds here and then update the
2516 sizes. */
efaf1ae0 2517 const gdb_byte *valaddr = arr->contents_for_printing ().data ();
9feb2d07 2518 CORE_ADDR address = arr->address ();
a7400e44 2519 gdb::array_view<const gdb_byte> view
df86565b 2520 = gdb::make_array_view (valaddr, type->length ());
a7400e44
TT
2521 type = resolve_dynamic_type (type, view, address);
2522 recursively_update_array_bitsize (type);
2523
d0c97917
TT
2524 if (type_byte_order (arr->type ()) == BFD_ENDIAN_BIG
2525 && ada_is_modular_type (arr->type ()))
61ee279c
PH
2526 {
2527 /* This is a (right-justified) modular type representing a packed
24b21115
SM
2528 array with no wrapper. In order to interpret the value through
2529 the (left-justified) packed array type we just built, we must
2530 first left-justify it. */
61ee279c
PH
2531 int bit_size, bit_pos;
2532 ULONGEST mod;
2533
d0c97917 2534 mod = ada_modulus (arr->type ()) - 1;
61ee279c
PH
2535 bit_size = 0;
2536 while (mod > 0)
2537 {
2538 bit_size += 1;
2539 mod >>= 1;
2540 }
d0c97917 2541 bit_pos = HOST_CHAR_BIT * arr->type ()->length () - bit_size;
61ee279c
PH
2542 arr = ada_value_primitive_packed_val (arr, NULL,
2543 bit_pos / HOST_CHAR_BIT,
2544 bit_pos % HOST_CHAR_BIT,
2545 bit_size,
2546 type);
2547 }
2548
4c4b4cd2 2549 return coerce_unspec_val_to_type (arr, type);
14f9c5c9
AS
2550}
2551
2552
2553/* The value of the element of packed array ARR at the ARITY indices
4c4b4cd2 2554 given in IND. ARR must be a simple array. */
14f9c5c9 2555
d2e4a39e
AS
2556static struct value *
2557value_subscript_packed (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
2558{
2559 int i;
2560 int bits, elt_off, bit_off;
2561 long elt_total_bit_offset;
d2e4a39e
AS
2562 struct type *elt_type;
2563 struct value *v;
14f9c5c9
AS
2564
2565 bits = 0;
2566 elt_total_bit_offset = 0;
d0c97917 2567 elt_type = ada_check_typedef (arr->type ());
d2e4a39e 2568 for (i = 0; i < arity; i += 1)
14f9c5c9 2569 {
78134374 2570 if (elt_type->code () != TYPE_CODE_ARRAY
3757d2d4 2571 || elt_type->field (0).bitsize () == 0)
dda83cd7
SM
2572 error
2573 (_("attempt to do packed indexing of "
0963b4bd 2574 "something other than a packed array"));
14f9c5c9 2575 else
dda83cd7
SM
2576 {
2577 struct type *range_type = elt_type->index_type ();
2578 LONGEST lowerbound, upperbound;
2579 LONGEST idx;
2580
1f8d2881 2581 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
dda83cd7
SM
2582 {
2583 lim_warning (_("don't know bounds of array"));
2584 lowerbound = upperbound = 0;
2585 }
2586
2587 idx = pos_atr (ind[i]);
2588 if (idx < lowerbound || idx > upperbound)
2589 lim_warning (_("packed array index %ld out of bounds"),
0963b4bd 2590 (long) idx);
3757d2d4 2591 bits = elt_type->field (0).bitsize ();
dda83cd7 2592 elt_total_bit_offset += (idx - lowerbound) * bits;
27710edb 2593 elt_type = ada_check_typedef (elt_type->target_type ());
dda83cd7 2594 }
14f9c5c9
AS
2595 }
2596 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2597 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
d2e4a39e
AS
2598
2599 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
dda83cd7 2600 bits, elt_type);
14f9c5c9
AS
2601 return v;
2602}
2603
4c4b4cd2 2604/* Non-zero iff TYPE includes negative integer values. */
14f9c5c9
AS
2605
2606static int
d2e4a39e 2607has_negatives (struct type *type)
14f9c5c9 2608{
78134374 2609 switch (type->code ())
d2e4a39e
AS
2610 {
2611 default:
2612 return 0;
2613 case TYPE_CODE_INT:
c6d940a9 2614 return !type->is_unsigned ();
d2e4a39e 2615 case TYPE_CODE_RANGE:
5537ddd0 2616 return type->bounds ()->low.const_val () - type->bounds ()->bias < 0;
d2e4a39e 2617 }
14f9c5c9 2618}
d2e4a39e 2619
f93fca70 2620/* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
5b639dea 2621 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
f93fca70 2622 the unpacked buffer.
14f9c5c9 2623
5b639dea
JB
2624 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2625 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2626
f93fca70
JB
2627 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2628 zero otherwise.
14f9c5c9 2629
f93fca70 2630 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
a1c95e6b 2631
f93fca70
JB
2632 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2633
2634static void
2635ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2636 gdb_byte *unpacked, int unpacked_len,
2637 int is_big_endian, int is_signed_type,
2638 int is_scalar)
2639{
a1c95e6b
JB
2640 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2641 int src_idx; /* Index into the source area */
2642 int src_bytes_left; /* Number of source bytes left to process. */
2643 int srcBitsLeft; /* Number of source bits left to move */
2644 int unusedLS; /* Number of bits in next significant
dda83cd7 2645 byte of source that are unused */
a1c95e6b 2646
a1c95e6b
JB
2647 int unpacked_idx; /* Index into the unpacked buffer */
2648 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2649
4c4b4cd2 2650 unsigned long accum; /* Staging area for bits being transferred */
a1c95e6b 2651 int accumSize; /* Number of meaningful bits in accum */
14f9c5c9 2652 unsigned char sign;
a1c95e6b 2653
4c4b4cd2
PH
2654 /* Transmit bytes from least to most significant; delta is the direction
2655 the indices move. */
f93fca70 2656 int delta = is_big_endian ? -1 : 1;
14f9c5c9 2657
5b639dea
JB
2658 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2659 bits from SRC. .*/
2660 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2661 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2662 bit_size, unpacked_len);
2663
14f9c5c9 2664 srcBitsLeft = bit_size;
086ca51f 2665 src_bytes_left = src_len;
f93fca70 2666 unpacked_bytes_left = unpacked_len;
14f9c5c9 2667 sign = 0;
f93fca70
JB
2668
2669 if (is_big_endian)
14f9c5c9 2670 {
086ca51f 2671 src_idx = src_len - 1;
f93fca70
JB
2672 if (is_signed_type
2673 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
dda83cd7 2674 sign = ~0;
d2e4a39e
AS
2675
2676 unusedLS =
dda83cd7
SM
2677 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2678 % HOST_CHAR_BIT;
14f9c5c9 2679
f93fca70
JB
2680 if (is_scalar)
2681 {
dda83cd7
SM
2682 accumSize = 0;
2683 unpacked_idx = unpacked_len - 1;
f93fca70
JB
2684 }
2685 else
2686 {
dda83cd7
SM
2687 /* Non-scalar values must be aligned at a byte boundary... */
2688 accumSize =
2689 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2690 /* ... And are placed at the beginning (most-significant) bytes
2691 of the target. */
2692 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2693 unpacked_bytes_left = unpacked_idx + 1;
f93fca70 2694 }
14f9c5c9 2695 }
d2e4a39e 2696 else
14f9c5c9
AS
2697 {
2698 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2699
086ca51f 2700 src_idx = unpacked_idx = 0;
14f9c5c9
AS
2701 unusedLS = bit_offset;
2702 accumSize = 0;
2703
f93fca70 2704 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
dda83cd7 2705 sign = ~0;
14f9c5c9 2706 }
d2e4a39e 2707
14f9c5c9 2708 accum = 0;
086ca51f 2709 while (src_bytes_left > 0)
14f9c5c9
AS
2710 {
2711 /* Mask for removing bits of the next source byte that are not
dda83cd7 2712 part of the value. */
d2e4a39e 2713 unsigned int unusedMSMask =
dda83cd7
SM
2714 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2715 1;
4c4b4cd2 2716 /* Sign-extend bits for this byte. */
14f9c5c9 2717 unsigned int signMask = sign & ~unusedMSMask;
5b4ee69b 2718
d2e4a39e 2719 accum |=
dda83cd7 2720 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
14f9c5c9 2721 accumSize += HOST_CHAR_BIT - unusedLS;
d2e4a39e 2722 if (accumSize >= HOST_CHAR_BIT)
dda83cd7
SM
2723 {
2724 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2725 accumSize -= HOST_CHAR_BIT;
2726 accum >>= HOST_CHAR_BIT;
2727 unpacked_bytes_left -= 1;
2728 unpacked_idx += delta;
2729 }
14f9c5c9
AS
2730 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2731 unusedLS = 0;
086ca51f
JB
2732 src_bytes_left -= 1;
2733 src_idx += delta;
14f9c5c9 2734 }
086ca51f 2735 while (unpacked_bytes_left > 0)
14f9c5c9
AS
2736 {
2737 accum |= sign << accumSize;
db297a65 2738 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
14f9c5c9 2739 accumSize -= HOST_CHAR_BIT;
9cd4d857
JB
2740 if (accumSize < 0)
2741 accumSize = 0;
14f9c5c9 2742 accum >>= HOST_CHAR_BIT;
086ca51f
JB
2743 unpacked_bytes_left -= 1;
2744 unpacked_idx += delta;
14f9c5c9 2745 }
f93fca70
JB
2746}
2747
2748/* Create a new value of type TYPE from the contents of OBJ starting
2749 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2750 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2751 assigning through the result will set the field fetched from.
2752 VALADDR is ignored unless OBJ is NULL, in which case,
2753 VALADDR+OFFSET must address the start of storage containing the
2754 packed value. The value returned in this case is never an lval.
2755 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2756
2757struct value *
2758ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2759 long offset, int bit_offset, int bit_size,
dda83cd7 2760 struct type *type)
f93fca70
JB
2761{
2762 struct value *v;
bfb1c796 2763 const gdb_byte *src; /* First byte containing data to unpack */
f93fca70 2764 gdb_byte *unpacked;
220475ed 2765 const int is_scalar = is_scalar_type (type);
d5a22e77 2766 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
d5722aa2 2767 gdb::byte_vector staging;
f93fca70
JB
2768
2769 type = ada_check_typedef (type);
2770
d0a9e810 2771 if (obj == NULL)
bfb1c796 2772 src = valaddr + offset;
d0a9e810 2773 else
efaf1ae0 2774 src = obj->contents ().data () + offset;
d0a9e810
JB
2775
2776 if (is_dynamic_type (type))
2777 {
2778 /* The length of TYPE might by dynamic, so we need to resolve
2779 TYPE in order to know its actual size, which we then use
2780 to create the contents buffer of the value we return.
2781 The difficulty is that the data containing our object is
2782 packed, and therefore maybe not at a byte boundary. So, what
2783 we do, is unpack the data into a byte-aligned buffer, and then
2784 use that buffer as our object's value for resolving the type. */
d5722aa2
PA
2785 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2786 staging.resize (staging_len);
d0a9e810
JB
2787
2788 ada_unpack_from_contents (src, bit_offset, bit_size,
dda83cd7 2789 staging.data (), staging.size (),
d0a9e810
JB
2790 is_big_endian, has_negatives (type),
2791 is_scalar);
b249d2c2 2792 type = resolve_dynamic_type (type, staging, 0);
df86565b 2793 if (type->length () < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
0cafa88c
JB
2794 {
2795 /* This happens when the length of the object is dynamic,
2796 and is actually smaller than the space reserved for it.
2797 For instance, in an array of variant records, the bit_size
2798 we're given is the array stride, which is constant and
2799 normally equal to the maximum size of its element.
2800 But, in reality, each element only actually spans a portion
2801 of that stride. */
df86565b 2802 bit_size = type->length () * HOST_CHAR_BIT;
0cafa88c 2803 }
d0a9e810
JB
2804 }
2805
f93fca70
JB
2806 if (obj == NULL)
2807 {
317c3ed9 2808 v = value::allocate (type);
bfb1c796 2809 src = valaddr + offset;
f93fca70 2810 }
736355f2 2811 else if (obj->lval () == lval_memory && obj->lazy ())
f93fca70 2812 {
0cafa88c 2813 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
bfb1c796 2814 gdb_byte *buf;
0cafa88c 2815
9feb2d07 2816 v = value_at (type, obj->address () + offset);
bfb1c796 2817 buf = (gdb_byte *) alloca (src_len);
9feb2d07 2818 read_memory (v->address (), buf, src_len);
bfb1c796 2819 src = buf;
f93fca70
JB
2820 }
2821 else
2822 {
317c3ed9 2823 v = value::allocate (type);
efaf1ae0 2824 src = obj->contents ().data () + offset;
f93fca70
JB
2825 }
2826
2827 if (obj != NULL)
2828 {
2829 long new_offset = offset;
2830
8181b7b6 2831 v->set_component_location (obj);
5011c493 2832 v->set_bitpos (bit_offset + obj->bitpos ());
f49d5fa2 2833 v->set_bitsize (bit_size);
5011c493 2834 if (v->bitpos () >= HOST_CHAR_BIT)
dda83cd7 2835 {
f93fca70 2836 ++new_offset;
5011c493 2837 v->set_bitpos (v->bitpos () - HOST_CHAR_BIT);
dda83cd7 2838 }
76675c4d 2839 v->set_offset (new_offset);
f93fca70
JB
2840
2841 /* Also set the parent value. This is needed when trying to
2842 assign a new value (in inferior memory). */
fac7bdaa 2843 v->set_parent (obj);
f93fca70
JB
2844 }
2845 else
f49d5fa2 2846 v->set_bitsize (bit_size);
bbe912ba 2847 unpacked = v->contents_writeable ().data ();
f93fca70
JB
2848
2849 if (bit_size == 0)
2850 {
df86565b 2851 memset (unpacked, 0, type->length ());
f93fca70
JB
2852 return v;
2853 }
2854
df86565b 2855 if (staging.size () == type->length ())
f93fca70 2856 {
d0a9e810
JB
2857 /* Small short-cut: If we've unpacked the data into a buffer
2858 of the same size as TYPE's length, then we can reuse that,
2859 instead of doing the unpacking again. */
d5722aa2 2860 memcpy (unpacked, staging.data (), staging.size ());
f93fca70 2861 }
d0a9e810
JB
2862 else
2863 ada_unpack_from_contents (src, bit_offset, bit_size,
df86565b 2864 unpacked, type->length (),
d0a9e810 2865 is_big_endian, has_negatives (type), is_scalar);
f93fca70 2866
14f9c5c9
AS
2867 return v;
2868}
d2e4a39e 2869
14f9c5c9
AS
2870/* Store the contents of FROMVAL into the location of TOVAL.
2871 Return a new value with the location of TOVAL and contents of
2872 FROMVAL. Handles assignment into packed fields that have
4c4b4cd2 2873 floating-point or non-scalar types. */
14f9c5c9 2874
d2e4a39e
AS
2875static struct value *
2876ada_value_assign (struct value *toval, struct value *fromval)
14f9c5c9 2877{
d0c97917 2878 struct type *type = toval->type ();
f49d5fa2 2879 int bits = toval->bitsize ();
14f9c5c9 2880
52ce6436
PH
2881 toval = ada_coerce_ref (toval);
2882 fromval = ada_coerce_ref (fromval);
2883
d0c97917 2884 if (ada_is_direct_array_type (toval->type ()))
52ce6436 2885 toval = ada_coerce_to_simple_array (toval);
d0c97917 2886 if (ada_is_direct_array_type (fromval->type ()))
52ce6436
PH
2887 fromval = ada_coerce_to_simple_array (fromval);
2888
4b53ca88 2889 if (!toval->deprecated_modifiable ())
323e0a4a 2890 error (_("Left operand of assignment is not a modifiable lvalue."));
14f9c5c9 2891
736355f2 2892 if (toval->lval () == lval_memory
14f9c5c9 2893 && bits > 0
78134374 2894 && (type->code () == TYPE_CODE_FLT
dda83cd7 2895 || type->code () == TYPE_CODE_STRUCT))
14f9c5c9 2896 {
5011c493 2897 int len = (toval->bitpos ()
df407dfe 2898 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
aced2898 2899 int from_size;
224c3ddb 2900 gdb_byte *buffer = (gdb_byte *) alloca (len);
d2e4a39e 2901 struct value *val;
9feb2d07 2902 CORE_ADDR to_addr = toval->address ();
14f9c5c9 2903
78134374 2904 if (type->code () == TYPE_CODE_FLT)
dda83cd7 2905 fromval = value_cast (type, fromval);
14f9c5c9 2906
52ce6436 2907 read_memory (to_addr, buffer, len);
f49d5fa2 2908 from_size = fromval->bitsize ();
aced2898 2909 if (from_size == 0)
d0c97917 2910 from_size = fromval->type ()->length () * TARGET_CHAR_BIT;
d48e62f4 2911
d5a22e77 2912 const int is_big_endian = type_byte_order (type) == BFD_ENDIAN_BIG;
d48e62f4 2913 ULONGEST from_offset = 0;
d0c97917 2914 if (is_big_endian && is_scalar_type (fromval->type ()))
d48e62f4 2915 from_offset = from_size - bits;
5011c493 2916 copy_bitwise (buffer, toval->bitpos (),
efaf1ae0 2917 fromval->contents ().data (), from_offset,
d48e62f4 2918 bits, is_big_endian);
972daa01 2919 write_memory_with_notification (to_addr, buffer, len);
8cebebb9 2920
cda03344 2921 val = toval->copy ();
bbe912ba 2922 memcpy (val->contents_raw ().data (),
efaf1ae0 2923 fromval->contents ().data (),
df86565b 2924 type->length ());
81ae560c 2925 val->deprecated_set_type (type);
d2e4a39e 2926
14f9c5c9
AS
2927 return val;
2928 }
2929
2930 return value_assign (toval, fromval);
2931}
2932
2933
7c512744
JB
2934/* Given that COMPONENT is a memory lvalue that is part of the lvalue
2935 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2936 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2937 COMPONENT, and not the inferior's memory. The current contents
2938 of COMPONENT are ignored.
2939
2940 Although not part of the initial design, this function also works
2941 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2942 had a null address, and COMPONENT had an address which is equal to
2943 its offset inside CONTAINER. */
2944
52ce6436
PH
2945static void
2946value_assign_to_component (struct value *container, struct value *component,
2947 struct value *val)
2948{
2949 LONGEST offset_in_container =
9feb2d07 2950 (LONGEST) (component->address () - container->address ());
7c512744 2951 int bit_offset_in_container =
5011c493 2952 component->bitpos () - container->bitpos ();
52ce6436 2953 int bits;
7c512744 2954
d0c97917 2955 val = value_cast (component->type (), val);
52ce6436 2956
f49d5fa2 2957 if (component->bitsize () == 0)
d0c97917 2958 bits = TARGET_CHAR_BIT * component->type ()->length ();
52ce6436 2959 else
f49d5fa2 2960 bits = component->bitsize ();
52ce6436 2961
d0c97917 2962 if (type_byte_order (container->type ()) == BFD_ENDIAN_BIG)
2a62dfa9
JB
2963 {
2964 int src_offset;
2965
d0c97917 2966 if (is_scalar_type (check_typedef (component->type ())))
dda83cd7 2967 src_offset
d0c97917 2968 = component->type ()->length () * TARGET_CHAR_BIT - bits;
2a62dfa9
JB
2969 else
2970 src_offset = 0;
bbe912ba 2971 copy_bitwise ((container->contents_writeable ().data ()
50888e42 2972 + offset_in_container),
5011c493 2973 container->bitpos () + bit_offset_in_container,
efaf1ae0 2974 val->contents ().data (), src_offset, bits, 1);
2a62dfa9 2975 }
52ce6436 2976 else
bbe912ba 2977 copy_bitwise ((container->contents_writeable ().data ()
50888e42 2978 + offset_in_container),
5011c493 2979 container->bitpos () + bit_offset_in_container,
efaf1ae0 2980 val->contents ().data (), 0, bits, 0);
7c512744
JB
2981}
2982
736ade86
XR
2983/* Determine if TYPE is an access to an unconstrained array. */
2984
d91e9ea8 2985bool
736ade86
XR
2986ada_is_access_to_unconstrained_array (struct type *type)
2987{
78134374 2988 return (type->code () == TYPE_CODE_TYPEDEF
736ade86
XR
2989 && is_thick_pntr (ada_typedef_target_type (type)));
2990}
2991
4c4b4cd2
PH
2992/* The value of the element of array ARR at the ARITY indices given in IND.
2993 ARR may be either a simple array, GNAT array descriptor, or pointer
14f9c5c9
AS
2994 thereto. */
2995
d2e4a39e
AS
2996struct value *
2997ada_value_subscript (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
2998{
2999 int k;
d2e4a39e
AS
3000 struct value *elt;
3001 struct type *elt_type;
14f9c5c9
AS
3002
3003 elt = ada_coerce_to_simple_array (arr);
3004
d0c97917 3005 elt_type = ada_check_typedef (elt->type ());
78134374 3006 if (elt_type->code () == TYPE_CODE_ARRAY
3757d2d4 3007 && elt_type->field (0).bitsize () > 0)
14f9c5c9
AS
3008 return value_subscript_packed (elt, arity, ind);
3009
3010 for (k = 0; k < arity; k += 1)
3011 {
27710edb 3012 struct type *saved_elt_type = elt_type->target_type ();
b9c50e9a 3013
78134374 3014 if (elt_type->code () != TYPE_CODE_ARRAY)
dda83cd7 3015 error (_("too many subscripts (%d expected)"), k);
b9c50e9a 3016
2497b498 3017 elt = value_subscript (elt, pos_atr (ind[k]));
b9c50e9a
XR
3018
3019 if (ada_is_access_to_unconstrained_array (saved_elt_type)
d0c97917 3020 && elt->type ()->code () != TYPE_CODE_TYPEDEF)
b9c50e9a
XR
3021 {
3022 /* The element is a typedef to an unconstrained array,
3023 except that the value_subscript call stripped the
3024 typedef layer. The typedef layer is GNAT's way to
3025 specify that the element is, at the source level, an
3026 access to the unconstrained array, rather than the
3027 unconstrained array. So, we need to restore that
3028 typedef layer, which we can do by forcing the element's
3029 type back to its original type. Otherwise, the returned
3030 value is going to be printed as the array, rather
3031 than as an access. Another symptom of the same issue
3032 would be that an expression trying to dereference the
3033 element would also be improperly rejected. */
81ae560c 3034 elt->deprecated_set_type (saved_elt_type);
b9c50e9a
XR
3035 }
3036
d0c97917 3037 elt_type = ada_check_typedef (elt->type ());
14f9c5c9 3038 }
b9c50e9a 3039
14f9c5c9
AS
3040 return elt;
3041}
3042
deede10c
JB
3043/* Assuming ARR is a pointer to a GDB array, the value of the element
3044 of *ARR at the ARITY indices given in IND.
919e6dbe
PMR
3045 Does not read the entire array into memory.
3046
3047 Note: Unlike what one would expect, this function is used instead of
3048 ada_value_subscript for basically all non-packed array types. The reason
3049 for this is that a side effect of doing our own pointer arithmetics instead
3050 of relying on value_subscript is that there is no implicit typedef peeling.
3051 This is important for arrays of array accesses, where it allows us to
3052 preserve the fact that the array's element is an array access, where the
3053 access part os encoded in a typedef layer. */
14f9c5c9 3054
2c0b251b 3055static struct value *
deede10c 3056ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
14f9c5c9
AS
3057{
3058 int k;
919e6dbe 3059 struct value *array_ind = ada_value_ind (arr);
deede10c 3060 struct type *type
463b870d 3061 = check_typedef (array_ind->enclosing_type ());
919e6dbe 3062
78134374 3063 if (type->code () == TYPE_CODE_ARRAY
3757d2d4 3064 && type->field (0).bitsize () > 0)
919e6dbe 3065 return value_subscript_packed (array_ind, arity, ind);
14f9c5c9
AS
3066
3067 for (k = 0; k < arity; k += 1)
3068 {
3069 LONGEST lwb, upb;
14f9c5c9 3070
78134374 3071 if (type->code () != TYPE_CODE_ARRAY)
dda83cd7 3072 error (_("too many subscripts (%d expected)"), k);
27710edb 3073 arr = value_cast (lookup_pointer_type (type->target_type ()),
cda03344 3074 arr->copy ());
3d967001 3075 get_discrete_bounds (type->index_type (), &lwb, &upb);
53a47a3e 3076 arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
27710edb 3077 type = type->target_type ();
14f9c5c9
AS
3078 }
3079
3080 return value_ind (arr);
3081}
3082
0b5d8877 3083/* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
aa715135
JG
3084 actual type of ARRAY_PTR is ignored), returns the Ada slice of
3085 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
3086 this array is LOW, as per Ada rules. */
0b5d8877 3087static struct value *
f5938064 3088ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
dda83cd7 3089 int low, int high)
0b5d8877 3090{
b0dd7688 3091 struct type *type0 = ada_check_typedef (type);
27710edb 3092 struct type *base_index_type = type0->index_type ()->target_type ();
e727c536 3093 type_allocator alloc (base_index_type);
0c9c3474 3094 struct type *index_type
e727c536 3095 = create_static_range_type (alloc, base_index_type, low, high);
9fe561ab 3096 struct type *slice_type = create_array_type_with_stride
9e76b17a 3097 (alloc, type0->target_type (), index_type,
24e99c6c 3098 type0->dyn_prop (DYN_PROP_BYTE_STRIDE),
3757d2d4 3099 type0->field (0).bitsize ());
3d967001 3100 int base_low = ada_discrete_type_low_bound (type0->index_type ());
6244c119 3101 gdb::optional<LONGEST> base_low_pos, low_pos;
aa715135
JG
3102 CORE_ADDR base;
3103
6244c119
SM
3104 low_pos = discrete_position (base_index_type, low);
3105 base_low_pos = discrete_position (base_index_type, base_low);
3106
3107 if (!low_pos.has_value () || !base_low_pos.has_value ())
aa715135
JG
3108 {
3109 warning (_("unable to get positions in slice, use bounds instead"));
3110 low_pos = low;
3111 base_low_pos = base_low;
3112 }
5b4ee69b 3113
3757d2d4 3114 ULONGEST stride = slice_type->field (0).bitsize () / 8;
7ff5b937 3115 if (stride == 0)
df86565b 3116 stride = type0->target_type ()->length ();
7ff5b937 3117
6244c119 3118 base = value_as_address (array_ptr) + (*low_pos - *base_low_pos) * stride;
f5938064 3119 return value_at_lazy (slice_type, base);
0b5d8877
PH
3120}
3121
3122
3123static struct value *
3124ada_value_slice (struct value *array, int low, int high)
3125{
d0c97917 3126 struct type *type = ada_check_typedef (array->type ());
27710edb 3127 struct type *base_index_type = type->index_type ()->target_type ();
e727c536 3128 type_allocator alloc (type->index_type ());
0c9c3474 3129 struct type *index_type
e727c536 3130 = create_static_range_type (alloc, type->index_type (), low, high);
9fe561ab 3131 struct type *slice_type = create_array_type_with_stride
9e76b17a 3132 (alloc, type->target_type (), index_type,
24e99c6c 3133 type->dyn_prop (DYN_PROP_BYTE_STRIDE),
3757d2d4 3134 type->field (0).bitsize ());
6244c119
SM
3135 gdb::optional<LONGEST> low_pos, high_pos;
3136
5b4ee69b 3137
6244c119
SM
3138 low_pos = discrete_position (base_index_type, low);
3139 high_pos = discrete_position (base_index_type, high);
3140
3141 if (!low_pos.has_value () || !high_pos.has_value ())
aa715135
JG
3142 {
3143 warning (_("unable to get positions in slice, use bounds instead"));
3144 low_pos = low;
3145 high_pos = high;
3146 }
3147
3148 return value_cast (slice_type,
6244c119 3149 value_slice (array, low, *high_pos - *low_pos + 1));
0b5d8877
PH
3150}
3151
14f9c5c9
AS
3152/* If type is a record type in the form of a standard GNAT array
3153 descriptor, returns the number of dimensions for type. If arr is a
3154 simple array, returns the number of "array of"s that prefix its
4c4b4cd2 3155 type designation. Otherwise, returns 0. */
14f9c5c9
AS
3156
3157int
d2e4a39e 3158ada_array_arity (struct type *type)
14f9c5c9
AS
3159{
3160 int arity;
3161
3162 if (type == NULL)
3163 return 0;
3164
3165 type = desc_base_type (type);
3166
3167 arity = 0;
78134374 3168 if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9 3169 return desc_arity (desc_bounds_type (type));
d2e4a39e 3170 else
78134374 3171 while (type->code () == TYPE_CODE_ARRAY)
14f9c5c9 3172 {
dda83cd7 3173 arity += 1;
27710edb 3174 type = ada_check_typedef (type->target_type ());
14f9c5c9 3175 }
d2e4a39e 3176
14f9c5c9
AS
3177 return arity;
3178}
3179
3180/* If TYPE is a record type in the form of a standard GNAT array
3181 descriptor or a simple array type, returns the element type for
3182 TYPE after indexing by NINDICES indices, or by all indices if
4c4b4cd2 3183 NINDICES is -1. Otherwise, returns NULL. */
14f9c5c9 3184
d2e4a39e
AS
3185struct type *
3186ada_array_element_type (struct type *type, int nindices)
14f9c5c9
AS
3187{
3188 type = desc_base_type (type);
3189
78134374 3190 if (type->code () == TYPE_CODE_STRUCT)
14f9c5c9
AS
3191 {
3192 int k;
d2e4a39e 3193 struct type *p_array_type;
14f9c5c9 3194
556bdfd4 3195 p_array_type = desc_data_target_type (type);
14f9c5c9
AS
3196
3197 k = ada_array_arity (type);
3198 if (k == 0)
dda83cd7 3199 return NULL;
d2e4a39e 3200
4c4b4cd2 3201 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
14f9c5c9 3202 if (nindices >= 0 && k > nindices)
dda83cd7 3203 k = nindices;
d2e4a39e 3204 while (k > 0 && p_array_type != NULL)
dda83cd7 3205 {
27710edb 3206 p_array_type = ada_check_typedef (p_array_type->target_type ());
dda83cd7
SM
3207 k -= 1;
3208 }
14f9c5c9
AS
3209 return p_array_type;
3210 }
78134374 3211 else if (type->code () == TYPE_CODE_ARRAY)
14f9c5c9 3212 {
78134374 3213 while (nindices != 0 && type->code () == TYPE_CODE_ARRAY)
dda83cd7 3214 {
27710edb 3215 type = type->target_type ();
6a40c6e4
TT
3216 /* A multi-dimensional array is represented using a sequence
3217 of array types. If one of these types has a name, then
3218 it is not another dimension of the outer array, but
3219 rather the element type of the outermost array. */
3220 if (type->name () != nullptr)
3221 break;
dda83cd7
SM
3222 nindices -= 1;
3223 }
14f9c5c9
AS
3224 return type;
3225 }
3226
3227 return NULL;
3228}
3229
08a057e6 3230/* See ada-lang.h. */
14f9c5c9 3231
08a057e6 3232struct type *
1eea4ebd 3233ada_index_type (struct type *type, int n, const char *name)
14f9c5c9 3234{
4c4b4cd2
PH
3235 struct type *result_type;
3236
14f9c5c9
AS
3237 type = desc_base_type (type);
3238
1eea4ebd
UW
3239 if (n < 0 || n > ada_array_arity (type))
3240 error (_("invalid dimension number to '%s"), name);
14f9c5c9 3241
4c4b4cd2 3242 if (ada_is_simple_array_type (type))
14f9c5c9
AS
3243 {
3244 int i;
3245
3246 for (i = 1; i < n; i += 1)
2869ac4b
TT
3247 {
3248 type = ada_check_typedef (type);
27710edb 3249 type = type->target_type ();
2869ac4b 3250 }
27710edb 3251 result_type = ada_check_typedef (type)->index_type ()->target_type ();
4c4b4cd2 3252 /* FIXME: The stabs type r(0,0);bound;bound in an array type
dda83cd7
SM
3253 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3254 perhaps stabsread.c would make more sense. */
78134374 3255 if (result_type && result_type->code () == TYPE_CODE_UNDEF)
dda83cd7 3256 result_type = NULL;
14f9c5c9 3257 }
d2e4a39e 3258 else
1eea4ebd
UW
3259 {
3260 result_type = desc_index_type (desc_bounds_type (type), n);
3261 if (result_type == NULL)
3262 error (_("attempt to take bound of something that is not an array"));
3263 }
3264
3265 return result_type;
14f9c5c9
AS
3266}
3267
3268/* Given that arr is an array type, returns the lower bound of the
3269 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
4c4b4cd2 3270 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
1eea4ebd
UW
3271 array-descriptor type. It works for other arrays with bounds supplied
3272 by run-time quantities other than discriminants. */
14f9c5c9 3273
abb68b3e 3274static LONGEST
fb5e3d5c 3275ada_array_bound_from_type (struct type *arr_type, int n, int which)
14f9c5c9 3276{
8a48ac95 3277 struct type *type, *index_type_desc, *index_type;
1ce677a4 3278 int i;
262452ec
JK
3279
3280 gdb_assert (which == 0 || which == 1);
14f9c5c9 3281
ad82864c
JB
3282 if (ada_is_constrained_packed_array_type (arr_type))
3283 arr_type = decode_constrained_packed_array_type (arr_type);
14f9c5c9 3284
4c4b4cd2 3285 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
66cf9350 3286 return - which;
14f9c5c9 3287
78134374 3288 if (arr_type->code () == TYPE_CODE_PTR)
27710edb 3289 type = arr_type->target_type ();
14f9c5c9
AS
3290 else
3291 type = arr_type;
3292
22c4c60c 3293 if (type->is_fixed_instance ())
bafffb51
JB
3294 {
3295 /* The array has already been fixed, so we do not need to
3296 check the parallel ___XA type again. That encoding has
3297 already been applied, so ignore it now. */
3298 index_type_desc = NULL;
3299 }
3300 else
3301 {
3302 index_type_desc = ada_find_parallel_type (type, "___XA");
3303 ada_fixup_array_indexes_type (index_type_desc);
3304 }
3305
262452ec 3306 if (index_type_desc != NULL)
940da03e 3307 index_type = to_fixed_range_type (index_type_desc->field (n - 1).type (),
28c85d6c 3308 NULL);
262452ec 3309 else
8a48ac95
JB
3310 {
3311 struct type *elt_type = check_typedef (type);
3312
3313 for (i = 1; i < n; i++)
27710edb 3314 elt_type = check_typedef (elt_type->target_type ());
8a48ac95 3315
3d967001 3316 index_type = elt_type->index_type ();
8a48ac95 3317 }
262452ec 3318
66cf9350
TT
3319 return (which == 0
3320 ? ada_discrete_type_low_bound (index_type)
3321 : ada_discrete_type_high_bound (index_type));
14f9c5c9
AS
3322}
3323
3324/* Given that arr is an array value, returns the lower bound of the
abb68b3e
JB
3325 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3326 WHICH is 1. This routine will also work for arrays with bounds
4c4b4cd2 3327 supplied by run-time quantities other than discriminants. */
14f9c5c9 3328
1eea4ebd 3329static LONGEST
4dc81987 3330ada_array_bound (struct value *arr, int n, int which)
14f9c5c9 3331{
eb479039
JB
3332 struct type *arr_type;
3333
d0c97917 3334 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
eb479039 3335 arr = value_ind (arr);
463b870d 3336 arr_type = arr->enclosing_type ();
14f9c5c9 3337
ad82864c
JB
3338 if (ada_is_constrained_packed_array_type (arr_type))
3339 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
4c4b4cd2 3340 else if (ada_is_simple_array_type (arr_type))
1eea4ebd 3341 return ada_array_bound_from_type (arr_type, n, which);
14f9c5c9 3342 else
1eea4ebd 3343 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
14f9c5c9
AS
3344}
3345
3346/* Given that arr is an array value, returns the length of the
3347 nth index. This routine will also work for arrays with bounds
4c4b4cd2
PH
3348 supplied by run-time quantities other than discriminants.
3349 Does not work for arrays indexed by enumeration types with representation
3350 clauses at the moment. */
14f9c5c9 3351
1eea4ebd 3352static LONGEST
d2e4a39e 3353ada_array_length (struct value *arr, int n)
14f9c5c9 3354{
aa715135
JG
3355 struct type *arr_type, *index_type;
3356 int low, high;
eb479039 3357
d0c97917 3358 if (check_typedef (arr->type ())->code () == TYPE_CODE_PTR)
eb479039 3359 arr = value_ind (arr);
463b870d 3360 arr_type = arr->enclosing_type ();
14f9c5c9 3361
ad82864c
JB
3362 if (ada_is_constrained_packed_array_type (arr_type))
3363 return ada_array_length (decode_constrained_packed_array (arr), n);
14f9c5c9 3364
4c4b4cd2 3365 if (ada_is_simple_array_type (arr_type))
aa715135
JG
3366 {
3367 low = ada_array_bound_from_type (arr_type, n, 0);
3368 high = ada_array_bound_from_type (arr_type, n, 1);
3369 }
14f9c5c9 3370 else
aa715135
JG
3371 {
3372 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3373 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3374 }
3375
f168693b 3376 arr_type = check_typedef (arr_type);
7150d33c 3377 index_type = ada_index_type (arr_type, n, "length");
aa715135
JG
3378 if (index_type != NULL)
3379 {
3380 struct type *base_type;
78134374 3381 if (index_type->code () == TYPE_CODE_RANGE)
27710edb 3382 base_type = index_type->target_type ();
aa715135
JG
3383 else
3384 base_type = index_type;
3385
3386 low = pos_atr (value_from_longest (base_type, low));
3387 high = pos_atr (value_from_longest (base_type, high));
3388 }
3389 return high - low + 1;
4c4b4cd2
PH
3390}
3391
bff8c71f
TT
3392/* An array whose type is that of ARR_TYPE (an array type), with
3393 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3394 less than LOW, then LOW-1 is used. */
4c4b4cd2
PH
3395
3396static struct value *
bff8c71f 3397empty_array (struct type *arr_type, int low, int high)
4c4b4cd2 3398{
b0dd7688 3399 struct type *arr_type0 = ada_check_typedef (arr_type);
e727c536 3400 type_allocator alloc (arr_type0->index_type ()->target_type ());
0c9c3474
SA
3401 struct type *index_type
3402 = create_static_range_type
e727c536 3403 (alloc, arr_type0->index_type ()->target_type (), low,
bff8c71f 3404 high < low ? low - 1 : high);
b0dd7688 3405 struct type *elt_type = ada_array_element_type (arr_type0, 1);
5b4ee69b 3406
9e76b17a 3407 return value::allocate (create_array_type (alloc, elt_type, index_type));
14f9c5c9 3408}
14f9c5c9 3409\f
d2e4a39e 3410
dda83cd7 3411 /* Name resolution */
14f9c5c9 3412
4c4b4cd2
PH
3413/* The "decoded" name for the user-definable Ada operator corresponding
3414 to OP. */
14f9c5c9 3415
d2e4a39e 3416static const char *
4c4b4cd2 3417ada_decoded_op_name (enum exp_opcode op)
14f9c5c9
AS
3418{
3419 int i;
3420
4c4b4cd2 3421 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
14f9c5c9
AS
3422 {
3423 if (ada_opname_table[i].op == op)
dda83cd7 3424 return ada_opname_table[i].decoded;
14f9c5c9 3425 }
323e0a4a 3426 error (_("Could not find operator name for opcode"));
14f9c5c9
AS
3427}
3428
de93309a
SM
3429/* Returns true (non-zero) iff decoded name N0 should appear before N1
3430 in a listing of choices during disambiguation (see sort_choices, below).
3431 The idea is that overloadings of a subprogram name from the
3432 same package should sort in their source order. We settle for ordering
3433 such symbols by their trailing number (__N or $N). */
14f9c5c9 3434
de93309a
SM
3435static int
3436encoded_ordered_before (const char *N0, const char *N1)
14f9c5c9 3437{
de93309a
SM
3438 if (N1 == NULL)
3439 return 0;
3440 else if (N0 == NULL)
3441 return 1;
3442 else
3443 {
3444 int k0, k1;
30b15541 3445
de93309a 3446 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
dda83cd7 3447 ;
de93309a 3448 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
dda83cd7 3449 ;
de93309a 3450 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
dda83cd7
SM
3451 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3452 {
3453 int n0, n1;
3454
3455 n0 = k0;
3456 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3457 n0 -= 1;
3458 n1 = k1;
3459 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3460 n1 -= 1;
3461 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3462 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3463 }
de93309a
SM
3464 return (strcmp (N0, N1) < 0);
3465 }
14f9c5c9
AS
3466}
3467
de93309a
SM
3468/* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3469 encoded names. */
14f9c5c9 3470
de93309a
SM
3471static void
3472sort_choices (struct block_symbol syms[], int nsyms)
14f9c5c9 3473{
14f9c5c9 3474 int i;
14f9c5c9 3475
de93309a 3476 for (i = 1; i < nsyms; i += 1)
14f9c5c9 3477 {
de93309a
SM
3478 struct block_symbol sym = syms[i];
3479 int j;
3480
3481 for (j = i - 1; j >= 0; j -= 1)
dda83cd7
SM
3482 {
3483 if (encoded_ordered_before (syms[j].symbol->linkage_name (),
3484 sym.symbol->linkage_name ()))
3485 break;
3486 syms[j + 1] = syms[j];
3487 }
de93309a
SM
3488 syms[j + 1] = sym;
3489 }
3490}
14f9c5c9 3491
de93309a
SM
3492/* Whether GDB should display formals and return types for functions in the
3493 overloads selection menu. */
3494static bool print_signatures = true;
4c4b4cd2 3495
de93309a
SM
3496/* Print the signature for SYM on STREAM according to the FLAGS options. For
3497 all but functions, the signature is just the name of the symbol. For
3498 functions, this is the name of the function, the list of types for formals
3499 and the return type (if any). */
4c4b4cd2 3500
de93309a
SM
3501static void
3502ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3503 const struct type_print_options *flags)
3504{
5f9c5a63 3505 struct type *type = sym->type ();
14f9c5c9 3506
6cb06a8c 3507 gdb_printf (stream, "%s", sym->print_name ());
de93309a
SM
3508 if (!print_signatures
3509 || type == NULL
78134374 3510 || type->code () != TYPE_CODE_FUNC)
de93309a 3511 return;
4c4b4cd2 3512
1f704f76 3513 if (type->num_fields () > 0)
de93309a
SM
3514 {
3515 int i;
14f9c5c9 3516
6cb06a8c 3517 gdb_printf (stream, " (");
1f704f76 3518 for (i = 0; i < type->num_fields (); ++i)
de93309a
SM
3519 {
3520 if (i > 0)
6cb06a8c 3521 gdb_printf (stream, "; ");
940da03e 3522 ada_print_type (type->field (i).type (), NULL, stream, -1, 0,
de93309a
SM
3523 flags);
3524 }
6cb06a8c 3525 gdb_printf (stream, ")");
de93309a 3526 }
27710edb
SM
3527 if (type->target_type () != NULL
3528 && type->target_type ()->code () != TYPE_CODE_VOID)
de93309a 3529 {
6cb06a8c 3530 gdb_printf (stream, " return ");
27710edb 3531 ada_print_type (type->target_type (), NULL, stream, -1, 0, flags);
de93309a
SM
3532 }
3533}
14f9c5c9 3534
de93309a
SM
3535/* Read and validate a set of numeric choices from the user in the
3536 range 0 .. N_CHOICES-1. Place the results in increasing
3537 order in CHOICES[0 .. N-1], and return N.
14f9c5c9 3538
de93309a
SM
3539 The user types choices as a sequence of numbers on one line
3540 separated by blanks, encoding them as follows:
14f9c5c9 3541
de93309a
SM
3542 + A choice of 0 means to cancel the selection, throwing an error.
3543 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3544 + The user chooses k by typing k+IS_ALL_CHOICE+1.
14f9c5c9 3545
de93309a 3546 The user is not allowed to choose more than MAX_RESULTS values.
14f9c5c9 3547
de93309a
SM
3548 ANNOTATION_SUFFIX, if present, is used to annotate the input
3549 prompts (for use with the -f switch). */
14f9c5c9 3550
de93309a
SM
3551static int
3552get_selections (int *choices, int n_choices, int max_results,
dda83cd7 3553 int is_all_choice, const char *annotation_suffix)
de93309a 3554{
992a7040 3555 const char *args;
de93309a
SM
3556 const char *prompt;
3557 int n_chosen;
3558 int first_choice = is_all_choice ? 2 : 1;
14f9c5c9 3559
de93309a
SM
3560 prompt = getenv ("PS2");
3561 if (prompt == NULL)
3562 prompt = "> ";
4c4b4cd2 3563
f8631e5e
SM
3564 std::string buffer;
3565 args = command_line_input (buffer, prompt, annotation_suffix);
4c4b4cd2 3566
de93309a
SM
3567 if (args == NULL)
3568 error_no_arg (_("one or more choice numbers"));
14f9c5c9 3569
de93309a 3570 n_chosen = 0;
4c4b4cd2 3571
de93309a
SM
3572 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3573 order, as given in args. Choices are validated. */
3574 while (1)
14f9c5c9 3575 {
de93309a
SM
3576 char *args2;
3577 int choice, j;
76a01679 3578
de93309a
SM
3579 args = skip_spaces (args);
3580 if (*args == '\0' && n_chosen == 0)
dda83cd7 3581 error_no_arg (_("one or more choice numbers"));
de93309a 3582 else if (*args == '\0')
dda83cd7 3583 break;
76a01679 3584
de93309a
SM
3585 choice = strtol (args, &args2, 10);
3586 if (args == args2 || choice < 0
dda83cd7
SM
3587 || choice > n_choices + first_choice - 1)
3588 error (_("Argument must be choice number"));
de93309a 3589 args = args2;
76a01679 3590
de93309a 3591 if (choice == 0)
dda83cd7 3592 error (_("cancelled"));
76a01679 3593
de93309a 3594 if (choice < first_choice)
dda83cd7
SM
3595 {
3596 n_chosen = n_choices;
3597 for (j = 0; j < n_choices; j += 1)
3598 choices[j] = j;
3599 break;
3600 }
de93309a 3601 choice -= first_choice;
76a01679 3602
de93309a 3603 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
dda83cd7
SM
3604 {
3605 }
4c4b4cd2 3606
de93309a 3607 if (j < 0 || choice != choices[j])
dda83cd7
SM
3608 {
3609 int k;
4c4b4cd2 3610
dda83cd7
SM
3611 for (k = n_chosen - 1; k > j; k -= 1)
3612 choices[k + 1] = choices[k];
3613 choices[j + 1] = choice;
3614 n_chosen += 1;
3615 }
14f9c5c9
AS
3616 }
3617
de93309a
SM
3618 if (n_chosen > max_results)
3619 error (_("Select no more than %d of the above"), max_results);
3620
3621 return n_chosen;
14f9c5c9
AS
3622}
3623
de93309a
SM
3624/* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3625 by asking the user (if necessary), returning the number selected,
3626 and setting the first elements of SYMS items. Error if no symbols
3627 selected. */
3628
3629/* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3630 to be re-integrated one of these days. */
14f9c5c9
AS
3631
3632static int
de93309a 3633user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
14f9c5c9 3634{
de93309a
SM
3635 int i;
3636 int *chosen = XALLOCAVEC (int , nsyms);
3637 int n_chosen;
3638 int first_choice = (max_results == 1) ? 1 : 2;
3639 const char *select_mode = multiple_symbols_select_mode ();
14f9c5c9 3640
de93309a
SM
3641 if (max_results < 1)
3642 error (_("Request to select 0 symbols!"));
3643 if (nsyms <= 1)
3644 return nsyms;
14f9c5c9 3645
de93309a
SM
3646 if (select_mode == multiple_symbols_cancel)
3647 error (_("\
3648canceled because the command is ambiguous\n\
3649See set/show multiple-symbol."));
14f9c5c9 3650
de93309a
SM
3651 /* If select_mode is "all", then return all possible symbols.
3652 Only do that if more than one symbol can be selected, of course.
3653 Otherwise, display the menu as usual. */
3654 if (select_mode == multiple_symbols_all && max_results > 1)
3655 return nsyms;
14f9c5c9 3656
6cb06a8c 3657 gdb_printf (_("[0] cancel\n"));
de93309a 3658 if (max_results > 1)
6cb06a8c 3659 gdb_printf (_("[1] all\n"));
14f9c5c9 3660
de93309a 3661 sort_choices (syms, nsyms);
14f9c5c9 3662
de93309a
SM
3663 for (i = 0; i < nsyms; i += 1)
3664 {
3665 if (syms[i].symbol == NULL)
dda83cd7 3666 continue;
14f9c5c9 3667
66d7f48f 3668 if (syms[i].symbol->aclass () == LOC_BLOCK)
dda83cd7
SM
3669 {
3670 struct symtab_and_line sal =
3671 find_function_start_sal (syms[i].symbol, 1);
14f9c5c9 3672
6cb06a8c 3673 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3674 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3675 &type_print_raw_options);
3676 if (sal.symtab == NULL)
6cb06a8c
TT
3677 gdb_printf (_(" at %p[<no source file available>%p]:%d\n"),
3678 metadata_style.style ().ptr (), nullptr, sal.line);
de93309a 3679 else
6cb06a8c 3680 gdb_printf
de93309a
SM
3681 (_(" at %ps:%d\n"),
3682 styled_string (file_name_style.style (),
3683 symtab_to_filename_for_display (sal.symtab)),
3684 sal.line);
dda83cd7
SM
3685 continue;
3686 }
76a01679 3687 else
dda83cd7
SM
3688 {
3689 int is_enumeral =
66d7f48f 3690 (syms[i].symbol->aclass () == LOC_CONST
5f9c5a63
SM
3691 && syms[i].symbol->type () != NULL
3692 && syms[i].symbol->type ()->code () == TYPE_CODE_ENUM);
de93309a 3693 struct symtab *symtab = NULL;
4c4b4cd2 3694
7b3ecc75 3695 if (syms[i].symbol->is_objfile_owned ())
4206d69e 3696 symtab = syms[i].symbol->symtab ();
de93309a 3697
5d0027b9 3698 if (syms[i].symbol->line () != 0 && symtab != NULL)
de93309a 3699 {
6cb06a8c 3700 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3701 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3702 &type_print_raw_options);
6cb06a8c
TT
3703 gdb_printf (_(" at %s:%d\n"),
3704 symtab_to_filename_for_display (symtab),
3705 syms[i].symbol->line ());
de93309a 3706 }
dda83cd7 3707 else if (is_enumeral
5f9c5a63 3708 && syms[i].symbol->type ()->name () != NULL)
dda83cd7 3709 {
6cb06a8c 3710 gdb_printf (("[%d] "), i + first_choice);
5f9c5a63 3711 ada_print_type (syms[i].symbol->type (), NULL,
dda83cd7 3712 gdb_stdout, -1, 0, &type_print_raw_options);
6cb06a8c
TT
3713 gdb_printf (_("'(%s) (enumeral)\n"),
3714 syms[i].symbol->print_name ());
dda83cd7 3715 }
de93309a
SM
3716 else
3717 {
6cb06a8c 3718 gdb_printf ("[%d] ", i + first_choice);
de93309a
SM
3719 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3720 &type_print_raw_options);
3721
3722 if (symtab != NULL)
6cb06a8c
TT
3723 gdb_printf (is_enumeral
3724 ? _(" in %s (enumeral)\n")
3725 : _(" at %s:?\n"),
3726 symtab_to_filename_for_display (symtab));
de93309a 3727 else
6cb06a8c
TT
3728 gdb_printf (is_enumeral
3729 ? _(" (enumeral)\n")
3730 : _(" at ?\n"));
de93309a 3731 }
dda83cd7 3732 }
14f9c5c9 3733 }
14f9c5c9 3734
de93309a 3735 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
dda83cd7 3736 "overload-choice");
14f9c5c9 3737
de93309a
SM
3738 for (i = 0; i < n_chosen; i += 1)
3739 syms[i] = syms[chosen[i]];
14f9c5c9 3740
de93309a
SM
3741 return n_chosen;
3742}
14f9c5c9 3743
cd9a3148
TT
3744/* See ada-lang.h. */
3745
3746block_symbol
7056f312 3747ada_find_operator_symbol (enum exp_opcode op, bool parse_completion,
cd9a3148
TT
3748 int nargs, value *argvec[])
3749{
3750 if (possible_user_operator_p (op, argvec))
3751 {
3752 std::vector<struct block_symbol> candidates
3753 = ada_lookup_symbol_list (ada_decoded_op_name (op),
3754 NULL, VAR_DOMAIN);
3755
3756 int i = ada_resolve_function (candidates, argvec,
3757 nargs, ada_decoded_op_name (op), NULL,
3758 parse_completion);
3759 if (i >= 0)
3760 return candidates[i];
3761 }
3762 return {};
3763}
3764
3765/* See ada-lang.h. */
3766
3767block_symbol
3768ada_resolve_funcall (struct symbol *sym, const struct block *block,
3769 struct type *context_type,
7056f312 3770 bool parse_completion,
cd9a3148
TT
3771 int nargs, value *argvec[],
3772 innermost_block_tracker *tracker)
3773{
3774 std::vector<struct block_symbol> candidates
3775 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3776
3777 int i;
3778 if (candidates.size () == 1)
3779 i = 0;
3780 else
3781 {
3782 i = ada_resolve_function
3783 (candidates,
3784 argvec, nargs,
3785 sym->linkage_name (),
3786 context_type, parse_completion);
3787 if (i < 0)
3788 error (_("Could not find a match for %s"), sym->print_name ());
3789 }
3790
3791 tracker->update (candidates[i]);
3792 return candidates[i];
3793}
3794
ba8694b6
TT
3795/* Resolve a mention of a name where the context type is an
3796 enumeration type. */
3797
3798static int
3799ada_resolve_enum (std::vector<struct block_symbol> &syms,
3800 const char *name, struct type *context_type,
3801 bool parse_completion)
3802{
3803 gdb_assert (context_type->code () == TYPE_CODE_ENUM);
3804 context_type = ada_check_typedef (context_type);
3805
74c36641
TV
3806 /* We already know the name matches, so we're just looking for
3807 an element of the correct enum type. */
3808 struct type *type1 = context_type;
3809 for (int i = 0; i < syms.size (); ++i)
3810 {
3811 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3812 if (type1 == type2)
3813 return i;
3814 }
3815
ba8694b6
TT
3816 for (int i = 0; i < syms.size (); ++i)
3817 {
74c36641
TV
3818 struct type *type2 = ada_check_typedef (syms[i].symbol->type ());
3819 if (type1->num_fields () != type2->num_fields ())
3820 continue;
3821 if (strcmp (type1->name (), type2->name ()) != 0)
3822 continue;
3823 if (ada_identical_enum_types_p (type1, type2))
ba8694b6
TT
3824 return i;
3825 }
3826
3827 error (_("No name '%s' in enumeration type '%s'"), name,
3828 ada_type_name (context_type));
3829}
3830
cd9a3148
TT
3831/* See ada-lang.h. */
3832
3833block_symbol
3834ada_resolve_variable (struct symbol *sym, const struct block *block,
3835 struct type *context_type,
7056f312 3836 bool parse_completion,
cd9a3148
TT
3837 int deprocedure_p,
3838 innermost_block_tracker *tracker)
3839{
3840 std::vector<struct block_symbol> candidates
3841 = ada_lookup_symbol_list (sym->linkage_name (), block, VAR_DOMAIN);
3842
3843 if (std::any_of (candidates.begin (),
3844 candidates.end (),
3845 [] (block_symbol &bsym)
3846 {
66d7f48f 3847 switch (bsym.symbol->aclass ())
cd9a3148
TT
3848 {
3849 case LOC_REGISTER:
3850 case LOC_ARG:
3851 case LOC_REF_ARG:
3852 case LOC_REGPARM_ADDR:
3853 case LOC_LOCAL:
3854 case LOC_COMPUTED:
3855 return true;
3856 default:
3857 return false;
3858 }
3859 }))
3860 {
3861 /* Types tend to get re-introduced locally, so if there
3862 are any local symbols that are not types, first filter
3863 out all types. */
3864 candidates.erase
3865 (std::remove_if
3866 (candidates.begin (),
3867 candidates.end (),
3868 [] (block_symbol &bsym)
3869 {
66d7f48f 3870 return bsym.symbol->aclass () == LOC_TYPEDEF;
cd9a3148
TT
3871 }),
3872 candidates.end ());
3873 }
3874
2c71f639
TV
3875 /* Filter out artificial symbols. */
3876 candidates.erase
3877 (std::remove_if
3878 (candidates.begin (),
3879 candidates.end (),
3880 [] (block_symbol &bsym)
3881 {
496feb16 3882 return bsym.symbol->is_artificial ();
2c71f639
TV
3883 }),
3884 candidates.end ());
3885
cd9a3148
TT
3886 int i;
3887 if (candidates.empty ())
3888 error (_("No definition found for %s"), sym->print_name ());
3889 else if (candidates.size () == 1)
3890 i = 0;
ba8694b6
TT
3891 else if (context_type != nullptr
3892 && context_type->code () == TYPE_CODE_ENUM)
3893 i = ada_resolve_enum (candidates, sym->linkage_name (), context_type,
3894 parse_completion);
ef136c7f
TV
3895 else if (context_type == nullptr
3896 && symbols_are_identical_enums (candidates))
3897 {
3898 /* If all the remaining symbols are identical enumerals, then
3899 just keep the first one and discard the rest.
3900
3901 Unlike what we did previously, we do not discard any entry
3902 unless they are ALL identical. This is because the symbol
3903 comparison is not a strict comparison, but rather a practical
3904 comparison. If all symbols are considered identical, then
3905 we can just go ahead and use the first one and discard the rest.
3906 But if we cannot reduce the list to a single element, we have
3907 to ask the user to disambiguate anyways. And if we have to
3908 present a multiple-choice menu, it's less confusing if the list
3909 isn't missing some choices that were identical and yet distinct. */
3910 candidates.resize (1);
3911 i = 0;
3912 }
cd9a3148
TT
3913 else if (deprocedure_p && !is_nonfunction (candidates))
3914 {
3915 i = ada_resolve_function
3916 (candidates, NULL, 0,
3917 sym->linkage_name (),
3918 context_type, parse_completion);
3919 if (i < 0)
3920 error (_("Could not find a match for %s"), sym->print_name ());
3921 }
3922 else
3923 {
6cb06a8c 3924 gdb_printf (_("Multiple matches for %s\n"), sym->print_name ());
cd9a3148
TT
3925 user_select_syms (candidates.data (), candidates.size (), 1);
3926 i = 0;
3927 }
3928
3929 tracker->update (candidates[i]);
3930 return candidates[i];
3931}
3932
db2534b7 3933/* Return non-zero if formal type FTYPE matches actual type ATYPE. */
de93309a
SM
3934/* The term "match" here is rather loose. The match is heuristic and
3935 liberal. */
14f9c5c9 3936
de93309a 3937static int
db2534b7 3938ada_type_match (struct type *ftype, struct type *atype)
14f9c5c9 3939{
de93309a
SM
3940 ftype = ada_check_typedef (ftype);
3941 atype = ada_check_typedef (atype);
14f9c5c9 3942
78134374 3943 if (ftype->code () == TYPE_CODE_REF)
27710edb 3944 ftype = ftype->target_type ();
78134374 3945 if (atype->code () == TYPE_CODE_REF)
27710edb 3946 atype = atype->target_type ();
14f9c5c9 3947
78134374 3948 switch (ftype->code ())
14f9c5c9 3949 {
de93309a 3950 default:
78134374 3951 return ftype->code () == atype->code ();
de93309a 3952 case TYPE_CODE_PTR:
db2534b7
TT
3953 if (atype->code () != TYPE_CODE_PTR)
3954 return 0;
27710edb 3955 atype = atype->target_type ();
db2534b7 3956 /* This can only happen if the actual argument is 'null'. */
df86565b 3957 if (atype->code () == TYPE_CODE_INT && atype->length () == 0)
db2534b7 3958 return 1;
27710edb 3959 return ada_type_match (ftype->target_type (), atype);
de93309a
SM
3960 case TYPE_CODE_INT:
3961 case TYPE_CODE_ENUM:
3962 case TYPE_CODE_RANGE:
78134374 3963 switch (atype->code ())
dda83cd7
SM
3964 {
3965 case TYPE_CODE_INT:
3966 case TYPE_CODE_ENUM:
3967 case TYPE_CODE_RANGE:
3968 return 1;
3969 default:
3970 return 0;
3971 }
d2e4a39e 3972
de93309a 3973 case TYPE_CODE_ARRAY:
78134374 3974 return (atype->code () == TYPE_CODE_ARRAY
dda83cd7 3975 || ada_is_array_descriptor_type (atype));
14f9c5c9 3976
de93309a
SM
3977 case TYPE_CODE_STRUCT:
3978 if (ada_is_array_descriptor_type (ftype))
dda83cd7
SM
3979 return (atype->code () == TYPE_CODE_ARRAY
3980 || ada_is_array_descriptor_type (atype));
de93309a 3981 else
dda83cd7
SM
3982 return (atype->code () == TYPE_CODE_STRUCT
3983 && !ada_is_array_descriptor_type (atype));
14f9c5c9 3984
de93309a
SM
3985 case TYPE_CODE_UNION:
3986 case TYPE_CODE_FLT:
78134374 3987 return (atype->code () == ftype->code ());
de93309a 3988 }
14f9c5c9
AS
3989}
3990
de93309a
SM
3991/* Return non-zero if the formals of FUNC "sufficiently match" the
3992 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3993 may also be an enumeral, in which case it is treated as a 0-
3994 argument function. */
14f9c5c9 3995
de93309a
SM
3996static int
3997ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3998{
3999 int i;
5f9c5a63 4000 struct type *func_type = func->type ();
14f9c5c9 4001
66d7f48f 4002 if (func->aclass () == LOC_CONST
78134374 4003 && func_type->code () == TYPE_CODE_ENUM)
de93309a 4004 return (n_actuals == 0);
78134374 4005 else if (func_type == NULL || func_type->code () != TYPE_CODE_FUNC)
de93309a 4006 return 0;
14f9c5c9 4007
1f704f76 4008 if (func_type->num_fields () != n_actuals)
de93309a 4009 return 0;
14f9c5c9 4010
de93309a
SM
4011 for (i = 0; i < n_actuals; i += 1)
4012 {
4013 if (actuals[i] == NULL)
dda83cd7 4014 return 0;
de93309a 4015 else
dda83cd7
SM
4016 {
4017 struct type *ftype = ada_check_typedef (func_type->field (i).type ());
d0c97917 4018 struct type *atype = ada_check_typedef (actuals[i]->type ());
14f9c5c9 4019
db2534b7 4020 if (!ada_type_match (ftype, atype))
dda83cd7
SM
4021 return 0;
4022 }
de93309a
SM
4023 }
4024 return 1;
4025}
d2e4a39e 4026
de93309a
SM
4027/* False iff function type FUNC_TYPE definitely does not produce a value
4028 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
4029 FUNC_TYPE is not a valid function type with a non-null return type
4030 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
14f9c5c9 4031
de93309a
SM
4032static int
4033return_match (struct type *func_type, struct type *context_type)
4034{
4035 struct type *return_type;
d2e4a39e 4036
de93309a
SM
4037 if (func_type == NULL)
4038 return 1;
14f9c5c9 4039
78134374 4040 if (func_type->code () == TYPE_CODE_FUNC)
27710edb 4041 return_type = get_base_type (func_type->target_type ());
de93309a
SM
4042 else
4043 return_type = get_base_type (func_type);
4044 if (return_type == NULL)
4045 return 1;
76a01679 4046
de93309a 4047 context_type = get_base_type (context_type);
14f9c5c9 4048
78134374 4049 if (return_type->code () == TYPE_CODE_ENUM)
de93309a
SM
4050 return context_type == NULL || return_type == context_type;
4051 else if (context_type == NULL)
78134374 4052 return return_type->code () != TYPE_CODE_VOID;
de93309a 4053 else
78134374 4054 return return_type->code () == context_type->code ();
de93309a 4055}
14f9c5c9 4056
14f9c5c9 4057
1bfa81ac 4058/* Returns the index in SYMS that contains the symbol for the
de93309a
SM
4059 function (if any) that matches the types of the NARGS arguments in
4060 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
4061 that returns that type, then eliminate matches that don't. If
4062 CONTEXT_TYPE is void and there is at least one match that does not
4063 return void, eliminate all matches that do.
14f9c5c9 4064
de93309a
SM
4065 Asks the user if there is more than one match remaining. Returns -1
4066 if there is no such symbol or none is selected. NAME is used
4067 solely for messages. May re-arrange and modify SYMS in
4068 the process; the index returned is for the modified vector. */
14f9c5c9 4069
de93309a 4070static int
d1183b06
TT
4071ada_resolve_function (std::vector<struct block_symbol> &syms,
4072 struct value **args, int nargs,
dda83cd7 4073 const char *name, struct type *context_type,
7056f312 4074 bool parse_completion)
de93309a
SM
4075{
4076 int fallback;
4077 int k;
4078 int m; /* Number of hits */
14f9c5c9 4079
de93309a
SM
4080 m = 0;
4081 /* In the first pass of the loop, we only accept functions matching
4082 context_type. If none are found, we add a second pass of the loop
4083 where every function is accepted. */
4084 for (fallback = 0; m == 0 && fallback < 2; fallback++)
4085 {
d1183b06 4086 for (k = 0; k < syms.size (); k += 1)
dda83cd7 4087 {
5f9c5a63 4088 struct type *type = ada_check_typedef (syms[k].symbol->type ());
5b4ee69b 4089
dda83cd7
SM
4090 if (ada_args_match (syms[k].symbol, args, nargs)
4091 && (fallback || return_match (type, context_type)))
4092 {
4093 syms[m] = syms[k];
4094 m += 1;
4095 }
4096 }
14f9c5c9
AS
4097 }
4098
de93309a
SM
4099 /* If we got multiple matches, ask the user which one to use. Don't do this
4100 interactive thing during completion, though, as the purpose of the
4101 completion is providing a list of all possible matches. Prompting the
4102 user to filter it down would be completely unexpected in this case. */
4103 if (m == 0)
4104 return -1;
4105 else if (m > 1 && !parse_completion)
4106 {
6cb06a8c 4107 gdb_printf (_("Multiple matches for %s\n"), name);
d1183b06 4108 user_select_syms (syms.data (), m, 1);
de93309a
SM
4109 return 0;
4110 }
4111 return 0;
14f9c5c9
AS
4112}
4113
14f9c5c9
AS
4114/* Type-class predicates */
4115
4c4b4cd2
PH
4116/* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4117 or FLOAT). */
14f9c5c9
AS
4118
4119static int
d2e4a39e 4120numeric_type_p (struct type *type)
14f9c5c9
AS
4121{
4122 if (type == NULL)
4123 return 0;
d2e4a39e
AS
4124 else
4125 {
78134374 4126 switch (type->code ())
dda83cd7
SM
4127 {
4128 case TYPE_CODE_INT:
4129 case TYPE_CODE_FLT:
c04da66c 4130 case TYPE_CODE_FIXED_POINT:
dda83cd7
SM
4131 return 1;
4132 case TYPE_CODE_RANGE:
27710edb
SM
4133 return (type == type->target_type ()
4134 || numeric_type_p (type->target_type ()));
dda83cd7
SM
4135 default:
4136 return 0;
4137 }
d2e4a39e 4138 }
14f9c5c9
AS
4139}
4140
4c4b4cd2 4141/* True iff TYPE is integral (an INT or RANGE of INTs). */
14f9c5c9
AS
4142
4143static int
d2e4a39e 4144integer_type_p (struct type *type)
14f9c5c9
AS
4145{
4146 if (type == NULL)
4147 return 0;
d2e4a39e
AS
4148 else
4149 {
78134374 4150 switch (type->code ())
dda83cd7
SM
4151 {
4152 case TYPE_CODE_INT:
4153 return 1;
4154 case TYPE_CODE_RANGE:
27710edb
SM
4155 return (type == type->target_type ()
4156 || integer_type_p (type->target_type ()));
dda83cd7
SM
4157 default:
4158 return 0;
4159 }
d2e4a39e 4160 }
14f9c5c9
AS
4161}
4162
4c4b4cd2 4163/* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
14f9c5c9
AS
4164
4165static int
d2e4a39e 4166scalar_type_p (struct type *type)
14f9c5c9
AS
4167{
4168 if (type == NULL)
4169 return 0;
d2e4a39e
AS
4170 else
4171 {
78134374 4172 switch (type->code ())
dda83cd7
SM
4173 {
4174 case TYPE_CODE_INT:
4175 case TYPE_CODE_RANGE:
4176 case TYPE_CODE_ENUM:
4177 case TYPE_CODE_FLT:
c04da66c 4178 case TYPE_CODE_FIXED_POINT:
dda83cd7
SM
4179 return 1;
4180 default:
4181 return 0;
4182 }
d2e4a39e 4183 }
14f9c5c9
AS
4184}
4185
98847c1e
TT
4186/* True iff TYPE is discrete, as defined in the Ada Reference Manual.
4187 This essentially means one of (INT, RANGE, ENUM) -- but note that
4188 "enum" includes character and boolean as well. */
14f9c5c9
AS
4189
4190static int
d2e4a39e 4191discrete_type_p (struct type *type)
14f9c5c9
AS
4192{
4193 if (type == NULL)
4194 return 0;
d2e4a39e
AS
4195 else
4196 {
78134374 4197 switch (type->code ())
dda83cd7
SM
4198 {
4199 case TYPE_CODE_INT:
4200 case TYPE_CODE_RANGE:
4201 case TYPE_CODE_ENUM:
4202 case TYPE_CODE_BOOL:
98847c1e 4203 case TYPE_CODE_CHAR:
dda83cd7
SM
4204 return 1;
4205 default:
4206 return 0;
4207 }
d2e4a39e 4208 }
14f9c5c9
AS
4209}
4210
4c4b4cd2
PH
4211/* Returns non-zero if OP with operands in the vector ARGS could be
4212 a user-defined function. Errs on the side of pre-defined operators
4213 (i.e., result 0). */
14f9c5c9
AS
4214
4215static int
d2e4a39e 4216possible_user_operator_p (enum exp_opcode op, struct value *args[])
14f9c5c9 4217{
76a01679 4218 struct type *type0 =
d0c97917 4219 (args[0] == NULL) ? NULL : ada_check_typedef (args[0]->type ());
d2e4a39e 4220 struct type *type1 =
d0c97917 4221 (args[1] == NULL) ? NULL : ada_check_typedef (args[1]->type ());
d2e4a39e 4222
4c4b4cd2
PH
4223 if (type0 == NULL)
4224 return 0;
4225
14f9c5c9
AS
4226 switch (op)
4227 {
4228 default:
4229 return 0;
4230
4231 case BINOP_ADD:
4232 case BINOP_SUB:
4233 case BINOP_MUL:
4234 case BINOP_DIV:
d2e4a39e 4235 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
14f9c5c9
AS
4236
4237 case BINOP_REM:
4238 case BINOP_MOD:
4239 case BINOP_BITWISE_AND:
4240 case BINOP_BITWISE_IOR:
4241 case BINOP_BITWISE_XOR:
d2e4a39e 4242 return (!(integer_type_p (type0) && integer_type_p (type1)));
14f9c5c9
AS
4243
4244 case BINOP_EQUAL:
4245 case BINOP_NOTEQUAL:
4246 case BINOP_LESS:
4247 case BINOP_GTR:
4248 case BINOP_LEQ:
4249 case BINOP_GEQ:
d2e4a39e 4250 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
14f9c5c9
AS
4251
4252 case BINOP_CONCAT:
ee90b9ab 4253 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
14f9c5c9
AS
4254
4255 case BINOP_EXP:
d2e4a39e 4256 return (!(numeric_type_p (type0) && integer_type_p (type1)));
14f9c5c9
AS
4257
4258 case UNOP_NEG:
4259 case UNOP_PLUS:
4260 case UNOP_LOGICAL_NOT:
d2e4a39e
AS
4261 case UNOP_ABS:
4262 return (!numeric_type_p (type0));
14f9c5c9
AS
4263
4264 }
4265}
4266\f
dda83cd7 4267 /* Renaming */
14f9c5c9 4268
aeb5907d
JB
4269/* NOTES:
4270
4271 1. In the following, we assume that a renaming type's name may
4272 have an ___XD suffix. It would be nice if this went away at some
4273 point.
4274 2. We handle both the (old) purely type-based representation of
4275 renamings and the (new) variable-based encoding. At some point,
4276 it is devoutly to be hoped that the former goes away
4277 (FIXME: hilfinger-2007-07-09).
4278 3. Subprogram renamings are not implemented, although the XRS
4279 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4280
4281/* If SYM encodes a renaming,
4282
4283 <renaming> renames <renamed entity>,
4284
4285 sets *LEN to the length of the renamed entity's name,
4286 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4287 the string describing the subcomponent selected from the renamed
0963b4bd 4288 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
aeb5907d
JB
4289 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4290 are undefined). Otherwise, returns a value indicating the category
4291 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4292 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4293 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4294 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4295 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4296 may be NULL, in which case they are not assigned.
4297
4298 [Currently, however, GCC does not generate subprogram renamings.] */
4299
4300enum ada_renaming_category
4301ada_parse_renaming (struct symbol *sym,
4302 const char **renamed_entity, int *len,
4303 const char **renaming_expr)
4304{
4305 enum ada_renaming_category kind;
4306 const char *info;
4307 const char *suffix;
4308
4309 if (sym == NULL)
4310 return ADA_NOT_RENAMING;
66d7f48f 4311 switch (sym->aclass ())
14f9c5c9 4312 {
aeb5907d
JB
4313 default:
4314 return ADA_NOT_RENAMING;
aeb5907d
JB
4315 case LOC_LOCAL:
4316 case LOC_STATIC:
4317 case LOC_COMPUTED:
4318 case LOC_OPTIMIZED_OUT:
987012b8 4319 info = strstr (sym->linkage_name (), "___XR");
aeb5907d
JB
4320 if (info == NULL)
4321 return ADA_NOT_RENAMING;
4322 switch (info[5])
4323 {
4324 case '_':
4325 kind = ADA_OBJECT_RENAMING;
4326 info += 6;
4327 break;
4328 case 'E':
4329 kind = ADA_EXCEPTION_RENAMING;
4330 info += 7;
4331 break;
4332 case 'P':
4333 kind = ADA_PACKAGE_RENAMING;
4334 info += 7;
4335 break;
4336 case 'S':
4337 kind = ADA_SUBPROGRAM_RENAMING;
4338 info += 7;
4339 break;
4340 default:
4341 return ADA_NOT_RENAMING;
4342 }
14f9c5c9 4343 }
4c4b4cd2 4344
de93309a
SM
4345 if (renamed_entity != NULL)
4346 *renamed_entity = info;
4347 suffix = strstr (info, "___XE");
4348 if (suffix == NULL || suffix == info)
4349 return ADA_NOT_RENAMING;
4350 if (len != NULL)
4351 *len = strlen (info) - strlen (suffix);
4352 suffix += 5;
4353 if (renaming_expr != NULL)
4354 *renaming_expr = suffix;
4355 return kind;
4356}
4357
4358/* Compute the value of the given RENAMING_SYM, which is expected to
4359 be a symbol encoding a renaming expression. BLOCK is the block
4360 used to evaluate the renaming. */
4361
4362static struct value *
4363ada_read_renaming_var_value (struct symbol *renaming_sym,
4364 const struct block *block)
4365{
4366 const char *sym_name;
4367
987012b8 4368 sym_name = renaming_sym->linkage_name ();
de93309a 4369 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
43048e46 4370 return expr->evaluate ();
de93309a
SM
4371}
4372\f
4373
dda83cd7 4374 /* Evaluation: Function Calls */
de93309a
SM
4375
4376/* Return an lvalue containing the value VAL. This is the identity on
4377 lvalues, and otherwise has the side-effect of allocating memory
4378 in the inferior where a copy of the value contents is copied. */
4379
4380static struct value *
4381ensure_lval (struct value *val)
4382{
736355f2
TT
4383 if (val->lval () == not_lval
4384 || val->lval () == lval_internalvar)
de93309a 4385 {
d0c97917 4386 int len = ada_check_typedef (val->type ())->length ();
de93309a 4387 const CORE_ADDR addr =
dda83cd7 4388 value_as_long (value_allocate_space_in_inferior (len));
de93309a 4389
6f9c9d71 4390 val->set_lval (lval_memory);
9feb2d07 4391 val->set_address (addr);
efaf1ae0 4392 write_memory (addr, val->contents ().data (), len);
de93309a
SM
4393 }
4394
4395 return val;
4396}
4397
4398/* Given ARG, a value of type (pointer or reference to a)*
4399 structure/union, extract the component named NAME from the ultimate
4400 target structure/union and return it as a value with its
4401 appropriate type.
4402
4403 The routine searches for NAME among all members of the structure itself
4404 and (recursively) among all members of any wrapper members
4405 (e.g., '_parent').
4406
4407 If NO_ERR, then simply return NULL in case of error, rather than
4408 calling error. */
4409
4410static struct value *
4411ada_value_struct_elt (struct value *arg, const char *name, int no_err)
4412{
4413 struct type *t, *t1;
4414 struct value *v;
4415 int check_tag;
4416
4417 v = NULL;
d0c97917 4418 t1 = t = ada_check_typedef (arg->type ());
78134374 4419 if (t->code () == TYPE_CODE_REF)
de93309a 4420 {
27710edb 4421 t1 = t->target_type ();
de93309a
SM
4422 if (t1 == NULL)
4423 goto BadValue;
4424 t1 = ada_check_typedef (t1);
78134374 4425 if (t1->code () == TYPE_CODE_PTR)
dda83cd7
SM
4426 {
4427 arg = coerce_ref (arg);
4428 t = t1;
4429 }
de93309a
SM
4430 }
4431
78134374 4432 while (t->code () == TYPE_CODE_PTR)
de93309a 4433 {
27710edb 4434 t1 = t->target_type ();
de93309a
SM
4435 if (t1 == NULL)
4436 goto BadValue;
4437 t1 = ada_check_typedef (t1);
78134374 4438 if (t1->code () == TYPE_CODE_PTR)
dda83cd7
SM
4439 {
4440 arg = value_ind (arg);
4441 t = t1;
4442 }
de93309a 4443 else
dda83cd7 4444 break;
de93309a 4445 }
aeb5907d 4446
78134374 4447 if (t1->code () != TYPE_CODE_STRUCT && t1->code () != TYPE_CODE_UNION)
de93309a 4448 goto BadValue;
52ce6436 4449
de93309a
SM
4450 if (t1 == t)
4451 v = ada_search_struct_field (name, arg, 0, t);
4452 else
4453 {
4454 int bit_offset, bit_size, byte_offset;
4455 struct type *field_type;
4456 CORE_ADDR address;
a5ee536b 4457
78134374 4458 if (t->code () == TYPE_CODE_PTR)
9feb2d07 4459 address = ada_value_ind (arg)->address ();
de93309a 4460 else
9feb2d07 4461 address = ada_coerce_ref (arg)->address ();
d2e4a39e 4462
de93309a 4463 /* Check to see if this is a tagged type. We also need to handle
dda83cd7
SM
4464 the case where the type is a reference to a tagged type, but
4465 we have to be careful to exclude pointers to tagged types.
4466 The latter should be shown as usual (as a pointer), whereas
4467 a reference should mostly be transparent to the user. */
14f9c5c9 4468
de93309a 4469 if (ada_is_tagged_type (t1, 0)
dda83cd7 4470 || (t1->code () == TYPE_CODE_REF
27710edb 4471 && ada_is_tagged_type (t1->target_type (), 0)))
dda83cd7
SM
4472 {
4473 /* We first try to find the searched field in the current type.
de93309a 4474 If not found then let's look in the fixed type. */
14f9c5c9 4475
dda83cd7 4476 if (!find_struct_field (name, t1, 0,
4d1795ac
TT
4477 nullptr, nullptr, nullptr,
4478 nullptr, nullptr))
de93309a
SM
4479 check_tag = 1;
4480 else
4481 check_tag = 0;
dda83cd7 4482 }
de93309a
SM
4483 else
4484 check_tag = 0;
c3e5cd34 4485
de93309a
SM
4486 /* Convert to fixed type in all cases, so that we have proper
4487 offsets to each field in unconstrained record types. */
4488 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
4489 address, NULL, check_tag);
4490
24aa1b02
TT
4491 /* Resolve the dynamic type as well. */
4492 arg = value_from_contents_and_address (t1, nullptr, address);
d0c97917 4493 t1 = arg->type ();
24aa1b02 4494
de93309a 4495 if (find_struct_field (name, t1, 0,
dda83cd7
SM
4496 &field_type, &byte_offset, &bit_offset,
4497 &bit_size, NULL))
4498 {
4499 if (bit_size != 0)
4500 {
4501 if (t->code () == TYPE_CODE_REF)
4502 arg = ada_coerce_ref (arg);
4503 else
4504 arg = ada_value_ind (arg);
4505 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
4506 bit_offset, bit_size,
4507 field_type);
4508 }
4509 else
4510 v = value_at_lazy (field_type, address + byte_offset);
4511 }
c3e5cd34 4512 }
14f9c5c9 4513
de93309a
SM
4514 if (v != NULL || no_err)
4515 return v;
4516 else
4517 error (_("There is no member named %s."), name);
4518
4519 BadValue:
4520 if (no_err)
4521 return NULL;
4522 else
4523 error (_("Attempt to extract a component of "
4524 "a value that is not a record."));
14f9c5c9
AS
4525}
4526
4527/* Return the value ACTUAL, converted to be an appropriate value for a
4528 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4529 allocating any necessary descriptors (fat pointers), or copies of
4c4b4cd2 4530 values not residing in memory, updating it as needed. */
14f9c5c9 4531
a93c0eb6 4532struct value *
40bc484c 4533ada_convert_actual (struct value *actual, struct type *formal_type0)
14f9c5c9 4534{
d0c97917 4535 struct type *actual_type = ada_check_typedef (actual->type ());
61ee279c 4536 struct type *formal_type = ada_check_typedef (formal_type0);
d2e4a39e 4537 struct type *formal_target =
78134374 4538 formal_type->code () == TYPE_CODE_PTR
27710edb 4539 ? ada_check_typedef (formal_type->target_type ()) : formal_type;
d2e4a39e 4540 struct type *actual_target =
78134374 4541 actual_type->code () == TYPE_CODE_PTR
27710edb 4542 ? ada_check_typedef (actual_type->target_type ()) : actual_type;
14f9c5c9 4543
4c4b4cd2 4544 if (ada_is_array_descriptor_type (formal_target)
78134374 4545 && actual_target->code () == TYPE_CODE_ARRAY)
40bc484c 4546 return make_array_descriptor (formal_type, actual);
78134374
SM
4547 else if (formal_type->code () == TYPE_CODE_PTR
4548 || formal_type->code () == TYPE_CODE_REF)
14f9c5c9 4549 {
a84a8a0d 4550 struct value *result;
5b4ee69b 4551
78134374 4552 if (formal_target->code () == TYPE_CODE_ARRAY
dda83cd7 4553 && ada_is_array_descriptor_type (actual_target))
a84a8a0d 4554 result = desc_data (actual);
78134374 4555 else if (formal_type->code () != TYPE_CODE_PTR)
dda83cd7 4556 {
736355f2 4557 if (actual->lval () != lval_memory)
dda83cd7
SM
4558 {
4559 struct value *val;
4560
d0c97917 4561 actual_type = ada_check_typedef (actual->type ());
317c3ed9 4562 val = value::allocate (actual_type);
efaf1ae0 4563 copy (actual->contents (), val->contents_raw ());
dda83cd7
SM
4564 actual = ensure_lval (val);
4565 }
4566 result = value_addr (actual);
4567 }
a84a8a0d
JB
4568 else
4569 return actual;
b1af9e97 4570 return value_cast_pointers (formal_type, result, 0);
14f9c5c9 4571 }
78134374 4572 else if (actual_type->code () == TYPE_CODE_PTR)
14f9c5c9 4573 return ada_value_ind (actual);
8344af1e
JB
4574 else if (ada_is_aligner_type (formal_type))
4575 {
4576 /* We need to turn this parameter into an aligner type
4577 as well. */
317c3ed9 4578 struct value *aligner = value::allocate (formal_type);
8344af1e
JB
4579 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4580
4581 value_assign_to_component (aligner, component, actual);
4582 return aligner;
4583 }
14f9c5c9
AS
4584
4585 return actual;
4586}
4587
438c98a1
JB
4588/* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4589 type TYPE. This is usually an inefficient no-op except on some targets
4590 (such as AVR) where the representation of a pointer and an address
4591 differs. */
4592
4593static CORE_ADDR
4594value_pointer (struct value *value, struct type *type)
4595{
df86565b 4596 unsigned len = type->length ();
224c3ddb 4597 gdb_byte *buf = (gdb_byte *) alloca (len);
438c98a1
JB
4598 CORE_ADDR addr;
4599
9feb2d07 4600 addr = value->address ();
8ee511af 4601 gdbarch_address_to_pointer (type->arch (), type, buf, addr);
34877895 4602 addr = extract_unsigned_integer (buf, len, type_byte_order (type));
438c98a1
JB
4603 return addr;
4604}
4605
14f9c5c9 4606
4c4b4cd2
PH
4607/* Push a descriptor of type TYPE for array value ARR on the stack at
4608 *SP, updating *SP to reflect the new descriptor. Return either
14f9c5c9 4609 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4c4b4cd2
PH
4610 to-descriptor type rather than a descriptor type), a struct value *
4611 representing a pointer to this descriptor. */
14f9c5c9 4612
d2e4a39e 4613static struct value *
40bc484c 4614make_array_descriptor (struct type *type, struct value *arr)
14f9c5c9 4615{
d2e4a39e
AS
4616 struct type *bounds_type = desc_bounds_type (type);
4617 struct type *desc_type = desc_base_type (type);
317c3ed9
TT
4618 struct value *descriptor = value::allocate (desc_type);
4619 struct value *bounds = value::allocate (bounds_type);
14f9c5c9 4620 int i;
d2e4a39e 4621
d0c97917 4622 for (i = ada_array_arity (ada_check_typedef (arr->type ()));
0963b4bd 4623 i > 0; i -= 1)
14f9c5c9 4624 {
d0c97917 4625 modify_field (bounds->type (),
bbe912ba 4626 bounds->contents_writeable ().data (),
19f220c3
JK
4627 ada_array_bound (arr, i, 0),
4628 desc_bound_bitpos (bounds_type, i, 0),
4629 desc_bound_bitsize (bounds_type, i, 0));
d0c97917 4630 modify_field (bounds->type (),
bbe912ba 4631 bounds->contents_writeable ().data (),
19f220c3
JK
4632 ada_array_bound (arr, i, 1),
4633 desc_bound_bitpos (bounds_type, i, 1),
4634 desc_bound_bitsize (bounds_type, i, 1));
14f9c5c9 4635 }
d2e4a39e 4636
40bc484c 4637 bounds = ensure_lval (bounds);
d2e4a39e 4638
d0c97917 4639 modify_field (descriptor->type (),
bbe912ba 4640 descriptor->contents_writeable ().data (),
19f220c3 4641 value_pointer (ensure_lval (arr),
940da03e 4642 desc_type->field (0).type ()),
19f220c3
JK
4643 fat_pntr_data_bitpos (desc_type),
4644 fat_pntr_data_bitsize (desc_type));
4645
d0c97917 4646 modify_field (descriptor->type (),
bbe912ba 4647 descriptor->contents_writeable ().data (),
19f220c3 4648 value_pointer (bounds,
940da03e 4649 desc_type->field (1).type ()),
19f220c3
JK
4650 fat_pntr_bounds_bitpos (desc_type),
4651 fat_pntr_bounds_bitsize (desc_type));
14f9c5c9 4652
40bc484c 4653 descriptor = ensure_lval (descriptor);
14f9c5c9 4654
78134374 4655 if (type->code () == TYPE_CODE_PTR)
14f9c5c9
AS
4656 return value_addr (descriptor);
4657 else
4658 return descriptor;
4659}
14f9c5c9 4660\f
dda83cd7 4661 /* Symbol Cache Module */
3d9434b5 4662
3d9434b5 4663/* Performance measurements made as of 2010-01-15 indicate that
ee01b665 4664 this cache does bring some noticeable improvements. Depending
3d9434b5
JB
4665 on the type of entity being printed, the cache can make it as much
4666 as an order of magnitude faster than without it.
4667
4668 The descriptive type DWARF extension has significantly reduced
4669 the need for this cache, at least when DWARF is being used. However,
4670 even in this case, some expensive name-based symbol searches are still
4671 sometimes necessary - to find an XVZ variable, mostly. */
4672
3d9434b5
JB
4673/* Clear all entries from the symbol cache. */
4674
4675static void
6114d650 4676ada_clear_symbol_cache (program_space *pspace)
3d9434b5 4677{
6114d650 4678 ada_pspace_data_handle.clear (pspace);
3d9434b5
JB
4679}
4680
fe978cb0 4681/* Search the symbol cache for an entry matching NAME and DOMAIN.
3d9434b5
JB
4682 Return 1 if found, 0 otherwise.
4683
4684 If an entry was found and SYM is not NULL, set *SYM to the entry's
4685 SYM. Same principle for BLOCK if not NULL. */
96d887e8 4686
96d887e8 4687static int
fe978cb0 4688lookup_cached_symbol (const char *name, domain_enum domain,
dda83cd7 4689 struct symbol **sym, const struct block **block)
96d887e8 4690{
9d1c303d
TT
4691 htab_t tab = get_ada_pspace_data (current_program_space);
4692 cache_entry_search search;
4693 search.name = name;
4694 search.domain = domain;
3d9434b5 4695
9d1c303d
TT
4696 cache_entry *e = (cache_entry *) htab_find_with_hash (tab, &search,
4697 search.hash ());
4698 if (e == nullptr)
3d9434b5 4699 return 0;
9d1c303d
TT
4700 if (sym != nullptr)
4701 *sym = e->sym;
4702 if (block != nullptr)
4703 *block = e->block;
3d9434b5 4704 return 1;
96d887e8
PH
4705}
4706
3d9434b5 4707/* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
fe978cb0 4708 in domain DOMAIN, save this result in our symbol cache. */
3d9434b5 4709
96d887e8 4710static void
fe978cb0 4711cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
dda83cd7 4712 const struct block *block)
96d887e8 4713{
1994afbf
DE
4714 /* Symbols for builtin types don't have a block.
4715 For now don't cache such symbols. */
7b3ecc75 4716 if (sym != NULL && !sym->is_objfile_owned ())
1994afbf
DE
4717 return;
4718
3d9434b5
JB
4719 /* If the symbol is a local symbol, then do not cache it, as a search
4720 for that symbol depends on the context. To determine whether
4721 the symbol is local or not, we check the block where we found it
4722 against the global and static blocks of its associated symtab. */
63d609de
SM
4723 if (sym != nullptr)
4724 {
4725 const blockvector &bv = *sym->symtab ()->compunit ()->blockvector ();
4726
4727 if (bv.global_block () != block && bv.static_block () != block)
4728 return;
4729 }
3d9434b5 4730
9d1c303d
TT
4731 htab_t tab = get_ada_pspace_data (current_program_space);
4732 cache_entry_search search;
4733 search.name = name;
4734 search.domain = domain;
4735
4736 void **slot = htab_find_slot_with_hash (tab, &search,
4737 search.hash (), INSERT);
4738
4739 cache_entry *e = new cache_entry;
4740 e->name = name;
fe978cb0 4741 e->domain = domain;
9d1c303d 4742 e->sym = sym;
3d9434b5 4743 e->block = block;
9d1c303d
TT
4744
4745 *slot = e;
96d887e8 4746}
4c4b4cd2 4747\f
dda83cd7 4748 /* Symbol Lookup */
4c4b4cd2 4749
b5ec771e
PA
4750/* Return the symbol name match type that should be used used when
4751 searching for all symbols matching LOOKUP_NAME.
c0431670
JB
4752
4753 LOOKUP_NAME is expected to be a symbol name after transformation
f98b2e33 4754 for Ada lookups. */
c0431670 4755
b5ec771e
PA
4756static symbol_name_match_type
4757name_match_type_from_name (const char *lookup_name)
c0431670 4758{
b5ec771e
PA
4759 return (strstr (lookup_name, "__") == NULL
4760 ? symbol_name_match_type::WILD
4761 : symbol_name_match_type::FULL);
c0431670
JB
4762}
4763
4c4b4cd2
PH
4764/* Return the result of a standard (literal, C-like) lookup of NAME in
4765 given DOMAIN, visible from lexical block BLOCK. */
4766
4767static struct symbol *
4768standard_lookup (const char *name, const struct block *block,
dda83cd7 4769 domain_enum domain)
4c4b4cd2 4770{
acbd605d 4771 /* Initialize it just to avoid a GCC false warning. */
6640a367 4772 struct block_symbol sym = {};
4c4b4cd2 4773
d12307c1
PMR
4774 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4775 return sym.symbol;
a2cd4f14 4776 ada_lookup_encoded_symbol (name, block, domain, &sym);
d12307c1
PMR
4777 cache_symbol (name, domain, sym.symbol, sym.block);
4778 return sym.symbol;
4c4b4cd2
PH
4779}
4780
4781
4782/* Non-zero iff there is at least one non-function/non-enumeral symbol
1bfa81ac 4783 in the symbol fields of SYMS. We treat enumerals as functions,
4c4b4cd2
PH
4784 since they contend in overloading in the same way. */
4785static int
d1183b06 4786is_nonfunction (const std::vector<struct block_symbol> &syms)
4c4b4cd2 4787{
d1183b06 4788 for (const block_symbol &sym : syms)
5f9c5a63
SM
4789 if (sym.symbol->type ()->code () != TYPE_CODE_FUNC
4790 && (sym.symbol->type ()->code () != TYPE_CODE_ENUM
66d7f48f 4791 || sym.symbol->aclass () != LOC_CONST))
14f9c5c9
AS
4792 return 1;
4793
4794 return 0;
4795}
4796
4797/* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4c4b4cd2 4798 struct types. Otherwise, they may not. */
14f9c5c9
AS
4799
4800static int
d2e4a39e 4801equiv_types (struct type *type0, struct type *type1)
14f9c5c9 4802{
d2e4a39e 4803 if (type0 == type1)
14f9c5c9 4804 return 1;
d2e4a39e 4805 if (type0 == NULL || type1 == NULL
78134374 4806 || type0->code () != type1->code ())
14f9c5c9 4807 return 0;
78134374
SM
4808 if ((type0->code () == TYPE_CODE_STRUCT
4809 || type0->code () == TYPE_CODE_ENUM)
14f9c5c9 4810 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4c4b4cd2 4811 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
14f9c5c9 4812 return 1;
d2e4a39e 4813
14f9c5c9
AS
4814 return 0;
4815}
4816
4817/* True iff SYM0 represents the same entity as SYM1, or one that is
4c4b4cd2 4818 no more defined than that of SYM1. */
14f9c5c9
AS
4819
4820static int
d2e4a39e 4821lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
14f9c5c9
AS
4822{
4823 if (sym0 == sym1)
4824 return 1;
6c9c307c 4825 if (sym0->domain () != sym1->domain ()
66d7f48f 4826 || sym0->aclass () != sym1->aclass ())
14f9c5c9
AS
4827 return 0;
4828
66d7f48f 4829 switch (sym0->aclass ())
14f9c5c9
AS
4830 {
4831 case LOC_UNDEF:
4832 return 1;
4833 case LOC_TYPEDEF:
4834 {
5f9c5a63
SM
4835 struct type *type0 = sym0->type ();
4836 struct type *type1 = sym1->type ();
dda83cd7
SM
4837 const char *name0 = sym0->linkage_name ();
4838 const char *name1 = sym1->linkage_name ();
4839 int len0 = strlen (name0);
4840
4841 return
4842 type0->code () == type1->code ()
4843 && (equiv_types (type0, type1)
4844 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4845 && startswith (name1 + len0, "___XV")));
14f9c5c9
AS
4846 }
4847 case LOC_CONST:
4aeddc50 4848 return sym0->value_longest () == sym1->value_longest ()
5f9c5a63 4849 && equiv_types (sym0->type (), sym1->type ());
4b610737
TT
4850
4851 case LOC_STATIC:
4852 {
dda83cd7
SM
4853 const char *name0 = sym0->linkage_name ();
4854 const char *name1 = sym1->linkage_name ();
4855 return (strcmp (name0, name1) == 0
4aeddc50 4856 && sym0->value_address () == sym1->value_address ());
4b610737
TT
4857 }
4858
d2e4a39e
AS
4859 default:
4860 return 0;
14f9c5c9
AS
4861 }
4862}
4863
d1183b06
TT
4864/* Append (SYM,BLOCK) to the end of the array of struct block_symbol
4865 records in RESULT. Do nothing if SYM is a duplicate. */
14f9c5c9
AS
4866
4867static void
d1183b06 4868add_defn_to_vec (std::vector<struct block_symbol> &result,
dda83cd7
SM
4869 struct symbol *sym,
4870 const struct block *block)
14f9c5c9 4871{
529cad9c
PH
4872 /* Do not try to complete stub types, as the debugger is probably
4873 already scanning all symbols matching a certain name at the
4874 time when this function is called. Trying to replace the stub
4875 type by its associated full type will cause us to restart a scan
4876 which may lead to an infinite recursion. Instead, the client
4877 collecting the matching symbols will end up collecting several
4878 matches, with at least one of them complete. It can then filter
4879 out the stub ones if needed. */
4880
d1183b06 4881 for (int i = result.size () - 1; i >= 0; i -= 1)
4c4b4cd2 4882 {
d1183b06 4883 if (lesseq_defined_than (sym, result[i].symbol))
dda83cd7 4884 return;
d1183b06 4885 else if (lesseq_defined_than (result[i].symbol, sym))
dda83cd7 4886 {
d1183b06
TT
4887 result[i].symbol = sym;
4888 result[i].block = block;
dda83cd7
SM
4889 return;
4890 }
4c4b4cd2
PH
4891 }
4892
d1183b06
TT
4893 struct block_symbol info;
4894 info.symbol = sym;
4895 info.block = block;
4896 result.push_back (info);
4c4b4cd2
PH
4897}
4898
7c7b6655
TT
4899/* Return a bound minimal symbol matching NAME according to Ada
4900 decoding rules. Returns an invalid symbol if there is no such
4901 minimal symbol. Names prefixed with "standard__" are handled
4902 specially: "standard__" is first stripped off, and only static and
4903 global symbols are searched. */
4c4b4cd2 4904
7c7b6655 4905struct bound_minimal_symbol
06a670e2 4906ada_lookup_simple_minsym (const char *name, struct objfile *objfile)
4c4b4cd2 4907{
7c7b6655 4908 struct bound_minimal_symbol result;
4c4b4cd2 4909
b5ec771e
PA
4910 symbol_name_match_type match_type = name_match_type_from_name (name);
4911 lookup_name_info lookup_name (name, match_type);
4912
4913 symbol_name_matcher_ftype *match_name
4914 = ada_get_symbol_name_matcher (lookup_name);
4c4b4cd2 4915
06a670e2 4916 gdbarch_iterate_over_objfiles_in_search_order
99d9c3b9 4917 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
06a670e2
MM
4918 [&result, lookup_name, match_name] (struct objfile *obj)
4919 {
4920 for (minimal_symbol *msymbol : obj->msymbols ())
4921 {
4922 if (match_name (msymbol->linkage_name (), lookup_name, nullptr)
4923 && msymbol->type () != mst_solib_trampoline)
4924 {
4925 result.minsym = msymbol;
4926 result.objfile = obj;
4927 return 1;
4928 }
4929 }
4930
4931 return 0;
4932 }, objfile);
4c4b4cd2 4933
7c7b6655 4934 return result;
96d887e8 4935}
4c4b4cd2 4936
96d887e8
PH
4937/* True if TYPE is definitely an artificial type supplied to a symbol
4938 for which no debugging information was given in the symbol file. */
14f9c5c9 4939
96d887e8
PH
4940static int
4941is_nondebugging_type (struct type *type)
4942{
0d5cff50 4943 const char *name = ada_type_name (type);
5b4ee69b 4944
96d887e8
PH
4945 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4946}
4c4b4cd2 4947
8f17729f
JB
4948/* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4949 that are deemed "identical" for practical purposes.
4950
4951 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4952 types and that their number of enumerals is identical (in other
1f704f76 4953 words, type1->num_fields () == type2->num_fields ()). */
8f17729f
JB
4954
4955static int
4956ada_identical_enum_types_p (struct type *type1, struct type *type2)
4957{
4958 int i;
4959
4960 /* The heuristic we use here is fairly conservative. We consider
4961 that 2 enumerate types are identical if they have the same
4962 number of enumerals and that all enumerals have the same
4963 underlying value and name. */
4964
4965 /* All enums in the type should have an identical underlying value. */
1f704f76 4966 for (i = 0; i < type1->num_fields (); i++)
970db518 4967 if (type1->field (i).loc_enumval () != type2->field (i).loc_enumval ())
8f17729f
JB
4968 return 0;
4969
4970 /* All enumerals should also have the same name (modulo any numerical
4971 suffix). */
1f704f76 4972 for (i = 0; i < type1->num_fields (); i++)
8f17729f 4973 {
33d16dd9
SM
4974 const char *name_1 = type1->field (i).name ();
4975 const char *name_2 = type2->field (i).name ();
8f17729f
JB
4976 int len_1 = strlen (name_1);
4977 int len_2 = strlen (name_2);
4978
33d16dd9
SM
4979 ada_remove_trailing_digits (type1->field (i).name (), &len_1);
4980 ada_remove_trailing_digits (type2->field (i).name (), &len_2);
8f17729f 4981 if (len_1 != len_2
33d16dd9
SM
4982 || strncmp (type1->field (i).name (),
4983 type2->field (i).name (),
8f17729f
JB
4984 len_1) != 0)
4985 return 0;
4986 }
4987
4988 return 1;
4989}
4990
4991/* Return nonzero if all the symbols in SYMS are all enumeral symbols
4992 that are deemed "identical" for practical purposes. Sometimes,
4993 enumerals are not strictly identical, but their types are so similar
4994 that they can be considered identical.
4995
4996 For instance, consider the following code:
4997
4998 type Color is (Black, Red, Green, Blue, White);
4999 type RGB_Color is new Color range Red .. Blue;
5000
5001 Type RGB_Color is a subrange of an implicit type which is a copy
5002 of type Color. If we call that implicit type RGB_ColorB ("B" is
5003 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5004 As a result, when an expression references any of the enumeral
5005 by name (Eg. "print green"), the expression is technically
5006 ambiguous and the user should be asked to disambiguate. But
5007 doing so would only hinder the user, since it wouldn't matter
5008 what choice he makes, the outcome would always be the same.
5009 So, for practical purposes, we consider them as the same. */
5010
5011static int
54d343a2 5012symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
8f17729f
JB
5013{
5014 int i;
5015
5016 /* Before performing a thorough comparison check of each type,
5017 we perform a series of inexpensive checks. We expect that these
5018 checks will quickly fail in the vast majority of cases, and thus
5019 help prevent the unnecessary use of a more expensive comparison.
5020 Said comparison also expects us to make some of these checks
5021 (see ada_identical_enum_types_p). */
5022
5023 /* Quick check: All symbols should have an enum type. */
54d343a2 5024 for (i = 0; i < syms.size (); i++)
5f9c5a63 5025 if (syms[i].symbol->type ()->code () != TYPE_CODE_ENUM)
8f17729f
JB
5026 return 0;
5027
5028 /* Quick check: They should all have the same value. */
54d343a2 5029 for (i = 1; i < syms.size (); i++)
4aeddc50 5030 if (syms[i].symbol->value_longest () != syms[0].symbol->value_longest ())
8f17729f
JB
5031 return 0;
5032
5033 /* Quick check: They should all have the same number of enumerals. */
54d343a2 5034 for (i = 1; i < syms.size (); i++)
5f9c5a63
SM
5035 if (syms[i].symbol->type ()->num_fields ()
5036 != syms[0].symbol->type ()->num_fields ())
8f17729f
JB
5037 return 0;
5038
5039 /* All the sanity checks passed, so we might have a set of
5040 identical enumeration types. Perform a more complete
5041 comparison of the type of each symbol. */
54d343a2 5042 for (i = 1; i < syms.size (); i++)
5f9c5a63
SM
5043 if (!ada_identical_enum_types_p (syms[i].symbol->type (),
5044 syms[0].symbol->type ()))
8f17729f
JB
5045 return 0;
5046
5047 return 1;
5048}
5049
54d343a2 5050/* Remove any non-debugging symbols in SYMS that definitely
96d887e8
PH
5051 duplicate other symbols in the list (The only case I know of where
5052 this happens is when object files containing stabs-in-ecoff are
5053 linked with files containing ordinary ecoff debugging symbols (or no
1bfa81ac 5054 debugging symbols)). Modifies SYMS to squeeze out deleted entries. */
4c4b4cd2 5055
d1183b06 5056static void
ff4631e2 5057remove_extra_symbols (std::vector<struct block_symbol> &syms)
96d887e8
PH
5058{
5059 int i, j;
4c4b4cd2 5060
8f17729f
JB
5061 /* We should never be called with less than 2 symbols, as there
5062 cannot be any extra symbol in that case. But it's easy to
5063 handle, since we have nothing to do in that case. */
ff4631e2 5064 if (syms.size () < 2)
d1183b06 5065 return;
8f17729f 5066
96d887e8 5067 i = 0;
ff4631e2 5068 while (i < syms.size ())
96d887e8 5069 {
44a37a98 5070 bool remove_p = false;
339c13b6
JB
5071
5072 /* If two symbols have the same name and one of them is a stub type,
dda83cd7 5073 the get rid of the stub. */
339c13b6 5074
ff4631e2
TT
5075 if (syms[i].symbol->type ()->is_stub ()
5076 && syms[i].symbol->linkage_name () != NULL)
dda83cd7 5077 {
44a37a98 5078 for (j = 0; !remove_p && j < syms.size (); j++)
dda83cd7
SM
5079 {
5080 if (j != i
ff4631e2
TT
5081 && !syms[j].symbol->type ()->is_stub ()
5082 && syms[j].symbol->linkage_name () != NULL
5083 && strcmp (syms[i].symbol->linkage_name (),
5084 syms[j].symbol->linkage_name ()) == 0)
44a37a98 5085 remove_p = true;
dda83cd7
SM
5086 }
5087 }
339c13b6
JB
5088
5089 /* Two symbols with the same name, same class and same address
dda83cd7 5090 should be identical. */
339c13b6 5091
ff4631e2
TT
5092 else if (syms[i].symbol->linkage_name () != NULL
5093 && syms[i].symbol->aclass () == LOC_STATIC
5094 && is_nondebugging_type (syms[i].symbol->type ()))
dda83cd7 5095 {
44a37a98 5096 for (j = 0; !remove_p && j < syms.size (); j += 1)
dda83cd7
SM
5097 {
5098 if (i != j
ff4631e2
TT
5099 && syms[j].symbol->linkage_name () != NULL
5100 && strcmp (syms[i].symbol->linkage_name (),
5101 syms[j].symbol->linkage_name ()) == 0
5102 && (syms[i].symbol->aclass ()
5103 == syms[j].symbol->aclass ())
5104 && syms[i].symbol->value_address ()
5105 == syms[j].symbol->value_address ())
44a37a98 5106 remove_p = true;
dda83cd7
SM
5107 }
5108 }
339c13b6 5109
e9151f7d
TT
5110 /* Two functions with the same block are identical. */
5111
5112 else if (syms[i].symbol->aclass () == LOC_BLOCK)
5113 {
5114 for (j = 0; !remove_p && j < syms.size (); j += 1)
5115 {
5116 if (i != j
5117 && syms[j].symbol->aclass () == LOC_BLOCK
5118 && (syms[i].symbol->value_block ()
5119 == syms[j].symbol->value_block ()))
5120 remove_p = true;
5121 }
5122 }
5123
a35ddb44 5124 if (remove_p)
ff4631e2 5125 syms.erase (syms.begin () + i);
1b788fb6
TT
5126 else
5127 i += 1;
14f9c5c9 5128 }
14f9c5c9
AS
5129}
5130
96d887e8
PH
5131/* Given a type that corresponds to a renaming entity, use the type name
5132 to extract the scope (package name or function name, fully qualified,
5133 and following the GNAT encoding convention) where this renaming has been
49d83361 5134 defined. */
4c4b4cd2 5135
49d83361 5136static std::string
96d887e8 5137xget_renaming_scope (struct type *renaming_type)
14f9c5c9 5138{
96d887e8 5139 /* The renaming types adhere to the following convention:
0963b4bd 5140 <scope>__<rename>___<XR extension>.
96d887e8
PH
5141 So, to extract the scope, we search for the "___XR" extension,
5142 and then backtrack until we find the first "__". */
76a01679 5143
7d93a1e0 5144 const char *name = renaming_type->name ();
108d56a4
SM
5145 const char *suffix = strstr (name, "___XR");
5146 const char *last;
14f9c5c9 5147
96d887e8
PH
5148 /* Now, backtrack a bit until we find the first "__". Start looking
5149 at suffix - 3, as the <rename> part is at least one character long. */
14f9c5c9 5150
96d887e8
PH
5151 for (last = suffix - 3; last > name; last--)
5152 if (last[0] == '_' && last[1] == '_')
5153 break;
76a01679 5154
96d887e8 5155 /* Make a copy of scope and return it. */
49d83361 5156 return std::string (name, last);
4c4b4cd2
PH
5157}
5158
96d887e8 5159/* Return nonzero if NAME corresponds to a package name. */
4c4b4cd2 5160
96d887e8
PH
5161static int
5162is_package_name (const char *name)
4c4b4cd2 5163{
96d887e8
PH
5164 /* Here, We take advantage of the fact that no symbols are generated
5165 for packages, while symbols are generated for each function.
5166 So the condition for NAME represent a package becomes equivalent
5167 to NAME not existing in our list of symbols. There is only one
5168 small complication with library-level functions (see below). */
4c4b4cd2 5169
96d887e8
PH
5170 /* If it is a function that has not been defined at library level,
5171 then we should be able to look it up in the symbols. */
5172 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5173 return 0;
14f9c5c9 5174
96d887e8
PH
5175 /* Library-level function names start with "_ada_". See if function
5176 "_ada_" followed by NAME can be found. */
14f9c5c9 5177
96d887e8 5178 /* Do a quick check that NAME does not contain "__", since library-level
e1d5a0d2 5179 functions names cannot contain "__" in them. */
96d887e8
PH
5180 if (strstr (name, "__") != NULL)
5181 return 0;
4c4b4cd2 5182
528e1572 5183 std::string fun_name = string_printf ("_ada_%s", name);
14f9c5c9 5184
528e1572 5185 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
96d887e8 5186}
14f9c5c9 5187
96d887e8 5188/* Return nonzero if SYM corresponds to a renaming entity that is
aeb5907d 5189 not visible from FUNCTION_NAME. */
14f9c5c9 5190
96d887e8 5191static int
0d5cff50 5192old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
96d887e8 5193{
66d7f48f 5194 if (sym->aclass () != LOC_TYPEDEF)
aeb5907d
JB
5195 return 0;
5196
5f9c5a63 5197 std::string scope = xget_renaming_scope (sym->type ());
14f9c5c9 5198
96d887e8 5199 /* If the rename has been defined in a package, then it is visible. */
49d83361
TT
5200 if (is_package_name (scope.c_str ()))
5201 return 0;
14f9c5c9 5202
96d887e8
PH
5203 /* Check that the rename is in the current function scope by checking
5204 that its name starts with SCOPE. */
76a01679 5205
96d887e8
PH
5206 /* If the function name starts with "_ada_", it means that it is
5207 a library-level function. Strip this prefix before doing the
5208 comparison, as the encoding for the renaming does not contain
5209 this prefix. */
61012eef 5210 if (startswith (function_name, "_ada_"))
96d887e8 5211 function_name += 5;
f26caa11 5212
49d83361 5213 return !startswith (function_name, scope.c_str ());
f26caa11
PH
5214}
5215
aeb5907d
JB
5216/* Remove entries from SYMS that corresponds to a renaming entity that
5217 is not visible from the function associated with CURRENT_BLOCK or
5218 that is superfluous due to the presence of more specific renaming
5219 information. Places surviving symbols in the initial entries of
d1183b06
TT
5220 SYMS.
5221
96d887e8 5222 Rationale:
aeb5907d
JB
5223 First, in cases where an object renaming is implemented as a
5224 reference variable, GNAT may produce both the actual reference
5225 variable and the renaming encoding. In this case, we discard the
5226 latter.
5227
5228 Second, GNAT emits a type following a specified encoding for each renaming
96d887e8
PH
5229 entity. Unfortunately, STABS currently does not support the definition
5230 of types that are local to a given lexical block, so all renamings types
5231 are emitted at library level. As a consequence, if an application
5232 contains two renaming entities using the same name, and a user tries to
5233 print the value of one of these entities, the result of the ada symbol
5234 lookup will also contain the wrong renaming type.
f26caa11 5235
96d887e8
PH
5236 This function partially covers for this limitation by attempting to
5237 remove from the SYMS list renaming symbols that should be visible
5238 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5239 method with the current information available. The implementation
5240 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5241
5242 - When the user tries to print a rename in a function while there
dda83cd7
SM
5243 is another rename entity defined in a package: Normally, the
5244 rename in the function has precedence over the rename in the
5245 package, so the latter should be removed from the list. This is
5246 currently not the case.
5247
96d887e8 5248 - This function will incorrectly remove valid renames if
dda83cd7
SM
5249 the CURRENT_BLOCK corresponds to a function which symbol name
5250 has been changed by an "Export" pragma. As a consequence,
5251 the user will be unable to print such rename entities. */
4c4b4cd2 5252
d1183b06 5253static void
54d343a2
TT
5254remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5255 const struct block *current_block)
4c4b4cd2
PH
5256{
5257 struct symbol *current_function;
0d5cff50 5258 const char *current_function_name;
4c4b4cd2 5259 int i;
aeb5907d
JB
5260 int is_new_style_renaming;
5261
5262 /* If there is both a renaming foo___XR... encoded as a variable and
5263 a simple variable foo in the same block, discard the latter.
0963b4bd 5264 First, zero out such symbols, then compress. */
aeb5907d 5265 is_new_style_renaming = 0;
54d343a2 5266 for (i = 0; i < syms->size (); i += 1)
aeb5907d 5267 {
54d343a2
TT
5268 struct symbol *sym = (*syms)[i].symbol;
5269 const struct block *block = (*syms)[i].block;
aeb5907d
JB
5270 const char *name;
5271 const char *suffix;
5272
66d7f48f 5273 if (sym == NULL || sym->aclass () == LOC_TYPEDEF)
aeb5907d 5274 continue;
987012b8 5275 name = sym->linkage_name ();
aeb5907d
JB
5276 suffix = strstr (name, "___XR");
5277
5278 if (suffix != NULL)
5279 {
5280 int name_len = suffix - name;
5281 int j;
5b4ee69b 5282
aeb5907d 5283 is_new_style_renaming = 1;
54d343a2
TT
5284 for (j = 0; j < syms->size (); j += 1)
5285 if (i != j && (*syms)[j].symbol != NULL
987012b8 5286 && strncmp (name, (*syms)[j].symbol->linkage_name (),
aeb5907d 5287 name_len) == 0
54d343a2
TT
5288 && block == (*syms)[j].block)
5289 (*syms)[j].symbol = NULL;
aeb5907d
JB
5290 }
5291 }
5292 if (is_new_style_renaming)
5293 {
5294 int j, k;
5295
54d343a2
TT
5296 for (j = k = 0; j < syms->size (); j += 1)
5297 if ((*syms)[j].symbol != NULL)
aeb5907d 5298 {
54d343a2 5299 (*syms)[k] = (*syms)[j];
aeb5907d
JB
5300 k += 1;
5301 }
d1183b06
TT
5302 syms->resize (k);
5303 return;
aeb5907d 5304 }
4c4b4cd2
PH
5305
5306 /* Extract the function name associated to CURRENT_BLOCK.
5307 Abort if unable to do so. */
76a01679 5308
4c4b4cd2 5309 if (current_block == NULL)
d1183b06 5310 return;
76a01679 5311
3c9d0506 5312 current_function = current_block->linkage_function ();
4c4b4cd2 5313 if (current_function == NULL)
d1183b06 5314 return;
4c4b4cd2 5315
987012b8 5316 current_function_name = current_function->linkage_name ();
4c4b4cd2 5317 if (current_function_name == NULL)
d1183b06 5318 return;
4c4b4cd2
PH
5319
5320 /* Check each of the symbols, and remove it from the list if it is
5321 a type corresponding to a renaming that is out of the scope of
5322 the current block. */
5323
5324 i = 0;
54d343a2 5325 while (i < syms->size ())
4c4b4cd2 5326 {
54d343a2 5327 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
dda83cd7
SM
5328 == ADA_OBJECT_RENAMING
5329 && old_renaming_is_invisible ((*syms)[i].symbol,
54d343a2
TT
5330 current_function_name))
5331 syms->erase (syms->begin () + i);
4c4b4cd2 5332 else
dda83cd7 5333 i += 1;
4c4b4cd2 5334 }
4c4b4cd2
PH
5335}
5336
d1183b06 5337/* Add to RESULT all symbols from BLOCK (and its super-blocks)
cd458349 5338 whose name and domain match LOOKUP_NAME and DOMAIN respectively.
339c13b6 5339
cd458349 5340 Note: This function assumes that RESULT is empty. */
339c13b6
JB
5341
5342static void
d1183b06 5343ada_add_local_symbols (std::vector<struct block_symbol> &result,
b5ec771e
PA
5344 const lookup_name_info &lookup_name,
5345 const struct block *block, domain_enum domain)
339c13b6 5346{
339c13b6
JB
5347 while (block != NULL)
5348 {
d1183b06 5349 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
339c13b6 5350
ba8694b6
TT
5351 /* If we found a non-function match, assume that's the one. We
5352 only check this when finding a function boundary, so that we
5353 can accumulate all results from intervening blocks first. */
6c00f721 5354 if (block->function () != nullptr && is_nonfunction (result))
dda83cd7 5355 return;
339c13b6 5356
f135fe72 5357 block = block->superblock ();
339c13b6 5358 }
339c13b6
JB
5359}
5360
2315bb2d 5361/* An object of this type is used as the callback argument when
40658b94 5362 calling the map_matching_symbols method. */
ccefe4c4 5363
40658b94 5364struct match_data
ccefe4c4 5365{
1bfa81ac
TT
5366 explicit match_data (std::vector<struct block_symbol> *rp)
5367 : resultp (rp)
5368 {
5369 }
5370 DISABLE_COPY_AND_ASSIGN (match_data);
5371
2315bb2d
TT
5372 bool operator() (struct block_symbol *bsym);
5373
1bfa81ac 5374 struct objfile *objfile = nullptr;
d1183b06 5375 std::vector<struct block_symbol> *resultp;
1bfa81ac 5376 struct symbol *arg_sym = nullptr;
1178743e 5377 bool found_sym = false;
ccefe4c4
TT
5378};
5379
2315bb2d
TT
5380/* A callback for add_nonlocal_symbols that adds symbol, found in
5381 BSYM, to a list of symbols. */
ccefe4c4 5382
2315bb2d
TT
5383bool
5384match_data::operator() (struct block_symbol *bsym)
ccefe4c4 5385{
199b4314
TT
5386 const struct block *block = bsym->block;
5387 struct symbol *sym = bsym->symbol;
5388
40658b94
PH
5389 if (sym == NULL)
5390 {
2315bb2d 5391 if (!found_sym && arg_sym != NULL)
dae58e04 5392 add_defn_to_vec (*resultp, arg_sym, block);
2315bb2d
TT
5393 found_sym = false;
5394 arg_sym = NULL;
40658b94
PH
5395 }
5396 else
5397 {
66d7f48f 5398 if (sym->aclass () == LOC_UNRESOLVED)
199b4314 5399 return true;
d9743061 5400 else if (sym->is_argument ())
2315bb2d 5401 arg_sym = sym;
40658b94
PH
5402 else
5403 {
2315bb2d 5404 found_sym = true;
dae58e04 5405 add_defn_to_vec (*resultp, sym, block);
40658b94
PH
5406 }
5407 }
199b4314 5408 return true;
40658b94
PH
5409}
5410
b5ec771e
PA
5411/* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5412 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
1bfa81ac 5413 symbols to RESULT. Return whether we found such symbols. */
22cee43f
PMR
5414
5415static int
d1183b06 5416ada_add_block_renamings (std::vector<struct block_symbol> &result,
22cee43f 5417 const struct block *block,
b5ec771e
PA
5418 const lookup_name_info &lookup_name,
5419 domain_enum domain)
22cee43f
PMR
5420{
5421 struct using_direct *renaming;
d1183b06 5422 int defns_mark = result.size ();
22cee43f 5423
b5ec771e
PA
5424 symbol_name_matcher_ftype *name_match
5425 = ada_get_symbol_name_matcher (lookup_name);
5426
3c45e9f9 5427 for (renaming = block->get_using ();
22cee43f
PMR
5428 renaming != NULL;
5429 renaming = renaming->next)
5430 {
5431 const char *r_name;
22cee43f
PMR
5432
5433 /* Avoid infinite recursions: skip this renaming if we are actually
5434 already traversing it.
5435
5436 Currently, symbol lookup in Ada don't use the namespace machinery from
5437 C++/Fortran support: skip namespace imports that use them. */
5438 if (renaming->searched
5439 || (renaming->import_src != NULL
5440 && renaming->import_src[0] != '\0')
5441 || (renaming->import_dest != NULL
5442 && renaming->import_dest[0] != '\0'))
5443 continue;
5444 renaming->searched = 1;
5445
5446 /* TODO: here, we perform another name-based symbol lookup, which can
5447 pull its own multiple overloads. In theory, we should be able to do
5448 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5449 not a simple name. But in order to do this, we would need to enhance
5450 the DWARF reader to associate a symbol to this renaming, instead of a
5451 name. So, for now, we do something simpler: re-use the C++/Fortran
5452 namespace machinery. */
5453 r_name = (renaming->alias != NULL
5454 ? renaming->alias
5455 : renaming->declaration);
b5ec771e
PA
5456 if (name_match (r_name, lookup_name, NULL))
5457 {
5458 lookup_name_info decl_lookup_name (renaming->declaration,
5459 lookup_name.match_type ());
d1183b06 5460 ada_add_all_symbols (result, block, decl_lookup_name, domain,
b5ec771e
PA
5461 1, NULL);
5462 }
22cee43f
PMR
5463 renaming->searched = 0;
5464 }
d1183b06 5465 return result.size () != defns_mark;
22cee43f
PMR
5466}
5467
db230ce3
JB
5468/* Implements compare_names, but only applying the comparision using
5469 the given CASING. */
5b4ee69b 5470
40658b94 5471static int
db230ce3
JB
5472compare_names_with_case (const char *string1, const char *string2,
5473 enum case_sensitivity casing)
40658b94
PH
5474{
5475 while (*string1 != '\0' && *string2 != '\0')
5476 {
db230ce3
JB
5477 char c1, c2;
5478
40658b94
PH
5479 if (isspace (*string1) || isspace (*string2))
5480 return strcmp_iw_ordered (string1, string2);
db230ce3
JB
5481
5482 if (casing == case_sensitive_off)
5483 {
5484 c1 = tolower (*string1);
5485 c2 = tolower (*string2);
5486 }
5487 else
5488 {
5489 c1 = *string1;
5490 c2 = *string2;
5491 }
5492 if (c1 != c2)
40658b94 5493 break;
db230ce3 5494
40658b94
PH
5495 string1 += 1;
5496 string2 += 1;
5497 }
db230ce3 5498
40658b94
PH
5499 switch (*string1)
5500 {
5501 case '(':
5502 return strcmp_iw_ordered (string1, string2);
5503 case '_':
5504 if (*string2 == '\0')
5505 {
052874e8 5506 if (is_name_suffix (string1))
40658b94
PH
5507 return 0;
5508 else
1a1d5513 5509 return 1;
40658b94 5510 }
dbb8534f 5511 /* FALLTHROUGH */
40658b94
PH
5512 default:
5513 if (*string2 == '(')
5514 return strcmp_iw_ordered (string1, string2);
5515 else
db230ce3
JB
5516 {
5517 if (casing == case_sensitive_off)
5518 return tolower (*string1) - tolower (*string2);
5519 else
5520 return *string1 - *string2;
5521 }
40658b94 5522 }
ccefe4c4
TT
5523}
5524
db230ce3
JB
5525/* Compare STRING1 to STRING2, with results as for strcmp.
5526 Compatible with strcmp_iw_ordered in that...
5527
5528 strcmp_iw_ordered (STRING1, STRING2) <= 0
5529
5530 ... implies...
5531
5532 compare_names (STRING1, STRING2) <= 0
5533
5534 (they may differ as to what symbols compare equal). */
5535
5536static int
5537compare_names (const char *string1, const char *string2)
5538{
5539 int result;
5540
5541 /* Similar to what strcmp_iw_ordered does, we need to perform
5542 a case-insensitive comparison first, and only resort to
5543 a second, case-sensitive, comparison if the first one was
5544 not sufficient to differentiate the two strings. */
5545
5546 result = compare_names_with_case (string1, string2, case_sensitive_off);
5547 if (result == 0)
5548 result = compare_names_with_case (string1, string2, case_sensitive_on);
5549
5550 return result;
5551}
5552
b5ec771e
PA
5553/* Convenience function to get at the Ada encoded lookup name for
5554 LOOKUP_NAME, as a C string. */
5555
5556static const char *
5557ada_lookup_name (const lookup_name_info &lookup_name)
5558{
5559 return lookup_name.ada ().lookup_name ().c_str ();
5560}
5561
0b7b2c2a
TT
5562/* A helper for add_nonlocal_symbols. Call expand_matching_symbols
5563 for OBJFILE, then walk the objfile's symtabs and update the
5564 results. */
5565
5566static void
5567map_matching_symbols (struct objfile *objfile,
5568 const lookup_name_info &lookup_name,
5569 bool is_wild_match,
5570 domain_enum domain,
5571 int global,
5572 match_data &data)
5573{
5574 data.objfile = objfile;
5575 objfile->expand_matching_symbols (lookup_name, domain, global,
5576 is_wild_match ? nullptr : compare_names);
5577
5578 const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
5579 for (compunit_symtab *symtab : objfile->compunits ())
5580 {
5581 const struct block *block
63d609de 5582 = symtab->blockvector ()->block (block_kind);
0b7b2c2a
TT
5583 if (!iterate_over_symbols_terminated (block, lookup_name,
5584 domain, data))
5585 break;
5586 }
5587}
5588
1bfa81ac 5589/* Add to RESULT all non-local symbols whose name and domain match
b5ec771e
PA
5590 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5591 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5592 symbols otherwise. */
339c13b6
JB
5593
5594static void
d1183b06 5595add_nonlocal_symbols (std::vector<struct block_symbol> &result,
b5ec771e
PA
5596 const lookup_name_info &lookup_name,
5597 domain_enum domain, int global)
339c13b6 5598{
1bfa81ac 5599 struct match_data data (&result);
339c13b6 5600
b5ec771e
PA
5601 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5602
2030c079 5603 for (objfile *objfile : current_program_space->objfiles ())
40658b94 5604 {
0b7b2c2a
TT
5605 map_matching_symbols (objfile, lookup_name, is_wild_match, domain,
5606 global, data);
22cee43f 5607
b669c953 5608 for (compunit_symtab *cu : objfile->compunits ())
22cee43f
PMR
5609 {
5610 const struct block *global_block
63d609de 5611 = cu->blockvector ()->global_block ();
22cee43f 5612
d1183b06 5613 if (ada_add_block_renamings (result, global_block, lookup_name,
b5ec771e 5614 domain))
1178743e 5615 data.found_sym = true;
22cee43f 5616 }
40658b94
PH
5617 }
5618
d1183b06 5619 if (result.empty () && global && !is_wild_match)
40658b94 5620 {
b5ec771e 5621 const char *name = ada_lookup_name (lookup_name);
e0802d59
TT
5622 std::string bracket_name = std::string ("<_ada_") + name + '>';
5623 lookup_name_info name1 (bracket_name, symbol_name_match_type::FULL);
b5ec771e 5624
2030c079 5625 for (objfile *objfile : current_program_space->objfiles ())
0b7b2c2a
TT
5626 map_matching_symbols (objfile, name1, false, domain, global, data);
5627 }
339c13b6
JB
5628}
5629
b5ec771e
PA
5630/* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5631 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
1bfa81ac 5632 returning the number of matches. Add these to RESULT.
4eeaa230 5633
22cee43f
PMR
5634 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5635 symbol match within the nest of blocks whose innermost member is BLOCK,
4c4b4cd2 5636 is the one match returned (no other matches in that or
d9680e73 5637 enclosing blocks is returned). If there are any matches in or
22cee43f 5638 surrounding BLOCK, then these alone are returned.
4eeaa230 5639
b5ec771e
PA
5640 Names prefixed with "standard__" are handled specially:
5641 "standard__" is first stripped off (by the lookup_name
5642 constructor), and only static and global symbols are searched.
14f9c5c9 5643
22cee43f
PMR
5644 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5645 to lookup global symbols. */
5646
5647static void
d1183b06 5648ada_add_all_symbols (std::vector<struct block_symbol> &result,
22cee43f 5649 const struct block *block,
b5ec771e 5650 const lookup_name_info &lookup_name,
22cee43f
PMR
5651 domain_enum domain,
5652 int full_search,
5653 int *made_global_lookup_p)
14f9c5c9
AS
5654{
5655 struct symbol *sym;
14f9c5c9 5656
22cee43f
PMR
5657 if (made_global_lookup_p)
5658 *made_global_lookup_p = 0;
339c13b6
JB
5659
5660 /* Special case: If the user specifies a symbol name inside package
5661 Standard, do a non-wild matching of the symbol name without
5662 the "standard__" prefix. This was primarily introduced in order
5663 to allow the user to specifically access the standard exceptions
5664 using, for instance, Standard.Constraint_Error when Constraint_Error
5665 is ambiguous (due to the user defining its own Constraint_Error
5666 entity inside its program). */
b5ec771e
PA
5667 if (lookup_name.ada ().standard_p ())
5668 block = NULL;
4c4b4cd2 5669
339c13b6 5670 /* Check the non-global symbols. If we have ANY match, then we're done. */
14f9c5c9 5671
4eeaa230
DE
5672 if (block != NULL)
5673 {
5674 if (full_search)
d1183b06 5675 ada_add_local_symbols (result, lookup_name, block, domain);
4eeaa230
DE
5676 else
5677 {
5678 /* In the !full_search case we're are being called by
4009ee92 5679 iterate_over_symbols, and we don't want to search
4eeaa230 5680 superblocks. */
d1183b06 5681 ada_add_block_symbols (result, block, lookup_name, domain, NULL);
4eeaa230 5682 }
d1183b06 5683 if (!result.empty () || !full_search)
22cee43f 5684 return;
4eeaa230 5685 }
d2e4a39e 5686
339c13b6
JB
5687 /* No non-global symbols found. Check our cache to see if we have
5688 already performed this search before. If we have, then return
5689 the same result. */
5690
b5ec771e
PA
5691 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5692 domain, &sym, &block))
4c4b4cd2
PH
5693 {
5694 if (sym != NULL)
d1183b06 5695 add_defn_to_vec (result, sym, block);
22cee43f 5696 return;
4c4b4cd2 5697 }
14f9c5c9 5698
22cee43f
PMR
5699 if (made_global_lookup_p)
5700 *made_global_lookup_p = 1;
b1eedac9 5701
339c13b6
JB
5702 /* Search symbols from all global blocks. */
5703
d1183b06 5704 add_nonlocal_symbols (result, lookup_name, domain, 1);
d2e4a39e 5705
4c4b4cd2 5706 /* Now add symbols from all per-file blocks if we've gotten no hits
339c13b6 5707 (not strictly correct, but perhaps better than an error). */
d2e4a39e 5708
d1183b06
TT
5709 if (result.empty ())
5710 add_nonlocal_symbols (result, lookup_name, domain, 0);
22cee43f
PMR
5711}
5712
b5ec771e 5713/* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
d1183b06
TT
5714 is non-zero, enclosing scope and in global scopes.
5715
5716 Returns (SYM,BLOCK) tuples, indicating the symbols found and the
5717 blocks and symbol tables (if any) in which they were found.
22cee43f
PMR
5718
5719 When full_search is non-zero, any non-function/non-enumeral
5720 symbol match within the nest of blocks whose innermost member is BLOCK,
5721 is the one match returned (no other matches in that or
5722 enclosing blocks is returned). If there are any matches in or
5723 surrounding BLOCK, then these alone are returned.
5724
5725 Names prefixed with "standard__" are handled specially: "standard__"
5726 is first stripped off, and only static and global symbols are searched. */
5727
d1183b06 5728static std::vector<struct block_symbol>
b5ec771e
PA
5729ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5730 const struct block *block,
22cee43f 5731 domain_enum domain,
22cee43f
PMR
5732 int full_search)
5733{
22cee43f 5734 int syms_from_global_search;
d1183b06 5735 std::vector<struct block_symbol> results;
22cee43f 5736
d1183b06 5737 ada_add_all_symbols (results, block, lookup_name,
b5ec771e 5738 domain, full_search, &syms_from_global_search);
14f9c5c9 5739
ff4631e2 5740 remove_extra_symbols (results);
4c4b4cd2 5741
d1183b06 5742 if (results.empty () && full_search && syms_from_global_search)
b5ec771e 5743 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
14f9c5c9 5744
d1183b06 5745 if (results.size () == 1 && full_search && syms_from_global_search)
b5ec771e 5746 cache_symbol (ada_lookup_name (lookup_name), domain,
d1183b06 5747 results[0].symbol, results[0].block);
ec6a20c2 5748
d1183b06
TT
5749 remove_irrelevant_renamings (&results, block);
5750 return results;
14f9c5c9
AS
5751}
5752
b5ec771e 5753/* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
d1183b06 5754 in global scopes, returning (SYM,BLOCK) tuples.
ec6a20c2 5755
4eeaa230
DE
5756 See ada_lookup_symbol_list_worker for further details. */
5757
d1183b06 5758std::vector<struct block_symbol>
b5ec771e 5759ada_lookup_symbol_list (const char *name, const struct block *block,
d1183b06 5760 domain_enum domain)
4eeaa230 5761{
b5ec771e
PA
5762 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5763 lookup_name_info lookup_name (name, name_match_type);
5764
d1183b06 5765 return ada_lookup_symbol_list_worker (lookup_name, block, domain, 1);
4eeaa230
DE
5766}
5767
4e5c77fe
JB
5768/* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5769 to 1, but choosing the first symbol found if there are multiple
5770 choices.
5771
5e2336be
JB
5772 The result is stored in *INFO, which must be non-NULL.
5773 If no match is found, INFO->SYM is set to NULL. */
4e5c77fe
JB
5774
5775void
5776ada_lookup_encoded_symbol (const char *name, const struct block *block,
fe978cb0 5777 domain_enum domain,
d12307c1 5778 struct block_symbol *info)
14f9c5c9 5779{
b5ec771e
PA
5780 /* Since we already have an encoded name, wrap it in '<>' to force a
5781 verbatim match. Otherwise, if the name happens to not look like
5782 an encoded name (because it doesn't include a "__"),
5783 ada_lookup_name_info would re-encode/fold it again, and that
5784 would e.g., incorrectly lowercase object renaming names like
5785 "R28b" -> "r28b". */
12932e2c 5786 std::string verbatim = add_angle_brackets (name);
b5ec771e 5787
5e2336be 5788 gdb_assert (info != NULL);
65392b3e 5789 *info = ada_lookup_symbol (verbatim.c_str (), block, domain);
4e5c77fe 5790}
aeb5907d
JB
5791
5792/* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5793 scope and in global scopes, or NULL if none. NAME is folded and
5794 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
65392b3e 5795 choosing the first symbol if there are multiple choices. */
4e5c77fe 5796
d12307c1 5797struct block_symbol
aeb5907d 5798ada_lookup_symbol (const char *name, const struct block *block0,
dda83cd7 5799 domain_enum domain)
aeb5907d 5800{
d1183b06
TT
5801 std::vector<struct block_symbol> candidates
5802 = ada_lookup_symbol_list (name, block0, domain);
f98fc17b 5803
d1183b06 5804 if (candidates.empty ())
54d343a2 5805 return {};
f98fc17b 5806
dae58e04 5807 return candidates[0];
4c4b4cd2 5808}
14f9c5c9 5809
14f9c5c9 5810
4c4b4cd2
PH
5811/* True iff STR is a possible encoded suffix of a normal Ada name
5812 that is to be ignored for matching purposes. Suffixes of parallel
5813 names (e.g., XVE) are not included here. Currently, the possible suffixes
5823c3ef 5814 are given by any of the regular expressions:
4c4b4cd2 5815
babe1480
JB
5816 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5817 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
9ac7f98e 5818 TKB [subprogram suffix for task bodies]
babe1480 5819 _E[0-9]+[bs]$ [protected object entry suffixes]
61ee279c 5820 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
babe1480
JB
5821
5822 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5823 match is performed. This sequence is used to differentiate homonyms,
5824 is an optional part of a valid name suffix. */
4c4b4cd2 5825
14f9c5c9 5826static int
d2e4a39e 5827is_name_suffix (const char *str)
14f9c5c9
AS
5828{
5829 int k;
4c4b4cd2
PH
5830 const char *matching;
5831 const int len = strlen (str);
5832
babe1480
JB
5833 /* Skip optional leading __[0-9]+. */
5834
4c4b4cd2
PH
5835 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5836 {
babe1480
JB
5837 str += 3;
5838 while (isdigit (str[0]))
dda83cd7 5839 str += 1;
4c4b4cd2 5840 }
babe1480
JB
5841
5842 /* [.$][0-9]+ */
4c4b4cd2 5843
babe1480 5844 if (str[0] == '.' || str[0] == '$')
4c4b4cd2 5845 {
babe1480 5846 matching = str + 1;
4c4b4cd2 5847 while (isdigit (matching[0]))
dda83cd7 5848 matching += 1;
4c4b4cd2 5849 if (matching[0] == '\0')
dda83cd7 5850 return 1;
4c4b4cd2
PH
5851 }
5852
5853 /* ___[0-9]+ */
babe1480 5854
4c4b4cd2
PH
5855 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5856 {
5857 matching = str + 3;
5858 while (isdigit (matching[0]))
dda83cd7 5859 matching += 1;
4c4b4cd2 5860 if (matching[0] == '\0')
dda83cd7 5861 return 1;
4c4b4cd2
PH
5862 }
5863
9ac7f98e
JB
5864 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5865
5866 if (strcmp (str, "TKB") == 0)
5867 return 1;
5868
529cad9c
PH
5869#if 0
5870 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
0963b4bd
MS
5871 with a N at the end. Unfortunately, the compiler uses the same
5872 convention for other internal types it creates. So treating
529cad9c 5873 all entity names that end with an "N" as a name suffix causes
0963b4bd
MS
5874 some regressions. For instance, consider the case of an enumerated
5875 type. To support the 'Image attribute, it creates an array whose
529cad9c
PH
5876 name ends with N.
5877 Having a single character like this as a suffix carrying some
0963b4bd 5878 information is a bit risky. Perhaps we should change the encoding
529cad9c
PH
5879 to be something like "_N" instead. In the meantime, do not do
5880 the following check. */
5881 /* Protected Object Subprograms */
5882 if (len == 1 && str [0] == 'N')
5883 return 1;
5884#endif
5885
5886 /* _E[0-9]+[bs]$ */
5887 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
5888 {
5889 matching = str + 3;
5890 while (isdigit (matching[0]))
dda83cd7 5891 matching += 1;
529cad9c 5892 if ((matching[0] == 'b' || matching[0] == 's')
dda83cd7
SM
5893 && matching [1] == '\0')
5894 return 1;
529cad9c
PH
5895 }
5896
4c4b4cd2
PH
5897 /* ??? We should not modify STR directly, as we are doing below. This
5898 is fine in this case, but may become problematic later if we find
5899 that this alternative did not work, and want to try matching
5900 another one from the begining of STR. Since we modified it, we
5901 won't be able to find the begining of the string anymore! */
14f9c5c9
AS
5902 if (str[0] == 'X')
5903 {
5904 str += 1;
d2e4a39e 5905 while (str[0] != '_' && str[0] != '\0')
dda83cd7
SM
5906 {
5907 if (str[0] != 'n' && str[0] != 'b')
5908 return 0;
5909 str += 1;
5910 }
14f9c5c9 5911 }
babe1480 5912
14f9c5c9
AS
5913 if (str[0] == '\000')
5914 return 1;
babe1480 5915
d2e4a39e 5916 if (str[0] == '_')
14f9c5c9
AS
5917 {
5918 if (str[1] != '_' || str[2] == '\000')
dda83cd7 5919 return 0;
d2e4a39e 5920 if (str[2] == '_')
dda83cd7
SM
5921 {
5922 if (strcmp (str + 3, "JM") == 0)
5923 return 1;
5924 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
5925 the LJM suffix in favor of the JM one. But we will
5926 still accept LJM as a valid suffix for a reasonable
5927 amount of time, just to allow ourselves to debug programs
5928 compiled using an older version of GNAT. */
5929 if (strcmp (str + 3, "LJM") == 0)
5930 return 1;
5931 if (str[3] != 'X')
5932 return 0;
5933 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
5934 || str[4] == 'U' || str[4] == 'P')
5935 return 1;
5936 if (str[4] == 'R' && str[5] != 'T')
5937 return 1;
5938 return 0;
5939 }
4c4b4cd2 5940 if (!isdigit (str[2]))
dda83cd7 5941 return 0;
4c4b4cd2 5942 for (k = 3; str[k] != '\0'; k += 1)
dda83cd7
SM
5943 if (!isdigit (str[k]) && str[k] != '_')
5944 return 0;
14f9c5c9
AS
5945 return 1;
5946 }
4c4b4cd2 5947 if (str[0] == '$' && isdigit (str[1]))
14f9c5c9 5948 {
4c4b4cd2 5949 for (k = 2; str[k] != '\0'; k += 1)
dda83cd7
SM
5950 if (!isdigit (str[k]) && str[k] != '_')
5951 return 0;
14f9c5c9
AS
5952 return 1;
5953 }
5954 return 0;
5955}
d2e4a39e 5956
aeb5907d
JB
5957/* Return non-zero if the string starting at NAME and ending before
5958 NAME_END contains no capital letters. */
529cad9c
PH
5959
5960static int
5961is_valid_name_for_wild_match (const char *name0)
5962{
f945dedf 5963 std::string decoded_name = ada_decode (name0);
529cad9c
PH
5964 int i;
5965
5823c3ef
JB
5966 /* If the decoded name starts with an angle bracket, it means that
5967 NAME0 does not follow the GNAT encoding format. It should then
5968 not be allowed as a possible wild match. */
5969 if (decoded_name[0] == '<')
5970 return 0;
5971
529cad9c
PH
5972 for (i=0; decoded_name[i] != '\0'; i++)
5973 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
5974 return 0;
5975
5976 return 1;
5977}
5978
59c8a30b
JB
5979/* Advance *NAMEP to next occurrence in the string NAME0 of the TARGET0
5980 character which could start a simple name. Assumes that *NAMEP points
5981 somewhere inside the string beginning at NAME0. */
4c4b4cd2 5982
14f9c5c9 5983static int
59c8a30b 5984advance_wild_match (const char **namep, const char *name0, char target0)
14f9c5c9 5985{
73589123 5986 const char *name = *namep;
5b4ee69b 5987
5823c3ef 5988 while (1)
14f9c5c9 5989 {
59c8a30b 5990 char t0, t1;
73589123
PH
5991
5992 t0 = *name;
5993 if (t0 == '_')
5994 {
5995 t1 = name[1];
5996 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
5997 {
5998 name += 1;
61012eef 5999 if (name == name0 + 5 && startswith (name0, "_ada"))
73589123
PH
6000 break;
6001 else
6002 name += 1;
6003 }
aa27d0b3
JB
6004 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
6005 || name[2] == target0))
73589123
PH
6006 {
6007 name += 2;
6008 break;
6009 }
86b44259
TT
6010 else if (t1 == '_' && name[2] == 'B' && name[3] == '_')
6011 {
6012 /* Names like "pkg__B_N__name", where N is a number, are
6013 block-local. We can handle these by simply skipping
6014 the "B_" here. */
6015 name += 4;
6016 }
73589123
PH
6017 else
6018 return 0;
6019 }
6020 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
6021 name += 1;
6022 else
5823c3ef 6023 return 0;
73589123
PH
6024 }
6025
6026 *namep = name;
6027 return 1;
6028}
6029
b5ec771e
PA
6030/* Return true iff NAME encodes a name of the form prefix.PATN.
6031 Ignores any informational suffixes of NAME (i.e., for which
6032 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6033 simple name. */
73589123 6034
b5ec771e 6035static bool
73589123
PH
6036wild_match (const char *name, const char *patn)
6037{
22e048c9 6038 const char *p;
73589123
PH
6039 const char *name0 = name;
6040
81eaa506
TT
6041 if (startswith (name, "___ghost_"))
6042 name += 9;
6043
73589123
PH
6044 while (1)
6045 {
6046 const char *match = name;
6047
6048 if (*name == *patn)
6049 {
6050 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6051 if (*p != *name)
6052 break;
6053 if (*p == '\0' && is_name_suffix (name))
b5ec771e 6054 return match == name0 || is_valid_name_for_wild_match (name0);
73589123
PH
6055
6056 if (name[-1] == '_')
6057 name -= 1;
6058 }
6059 if (!advance_wild_match (&name, name0, *patn))
b5ec771e 6060 return false;
96d887e8 6061 }
96d887e8
PH
6062}
6063
d1183b06 6064/* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to RESULT (if
b5ec771e 6065 necessary). OBJFILE is the section containing BLOCK. */
96d887e8
PH
6066
6067static void
d1183b06 6068ada_add_block_symbols (std::vector<struct block_symbol> &result,
b5ec771e
PA
6069 const struct block *block,
6070 const lookup_name_info &lookup_name,
6071 domain_enum domain, struct objfile *objfile)
96d887e8 6072{
96d887e8
PH
6073 /* A matching argument symbol, if any. */
6074 struct symbol *arg_sym;
6075 /* Set true when we find a matching non-argument symbol. */
1178743e 6076 bool found_sym;
96d887e8
PH
6077
6078 arg_sym = NULL;
1178743e 6079 found_sym = false;
1c49bb45 6080 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
96d887e8 6081 {
911e1e79 6082 if (sym->matches (domain))
b5ec771e 6083 {
66d7f48f 6084 if (sym->aclass () != LOC_UNRESOLVED)
b5ec771e 6085 {
d9743061 6086 if (sym->is_argument ())
b5ec771e
PA
6087 arg_sym = sym;
6088 else
6089 {
1178743e 6090 found_sym = true;
dae58e04 6091 add_defn_to_vec (result, sym, block);
b5ec771e
PA
6092 }
6093 }
6094 }
96d887e8
PH
6095 }
6096
22cee43f
PMR
6097 /* Handle renamings. */
6098
d1183b06 6099 if (ada_add_block_renamings (result, block, lookup_name, domain))
1178743e 6100 found_sym = true;
22cee43f 6101
96d887e8
PH
6102 if (!found_sym && arg_sym != NULL)
6103 {
dae58e04 6104 add_defn_to_vec (result, arg_sym, block);
96d887e8
PH
6105 }
6106
b5ec771e 6107 if (!lookup_name.ada ().wild_match_p ())
96d887e8
PH
6108 {
6109 arg_sym = NULL;
1178743e 6110 found_sym = false;
b5ec771e
PA
6111 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6112 const char *name = ada_lookup_name.c_str ();
6113 size_t name_len = ada_lookup_name.size ();
96d887e8 6114
548a89df 6115 for (struct symbol *sym : block_iterator_range (block))
76a01679 6116 {
911e1e79 6117 if (sym->matches (domain))
dda83cd7
SM
6118 {
6119 int cmp;
6120
6121 cmp = (int) '_' - (int) sym->linkage_name ()[0];
6122 if (cmp == 0)
6123 {
6124 cmp = !startswith (sym->linkage_name (), "_ada_");
6125 if (cmp == 0)
6126 cmp = strncmp (name, sym->linkage_name () + 5,
6127 name_len);
6128 }
6129
6130 if (cmp == 0
6131 && is_name_suffix (sym->linkage_name () + name_len + 5))
6132 {
66d7f48f 6133 if (sym->aclass () != LOC_UNRESOLVED)
2a2d4dc3 6134 {
d9743061 6135 if (sym->is_argument ())
2a2d4dc3
AS
6136 arg_sym = sym;
6137 else
6138 {
1178743e 6139 found_sym = true;
dae58e04 6140 add_defn_to_vec (result, sym, block);
2a2d4dc3
AS
6141 }
6142 }
dda83cd7
SM
6143 }
6144 }
76a01679 6145 }
96d887e8
PH
6146
6147 /* NOTE: This really shouldn't be needed for _ada_ symbols.
dda83cd7 6148 They aren't parameters, right? */
96d887e8 6149 if (!found_sym && arg_sym != NULL)
dda83cd7 6150 {
dae58e04 6151 add_defn_to_vec (result, arg_sym, block);
dda83cd7 6152 }
96d887e8
PH
6153 }
6154}
6155\f
41d27058 6156
dda83cd7 6157 /* Symbol Completion */
41d27058 6158
b5ec771e 6159/* See symtab.h. */
41d27058 6160
b5ec771e
PA
6161bool
6162ada_lookup_name_info::matches
6163 (const char *sym_name,
6164 symbol_name_match_type match_type,
a207cff2 6165 completion_match_result *comp_match_res) const
41d27058 6166{
b5ec771e
PA
6167 bool match = false;
6168 const char *text = m_encoded_name.c_str ();
6169 size_t text_len = m_encoded_name.size ();
41d27058
JB
6170
6171 /* First, test against the fully qualified name of the symbol. */
6172
6173 if (strncmp (sym_name, text, text_len) == 0)
b5ec771e 6174 match = true;
41d27058 6175
f945dedf 6176 std::string decoded_name = ada_decode (sym_name);
b5ec771e 6177 if (match && !m_encoded_p)
41d27058
JB
6178 {
6179 /* One needed check before declaring a positive match is to verify
dda83cd7
SM
6180 that iff we are doing a verbatim match, the decoded version
6181 of the symbol name starts with '<'. Otherwise, this symbol name
6182 is not a suitable completion. */
41d27058 6183
f945dedf 6184 bool has_angle_bracket = (decoded_name[0] == '<');
b5ec771e 6185 match = (has_angle_bracket == m_verbatim_p);
41d27058
JB
6186 }
6187
b5ec771e 6188 if (match && !m_verbatim_p)
41d27058
JB
6189 {
6190 /* When doing non-verbatim match, another check that needs to
dda83cd7
SM
6191 be done is to verify that the potentially matching symbol name
6192 does not include capital letters, because the ada-mode would
6193 not be able to understand these symbol names without the
6194 angle bracket notation. */
41d27058
JB
6195 const char *tmp;
6196
6197 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6198 if (*tmp != '\0')
b5ec771e 6199 match = false;
41d27058
JB
6200 }
6201
6202 /* Second: Try wild matching... */
6203
b5ec771e 6204 if (!match && m_wild_match_p)
41d27058
JB
6205 {
6206 /* Since we are doing wild matching, this means that TEXT
dda83cd7
SM
6207 may represent an unqualified symbol name. We therefore must
6208 also compare TEXT against the unqualified name of the symbol. */
f945dedf 6209 sym_name = ada_unqualified_name (decoded_name.c_str ());
41d27058
JB
6210
6211 if (strncmp (sym_name, text, text_len) == 0)
b5ec771e 6212 match = true;
41d27058
JB
6213 }
6214
b5ec771e 6215 /* Finally: If we found a match, prepare the result to return. */
41d27058
JB
6216
6217 if (!match)
b5ec771e 6218 return false;
41d27058 6219
a207cff2 6220 if (comp_match_res != NULL)
b5ec771e 6221 {
a207cff2 6222 std::string &match_str = comp_match_res->match.storage ();
41d27058 6223
b5ec771e 6224 if (!m_encoded_p)
a207cff2 6225 match_str = ada_decode (sym_name);
b5ec771e
PA
6226 else
6227 {
6228 if (m_verbatim_p)
6229 match_str = add_angle_brackets (sym_name);
6230 else
6231 match_str = sym_name;
41d27058 6232
b5ec771e 6233 }
a207cff2
PA
6234
6235 comp_match_res->set_match (match_str.c_str ());
41d27058
JB
6236 }
6237
b5ec771e 6238 return true;
41d27058
JB
6239}
6240
dda83cd7 6241 /* Field Access */
96d887e8 6242
73fb9985
JB
6243/* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6244 for tagged types. */
6245
6246static int
6247ada_is_dispatch_table_ptr_type (struct type *type)
6248{
0d5cff50 6249 const char *name;
73fb9985 6250
78134374 6251 if (type->code () != TYPE_CODE_PTR)
73fb9985
JB
6252 return 0;
6253
27710edb 6254 name = type->target_type ()->name ();
73fb9985
JB
6255 if (name == NULL)
6256 return 0;
6257
6258 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6259}
6260
ac4a2da4
JG
6261/* Return non-zero if TYPE is an interface tag. */
6262
6263static int
6264ada_is_interface_tag (struct type *type)
6265{
7d93a1e0 6266 const char *name = type->name ();
ac4a2da4
JG
6267
6268 if (name == NULL)
6269 return 0;
6270
6271 return (strcmp (name, "ada__tags__interface_tag") == 0);
6272}
6273
963a6417
PH
6274/* True if field number FIELD_NUM in struct or union type TYPE is supposed
6275 to be invisible to users. */
96d887e8 6276
963a6417
PH
6277int
6278ada_is_ignored_field (struct type *type, int field_num)
96d887e8 6279{
1f704f76 6280 if (field_num < 0 || field_num > type->num_fields ())
963a6417 6281 return 1;
ffde82bf 6282
73fb9985
JB
6283 /* Check the name of that field. */
6284 {
33d16dd9 6285 const char *name = type->field (field_num).name ();
73fb9985
JB
6286
6287 /* Anonymous field names should not be printed.
6288 brobecker/2007-02-20: I don't think this can actually happen
30baf67b 6289 but we don't want to print the value of anonymous fields anyway. */
73fb9985
JB
6290 if (name == NULL)
6291 return 1;
6292
ffde82bf
JB
6293 /* Normally, fields whose name start with an underscore ("_")
6294 are fields that have been internally generated by the compiler,
6295 and thus should not be printed. The "_parent" field is special,
6296 however: This is a field internally generated by the compiler
6297 for tagged types, and it contains the components inherited from
6298 the parent type. This field should not be printed as is, but
6299 should not be ignored either. */
61012eef 6300 if (name[0] == '_' && !startswith (name, "_parent"))
73fb9985 6301 return 1;
d537777d
TT
6302
6303 /* The compiler doesn't document this, but sometimes it emits
6304 a field whose name starts with a capital letter, like 'V148s'.
6305 These aren't marked as artificial in any way, but we know they
6306 should be ignored. However, wrapper fields should not be
6307 ignored. */
6308 if (name[0] == 'S' || name[0] == 'R' || name[0] == 'O')
6309 {
6310 /* Wrapper field. */
6311 }
6312 else if (isupper (name[0]))
6313 return 1;
73fb9985
JB
6314 }
6315
ac4a2da4
JG
6316 /* If this is the dispatch table of a tagged type or an interface tag,
6317 then ignore. */
73fb9985 6318 if (ada_is_tagged_type (type, 1)
940da03e
SM
6319 && (ada_is_dispatch_table_ptr_type (type->field (field_num).type ())
6320 || ada_is_interface_tag (type->field (field_num).type ())))
73fb9985
JB
6321 return 1;
6322
6323 /* Not a special field, so it should not be ignored. */
6324 return 0;
963a6417 6325}
96d887e8 6326
963a6417 6327/* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
0963b4bd 6328 pointer or reference type whose ultimate target has a tag field. */
96d887e8 6329
963a6417
PH
6330int
6331ada_is_tagged_type (struct type *type, int refok)
6332{
988f6b3d 6333 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
963a6417 6334}
96d887e8 6335
963a6417 6336/* True iff TYPE represents the type of X'Tag */
96d887e8 6337
963a6417
PH
6338int
6339ada_is_tag_type (struct type *type)
6340{
460efde1
JB
6341 type = ada_check_typedef (type);
6342
78134374 6343 if (type == NULL || type->code () != TYPE_CODE_PTR)
963a6417
PH
6344 return 0;
6345 else
96d887e8 6346 {
27710edb 6347 const char *name = ada_type_name (type->target_type ());
5b4ee69b 6348
963a6417 6349 return (name != NULL
dda83cd7 6350 && strcmp (name, "ada__tags__dispatch_table") == 0);
96d887e8 6351 }
96d887e8
PH
6352}
6353
963a6417 6354/* The type of the tag on VAL. */
76a01679 6355
de93309a 6356static struct type *
963a6417 6357ada_tag_type (struct value *val)
96d887e8 6358{
d0c97917 6359 return ada_lookup_struct_elt_type (val->type (), "_tag", 1, 0);
963a6417 6360}
96d887e8 6361
b50d69b5
JG
6362/* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6363 retired at Ada 05). */
6364
6365static int
6366is_ada95_tag (struct value *tag)
6367{
6368 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6369}
6370
963a6417 6371/* The value of the tag on VAL. */
96d887e8 6372
de93309a 6373static struct value *
963a6417
PH
6374ada_value_tag (struct value *val)
6375{
03ee6b2e 6376 return ada_value_struct_elt (val, "_tag", 0);
96d887e8
PH
6377}
6378
963a6417
PH
6379/* The value of the tag on the object of type TYPE whose contents are
6380 saved at VALADDR, if it is non-null, or is at memory address
0963b4bd 6381 ADDRESS. */
96d887e8 6382
963a6417 6383static struct value *
10a2c479 6384value_tag_from_contents_and_address (struct type *type,
fc1a4b47 6385 const gdb_byte *valaddr,
dda83cd7 6386 CORE_ADDR address)
96d887e8 6387{
b5385fc0 6388 int tag_byte_offset;
963a6417 6389 struct type *tag_type;
5b4ee69b 6390
4d1795ac
TT
6391 gdb::array_view<const gdb_byte> contents;
6392 if (valaddr != nullptr)
df86565b 6393 contents = gdb::make_array_view (valaddr, type->length ());
4d1795ac
TT
6394 struct type *resolved_type = resolve_dynamic_type (type, contents, address);
6395 if (find_struct_field ("_tag", resolved_type, 0, &tag_type, &tag_byte_offset,
dda83cd7 6396 NULL, NULL, NULL))
96d887e8 6397 {
fc1a4b47 6398 const gdb_byte *valaddr1 = ((valaddr == NULL)
10a2c479
AC
6399 ? NULL
6400 : valaddr + tag_byte_offset);
963a6417 6401 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
96d887e8 6402
963a6417 6403 return value_from_contents_and_address (tag_type, valaddr1, address1);
96d887e8 6404 }
963a6417
PH
6405 return NULL;
6406}
96d887e8 6407
963a6417
PH
6408static struct type *
6409type_from_tag (struct value *tag)
6410{
f5272a3b 6411 gdb::unique_xmalloc_ptr<char> type_name = ada_tag_name (tag);
5b4ee69b 6412
963a6417 6413 if (type_name != NULL)
5c4258f4 6414 return ada_find_any_type (ada_encode (type_name.get ()).c_str ());
963a6417
PH
6415 return NULL;
6416}
96d887e8 6417
b50d69b5
JG
6418/* Given a value OBJ of a tagged type, return a value of this
6419 type at the base address of the object. The base address, as
6420 defined in Ada.Tags, it is the address of the primary tag of
6421 the object, and therefore where the field values of its full
6422 view can be fetched. */
6423
6424struct value *
6425ada_tag_value_at_base_address (struct value *obj)
6426{
b50d69b5
JG
6427 struct value *val;
6428 LONGEST offset_to_top = 0;
6429 struct type *ptr_type, *obj_type;
6430 struct value *tag;
6431 CORE_ADDR base_address;
6432
d0c97917 6433 obj_type = obj->type ();
b50d69b5 6434
33b5899f 6435 /* It is the responsibility of the caller to deref pointers. */
b50d69b5 6436
78134374 6437 if (obj_type->code () == TYPE_CODE_PTR || obj_type->code () == TYPE_CODE_REF)
b50d69b5
JG
6438 return obj;
6439
6440 tag = ada_value_tag (obj);
6441 if (!tag)
6442 return obj;
6443
6444 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6445
6446 if (is_ada95_tag (tag))
6447 return obj;
6448
d537777d
TT
6449 struct type *offset_type
6450 = language_lookup_primitive_type (language_def (language_ada),
99d9c3b9
SM
6451 current_inferior ()->arch (),
6452 "storage_offset");
d537777d 6453 ptr_type = lookup_pointer_type (offset_type);
b50d69b5
JG
6454 val = value_cast (ptr_type, tag);
6455 if (!val)
6456 return obj;
6457
6458 /* It is perfectly possible that an exception be raised while
6459 trying to determine the base address, just like for the tag;
6460 see ada_tag_name for more details. We do not print the error
6461 message for the same reason. */
6462
a70b8144 6463 try
b50d69b5
JG
6464 {
6465 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6466 }
6467
230d2906 6468 catch (const gdb_exception_error &e)
492d29ea
PA
6469 {
6470 return obj;
6471 }
b50d69b5
JG
6472
6473 /* If offset is null, nothing to do. */
6474
6475 if (offset_to_top == 0)
6476 return obj;
6477
6478 /* -1 is a special case in Ada.Tags; however, what should be done
6479 is not quite clear from the documentation. So do nothing for
6480 now. */
6481
6482 if (offset_to_top == -1)
6483 return obj;
6484
d537777d
TT
6485 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6486 top is used. In this situation the offset is stored just after
6487 the tag, in the object itself. */
df86565b 6488 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
d537777d
TT
6489 if (offset_to_top == last)
6490 {
6491 struct value *tem = value_addr (tag);
6492 tem = value_ptradd (tem, 1);
6493 tem = value_cast (ptr_type, tem);
6494 offset_to_top = value_as_long (value_ind (tem));
6495 }
05527d8c
TV
6496
6497 if (offset_to_top > 0)
d537777d
TT
6498 {
6499 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6500 from the base address. This was however incompatible with
6501 C++ dispatch table: C++ uses a *negative* value to *add*
6502 to the base address. Ada's convention has therefore been
6503 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6504 use the same convention. Here, we support both cases by
6505 checking the sign of OFFSET_TO_TOP. */
6506 offset_to_top = -offset_to_top;
6507 }
08f49010 6508
9feb2d07 6509 base_address = obj->address () + offset_to_top;
b50d69b5
JG
6510 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6511
6512 /* Make sure that we have a proper tag at the new address.
6513 Otherwise, offset_to_top is bogus (which can happen when
6514 the object is not initialized yet). */
6515
6516 if (!tag)
6517 return obj;
6518
6519 obj_type = type_from_tag (tag);
6520
6521 if (!obj_type)
6522 return obj;
6523
6524 return value_from_contents_and_address (obj_type, NULL, base_address);
6525}
6526
1b611343
JB
6527/* Return the "ada__tags__type_specific_data" type. */
6528
6529static struct type *
6530ada_get_tsd_type (struct inferior *inf)
963a6417 6531{
1b611343 6532 struct ada_inferior_data *data = get_ada_inferior_data (inf);
4c4b4cd2 6533
1b611343
JB
6534 if (data->tsd_type == 0)
6535 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6536 return data->tsd_type;
6537}
529cad9c 6538
1b611343
JB
6539/* Return the TSD (type-specific data) associated to the given TAG.
6540 TAG is assumed to be the tag of a tagged-type entity.
529cad9c 6541
1b611343 6542 May return NULL if we are unable to get the TSD. */
4c4b4cd2 6543
1b611343
JB
6544static struct value *
6545ada_get_tsd_from_tag (struct value *tag)
4c4b4cd2 6546{
4c4b4cd2 6547 struct value *val;
1b611343 6548 struct type *type;
5b4ee69b 6549
1b611343
JB
6550 /* First option: The TSD is simply stored as a field of our TAG.
6551 Only older versions of GNAT would use this format, but we have
6552 to test it first, because there are no visible markers for
6553 the current approach except the absence of that field. */
529cad9c 6554
1b611343
JB
6555 val = ada_value_struct_elt (tag, "tsd", 1);
6556 if (val)
6557 return val;
e802dbe0 6558
1b611343
JB
6559 /* Try the second representation for the dispatch table (in which
6560 there is no explicit 'tsd' field in the referent of the tag pointer,
6561 and instead the tsd pointer is stored just before the dispatch
6562 table. */
e802dbe0 6563
1b611343
JB
6564 type = ada_get_tsd_type (current_inferior());
6565 if (type == NULL)
6566 return NULL;
6567 type = lookup_pointer_type (lookup_pointer_type (type));
6568 val = value_cast (type, tag);
6569 if (val == NULL)
6570 return NULL;
6571 return value_ind (value_ptradd (val, -1));
e802dbe0
JB
6572}
6573
1b611343
JB
6574/* Given the TSD of a tag (type-specific data), return a string
6575 containing the name of the associated type.
6576
f5272a3b 6577 May return NULL if we are unable to determine the tag name. */
1b611343 6578
f5272a3b 6579static gdb::unique_xmalloc_ptr<char>
1b611343 6580ada_tag_name_from_tsd (struct value *tsd)
529cad9c 6581{
1b611343 6582 struct value *val;
529cad9c 6583
1b611343 6584 val = ada_value_struct_elt (tsd, "expanded_name", 1);
4c4b4cd2 6585 if (val == NULL)
1b611343 6586 return NULL;
66920317
TT
6587 gdb::unique_xmalloc_ptr<char> buffer
6588 = target_read_string (value_as_address (val), INT_MAX);
6589 if (buffer == nullptr)
f5272a3b
TT
6590 return nullptr;
6591
315e4ebb 6592 try
f5272a3b 6593 {
315e4ebb
TT
6594 /* Let this throw an exception on error. If the data is
6595 uninitialized, we'd rather not have the user see a
6596 warning. */
6597 const char *folded = ada_fold_name (buffer.get (), true);
6598 return make_unique_xstrdup (folded);
6599 }
6600 catch (const gdb_exception &)
6601 {
6602 return nullptr;
f5272a3b 6603 }
4c4b4cd2
PH
6604}
6605
6606/* The type name of the dynamic type denoted by the 'tag value TAG, as
1b611343
JB
6607 a C string.
6608
6609 Return NULL if the TAG is not an Ada tag, or if we were unable to
f5272a3b 6610 determine the name of that tag. */
4c4b4cd2 6611
f5272a3b 6612gdb::unique_xmalloc_ptr<char>
4c4b4cd2
PH
6613ada_tag_name (struct value *tag)
6614{
f5272a3b 6615 gdb::unique_xmalloc_ptr<char> name;
5b4ee69b 6616
d0c97917 6617 if (!ada_is_tag_type (tag->type ()))
4c4b4cd2 6618 return NULL;
1b611343
JB
6619
6620 /* It is perfectly possible that an exception be raised while trying
6621 to determine the TAG's name, even under normal circumstances:
6622 The associated variable may be uninitialized or corrupted, for
6623 instance. We do not let any exception propagate past this point.
6624 instead we return NULL.
6625
6626 We also do not print the error message either (which often is very
6627 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6628 the caller print a more meaningful message if necessary. */
a70b8144 6629 try
1b611343
JB
6630 {
6631 struct value *tsd = ada_get_tsd_from_tag (tag);
6632
6633 if (tsd != NULL)
6634 name = ada_tag_name_from_tsd (tsd);
6635 }
230d2906 6636 catch (const gdb_exception_error &e)
492d29ea
PA
6637 {
6638 }
1b611343
JB
6639
6640 return name;
4c4b4cd2
PH
6641}
6642
6643/* The parent type of TYPE, or NULL if none. */
14f9c5c9 6644
d2e4a39e 6645struct type *
ebf56fd3 6646ada_parent_type (struct type *type)
14f9c5c9
AS
6647{
6648 int i;
6649
61ee279c 6650 type = ada_check_typedef (type);
14f9c5c9 6651
78134374 6652 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
14f9c5c9
AS
6653 return NULL;
6654
1f704f76 6655 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 6656 if (ada_is_parent_field (type, i))
0c1f74cf 6657 {
dda83cd7 6658 struct type *parent_type = type->field (i).type ();
0c1f74cf 6659
dda83cd7
SM
6660 /* If the _parent field is a pointer, then dereference it. */
6661 if (parent_type->code () == TYPE_CODE_PTR)
27710edb 6662 parent_type = parent_type->target_type ();
dda83cd7
SM
6663 /* If there is a parallel XVS type, get the actual base type. */
6664 parent_type = ada_get_base_type (parent_type);
0c1f74cf 6665
dda83cd7 6666 return ada_check_typedef (parent_type);
0c1f74cf 6667 }
14f9c5c9
AS
6668
6669 return NULL;
6670}
6671
4c4b4cd2
PH
6672/* True iff field number FIELD_NUM of structure type TYPE contains the
6673 parent-type (inherited) fields of a derived type. Assumes TYPE is
6674 a structure type with at least FIELD_NUM+1 fields. */
14f9c5c9
AS
6675
6676int
ebf56fd3 6677ada_is_parent_field (struct type *type, int field_num)
14f9c5c9 6678{
33d16dd9 6679 const char *name = ada_check_typedef (type)->field (field_num).name ();
5b4ee69b 6680
4c4b4cd2 6681 return (name != NULL
dda83cd7
SM
6682 && (startswith (name, "PARENT")
6683 || startswith (name, "_parent")));
14f9c5c9
AS
6684}
6685
4c4b4cd2 6686/* True iff field number FIELD_NUM of structure type TYPE is a
14f9c5c9 6687 transparent wrapper field (which should be silently traversed when doing
4c4b4cd2 6688 field selection and flattened when printing). Assumes TYPE is a
14f9c5c9 6689 structure type with at least FIELD_NUM+1 fields. Such fields are always
4c4b4cd2 6690 structures. */
14f9c5c9
AS
6691
6692int
ebf56fd3 6693ada_is_wrapper_field (struct type *type, int field_num)
14f9c5c9 6694{
33d16dd9 6695 const char *name = type->field (field_num).name ();
5b4ee69b 6696
dddc0e16
JB
6697 if (name != NULL && strcmp (name, "RETVAL") == 0)
6698 {
6699 /* This happens in functions with "out" or "in out" parameters
6700 which are passed by copy. For such functions, GNAT describes
6701 the function's return type as being a struct where the return
6702 value is in a field called RETVAL, and where the other "out"
6703 or "in out" parameters are fields of that struct. This is not
6704 a wrapper. */
6705 return 0;
6706 }
6707
d2e4a39e 6708 return (name != NULL
dda83cd7
SM
6709 && (startswith (name, "PARENT")
6710 || strcmp (name, "REP") == 0
6711 || startswith (name, "_parent")
6712 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
14f9c5c9
AS
6713}
6714
4c4b4cd2
PH
6715/* True iff field number FIELD_NUM of structure or union type TYPE
6716 is a variant wrapper. Assumes TYPE is a structure type with at least
6717 FIELD_NUM+1 fields. */
14f9c5c9
AS
6718
6719int
ebf56fd3 6720ada_is_variant_part (struct type *type, int field_num)
14f9c5c9 6721{
8ecb59f8
TT
6722 /* Only Ada types are eligible. */
6723 if (!ADA_TYPE_P (type))
6724 return 0;
6725
940da03e 6726 struct type *field_type = type->field (field_num).type ();
5b4ee69b 6727
78134374
SM
6728 return (field_type->code () == TYPE_CODE_UNION
6729 || (is_dynamic_field (type, field_num)
27710edb 6730 && (field_type->target_type ()->code ()
c3e5cd34 6731 == TYPE_CODE_UNION)));
14f9c5c9
AS
6732}
6733
6734/* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
4c4b4cd2 6735 whose discriminants are contained in the record type OUTER_TYPE,
7c964f07
UW
6736 returns the type of the controlling discriminant for the variant.
6737 May return NULL if the type could not be found. */
14f9c5c9 6738
d2e4a39e 6739struct type *
ebf56fd3 6740ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
14f9c5c9 6741{
a121b7c1 6742 const char *name = ada_variant_discrim_name (var_type);
5b4ee69b 6743
988f6b3d 6744 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
14f9c5c9
AS
6745}
6746
4c4b4cd2 6747/* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
14f9c5c9 6748 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
4c4b4cd2 6749 represents a 'when others' clause; otherwise 0. */
14f9c5c9 6750
de93309a 6751static int
ebf56fd3 6752ada_is_others_clause (struct type *type, int field_num)
14f9c5c9 6753{
33d16dd9 6754 const char *name = type->field (field_num).name ();
5b4ee69b 6755
14f9c5c9
AS
6756 return (name != NULL && name[0] == 'O');
6757}
6758
6759/* Assuming that TYPE0 is the type of the variant part of a record,
4c4b4cd2
PH
6760 returns the name of the discriminant controlling the variant.
6761 The value is valid until the next call to ada_variant_discrim_name. */
14f9c5c9 6762
a121b7c1 6763const char *
ebf56fd3 6764ada_variant_discrim_name (struct type *type0)
14f9c5c9 6765{
5f9febe0 6766 static std::string result;
d2e4a39e
AS
6767 struct type *type;
6768 const char *name;
6769 const char *discrim_end;
6770 const char *discrim_start;
14f9c5c9 6771
78134374 6772 if (type0->code () == TYPE_CODE_PTR)
27710edb 6773 type = type0->target_type ();
14f9c5c9
AS
6774 else
6775 type = type0;
6776
6777 name = ada_type_name (type);
6778
6779 if (name == NULL || name[0] == '\000')
6780 return "";
6781
6782 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6783 discrim_end -= 1)
6784 {
61012eef 6785 if (startswith (discrim_end, "___XVN"))
dda83cd7 6786 break;
14f9c5c9
AS
6787 }
6788 if (discrim_end == name)
6789 return "";
6790
d2e4a39e 6791 for (discrim_start = discrim_end; discrim_start != name + 3;
14f9c5c9
AS
6792 discrim_start -= 1)
6793 {
d2e4a39e 6794 if (discrim_start == name + 1)
dda83cd7 6795 return "";
76a01679 6796 if ((discrim_start > name + 3
dda83cd7
SM
6797 && startswith (discrim_start - 3, "___"))
6798 || discrim_start[-1] == '.')
6799 break;
14f9c5c9
AS
6800 }
6801
5f9febe0
TT
6802 result = std::string (discrim_start, discrim_end - discrim_start);
6803 return result.c_str ();
14f9c5c9
AS
6804}
6805
4c4b4cd2
PH
6806/* Scan STR for a subtype-encoded number, beginning at position K.
6807 Put the position of the character just past the number scanned in
6808 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6809 Return 1 if there was a valid number at the given position, and 0
6810 otherwise. A "subtype-encoded" number consists of the absolute value
6811 in decimal, followed by the letter 'm' to indicate a negative number.
6812 Assumes 0m does not occur. */
14f9c5c9
AS
6813
6814int
d2e4a39e 6815ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
14f9c5c9
AS
6816{
6817 ULONGEST RU;
6818
d2e4a39e 6819 if (!isdigit (str[k]))
14f9c5c9
AS
6820 return 0;
6821
4c4b4cd2 6822 /* Do it the hard way so as not to make any assumption about
14f9c5c9 6823 the relationship of unsigned long (%lu scan format code) and
4c4b4cd2 6824 LONGEST. */
14f9c5c9
AS
6825 RU = 0;
6826 while (isdigit (str[k]))
6827 {
d2e4a39e 6828 RU = RU * 10 + (str[k] - '0');
14f9c5c9
AS
6829 k += 1;
6830 }
6831
d2e4a39e 6832 if (str[k] == 'm')
14f9c5c9
AS
6833 {
6834 if (R != NULL)
dda83cd7 6835 *R = (-(LONGEST) (RU - 1)) - 1;
14f9c5c9
AS
6836 k += 1;
6837 }
6838 else if (R != NULL)
6839 *R = (LONGEST) RU;
6840
4c4b4cd2 6841 /* NOTE on the above: Technically, C does not say what the results of
14f9c5c9
AS
6842 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6843 number representable as a LONGEST (although either would probably work
6844 in most implementations). When RU>0, the locution in the then branch
4c4b4cd2 6845 above is always equivalent to the negative of RU. */
14f9c5c9
AS
6846
6847 if (new_k != NULL)
6848 *new_k = k;
6849 return 1;
6850}
6851
4c4b4cd2
PH
6852/* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6853 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6854 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
14f9c5c9 6855
de93309a 6856static int
ebf56fd3 6857ada_in_variant (LONGEST val, struct type *type, int field_num)
14f9c5c9 6858{
33d16dd9 6859 const char *name = type->field (field_num).name ();
14f9c5c9
AS
6860 int p;
6861
6862 p = 0;
6863 while (1)
6864 {
d2e4a39e 6865 switch (name[p])
dda83cd7
SM
6866 {
6867 case '\0':
6868 return 0;
6869 case 'S':
6870 {
6871 LONGEST W;
6872
6873 if (!ada_scan_number (name, p + 1, &W, &p))
6874 return 0;
6875 if (val == W)
6876 return 1;
6877 break;
6878 }
6879 case 'R':
6880 {
6881 LONGEST L, U;
6882
6883 if (!ada_scan_number (name, p + 1, &L, &p)
6884 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6885 return 0;
6886 if (val >= L && val <= U)
6887 return 1;
6888 break;
6889 }
6890 case 'O':
6891 return 1;
6892 default:
6893 return 0;
6894 }
4c4b4cd2
PH
6895 }
6896}
6897
0963b4bd 6898/* FIXME: Lots of redundancy below. Try to consolidate. */
4c4b4cd2
PH
6899
6900/* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6901 ARG_TYPE, extract and return the value of one of its (non-static)
6902 fields. FIELDNO says which field. Differs from value_primitive_field
6903 only in that it can handle packed values of arbitrary type. */
14f9c5c9 6904
5eb68a39 6905struct value *
d2e4a39e 6906ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
dda83cd7 6907 struct type *arg_type)
14f9c5c9 6908{
14f9c5c9
AS
6909 struct type *type;
6910
61ee279c 6911 arg_type = ada_check_typedef (arg_type);
940da03e 6912 type = arg_type->field (fieldno).type ();
14f9c5c9 6913
4504bbde
TT
6914 /* Handle packed fields. It might be that the field is not packed
6915 relative to its containing structure, but the structure itself is
6916 packed; in this case we must take the bit-field path. */
3757d2d4 6917 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
14f9c5c9 6918 {
b610c045 6919 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
3757d2d4 6920 int bit_size = arg_type->field (fieldno).bitsize ();
d2e4a39e 6921
50888e42 6922 return ada_value_primitive_packed_val (arg1,
efaf1ae0 6923 arg1->contents ().data (),
dda83cd7
SM
6924 offset + bit_pos / 8,
6925 bit_pos % 8, bit_size, type);
14f9c5c9
AS
6926 }
6927 else
6c49729e 6928 return arg1->primitive_field (offset, fieldno, arg_type);
14f9c5c9
AS
6929}
6930
52ce6436
PH
6931/* Find field with name NAME in object of type TYPE. If found,
6932 set the following for each argument that is non-null:
6933 - *FIELD_TYPE_P to the field's type;
6934 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6935 an object of that type;
6936 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6937 - *BIT_SIZE_P to its size in bits if the field is packed, and
6938 0 otherwise;
6939 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6940 fields up to but not including the desired field, or by the total
6941 number of fields if not found. A NULL value of NAME never
6942 matches; the function just counts visible fields in this case.
6943
828d5846
XR
6944 Notice that we need to handle when a tagged record hierarchy
6945 has some components with the same name, like in this scenario:
6946
6947 type Top_T is tagged record
dda83cd7
SM
6948 N : Integer := 1;
6949 U : Integer := 974;
6950 A : Integer := 48;
828d5846
XR
6951 end record;
6952
6953 type Middle_T is new Top.Top_T with record
dda83cd7
SM
6954 N : Character := 'a';
6955 C : Integer := 3;
828d5846
XR
6956 end record;
6957
6958 type Bottom_T is new Middle.Middle_T with record
dda83cd7
SM
6959 N : Float := 4.0;
6960 C : Character := '5';
6961 X : Integer := 6;
6962 A : Character := 'J';
828d5846
XR
6963 end record;
6964
6965 Let's say we now have a variable declared and initialized as follow:
6966
6967 TC : Top_A := new Bottom_T;
6968
6969 And then we use this variable to call this function
6970
6971 procedure Assign (Obj: in out Top_T; TV : Integer);
6972
6973 as follow:
6974
6975 Assign (Top_T (B), 12);
6976
6977 Now, we're in the debugger, and we're inside that procedure
6978 then and we want to print the value of obj.c:
6979
6980 Usually, the tagged record or one of the parent type owns the
6981 component to print and there's no issue but in this particular
6982 case, what does it mean to ask for Obj.C? Since the actual
6983 type for object is type Bottom_T, it could mean two things: type
6984 component C from the Middle_T view, but also component C from
6985 Bottom_T. So in that "undefined" case, when the component is
6986 not found in the non-resolved type (which includes all the
6987 components of the parent type), then resolve it and see if we
6988 get better luck once expanded.
6989
6990 In the case of homonyms in the derived tagged type, we don't
6991 guaranty anything, and pick the one that's easiest for us
6992 to program.
6993
0963b4bd 6994 Returns 1 if found, 0 otherwise. */
52ce6436 6995
4c4b4cd2 6996static int
0d5cff50 6997find_struct_field (const char *name, struct type *type, int offset,
dda83cd7
SM
6998 struct type **field_type_p,
6999 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
52ce6436 7000 int *index_p)
4c4b4cd2
PH
7001{
7002 int i;
828d5846 7003 int parent_offset = -1;
4c4b4cd2 7004
61ee279c 7005 type = ada_check_typedef (type);
76a01679 7006
52ce6436
PH
7007 if (field_type_p != NULL)
7008 *field_type_p = NULL;
7009 if (byte_offset_p != NULL)
d5d6fca5 7010 *byte_offset_p = 0;
52ce6436
PH
7011 if (bit_offset_p != NULL)
7012 *bit_offset_p = 0;
7013 if (bit_size_p != NULL)
7014 *bit_size_p = 0;
7015
1f704f76 7016 for (i = 0; i < type->num_fields (); i += 1)
4c4b4cd2 7017 {
4d1795ac
TT
7018 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
7019 type. However, we only need the values to be correct when
7020 the caller asks for them. */
7021 int bit_pos = 0, fld_offset = 0;
7022 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7023 {
b610c045 7024 bit_pos = type->field (i).loc_bitpos ();
4d1795ac
TT
7025 fld_offset = offset + bit_pos / 8;
7026 }
7027
33d16dd9 7028 const char *t_field_name = type->field (i).name ();
76a01679 7029
4c4b4cd2 7030 if (t_field_name == NULL)
dda83cd7 7031 continue;
4c4b4cd2 7032
828d5846 7033 else if (ada_is_parent_field (type, i))
dda83cd7 7034 {
828d5846
XR
7035 /* This is a field pointing us to the parent type of a tagged
7036 type. As hinted in this function's documentation, we give
7037 preference to fields in the current record first, so what
7038 we do here is just record the index of this field before
7039 we skip it. If it turns out we couldn't find our field
7040 in the current record, then we'll get back to it and search
7041 inside it whether the field might exist in the parent. */
7042
dda83cd7
SM
7043 parent_offset = i;
7044 continue;
7045 }
828d5846 7046
52ce6436 7047 else if (name != NULL && field_name_match (t_field_name, name))
dda83cd7 7048 {
3757d2d4 7049 int bit_size = type->field (i).bitsize ();
5b4ee69b 7050
52ce6436 7051 if (field_type_p != NULL)
940da03e 7052 *field_type_p = type->field (i).type ();
52ce6436
PH
7053 if (byte_offset_p != NULL)
7054 *byte_offset_p = fld_offset;
7055 if (bit_offset_p != NULL)
7056 *bit_offset_p = bit_pos % 8;
7057 if (bit_size_p != NULL)
7058 *bit_size_p = bit_size;
dda83cd7
SM
7059 return 1;
7060 }
4c4b4cd2 7061 else if (ada_is_wrapper_field (type, i))
dda83cd7 7062 {
940da03e 7063 if (find_struct_field (name, type->field (i).type (), fld_offset,
52ce6436
PH
7064 field_type_p, byte_offset_p, bit_offset_p,
7065 bit_size_p, index_p))
dda83cd7
SM
7066 return 1;
7067 }
4c4b4cd2 7068 else if (ada_is_variant_part (type, i))
dda83cd7 7069 {
52ce6436
PH
7070 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7071 fixed type?? */
dda83cd7
SM
7072 int j;
7073 struct type *field_type
940da03e 7074 = ada_check_typedef (type->field (i).type ());
4c4b4cd2 7075
dda83cd7
SM
7076 for (j = 0; j < field_type->num_fields (); j += 1)
7077 {
7078 if (find_struct_field (name, field_type->field (j).type (),
7079 fld_offset
b610c045 7080 + field_type->field (j).loc_bitpos () / 8,
dda83cd7
SM
7081 field_type_p, byte_offset_p,
7082 bit_offset_p, bit_size_p, index_p))
7083 return 1;
7084 }
7085 }
52ce6436
PH
7086 else if (index_p != NULL)
7087 *index_p += 1;
4c4b4cd2 7088 }
828d5846
XR
7089
7090 /* Field not found so far. If this is a tagged type which
7091 has a parent, try finding that field in the parent now. */
7092
7093 if (parent_offset != -1)
7094 {
4d1795ac
TT
7095 /* As above, only compute the offset when truly needed. */
7096 int fld_offset = offset;
7097 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7098 {
b610c045 7099 int bit_pos = type->field (parent_offset).loc_bitpos ();
4d1795ac
TT
7100 fld_offset += bit_pos / 8;
7101 }
828d5846 7102
940da03e 7103 if (find_struct_field (name, type->field (parent_offset).type (),
dda83cd7
SM
7104 fld_offset, field_type_p, byte_offset_p,
7105 bit_offset_p, bit_size_p, index_p))
7106 return 1;
828d5846
XR
7107 }
7108
4c4b4cd2
PH
7109 return 0;
7110}
7111
0963b4bd 7112/* Number of user-visible fields in record type TYPE. */
4c4b4cd2 7113
52ce6436
PH
7114static int
7115num_visible_fields (struct type *type)
7116{
7117 int n;
5b4ee69b 7118
52ce6436
PH
7119 n = 0;
7120 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7121 return n;
7122}
14f9c5c9 7123
4c4b4cd2 7124/* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
14f9c5c9
AS
7125 and search in it assuming it has (class) type TYPE.
7126 If found, return value, else return NULL.
7127
828d5846
XR
7128 Searches recursively through wrapper fields (e.g., '_parent').
7129
7130 In the case of homonyms in the tagged types, please refer to the
7131 long explanation in find_struct_field's function documentation. */
14f9c5c9 7132
4c4b4cd2 7133static struct value *
108d56a4 7134ada_search_struct_field (const char *name, struct value *arg, int offset,
dda83cd7 7135 struct type *type)
14f9c5c9
AS
7136{
7137 int i;
828d5846 7138 int parent_offset = -1;
14f9c5c9 7139
5b4ee69b 7140 type = ada_check_typedef (type);
1f704f76 7141 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 7142 {
33d16dd9 7143 const char *t_field_name = type->field (i).name ();
14f9c5c9
AS
7144
7145 if (t_field_name == NULL)
dda83cd7 7146 continue;
14f9c5c9 7147
828d5846 7148 else if (ada_is_parent_field (type, i))
dda83cd7 7149 {
828d5846
XR
7150 /* This is a field pointing us to the parent type of a tagged
7151 type. As hinted in this function's documentation, we give
7152 preference to fields in the current record first, so what
7153 we do here is just record the index of this field before
7154 we skip it. If it turns out we couldn't find our field
7155 in the current record, then we'll get back to it and search
7156 inside it whether the field might exist in the parent. */
7157
dda83cd7
SM
7158 parent_offset = i;
7159 continue;
7160 }
828d5846 7161
14f9c5c9 7162 else if (field_name_match (t_field_name, name))
dda83cd7 7163 return ada_value_primitive_field (arg, offset, i, type);
14f9c5c9
AS
7164
7165 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7166 {
7167 struct value *v = /* Do not let indent join lines here. */
7168 ada_search_struct_field (name, arg,
b610c045 7169 offset + type->field (i).loc_bitpos () / 8,
dda83cd7 7170 type->field (i).type ());
5b4ee69b 7171
dda83cd7
SM
7172 if (v != NULL)
7173 return v;
7174 }
14f9c5c9
AS
7175
7176 else if (ada_is_variant_part (type, i))
dda83cd7 7177 {
0963b4bd 7178 /* PNH: Do we ever get here? See find_struct_field. */
dda83cd7
SM
7179 int j;
7180 struct type *field_type = ada_check_typedef (type->field (i).type ());
b610c045 7181 int var_offset = offset + type->field (i).loc_bitpos () / 8;
4c4b4cd2 7182
dda83cd7
SM
7183 for (j = 0; j < field_type->num_fields (); j += 1)
7184 {
7185 struct value *v = ada_search_struct_field /* Force line
0963b4bd 7186 break. */
dda83cd7 7187 (name, arg,
b610c045 7188 var_offset + field_type->field (j).loc_bitpos () / 8,
dda83cd7 7189 field_type->field (j).type ());
5b4ee69b 7190
dda83cd7
SM
7191 if (v != NULL)
7192 return v;
7193 }
7194 }
14f9c5c9 7195 }
828d5846
XR
7196
7197 /* Field not found so far. If this is a tagged type which
7198 has a parent, try finding that field in the parent now. */
7199
7200 if (parent_offset != -1)
7201 {
7202 struct value *v = ada_search_struct_field (
b610c045 7203 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
940da03e 7204 type->field (parent_offset).type ());
828d5846
XR
7205
7206 if (v != NULL)
dda83cd7 7207 return v;
828d5846
XR
7208 }
7209
14f9c5c9
AS
7210 return NULL;
7211}
d2e4a39e 7212
52ce6436
PH
7213static struct value *ada_index_struct_field_1 (int *, struct value *,
7214 int, struct type *);
7215
7216
7217/* Return field #INDEX in ARG, where the index is that returned by
7218 * find_struct_field through its INDEX_P argument. Adjust the address
7219 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
0963b4bd 7220 * If found, return value, else return NULL. */
52ce6436
PH
7221
7222static struct value *
7223ada_index_struct_field (int index, struct value *arg, int offset,
7224 struct type *type)
7225{
7226 return ada_index_struct_field_1 (&index, arg, offset, type);
7227}
7228
7229
7230/* Auxiliary function for ada_index_struct_field. Like
7231 * ada_index_struct_field, but takes index from *INDEX_P and modifies
0963b4bd 7232 * *INDEX_P. */
52ce6436
PH
7233
7234static struct value *
7235ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7236 struct type *type)
7237{
7238 int i;
7239 type = ada_check_typedef (type);
7240
1f704f76 7241 for (i = 0; i < type->num_fields (); i += 1)
52ce6436 7242 {
33d16dd9 7243 if (type->field (i).name () == NULL)
dda83cd7 7244 continue;
52ce6436 7245 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7246 {
7247 struct value *v = /* Do not let indent join lines here. */
7248 ada_index_struct_field_1 (index_p, arg,
b610c045 7249 offset + type->field (i).loc_bitpos () / 8,
940da03e 7250 type->field (i).type ());
5b4ee69b 7251
dda83cd7
SM
7252 if (v != NULL)
7253 return v;
7254 }
52ce6436
PH
7255
7256 else if (ada_is_variant_part (type, i))
dda83cd7 7257 {
52ce6436 7258 /* PNH: Do we ever get here? See ada_search_struct_field,
0963b4bd 7259 find_struct_field. */
52ce6436 7260 error (_("Cannot assign this kind of variant record"));
dda83cd7 7261 }
52ce6436 7262 else if (*index_p == 0)
dda83cd7 7263 return ada_value_primitive_field (arg, offset, i, type);
52ce6436
PH
7264 else
7265 *index_p -= 1;
7266 }
7267 return NULL;
7268}
7269
3b4de39c 7270/* Return a string representation of type TYPE. */
99bbb428 7271
3b4de39c 7272static std::string
99bbb428
PA
7273type_as_string (struct type *type)
7274{
d7e74731 7275 string_file tmp_stream;
99bbb428 7276
d7e74731 7277 type_print (type, "", &tmp_stream, -1);
99bbb428 7278
5d10a204 7279 return tmp_stream.release ();
99bbb428
PA
7280}
7281
14f9c5c9 7282/* Given a type TYPE, look up the type of the component of type named NAME.
14f9c5c9
AS
7283
7284 Matches any field whose name has NAME as a prefix, possibly
4c4b4cd2 7285 followed by "___".
14f9c5c9 7286
0963b4bd 7287 TYPE can be either a struct or union. If REFOK, TYPE may also
4c4b4cd2
PH
7288 be a (pointer or reference)+ to a struct or union, and the
7289 ultimate target type will be searched.
14f9c5c9
AS
7290
7291 Looks recursively into variant clauses and parent types.
7292
828d5846
XR
7293 In the case of homonyms in the tagged types, please refer to the
7294 long explanation in find_struct_field's function documentation.
7295
4c4b4cd2
PH
7296 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7297 TYPE is not a type of the right kind. */
14f9c5c9 7298
4c4b4cd2 7299static struct type *
a121b7c1 7300ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
dda83cd7 7301 int noerr)
14f9c5c9 7302{
14f9c5c9
AS
7303 if (name == NULL)
7304 goto BadName;
7305
76a01679 7306 if (refok && type != NULL)
4c4b4cd2
PH
7307 while (1)
7308 {
dda83cd7
SM
7309 type = ada_check_typedef (type);
7310 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7311 break;
27710edb 7312 type = type->target_type ();
4c4b4cd2 7313 }
14f9c5c9 7314
76a01679 7315 if (type == NULL
78134374
SM
7316 || (type->code () != TYPE_CODE_STRUCT
7317 && type->code () != TYPE_CODE_UNION))
14f9c5c9 7318 {
4c4b4cd2 7319 if (noerr)
dda83cd7 7320 return NULL;
99bbb428 7321
3b4de39c
PA
7322 error (_("Type %s is not a structure or union type"),
7323 type != NULL ? type_as_string (type).c_str () : _("(null)"));
14f9c5c9
AS
7324 }
7325
7326 type = to_static_fixed_type (type);
7327
f0874f41
TT
7328 struct type *result;
7329 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7330 nullptr);
7331 if (result != nullptr)
7332 return result;
828d5846 7333
14f9c5c9 7334BadName:
d2e4a39e 7335 if (!noerr)
14f9c5c9 7336 {
2b2798cc 7337 const char *name_str = name != NULL ? name : _("<null>");
99bbb428
PA
7338
7339 error (_("Type %s has no component named %s"),
3b4de39c 7340 type_as_string (type).c_str (), name_str);
14f9c5c9
AS
7341 }
7342
7343 return NULL;
7344}
7345
b1f33ddd
JB
7346/* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7347 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7348 represents an unchecked union (that is, the variant part of a
0963b4bd 7349 record that is named in an Unchecked_Union pragma). */
b1f33ddd
JB
7350
7351static int
7352is_unchecked_variant (struct type *var_type, struct type *outer_type)
7353{
a121b7c1 7354 const char *discrim_name = ada_variant_discrim_name (var_type);
5b4ee69b 7355
988f6b3d 7356 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
b1f33ddd
JB
7357}
7358
7359
14f9c5c9 7360/* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
d8af9068 7361 within OUTER, determine which variant clause (field number in VAR_TYPE,
4c4b4cd2 7362 numbering from 0) is applicable. Returns -1 if none are. */
14f9c5c9 7363
d2e4a39e 7364int
d8af9068 7365ada_which_variant_applies (struct type *var_type, struct value *outer)
14f9c5c9
AS
7366{
7367 int others_clause;
7368 int i;
a121b7c1 7369 const char *discrim_name = ada_variant_discrim_name (var_type);
0c281816 7370 struct value *discrim;
14f9c5c9
AS
7371 LONGEST discrim_val;
7372
012370f6
TT
7373 /* Using plain value_from_contents_and_address here causes problems
7374 because we will end up trying to resolve a type that is currently
7375 being constructed. */
0c281816
JB
7376 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7377 if (discrim == NULL)
14f9c5c9 7378 return -1;
0c281816 7379 discrim_val = value_as_long (discrim);
14f9c5c9
AS
7380
7381 others_clause = -1;
1f704f76 7382 for (i = 0; i < var_type->num_fields (); i += 1)
14f9c5c9
AS
7383 {
7384 if (ada_is_others_clause (var_type, i))
dda83cd7 7385 others_clause = i;
14f9c5c9 7386 else if (ada_in_variant (discrim_val, var_type, i))
dda83cd7 7387 return i;
14f9c5c9
AS
7388 }
7389
7390 return others_clause;
7391}
d2e4a39e 7392\f
14f9c5c9
AS
7393
7394
dda83cd7 7395 /* Dynamic-Sized Records */
14f9c5c9
AS
7396
7397/* Strategy: The type ostensibly attached to a value with dynamic size
7398 (i.e., a size that is not statically recorded in the debugging
7399 data) does not accurately reflect the size or layout of the value.
7400 Our strategy is to convert these values to values with accurate,
4c4b4cd2 7401 conventional types that are constructed on the fly. */
14f9c5c9
AS
7402
7403/* There is a subtle and tricky problem here. In general, we cannot
7404 determine the size of dynamic records without its data. However,
7405 the 'struct value' data structure, which GDB uses to represent
7406 quantities in the inferior process (the target), requires the size
7407 of the type at the time of its allocation in order to reserve space
7408 for GDB's internal copy of the data. That's why the
7409 'to_fixed_xxx_type' routines take (target) addresses as parameters,
4c4b4cd2 7410 rather than struct value*s.
14f9c5c9
AS
7411
7412 However, GDB's internal history variables ($1, $2, etc.) are
7413 struct value*s containing internal copies of the data that are not, in
7414 general, the same as the data at their corresponding addresses in
7415 the target. Fortunately, the types we give to these values are all
7416 conventional, fixed-size types (as per the strategy described
7417 above), so that we don't usually have to perform the
7418 'to_fixed_xxx_type' conversions to look at their values.
7419 Unfortunately, there is one exception: if one of the internal
7420 history variables is an array whose elements are unconstrained
7421 records, then we will need to create distinct fixed types for each
7422 element selected. */
7423
7424/* The upshot of all of this is that many routines take a (type, host
7425 address, target address) triple as arguments to represent a value.
7426 The host address, if non-null, is supposed to contain an internal
7427 copy of the relevant data; otherwise, the program is to consult the
4c4b4cd2 7428 target at the target address. */
14f9c5c9
AS
7429
7430/* Assuming that VAL0 represents a pointer value, the result of
7431 dereferencing it. Differs from value_ind in its treatment of
4c4b4cd2 7432 dynamic-sized types. */
14f9c5c9 7433
d2e4a39e
AS
7434struct value *
7435ada_value_ind (struct value *val0)
14f9c5c9 7436{
c48db5ca 7437 struct value *val = value_ind (val0);
5b4ee69b 7438
d0c97917 7439 if (ada_is_tagged_type (val->type (), 0))
b50d69b5
JG
7440 val = ada_tag_value_at_base_address (val);
7441
4c4b4cd2 7442 return ada_to_fixed_value (val);
14f9c5c9
AS
7443}
7444
7445/* The value resulting from dereferencing any "reference to"
4c4b4cd2
PH
7446 qualifiers on VAL0. */
7447
d2e4a39e
AS
7448static struct value *
7449ada_coerce_ref (struct value *val0)
7450{
d0c97917 7451 if (val0->type ()->code () == TYPE_CODE_REF)
d2e4a39e
AS
7452 {
7453 struct value *val = val0;
5b4ee69b 7454
994b9211 7455 val = coerce_ref (val);
b50d69b5 7456
d0c97917 7457 if (ada_is_tagged_type (val->type (), 0))
b50d69b5
JG
7458 val = ada_tag_value_at_base_address (val);
7459
4c4b4cd2 7460 return ada_to_fixed_value (val);
d2e4a39e
AS
7461 }
7462 else
14f9c5c9
AS
7463 return val0;
7464}
7465
4c4b4cd2 7466/* Return the bit alignment required for field #F of template type TYPE. */
14f9c5c9
AS
7467
7468static unsigned int
ebf56fd3 7469field_alignment (struct type *type, int f)
14f9c5c9 7470{
33d16dd9 7471 const char *name = type->field (f).name ();
64a1bf19 7472 int len;
14f9c5c9
AS
7473 int align_offset;
7474
64a1bf19
JB
7475 /* The field name should never be null, unless the debugging information
7476 is somehow malformed. In this case, we assume the field does not
7477 require any alignment. */
7478 if (name == NULL)
7479 return 1;
7480
7481 len = strlen (name);
7482
4c4b4cd2
PH
7483 if (!isdigit (name[len - 1]))
7484 return 1;
14f9c5c9 7485
d2e4a39e 7486 if (isdigit (name[len - 2]))
14f9c5c9
AS
7487 align_offset = len - 2;
7488 else
7489 align_offset = len - 1;
7490
61012eef 7491 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
14f9c5c9
AS
7492 return TARGET_CHAR_BIT;
7493
4c4b4cd2
PH
7494 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7495}
7496
852dff6c 7497/* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
4c4b4cd2 7498
852dff6c
JB
7499static struct symbol *
7500ada_find_any_type_symbol (const char *name)
4c4b4cd2
PH
7501{
7502 struct symbol *sym;
7503
7504 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
66d7f48f 7505 if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
4c4b4cd2
PH
7506 return sym;
7507
4186eb54
KS
7508 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7509 return sym;
14f9c5c9
AS
7510}
7511
dddfab26
UW
7512/* Find a type named NAME. Ignores ambiguity. This routine will look
7513 solely for types defined by debug info, it will not search the GDB
7514 primitive types. */
4c4b4cd2 7515
852dff6c 7516static struct type *
ebf56fd3 7517ada_find_any_type (const char *name)
14f9c5c9 7518{
852dff6c 7519 struct symbol *sym = ada_find_any_type_symbol (name);
14f9c5c9 7520
14f9c5c9 7521 if (sym != NULL)
5f9c5a63 7522 return sym->type ();
14f9c5c9 7523
dddfab26 7524 return NULL;
14f9c5c9
AS
7525}
7526
739593e0
JB
7527/* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7528 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7529 symbol, in which case it is returned. Otherwise, this looks for
7530 symbols whose name is that of NAME_SYM suffixed with "___XR".
7531 Return symbol if found, and NULL otherwise. */
4c4b4cd2 7532
c0e70c62
TT
7533static bool
7534ada_is_renaming_symbol (struct symbol *name_sym)
aeb5907d 7535{
987012b8 7536 const char *name = name_sym->linkage_name ();
c0e70c62 7537 return strstr (name, "___XR") != NULL;
4c4b4cd2
PH
7538}
7539
14f9c5c9 7540/* Because of GNAT encoding conventions, several GDB symbols may match a
4c4b4cd2 7541 given type name. If the type denoted by TYPE0 is to be preferred to
14f9c5c9 7542 that of TYPE1 for purposes of type printing, return non-zero;
4c4b4cd2
PH
7543 otherwise return 0. */
7544
14f9c5c9 7545int
d2e4a39e 7546ada_prefer_type (struct type *type0, struct type *type1)
14f9c5c9
AS
7547{
7548 if (type1 == NULL)
7549 return 1;
7550 else if (type0 == NULL)
7551 return 0;
78134374 7552 else if (type1->code () == TYPE_CODE_VOID)
14f9c5c9 7553 return 1;
78134374 7554 else if (type0->code () == TYPE_CODE_VOID)
14f9c5c9 7555 return 0;
7d93a1e0 7556 else if (type1->name () == NULL && type0->name () != NULL)
4c4b4cd2 7557 return 1;
ad82864c 7558 else if (ada_is_constrained_packed_array_type (type0))
14f9c5c9 7559 return 1;
4c4b4cd2 7560 else if (ada_is_array_descriptor_type (type0)
dda83cd7 7561 && !ada_is_array_descriptor_type (type1))
14f9c5c9 7562 return 1;
aeb5907d
JB
7563 else
7564 {
7d93a1e0
SM
7565 const char *type0_name = type0->name ();
7566 const char *type1_name = type1->name ();
aeb5907d
JB
7567
7568 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7569 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7570 return 1;
7571 }
14f9c5c9
AS
7572 return 0;
7573}
7574
e86ca25f
TT
7575/* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7576 null. */
4c4b4cd2 7577
0d5cff50 7578const char *
d2e4a39e 7579ada_type_name (struct type *type)
14f9c5c9 7580{
d2e4a39e 7581 if (type == NULL)
14f9c5c9 7582 return NULL;
7d93a1e0 7583 return type->name ();
14f9c5c9
AS
7584}
7585
b4ba55a1
JB
7586/* Search the list of "descriptive" types associated to TYPE for a type
7587 whose name is NAME. */
7588
7589static struct type *
7590find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7591{
931e5bc3 7592 struct type *result, *tmp;
b4ba55a1 7593
c6044dd1
JB
7594 if (ada_ignore_descriptive_types_p)
7595 return NULL;
7596
b4ba55a1
JB
7597 /* If there no descriptive-type info, then there is no parallel type
7598 to be found. */
7599 if (!HAVE_GNAT_AUX_INFO (type))
7600 return NULL;
7601
7602 result = TYPE_DESCRIPTIVE_TYPE (type);
7603 while (result != NULL)
7604 {
0d5cff50 7605 const char *result_name = ada_type_name (result);
b4ba55a1
JB
7606
7607 if (result_name == NULL)
dda83cd7
SM
7608 {
7609 warning (_("unexpected null name on descriptive type"));
7610 return NULL;
7611 }
b4ba55a1
JB
7612
7613 /* If the names match, stop. */
7614 if (strcmp (result_name, name) == 0)
7615 break;
7616
7617 /* Otherwise, look at the next item on the list, if any. */
7618 if (HAVE_GNAT_AUX_INFO (result))
931e5bc3
JG
7619 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7620 else
7621 tmp = NULL;
7622
7623 /* If not found either, try after having resolved the typedef. */
7624 if (tmp != NULL)
7625 result = tmp;
b4ba55a1 7626 else
931e5bc3 7627 {
f168693b 7628 result = check_typedef (result);
931e5bc3
JG
7629 if (HAVE_GNAT_AUX_INFO (result))
7630 result = TYPE_DESCRIPTIVE_TYPE (result);
7631 else
7632 result = NULL;
7633 }
b4ba55a1
JB
7634 }
7635
7636 /* If we didn't find a match, see whether this is a packed array. With
7637 older compilers, the descriptive type information is either absent or
7638 irrelevant when it comes to packed arrays so the above lookup fails.
7639 Fall back to using a parallel lookup by name in this case. */
12ab9e09 7640 if (result == NULL && ada_is_constrained_packed_array_type (type))
b4ba55a1
JB
7641 return ada_find_any_type (name);
7642
7643 return result;
7644}
7645
7646/* Find a parallel type to TYPE with the specified NAME, using the
7647 descriptive type taken from the debugging information, if available,
7648 and otherwise using the (slower) name-based method. */
7649
7650static struct type *
7651ada_find_parallel_type_with_name (struct type *type, const char *name)
7652{
7653 struct type *result = NULL;
7654
7655 if (HAVE_GNAT_AUX_INFO (type))
7656 result = find_parallel_type_by_descriptive_type (type, name);
7657 else
7658 result = ada_find_any_type (name);
7659
7660 return result;
7661}
7662
7663/* Same as above, but specify the name of the parallel type by appending
4c4b4cd2 7664 SUFFIX to the name of TYPE. */
14f9c5c9 7665
d2e4a39e 7666struct type *
ebf56fd3 7667ada_find_parallel_type (struct type *type, const char *suffix)
14f9c5c9 7668{
0d5cff50 7669 char *name;
fe978cb0 7670 const char *type_name = ada_type_name (type);
14f9c5c9 7671 int len;
d2e4a39e 7672
fe978cb0 7673 if (type_name == NULL)
14f9c5c9
AS
7674 return NULL;
7675
fe978cb0 7676 len = strlen (type_name);
14f9c5c9 7677
b4ba55a1 7678 name = (char *) alloca (len + strlen (suffix) + 1);
14f9c5c9 7679
fe978cb0 7680 strcpy (name, type_name);
14f9c5c9
AS
7681 strcpy (name + len, suffix);
7682
b4ba55a1 7683 return ada_find_parallel_type_with_name (type, name);
14f9c5c9
AS
7684}
7685
14f9c5c9 7686/* If TYPE is a variable-size record type, return the corresponding template
4c4b4cd2 7687 type describing its fields. Otherwise, return NULL. */
14f9c5c9 7688
d2e4a39e
AS
7689static struct type *
7690dynamic_template_type (struct type *type)
14f9c5c9 7691{
61ee279c 7692 type = ada_check_typedef (type);
14f9c5c9 7693
78134374 7694 if (type == NULL || type->code () != TYPE_CODE_STRUCT
d2e4a39e 7695 || ada_type_name (type) == NULL)
14f9c5c9 7696 return NULL;
d2e4a39e 7697 else
14f9c5c9
AS
7698 {
7699 int len = strlen (ada_type_name (type));
5b4ee69b 7700
4c4b4cd2 7701 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
dda83cd7 7702 return type;
14f9c5c9 7703 else
dda83cd7 7704 return ada_find_parallel_type (type, "___XVE");
14f9c5c9
AS
7705 }
7706}
7707
7708/* Assuming that TEMPL_TYPE is a union or struct type, returns
4c4b4cd2 7709 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
14f9c5c9 7710
d2e4a39e
AS
7711static int
7712is_dynamic_field (struct type *templ_type, int field_num)
14f9c5c9 7713{
33d16dd9 7714 const char *name = templ_type->field (field_num).name ();
5b4ee69b 7715
d2e4a39e 7716 return name != NULL
940da03e 7717 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
14f9c5c9
AS
7718 && strstr (name, "___XVL") != NULL;
7719}
7720
4c4b4cd2
PH
7721/* The index of the variant field of TYPE, or -1 if TYPE does not
7722 represent a variant record type. */
14f9c5c9 7723
d2e4a39e 7724static int
4c4b4cd2 7725variant_field_index (struct type *type)
14f9c5c9
AS
7726{
7727 int f;
7728
78134374 7729 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
4c4b4cd2
PH
7730 return -1;
7731
1f704f76 7732 for (f = 0; f < type->num_fields (); f += 1)
4c4b4cd2
PH
7733 {
7734 if (ada_is_variant_part (type, f))
dda83cd7 7735 return f;
4c4b4cd2
PH
7736 }
7737 return -1;
14f9c5c9
AS
7738}
7739
4c4b4cd2
PH
7740/* A record type with no fields. */
7741
d2e4a39e 7742static struct type *
fe978cb0 7743empty_record (struct type *templ)
14f9c5c9 7744{
9fa83a7a 7745 struct type *type = type_allocator (templ).new_type ();
5b4ee69b 7746
67607e24 7747 type->set_code (TYPE_CODE_STRUCT);
8ecb59f8 7748 INIT_NONE_SPECIFIC (type);
d0e39ea2 7749 type->set_name ("<empty>");
b6cdbc9a 7750 type->set_length (0);
14f9c5c9
AS
7751 return type;
7752}
7753
7754/* An ordinary record type (with fixed-length fields) that describes
4c4b4cd2
PH
7755 the value of type TYPE at VALADDR or ADDRESS (see comments at
7756 the beginning of this section) VAL according to GNAT conventions.
7757 DVAL0 should describe the (portion of a) record that contains any
d0c97917 7758 necessary discriminants. It should be NULL if VAL->type () is
14f9c5c9
AS
7759 an outer-level type (i.e., as opposed to a branch of a variant.) A
7760 variant field (unless unchecked) is replaced by a particular branch
4c4b4cd2 7761 of the variant.
14f9c5c9 7762
4c4b4cd2
PH
7763 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7764 length are not statically known are discarded. As a consequence,
7765 VALADDR, ADDRESS and DVAL0 are ignored.
7766
7767 NOTE: Limitations: For now, we assume that dynamic fields and
7768 variants occupy whole numbers of bytes. However, they need not be
7769 byte-aligned. */
7770
7771struct type *
10a2c479 7772ada_template_to_fixed_record_type_1 (struct type *type,
fc1a4b47 7773 const gdb_byte *valaddr,
dda83cd7
SM
7774 CORE_ADDR address, struct value *dval0,
7775 int keep_dynamic_fields)
14f9c5c9 7776{
d2e4a39e
AS
7777 struct value *dval;
7778 struct type *rtype;
14f9c5c9 7779 int nfields, bit_len;
4c4b4cd2 7780 int variant_field;
14f9c5c9 7781 long off;
d94e4f4f 7782 int fld_bit_len;
14f9c5c9
AS
7783 int f;
7784
65558ca5
TT
7785 scoped_value_mark mark;
7786
4c4b4cd2
PH
7787 /* Compute the number of fields in this record type that are going
7788 to be processed: unless keep_dynamic_fields, this includes only
7789 fields whose position and length are static will be processed. */
7790 if (keep_dynamic_fields)
1f704f76 7791 nfields = type->num_fields ();
4c4b4cd2
PH
7792 else
7793 {
7794 nfields = 0;
1f704f76 7795 while (nfields < type->num_fields ()
dda83cd7
SM
7796 && !ada_is_variant_part (type, nfields)
7797 && !is_dynamic_field (type, nfields))
7798 nfields++;
4c4b4cd2
PH
7799 }
7800
9fa83a7a 7801 rtype = type_allocator (type).new_type ();
67607e24 7802 rtype->set_code (TYPE_CODE_STRUCT);
8ecb59f8 7803 INIT_NONE_SPECIFIC (rtype);
2774f2da 7804 rtype->alloc_fields (nfields);
d0e39ea2 7805 rtype->set_name (ada_type_name (type));
9cdd0d12 7806 rtype->set_is_fixed_instance (true);
14f9c5c9 7807
d2e4a39e
AS
7808 off = 0;
7809 bit_len = 0;
4c4b4cd2
PH
7810 variant_field = -1;
7811
14f9c5c9
AS
7812 for (f = 0; f < nfields; f += 1)
7813 {
a89febbd 7814 off = align_up (off, field_alignment (type, f))
b610c045 7815 + type->field (f).loc_bitpos ();
cd3f655c 7816 rtype->field (f).set_loc_bitpos (off);
886176b8 7817 rtype->field (f).set_bitsize (0);
14f9c5c9 7818
d2e4a39e 7819 if (ada_is_variant_part (type, f))
dda83cd7
SM
7820 {
7821 variant_field = f;
7822 fld_bit_len = 0;
7823 }
14f9c5c9 7824 else if (is_dynamic_field (type, f))
dda83cd7 7825 {
284614f0
JB
7826 const gdb_byte *field_valaddr = valaddr;
7827 CORE_ADDR field_address = address;
27710edb 7828 struct type *field_type = type->field (f).type ()->target_type ();
284614f0 7829
dda83cd7 7830 if (dval0 == NULL)
b5304971 7831 {
012370f6
TT
7832 /* Using plain value_from_contents_and_address here
7833 causes problems because we will end up trying to
7834 resolve a type that is currently being
7835 constructed. */
7836 dval = value_from_contents_and_address_unresolved (rtype,
7837 valaddr,
7838 address);
d0c97917 7839 rtype = dval->type ();
b5304971 7840 }
dda83cd7
SM
7841 else
7842 dval = dval0;
4c4b4cd2 7843
284614f0
JB
7844 /* If the type referenced by this field is an aligner type, we need
7845 to unwrap that aligner type, because its size might not be set.
7846 Keeping the aligner type would cause us to compute the wrong
7847 size for this field, impacting the offset of the all the fields
7848 that follow this one. */
7849 if (ada_is_aligner_type (field_type))
7850 {
b610c045 7851 long field_offset = type->field (f).loc_bitpos ();
284614f0
JB
7852
7853 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7854 field_address = cond_offset_target (field_address, field_offset);
7855 field_type = ada_aligned_type (field_type);
7856 }
7857
7858 field_valaddr = cond_offset_host (field_valaddr,
7859 off / TARGET_CHAR_BIT);
7860 field_address = cond_offset_target (field_address,
7861 off / TARGET_CHAR_BIT);
7862
7863 /* Get the fixed type of the field. Note that, in this case,
7864 we do not want to get the real type out of the tag: if
7865 the current field is the parent part of a tagged record,
7866 we will get the tag of the object. Clearly wrong: the real
7867 type of the parent is not the real type of the child. We
7868 would end up in an infinite loop. */
7869 field_type = ada_get_base_type (field_type);
7870 field_type = ada_to_fixed_type (field_type, field_valaddr,
7871 field_address, dval, 0);
7872
5d14b6e5 7873 rtype->field (f).set_type (field_type);
33d16dd9 7874 rtype->field (f).set_name (type->field (f).name ());
27f2a97b
JB
7875 /* The multiplication can potentially overflow. But because
7876 the field length has been size-checked just above, and
7877 assuming that the maximum size is a reasonable value,
7878 an overflow should not happen in practice. So rather than
7879 adding overflow recovery code to this already complex code,
7880 we just assume that it's not going to happen. */
df86565b 7881 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
dda83cd7 7882 }
14f9c5c9 7883 else
dda83cd7 7884 {
5ded5331
JB
7885 /* Note: If this field's type is a typedef, it is important
7886 to preserve the typedef layer.
7887
7888 Otherwise, we might be transforming a typedef to a fat
7889 pointer (encoding a pointer to an unconstrained array),
7890 into a basic fat pointer (encoding an unconstrained
7891 array). As both types are implemented using the same
7892 structure, the typedef is the only clue which allows us
7893 to distinguish between the two options. Stripping it
7894 would prevent us from printing this field appropriately. */
dda83cd7 7895 rtype->field (f).set_type (type->field (f).type ());
33d16dd9 7896 rtype->field (f).set_name (type->field (f).name ());
3757d2d4 7897 if (type->field (f).bitsize () > 0)
886176b8 7898 {
3757d2d4 7899 fld_bit_len = type->field (f).bitsize ();
886176b8
SM
7900 rtype->field (f).set_bitsize (fld_bit_len);
7901 }
dda83cd7 7902 else
5ded5331 7903 {
940da03e 7904 struct type *field_type = type->field (f).type ();
5ded5331
JB
7905
7906 /* We need to be careful of typedefs when computing
7907 the length of our field. If this is a typedef,
7908 get the length of the target type, not the length
7909 of the typedef. */
78134374 7910 if (field_type->code () == TYPE_CODE_TYPEDEF)
5ded5331
JB
7911 field_type = ada_typedef_target_type (field_type);
7912
dda83cd7 7913 fld_bit_len =
df86565b 7914 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
5ded5331 7915 }
dda83cd7 7916 }
14f9c5c9 7917 if (off + fld_bit_len > bit_len)
dda83cd7 7918 bit_len = off + fld_bit_len;
d94e4f4f 7919 off += fld_bit_len;
b6cdbc9a 7920 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
14f9c5c9 7921 }
4c4b4cd2
PH
7922
7923 /* We handle the variant part, if any, at the end because of certain
b1f33ddd 7924 odd cases in which it is re-ordered so as NOT to be the last field of
4c4b4cd2
PH
7925 the record. This can happen in the presence of representation
7926 clauses. */
7927 if (variant_field >= 0)
7928 {
7929 struct type *branch_type;
7930
b610c045 7931 off = rtype->field (variant_field).loc_bitpos ();
4c4b4cd2
PH
7932
7933 if (dval0 == NULL)
9f1f738a 7934 {
012370f6
TT
7935 /* Using plain value_from_contents_and_address here causes
7936 problems because we will end up trying to resolve a type
7937 that is currently being constructed. */
7938 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7939 address);
d0c97917 7940 rtype = dval->type ();
9f1f738a 7941 }
4c4b4cd2 7942 else
dda83cd7 7943 dval = dval0;
4c4b4cd2
PH
7944
7945 branch_type =
dda83cd7
SM
7946 to_fixed_variant_branch_type
7947 (type->field (variant_field).type (),
7948 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7949 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
4c4b4cd2 7950 if (branch_type == NULL)
dda83cd7
SM
7951 {
7952 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7953 rtype->field (f - 1) = rtype->field (f);
5e33d5f4 7954 rtype->set_num_fields (rtype->num_fields () - 1);
dda83cd7 7955 }
4c4b4cd2 7956 else
dda83cd7
SM
7957 {
7958 rtype->field (variant_field).set_type (branch_type);
d3fd12df 7959 rtype->field (variant_field).set_name ("S");
dda83cd7 7960 fld_bit_len =
df86565b 7961 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
dda83cd7
SM
7962 if (off + fld_bit_len > bit_len)
7963 bit_len = off + fld_bit_len;
b6cdbc9a
SM
7964
7965 rtype->set_length
7966 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
dda83cd7 7967 }
4c4b4cd2
PH
7968 }
7969
714e53ab
PH
7970 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7971 should contain the alignment of that record, which should be a strictly
7972 positive value. If null or negative, then something is wrong, most
7973 probably in the debug info. In that case, we don't round up the size
0963b4bd 7974 of the resulting type. If this record is not part of another structure,
714e53ab 7975 the current RTYPE length might be good enough for our purposes. */
df86565b 7976 if (type->length () <= 0)
714e53ab 7977 {
7d93a1e0 7978 if (rtype->name ())
cc1defb1 7979 warning (_("Invalid type size for `%s' detected: %s."),
df86565b 7980 rtype->name (), pulongest (type->length ()));
323e0a4a 7981 else
cc1defb1 7982 warning (_("Invalid type size for <unnamed> detected: %s."),
df86565b 7983 pulongest (type->length ()));
714e53ab
PH
7984 }
7985 else
df86565b 7986 rtype->set_length (align_up (rtype->length (), type->length ()));
14f9c5c9 7987
14f9c5c9
AS
7988 return rtype;
7989}
7990
4c4b4cd2
PH
7991/* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7992 of 1. */
14f9c5c9 7993
d2e4a39e 7994static struct type *
fc1a4b47 7995template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
dda83cd7 7996 CORE_ADDR address, struct value *dval0)
4c4b4cd2
PH
7997{
7998 return ada_template_to_fixed_record_type_1 (type, valaddr,
dda83cd7 7999 address, dval0, 1);
4c4b4cd2
PH
8000}
8001
8002/* An ordinary record type in which ___XVL-convention fields and
8003 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8004 static approximations, containing all possible fields. Uses
8005 no runtime values. Useless for use in values, but that's OK,
8006 since the results are used only for type determinations. Works on both
8007 structs and unions. Representation note: to save space, we memorize
27710edb 8008 the result of this function in the type::target_type of the
4c4b4cd2
PH
8009 template type. */
8010
8011static struct type *
8012template_to_static_fixed_type (struct type *type0)
14f9c5c9
AS
8013{
8014 struct type *type;
8015 int nfields;
8016 int f;
8017
9e195661 8018 /* No need no do anything if the input type is already fixed. */
22c4c60c 8019 if (type0->is_fixed_instance ())
9e195661
PMR
8020 return type0;
8021
8022 /* Likewise if we already have computed the static approximation. */
27710edb
SM
8023 if (type0->target_type () != NULL)
8024 return type0->target_type ();
4c4b4cd2 8025
9e195661 8026 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
4c4b4cd2 8027 type = type0;
1f704f76 8028 nfields = type0->num_fields ();
9e195661
PMR
8029
8030 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8031 recompute all over next time. */
8a50fdce 8032 type0->set_target_type (type);
14f9c5c9
AS
8033
8034 for (f = 0; f < nfields; f += 1)
8035 {
940da03e 8036 struct type *field_type = type0->field (f).type ();
4c4b4cd2 8037 struct type *new_type;
14f9c5c9 8038
4c4b4cd2 8039 if (is_dynamic_field (type0, f))
460efde1
JB
8040 {
8041 field_type = ada_check_typedef (field_type);
27710edb 8042 new_type = to_static_fixed_type (field_type->target_type ());
460efde1 8043 }
14f9c5c9 8044 else
dda83cd7 8045 new_type = static_unwrap_type (field_type);
9e195661
PMR
8046
8047 if (new_type != field_type)
8048 {
8049 /* Clone TYPE0 only the first time we get a new field type. */
8050 if (type == type0)
8051 {
9fa83a7a 8052 type = type_allocator (type0).new_type ();
8a50fdce 8053 type0->set_target_type (type);
78134374 8054 type->set_code (type0->code ());
8ecb59f8 8055 INIT_NONE_SPECIFIC (type);
3cabb6b0 8056
2774f2da 8057 type->copy_fields (type0);
3cabb6b0 8058
d0e39ea2 8059 type->set_name (ada_type_name (type0));
9cdd0d12 8060 type->set_is_fixed_instance (true);
b6cdbc9a 8061 type->set_length (0);
9e195661 8062 }
5d14b6e5 8063 type->field (f).set_type (new_type);
33d16dd9 8064 type->field (f).set_name (type0->field (f).name ());
9e195661 8065 }
14f9c5c9 8066 }
9e195661 8067
14f9c5c9
AS
8068 return type;
8069}
8070
4c4b4cd2 8071/* Given an object of type TYPE whose contents are at VALADDR and
5823c3ef
JB
8072 whose address in memory is ADDRESS, returns a revision of TYPE,
8073 which should be a non-dynamic-sized record, in which the variant
8074 part, if any, is replaced with the appropriate branch. Looks
4c4b4cd2
PH
8075 for discriminant values in DVAL0, which can be NULL if the record
8076 contains the necessary discriminant values. */
8077
d2e4a39e 8078static struct type *
fc1a4b47 8079to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
dda83cd7 8080 CORE_ADDR address, struct value *dval0)
14f9c5c9 8081{
4c4b4cd2 8082 struct value *dval;
d2e4a39e 8083 struct type *rtype;
14f9c5c9 8084 struct type *branch_type;
1f704f76 8085 int nfields = type->num_fields ();
4c4b4cd2 8086 int variant_field = variant_field_index (type);
14f9c5c9 8087
4c4b4cd2 8088 if (variant_field == -1)
14f9c5c9
AS
8089 return type;
8090
65558ca5 8091 scoped_value_mark mark;
4c4b4cd2 8092 if (dval0 == NULL)
9f1f738a
SA
8093 {
8094 dval = value_from_contents_and_address (type, valaddr, address);
d0c97917 8095 type = dval->type ();
9f1f738a 8096 }
4c4b4cd2
PH
8097 else
8098 dval = dval0;
8099
9fa83a7a 8100 rtype = type_allocator (type).new_type ();
67607e24 8101 rtype->set_code (TYPE_CODE_STRUCT);
8ecb59f8 8102 INIT_NONE_SPECIFIC (rtype);
2774f2da 8103 rtype->copy_fields (type);
3cabb6b0 8104
d0e39ea2 8105 rtype->set_name (ada_type_name (type));
9cdd0d12 8106 rtype->set_is_fixed_instance (true);
df86565b 8107 rtype->set_length (type->length ());
14f9c5c9 8108
4c4b4cd2 8109 branch_type = to_fixed_variant_branch_type
940da03e 8110 (type->field (variant_field).type (),
d2e4a39e 8111 cond_offset_host (valaddr,
b610c045 8112 type->field (variant_field).loc_bitpos ()
dda83cd7 8113 / TARGET_CHAR_BIT),
d2e4a39e 8114 cond_offset_target (address,
b610c045 8115 type->field (variant_field).loc_bitpos ()
dda83cd7 8116 / TARGET_CHAR_BIT), dval);
d2e4a39e 8117 if (branch_type == NULL)
14f9c5c9 8118 {
4c4b4cd2 8119 int f;
5b4ee69b 8120
4c4b4cd2 8121 for (f = variant_field + 1; f < nfields; f += 1)
dda83cd7 8122 rtype->field (f - 1) = rtype->field (f);
5e33d5f4 8123 rtype->set_num_fields (rtype->num_fields () - 1);
14f9c5c9
AS
8124 }
8125 else
8126 {
5d14b6e5 8127 rtype->field (variant_field).set_type (branch_type);
d3fd12df 8128 rtype->field (variant_field).set_name ("S");
886176b8 8129 rtype->field (variant_field).set_bitsize (0);
df86565b 8130 rtype->set_length (rtype->length () + branch_type->length ());
14f9c5c9 8131 }
b6cdbc9a 8132
df86565b
SM
8133 rtype->set_length (rtype->length ()
8134 - type->field (variant_field).type ()->length ());
d2e4a39e 8135
14f9c5c9
AS
8136 return rtype;
8137}
8138
8139/* An ordinary record type (with fixed-length fields) that describes
8140 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8141 beginning of this section]. Any necessary discriminants' values
4c4b4cd2
PH
8142 should be in DVAL, a record value; it may be NULL if the object
8143 at ADDR itself contains any necessary discriminant values.
8144 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8145 values from the record are needed. Except in the case that DVAL,
8146 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8147 unchecked) is replaced by a particular branch of the variant.
8148
8149 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8150 is questionable and may be removed. It can arise during the
8151 processing of an unconstrained-array-of-record type where all the
8152 variant branches have exactly the same size. This is because in
8153 such cases, the compiler does not bother to use the XVS convention
8154 when encoding the record. I am currently dubious of this
8155 shortcut and suspect the compiler should be altered. FIXME. */
14f9c5c9 8156
d2e4a39e 8157static struct type *
fc1a4b47 8158to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
dda83cd7 8159 CORE_ADDR address, struct value *dval)
14f9c5c9 8160{
d2e4a39e 8161 struct type *templ_type;
14f9c5c9 8162
22c4c60c 8163 if (type0->is_fixed_instance ())
4c4b4cd2
PH
8164 return type0;
8165
d2e4a39e 8166 templ_type = dynamic_template_type (type0);
14f9c5c9
AS
8167
8168 if (templ_type != NULL)
8169 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
4c4b4cd2
PH
8170 else if (variant_field_index (type0) >= 0)
8171 {
8172 if (dval == NULL && valaddr == NULL && address == 0)
dda83cd7 8173 return type0;
4c4b4cd2 8174 return to_record_with_fixed_variant_part (type0, valaddr, address,
dda83cd7 8175 dval);
4c4b4cd2 8176 }
14f9c5c9
AS
8177 else
8178 {
9cdd0d12 8179 type0->set_is_fixed_instance (true);
14f9c5c9
AS
8180 return type0;
8181 }
8182
8183}
8184
8185/* An ordinary record type (with fixed-length fields) that describes
8186 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8187 union type. Any necessary discriminants' values should be in DVAL,
8188 a record value. That is, this routine selects the appropriate
8189 branch of the union at ADDR according to the discriminant value
b1f33ddd 8190 indicated in the union's type name. Returns VAR_TYPE0 itself if
0963b4bd 8191 it represents a variant subject to a pragma Unchecked_Union. */
14f9c5c9 8192
d2e4a39e 8193static struct type *
fc1a4b47 8194to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
dda83cd7 8195 CORE_ADDR address, struct value *dval)
14f9c5c9
AS
8196{
8197 int which;
d2e4a39e
AS
8198 struct type *templ_type;
8199 struct type *var_type;
14f9c5c9 8200
78134374 8201 if (var_type0->code () == TYPE_CODE_PTR)
27710edb 8202 var_type = var_type0->target_type ();
d2e4a39e 8203 else
14f9c5c9
AS
8204 var_type = var_type0;
8205
8206 templ_type = ada_find_parallel_type (var_type, "___XVU");
8207
8208 if (templ_type != NULL)
8209 var_type = templ_type;
8210
d0c97917 8211 if (is_unchecked_variant (var_type, dval->type ()))
b1f33ddd 8212 return var_type0;
d8af9068 8213 which = ada_which_variant_applies (var_type, dval);
14f9c5c9
AS
8214
8215 if (which < 0)
e9bb382b 8216 return empty_record (var_type);
14f9c5c9 8217 else if (is_dynamic_field (var_type, which))
4c4b4cd2 8218 return to_fixed_record_type
27710edb 8219 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
940da03e 8220 else if (variant_field_index (var_type->field (which).type ()) >= 0)
d2e4a39e
AS
8221 return
8222 to_fixed_record_type
940da03e 8223 (var_type->field (which).type (), valaddr, address, dval);
14f9c5c9 8224 else
940da03e 8225 return var_type->field (which).type ();
14f9c5c9
AS
8226}
8227
8908fca5
JB
8228/* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8229 ENCODING_TYPE, a type following the GNAT conventions for discrete
8230 type encodings, only carries redundant information. */
8231
8232static int
8233ada_is_redundant_range_encoding (struct type *range_type,
8234 struct type *encoding_type)
8235{
108d56a4 8236 const char *bounds_str;
8908fca5
JB
8237 int n;
8238 LONGEST lo, hi;
8239
78134374 8240 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8908fca5 8241
78134374
SM
8242 if (get_base_type (range_type)->code ()
8243 != get_base_type (encoding_type)->code ())
005e2509
JB
8244 {
8245 /* The compiler probably used a simple base type to describe
8246 the range type instead of the range's actual base type,
8247 expecting us to get the real base type from the encoding
8248 anyway. In this situation, the encoding cannot be ignored
8249 as redundant. */
8250 return 0;
8251 }
8252
8908fca5
JB
8253 if (is_dynamic_type (range_type))
8254 return 0;
8255
7d93a1e0 8256 if (encoding_type->name () == NULL)
8908fca5
JB
8257 return 0;
8258
7d93a1e0 8259 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8908fca5
JB
8260 if (bounds_str == NULL)
8261 return 0;
8262
8263 n = 8; /* Skip "___XDLU_". */
8264 if (!ada_scan_number (bounds_str, n, &lo, &n))
8265 return 0;
5537ddd0 8266 if (range_type->bounds ()->low.const_val () != lo)
8908fca5
JB
8267 return 0;
8268
8269 n += 2; /* Skip the "__" separator between the two bounds. */
8270 if (!ada_scan_number (bounds_str, n, &hi, &n))
8271 return 0;
5537ddd0 8272 if (range_type->bounds ()->high.const_val () != hi)
8908fca5
JB
8273 return 0;
8274
8275 return 1;
8276}
8277
8278/* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8279 a type following the GNAT encoding for describing array type
8280 indices, only carries redundant information. */
8281
8282static int
8283ada_is_redundant_index_type_desc (struct type *array_type,
8284 struct type *desc_type)
8285{
8286 struct type *this_layer = check_typedef (array_type);
8287 int i;
8288
1f704f76 8289 for (i = 0; i < desc_type->num_fields (); i++)
8908fca5 8290 {
3d967001 8291 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
940da03e 8292 desc_type->field (i).type ()))
8908fca5 8293 return 0;
27710edb 8294 this_layer = check_typedef (this_layer->target_type ());
8908fca5
JB
8295 }
8296
8297 return 1;
8298}
8299
14f9c5c9
AS
8300/* Assuming that TYPE0 is an array type describing the type of a value
8301 at ADDR, and that DVAL describes a record containing any
8302 discriminants used in TYPE0, returns a type for the value that
8303 contains no dynamic components (that is, no components whose sizes
8304 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8305 true, gives an error message if the resulting type's size is over
4c4b4cd2 8306 varsize_limit. */
14f9c5c9 8307
d2e4a39e
AS
8308static struct type *
8309to_fixed_array_type (struct type *type0, struct value *dval,
dda83cd7 8310 int ignore_too_big)
14f9c5c9 8311{
d2e4a39e
AS
8312 struct type *index_type_desc;
8313 struct type *result;
ad82864c 8314 int constrained_packed_array_p;
931e5bc3 8315 static const char *xa_suffix = "___XA";
14f9c5c9 8316
b0dd7688 8317 type0 = ada_check_typedef (type0);
22c4c60c 8318 if (type0->is_fixed_instance ())
4c4b4cd2 8319 return type0;
14f9c5c9 8320
ad82864c
JB
8321 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8322 if (constrained_packed_array_p)
75fd6a26
TT
8323 {
8324 type0 = decode_constrained_packed_array_type (type0);
8325 if (type0 == nullptr)
8326 error (_("could not decode constrained packed array type"));
8327 }
284614f0 8328
931e5bc3
JG
8329 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8330
8331 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8332 encoding suffixed with 'P' may still be generated. If so,
8333 it should be used to find the XA type. */
8334
8335 if (index_type_desc == NULL)
8336 {
1da0522e 8337 const char *type_name = ada_type_name (type0);
931e5bc3 8338
1da0522e 8339 if (type_name != NULL)
931e5bc3 8340 {
1da0522e 8341 const int len = strlen (type_name);
931e5bc3
JG
8342 char *name = (char *) alloca (len + strlen (xa_suffix));
8343
1da0522e 8344 if (type_name[len - 1] == 'P')
931e5bc3 8345 {
1da0522e 8346 strcpy (name, type_name);
931e5bc3
JG
8347 strcpy (name + len - 1, xa_suffix);
8348 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8349 }
8350 }
8351 }
8352
28c85d6c 8353 ada_fixup_array_indexes_type (index_type_desc);
8908fca5
JB
8354 if (index_type_desc != NULL
8355 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8356 {
8357 /* Ignore this ___XA parallel type, as it does not bring any
8358 useful information. This allows us to avoid creating fixed
8359 versions of the array's index types, which would be identical
8360 to the original ones. This, in turn, can also help avoid
8361 the creation of fixed versions of the array itself. */
8362 index_type_desc = NULL;
8363 }
8364
14f9c5c9
AS
8365 if (index_type_desc == NULL)
8366 {
27710edb 8367 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
5b4ee69b 8368
14f9c5c9 8369 /* NOTE: elt_type---the fixed version of elt_type0---should never
dda83cd7
SM
8370 depend on the contents of the array in properly constructed
8371 debugging data. */
529cad9c 8372 /* Create a fixed version of the array element type.
dda83cd7
SM
8373 We're not providing the address of an element here,
8374 and thus the actual object value cannot be inspected to do
8375 the conversion. This should not be a problem, since arrays of
8376 unconstrained objects are not allowed. In particular, all
8377 the elements of an array of a tagged type should all be of
8378 the same type specified in the debugging info. No need to
8379 consult the object tag. */
1ed6ede0 8380 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
14f9c5c9 8381
284614f0
JB
8382 /* Make sure we always create a new array type when dealing with
8383 packed array types, since we're going to fix-up the array
8384 type length and element bitsize a little further down. */
ad82864c 8385 if (elt_type0 == elt_type && !constrained_packed_array_p)
dda83cd7 8386 result = type0;
14f9c5c9 8387 else
9e76b17a
TT
8388 {
8389 type_allocator alloc (type0);
8390 result = create_array_type (alloc, elt_type, type0->index_type ());
8391 }
14f9c5c9
AS
8392 }
8393 else
8394 {
8395 int i;
8396 struct type *elt_type0;
8397
8398 elt_type0 = type0;
1f704f76 8399 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
27710edb 8400 elt_type0 = elt_type0->target_type ();
14f9c5c9
AS
8401
8402 /* NOTE: result---the fixed version of elt_type0---should never
dda83cd7
SM
8403 depend on the contents of the array in properly constructed
8404 debugging data. */
529cad9c 8405 /* Create a fixed version of the array element type.
dda83cd7
SM
8406 We're not providing the address of an element here,
8407 and thus the actual object value cannot be inspected to do
8408 the conversion. This should not be a problem, since arrays of
8409 unconstrained objects are not allowed. In particular, all
8410 the elements of an array of a tagged type should all be of
8411 the same type specified in the debugging info. No need to
8412 consult the object tag. */
1ed6ede0 8413 result =
dda83cd7 8414 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
1ce677a4
UW
8415
8416 elt_type0 = type0;
1f704f76 8417 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
dda83cd7
SM
8418 {
8419 struct type *range_type =
8420 to_fixed_range_type (index_type_desc->field (i).type (), dval);
5b4ee69b 8421
9e76b17a
TT
8422 type_allocator alloc (elt_type0);
8423 result = create_array_type (alloc, result, range_type);
27710edb 8424 elt_type0 = elt_type0->target_type ();
dda83cd7 8425 }
14f9c5c9
AS
8426 }
8427
2e6fda7d
JB
8428 /* We want to preserve the type name. This can be useful when
8429 trying to get the type name of a value that has already been
8430 printed (for instance, if the user did "print VAR; whatis $". */
7d93a1e0 8431 result->set_name (type0->name ());
2e6fda7d 8432
ad82864c 8433 if (constrained_packed_array_p)
284614f0
JB
8434 {
8435 /* So far, the resulting type has been created as if the original
8436 type was a regular (non-packed) array type. As a result, the
8437 bitsize of the array elements needs to be set again, and the array
8438 length needs to be recomputed based on that bitsize. */
df86565b 8439 int len = result->length () / result->target_type ()->length ();
3757d2d4 8440 int elt_bitsize = type0->field (0).bitsize ();
284614f0 8441
3757d2d4 8442 result->field (0).set_bitsize (elt_bitsize);
b6cdbc9a 8443 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
df86565b
SM
8444 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8445 result->set_length (result->length () + 1);
284614f0
JB
8446 }
8447
9cdd0d12 8448 result->set_is_fixed_instance (true);
14f9c5c9 8449 return result;
d2e4a39e 8450}
14f9c5c9
AS
8451
8452
8453/* A standard type (containing no dynamically sized components)
8454 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8455 DVAL describes a record containing any discriminants used in TYPE0,
4c4b4cd2 8456 and may be NULL if there are none, or if the object of type TYPE at
529cad9c
PH
8457 ADDRESS or in VALADDR contains these discriminants.
8458
1ed6ede0
JB
8459 If CHECK_TAG is not null, in the case of tagged types, this function
8460 attempts to locate the object's tag and use it to compute the actual
8461 type. However, when ADDRESS is null, we cannot use it to determine the
8462 location of the tag, and therefore compute the tagged type's actual type.
8463 So we return the tagged type without consulting the tag. */
529cad9c 8464
f192137b
JB
8465static struct type *
8466ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
dda83cd7 8467 CORE_ADDR address, struct value *dval, int check_tag)
14f9c5c9 8468{
61ee279c 8469 type = ada_check_typedef (type);
8ecb59f8
TT
8470
8471 /* Only un-fixed types need to be handled here. */
8472 if (!HAVE_GNAT_AUX_INFO (type))
8473 return type;
8474
78134374 8475 switch (type->code ())
d2e4a39e
AS
8476 {
8477 default:
14f9c5c9 8478 return type;
d2e4a39e 8479 case TYPE_CODE_STRUCT:
4c4b4cd2 8480 {
dda83cd7
SM
8481 struct type *static_type = to_static_fixed_type (type);
8482 struct type *fixed_record_type =
8483 to_fixed_record_type (type, valaddr, address, NULL);
8484
8485 /* If STATIC_TYPE is a tagged type and we know the object's address,
8486 then we can determine its tag, and compute the object's actual
8487 type from there. Note that we have to use the fixed record
8488 type (the parent part of the record may have dynamic fields
8489 and the way the location of _tag is expressed may depend on
8490 them). */
8491
8492 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8493 {
b50d69b5
JG
8494 struct value *tag =
8495 value_tag_from_contents_and_address
8496 (fixed_record_type,
8497 valaddr,
8498 address);
8499 struct type *real_type = type_from_tag (tag);
8500 struct value *obj =
8501 value_from_contents_and_address (fixed_record_type,
8502 valaddr,
8503 address);
d0c97917 8504 fixed_record_type = obj->type ();
dda83cd7
SM
8505 if (real_type != NULL)
8506 return to_fixed_record_type
b50d69b5 8507 (real_type, NULL,
9feb2d07 8508 ada_tag_value_at_base_address (obj)->address (), NULL);
dda83cd7
SM
8509 }
8510
8511 /* Check to see if there is a parallel ___XVZ variable.
8512 If there is, then it provides the actual size of our type. */
8513 else if (ada_type_name (fixed_record_type) != NULL)
8514 {
8515 const char *name = ada_type_name (fixed_record_type);
8516 char *xvz_name
224c3ddb 8517 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
eccab96d 8518 bool xvz_found = false;
dda83cd7 8519 LONGEST size;
4af88198 8520
dda83cd7 8521 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
a70b8144 8522 try
eccab96d
JB
8523 {
8524 xvz_found = get_int_var_value (xvz_name, size);
8525 }
230d2906 8526 catch (const gdb_exception_error &except)
eccab96d
JB
8527 {
8528 /* We found the variable, but somehow failed to read
8529 its value. Rethrow the same error, but with a little
8530 bit more information, to help the user understand
8531 what went wrong (Eg: the variable might have been
8532 optimized out). */
8533 throw_error (except.error,
8534 _("unable to read value of %s (%s)"),
3d6e9d23 8535 xvz_name, except.what ());
eccab96d 8536 }
eccab96d 8537
df86565b 8538 if (xvz_found && fixed_record_type->length () != size)
dda83cd7
SM
8539 {
8540 fixed_record_type = copy_type (fixed_record_type);
b6cdbc9a 8541 fixed_record_type->set_length (size);
dda83cd7
SM
8542
8543 /* The FIXED_RECORD_TYPE may have be a stub. We have
8544 observed this when the debugging info is STABS, and
8545 apparently it is something that is hard to fix.
8546
8547 In practice, we don't need the actual type definition
8548 at all, because the presence of the XVZ variable allows us
8549 to assume that there must be a XVS type as well, which we
8550 should be able to use later, when we need the actual type
8551 definition.
8552
8553 In the meantime, pretend that the "fixed" type we are
8554 returning is NOT a stub, because this can cause trouble
8555 when using this type to create new types targeting it.
8556 Indeed, the associated creation routines often check
8557 whether the target type is a stub and will try to replace
8558 it, thus using a type with the wrong size. This, in turn,
8559 might cause the new type to have the wrong size too.
8560 Consider the case of an array, for instance, where the size
8561 of the array is computed from the number of elements in
8562 our array multiplied by the size of its element. */
b4b73759 8563 fixed_record_type->set_is_stub (false);
dda83cd7
SM
8564 }
8565 }
8566 return fixed_record_type;
4c4b4cd2 8567 }
d2e4a39e 8568 case TYPE_CODE_ARRAY:
4c4b4cd2 8569 return to_fixed_array_type (type, dval, 1);
d2e4a39e
AS
8570 case TYPE_CODE_UNION:
8571 if (dval == NULL)
dda83cd7 8572 return type;
d2e4a39e 8573 else
dda83cd7 8574 return to_fixed_variant_branch_type (type, valaddr, address, dval);
d2e4a39e 8575 }
14f9c5c9
AS
8576}
8577
f192137b
JB
8578/* The same as ada_to_fixed_type_1, except that it preserves the type
8579 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
96dbd2c1
JB
8580
8581 The typedef layer needs be preserved in order to differentiate between
8582 arrays and array pointers when both types are implemented using the same
8583 fat pointer. In the array pointer case, the pointer is encoded as
8584 a typedef of the pointer type. For instance, considering:
8585
8586 type String_Access is access String;
8587 S1 : String_Access := null;
8588
8589 To the debugger, S1 is defined as a typedef of type String. But
8590 to the user, it is a pointer. So if the user tries to print S1,
8591 we should not dereference the array, but print the array address
8592 instead.
8593
8594 If we didn't preserve the typedef layer, we would lose the fact that
8595 the type is to be presented as a pointer (needs de-reference before
8596 being printed). And we would also use the source-level type name. */
f192137b
JB
8597
8598struct type *
8599ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
dda83cd7 8600 CORE_ADDR address, struct value *dval, int check_tag)
f192137b
JB
8601
8602{
8603 struct type *fixed_type =
8604 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8605
96dbd2c1
JB
8606 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8607 then preserve the typedef layer.
8608
8609 Implementation note: We can only check the main-type portion of
8610 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8611 from TYPE now returns a type that has the same instance flags
8612 as TYPE. For instance, if TYPE is a "typedef const", and its
8613 target type is a "struct", then the typedef elimination will return
8614 a "const" version of the target type. See check_typedef for more
8615 details about how the typedef layer elimination is done.
8616
8617 brobecker/2010-11-19: It seems to me that the only case where it is
8618 useful to preserve the typedef layer is when dealing with fat pointers.
8619 Perhaps, we could add a check for that and preserve the typedef layer
85102364 8620 only in that situation. But this seems unnecessary so far, probably
96dbd2c1
JB
8621 because we call check_typedef/ada_check_typedef pretty much everywhere.
8622 */
78134374 8623 if (type->code () == TYPE_CODE_TYPEDEF
720d1a40 8624 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
96dbd2c1 8625 == TYPE_MAIN_TYPE (fixed_type)))
f192137b
JB
8626 return type;
8627
8628 return fixed_type;
8629}
8630
14f9c5c9 8631/* A standard (static-sized) type corresponding as well as possible to
4c4b4cd2 8632 TYPE0, but based on no runtime data. */
14f9c5c9 8633
d2e4a39e
AS
8634static struct type *
8635to_static_fixed_type (struct type *type0)
14f9c5c9 8636{
d2e4a39e 8637 struct type *type;
14f9c5c9
AS
8638
8639 if (type0 == NULL)
8640 return NULL;
8641
22c4c60c 8642 if (type0->is_fixed_instance ())
4c4b4cd2
PH
8643 return type0;
8644
61ee279c 8645 type0 = ada_check_typedef (type0);
d2e4a39e 8646
78134374 8647 switch (type0->code ())
14f9c5c9
AS
8648 {
8649 default:
8650 return type0;
8651 case TYPE_CODE_STRUCT:
8652 type = dynamic_template_type (type0);
d2e4a39e 8653 if (type != NULL)
dda83cd7 8654 return template_to_static_fixed_type (type);
4c4b4cd2 8655 else
dda83cd7 8656 return template_to_static_fixed_type (type0);
14f9c5c9
AS
8657 case TYPE_CODE_UNION:
8658 type = ada_find_parallel_type (type0, "___XVU");
8659 if (type != NULL)
dda83cd7 8660 return template_to_static_fixed_type (type);
4c4b4cd2 8661 else
dda83cd7 8662 return template_to_static_fixed_type (type0);
14f9c5c9
AS
8663 }
8664}
8665
4c4b4cd2
PH
8666/* A static approximation of TYPE with all type wrappers removed. */
8667
d2e4a39e
AS
8668static struct type *
8669static_unwrap_type (struct type *type)
14f9c5c9
AS
8670{
8671 if (ada_is_aligner_type (type))
8672 {
940da03e 8673 struct type *type1 = ada_check_typedef (type)->field (0).type ();
14f9c5c9 8674 if (ada_type_name (type1) == NULL)
d0e39ea2 8675 type1->set_name (ada_type_name (type));
14f9c5c9
AS
8676
8677 return static_unwrap_type (type1);
8678 }
d2e4a39e 8679 else
14f9c5c9 8680 {
d2e4a39e 8681 struct type *raw_real_type = ada_get_base_type (type);
5b4ee69b 8682
d2e4a39e 8683 if (raw_real_type == type)
dda83cd7 8684 return type;
14f9c5c9 8685 else
dda83cd7 8686 return to_static_fixed_type (raw_real_type);
14f9c5c9
AS
8687 }
8688}
8689
8690/* In some cases, incomplete and private types require
4c4b4cd2 8691 cross-references that are not resolved as records (for example,
14f9c5c9
AS
8692 type Foo;
8693 type FooP is access Foo;
8694 V: FooP;
8695 type Foo is array ...;
4c4b4cd2 8696 ). In these cases, since there is no mechanism for producing
14f9c5c9
AS
8697 cross-references to such types, we instead substitute for FooP a
8698 stub enumeration type that is nowhere resolved, and whose tag is
4c4b4cd2 8699 the name of the actual type. Call these types "non-record stubs". */
14f9c5c9
AS
8700
8701/* A type equivalent to TYPE that is not a non-record stub, if one
4c4b4cd2
PH
8702 exists, otherwise TYPE. */
8703
d2e4a39e 8704struct type *
61ee279c 8705ada_check_typedef (struct type *type)
14f9c5c9 8706{
727e3d2e
JB
8707 if (type == NULL)
8708 return NULL;
8709
736ade86
XR
8710 /* If our type is an access to an unconstrained array, which is encoded
8711 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
720d1a40
JB
8712 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8713 what allows us to distinguish between fat pointers that represent
8714 array types, and fat pointers that represent array access types
8715 (in both cases, the compiler implements them as fat pointers). */
736ade86 8716 if (ada_is_access_to_unconstrained_array (type))
720d1a40
JB
8717 return type;
8718
f168693b 8719 type = check_typedef (type);
78134374 8720 if (type == NULL || type->code () != TYPE_CODE_ENUM
e46d3488 8721 || !type->is_stub ()
7d93a1e0 8722 || type->name () == NULL)
14f9c5c9 8723 return type;
d2e4a39e 8724 else
14f9c5c9 8725 {
7d93a1e0 8726 const char *name = type->name ();
d2e4a39e 8727 struct type *type1 = ada_find_any_type (name);
5b4ee69b 8728
05e522ef 8729 if (type1 == NULL)
dda83cd7 8730 return type;
05e522ef
JB
8731
8732 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8733 stubs pointing to arrays, as we don't create symbols for array
3a867c22
JB
8734 types, only for the typedef-to-array types). If that's the case,
8735 strip the typedef layer. */
78134374 8736 if (type1->code () == TYPE_CODE_TYPEDEF)
3a867c22
JB
8737 type1 = ada_check_typedef (type1);
8738
8739 return type1;
14f9c5c9
AS
8740 }
8741}
8742
8743/* A value representing the data at VALADDR/ADDRESS as described by
8744 type TYPE0, but with a standard (static-sized) type that correctly
8745 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8746 type, then return VAL0 [this feature is simply to avoid redundant
4c4b4cd2 8747 creation of struct values]. */
14f9c5c9 8748
4c4b4cd2
PH
8749static struct value *
8750ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
dda83cd7 8751 struct value *val0)
14f9c5c9 8752{
1ed6ede0 8753 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
5b4ee69b 8754
14f9c5c9
AS
8755 if (type == type0 && val0 != NULL)
8756 return val0;
cc0e770c 8757
736355f2 8758 if (val0->lval () != lval_memory)
cc0e770c
JB
8759 {
8760 /* Our value does not live in memory; it could be a convenience
8761 variable, for instance. Create a not_lval value using val0's
8762 contents. */
efaf1ae0 8763 return value_from_contents (type, val0->contents ().data ());
cc0e770c
JB
8764 }
8765
8766 return value_from_contents_and_address (type, 0, address);
4c4b4cd2
PH
8767}
8768
8769/* A value representing VAL, but with a standard (static-sized) type
8770 that correctly describes it. Does not necessarily create a new
8771 value. */
8772
0c3acc09 8773struct value *
4c4b4cd2
PH
8774ada_to_fixed_value (struct value *val)
8775{
c48db5ca 8776 val = unwrap_value (val);
9feb2d07 8777 val = ada_to_fixed_value_create (val->type (), val->address (), val);
c48db5ca 8778 return val;
14f9c5c9 8779}
d2e4a39e 8780\f
14f9c5c9 8781
14f9c5c9
AS
8782/* Attributes */
8783
4c4b4cd2 8784/* Evaluate the 'POS attribute applied to ARG. */
14f9c5c9 8785
4c4b4cd2
PH
8786static LONGEST
8787pos_atr (struct value *arg)
14f9c5c9 8788{
24209737 8789 struct value *val = coerce_ref (arg);
d0c97917 8790 struct type *type = val->type ();
14f9c5c9 8791
d2e4a39e 8792 if (!discrete_type_p (type))
323e0a4a 8793 error (_("'POS only defined on discrete types"));
14f9c5c9 8794
6244c119
SM
8795 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8796 if (!result.has_value ())
aa715135 8797 error (_("enumeration value is invalid: can't find 'POS"));
14f9c5c9 8798
6244c119 8799 return *result;
4c4b4cd2
PH
8800}
8801
7631cf6c 8802struct value *
7992accc
TT
8803ada_pos_atr (struct type *expect_type,
8804 struct expression *exp,
8805 enum noside noside, enum exp_opcode op,
8806 struct value *arg)
4c4b4cd2 8807{
7992accc
TT
8808 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8809 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 8810 return value::zero (type, not_lval);
3cb382c9 8811 return value_from_longest (type, pos_atr (arg));
14f9c5c9
AS
8812}
8813
4c4b4cd2 8814/* Evaluate the TYPE'VAL attribute applied to ARG. */
14f9c5c9 8815
d2e4a39e 8816static struct value *
53a47a3e 8817val_atr (struct type *type, LONGEST val)
14f9c5c9 8818{
53a47a3e 8819 gdb_assert (discrete_type_p (type));
0bc2354b 8820 if (type->code () == TYPE_CODE_RANGE)
27710edb 8821 type = type->target_type ();
78134374 8822 if (type->code () == TYPE_CODE_ENUM)
14f9c5c9 8823 {
53a47a3e 8824 if (val < 0 || val >= type->num_fields ())
dda83cd7 8825 error (_("argument to 'VAL out of range"));
970db518 8826 val = type->field (val).loc_enumval ();
14f9c5c9 8827 }
53a47a3e
TT
8828 return value_from_longest (type, val);
8829}
8830
9e99f48f 8831struct value *
22f6f797
TT
8832ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8833 struct value *arg)
53a47a3e 8834{
3848abd6 8835 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 8836 return value::zero (type, not_lval);
3848abd6 8837
53a47a3e
TT
8838 if (!discrete_type_p (type))
8839 error (_("'VAL only defined on discrete types"));
d0c97917 8840 if (!integer_type_p (arg->type ()))
53a47a3e
TT
8841 error (_("'VAL requires integral argument"));
8842
8843 return val_atr (type, value_as_long (arg));
14f9c5c9 8844}
22f6f797
TT
8845
8846/* Implementation of the enum_rep attribute. */
8847struct value *
8848ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8849 struct value *arg)
8850{
8851 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8852 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8853 return value::zero (inttype, not_lval);
8854
8855 if (type->code () == TYPE_CODE_RANGE)
8856 type = type->target_type ();
8857 if (type->code () != TYPE_CODE_ENUM)
8858 error (_("'Enum_Rep only defined on enum types"));
8859 if (!types_equal (type, arg->type ()))
8860 error (_("'Enum_Rep requires argument to have same type as enum"));
8861
8862 return value_cast (inttype, arg);
8863}
8864
8865/* Implementation of the enum_val attribute. */
8866struct value *
8867ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8868 struct value *arg)
8869{
8870 struct type *original_type = type;
8871 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8872 return value::zero (original_type, not_lval);
8873
8874 if (type->code () == TYPE_CODE_RANGE)
8875 type = type->target_type ();
8876 if (type->code () != TYPE_CODE_ENUM)
8877 error (_("'Enum_Val only defined on enum types"));
8878 if (!integer_type_p (arg->type ()))
8879 error (_("'Enum_Val requires integral argument"));
8880
8881 LONGEST value = value_as_long (arg);
8882 for (int i = 0; i < type->num_fields (); ++i)
8883 {
8884 if (type->field (i).loc_enumval () == value)
8885 return value_from_longest (original_type, value);
8886 }
8887
8888 error (_("value %s not found in enum"), plongest (value));
8889}
8890
14f9c5c9 8891\f
d2e4a39e 8892
dda83cd7 8893 /* Evaluation */
14f9c5c9 8894
4c4b4cd2
PH
8895/* True if TYPE appears to be an Ada character type.
8896 [At the moment, this is true only for Character and Wide_Character;
8897 It is a heuristic test that could stand improvement]. */
14f9c5c9 8898
fc913e53 8899bool
d2e4a39e 8900ada_is_character_type (struct type *type)
14f9c5c9 8901{
7b9f71f2
JB
8902 const char *name;
8903
8904 /* If the type code says it's a character, then assume it really is,
8905 and don't check any further. */
78134374 8906 if (type->code () == TYPE_CODE_CHAR)
fc913e53 8907 return true;
7b9f71f2
JB
8908
8909 /* Otherwise, assume it's a character type iff it is a discrete type
8910 with a known character type name. */
8911 name = ada_type_name (type);
8912 return (name != NULL
dda83cd7
SM
8913 && (type->code () == TYPE_CODE_INT
8914 || type->code () == TYPE_CODE_RANGE)
8915 && (strcmp (name, "character") == 0
8916 || strcmp (name, "wide_character") == 0
8917 || strcmp (name, "wide_wide_character") == 0
8918 || strcmp (name, "unsigned char") == 0));
14f9c5c9
AS
8919}
8920
4c4b4cd2 8921/* True if TYPE appears to be an Ada string type. */
14f9c5c9 8922
fc913e53 8923bool
ebf56fd3 8924ada_is_string_type (struct type *type)
14f9c5c9 8925{
61ee279c 8926 type = ada_check_typedef (type);
d2e4a39e 8927 if (type != NULL
78134374 8928 && type->code () != TYPE_CODE_PTR
76a01679 8929 && (ada_is_simple_array_type (type)
dda83cd7 8930 || ada_is_array_descriptor_type (type))
14f9c5c9
AS
8931 && ada_array_arity (type) == 1)
8932 {
8933 struct type *elttype = ada_array_element_type (type, 1);
8934
8935 return ada_is_character_type (elttype);
8936 }
d2e4a39e 8937 else
fc913e53 8938 return false;
14f9c5c9
AS
8939}
8940
5bf03f13
JB
8941/* The compiler sometimes provides a parallel XVS type for a given
8942 PAD type. Normally, it is safe to follow the PAD type directly,
8943 but older versions of the compiler have a bug that causes the offset
8944 of its "F" field to be wrong. Following that field in that case
8945 would lead to incorrect results, but this can be worked around
8946 by ignoring the PAD type and using the associated XVS type instead.
8947
8948 Set to True if the debugger should trust the contents of PAD types.
8949 Otherwise, ignore the PAD type if there is a parallel XVS type. */
491144b5 8950static bool trust_pad_over_xvs = true;
14f9c5c9
AS
8951
8952/* True if TYPE is a struct type introduced by the compiler to force the
8953 alignment of a value. Such types have a single field with a
4c4b4cd2 8954 distinctive name. */
14f9c5c9
AS
8955
8956int
ebf56fd3 8957ada_is_aligner_type (struct type *type)
14f9c5c9 8958{
61ee279c 8959 type = ada_check_typedef (type);
714e53ab 8960
5bf03f13 8961 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
714e53ab
PH
8962 return 0;
8963
78134374 8964 return (type->code () == TYPE_CODE_STRUCT
dda83cd7 8965 && type->num_fields () == 1
33d16dd9 8966 && strcmp (type->field (0).name (), "F") == 0);
14f9c5c9
AS
8967}
8968
8969/* If there is an ___XVS-convention type parallel to SUBTYPE, return
4c4b4cd2 8970 the parallel type. */
14f9c5c9 8971
d2e4a39e
AS
8972struct type *
8973ada_get_base_type (struct type *raw_type)
14f9c5c9 8974{
d2e4a39e
AS
8975 struct type *real_type_namer;
8976 struct type *raw_real_type;
14f9c5c9 8977
78134374 8978 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
14f9c5c9
AS
8979 return raw_type;
8980
284614f0
JB
8981 if (ada_is_aligner_type (raw_type))
8982 /* The encoding specifies that we should always use the aligner type.
8983 So, even if this aligner type has an associated XVS type, we should
8984 simply ignore it.
8985
8986 According to the compiler gurus, an XVS type parallel to an aligner
8987 type may exist because of a stabs limitation. In stabs, aligner
8988 types are empty because the field has a variable-sized type, and
8989 thus cannot actually be used as an aligner type. As a result,
8990 we need the associated parallel XVS type to decode the type.
8991 Since the policy in the compiler is to not change the internal
8992 representation based on the debugging info format, we sometimes
8993 end up having a redundant XVS type parallel to the aligner type. */
8994 return raw_type;
8995
14f9c5c9 8996 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
d2e4a39e 8997 if (real_type_namer == NULL
78134374 8998 || real_type_namer->code () != TYPE_CODE_STRUCT
1f704f76 8999 || real_type_namer->num_fields () != 1)
14f9c5c9
AS
9000 return raw_type;
9001
940da03e 9002 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
f80d3ff2
JB
9003 {
9004 /* This is an older encoding form where the base type needs to be
85102364 9005 looked up by name. We prefer the newer encoding because it is
f80d3ff2 9006 more efficient. */
33d16dd9 9007 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
f80d3ff2
JB
9008 if (raw_real_type == NULL)
9009 return raw_type;
9010 else
9011 return raw_real_type;
9012 }
9013
9014 /* The field in our XVS type is a reference to the base type. */
27710edb 9015 return real_type_namer->field (0).type ()->target_type ();
d2e4a39e 9016}
14f9c5c9 9017
4c4b4cd2 9018/* The type of value designated by TYPE, with all aligners removed. */
14f9c5c9 9019
d2e4a39e
AS
9020struct type *
9021ada_aligned_type (struct type *type)
14f9c5c9
AS
9022{
9023 if (ada_is_aligner_type (type))
940da03e 9024 return ada_aligned_type (type->field (0).type ());
14f9c5c9
AS
9025 else
9026 return ada_get_base_type (type);
9027}
9028
9029
9030/* The address of the aligned value in an object at address VALADDR
4c4b4cd2 9031 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
14f9c5c9 9032
fc1a4b47
AC
9033const gdb_byte *
9034ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
14f9c5c9 9035{
d2e4a39e 9036 if (ada_is_aligner_type (type))
b610c045
SM
9037 return ada_aligned_value_addr
9038 (type->field (0).type (),
9039 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
14f9c5c9
AS
9040 else
9041 return valaddr;
9042}
9043
4c4b4cd2
PH
9044
9045
14f9c5c9 9046/* The printed representation of an enumeration literal with encoded
4c4b4cd2 9047 name NAME. The value is good to the next call of ada_enum_name. */
d2e4a39e
AS
9048const char *
9049ada_enum_name (const char *name)
14f9c5c9 9050{
5f9febe0 9051 static std::string storage;
e6a959d6 9052 const char *tmp;
14f9c5c9 9053
4c4b4cd2
PH
9054 /* First, unqualify the enumeration name:
9055 1. Search for the last '.' character. If we find one, then skip
177b42fe 9056 all the preceding characters, the unqualified name starts
76a01679 9057 right after that dot.
4c4b4cd2 9058 2. Otherwise, we may be debugging on a target where the compiler
76a01679
JB
9059 translates dots into "__". Search forward for double underscores,
9060 but stop searching when we hit an overloading suffix, which is
9061 of the form "__" followed by digits. */
4c4b4cd2 9062
c3e5cd34
PH
9063 tmp = strrchr (name, '.');
9064 if (tmp != NULL)
4c4b4cd2
PH
9065 name = tmp + 1;
9066 else
14f9c5c9 9067 {
4c4b4cd2 9068 while ((tmp = strstr (name, "__")) != NULL)
dda83cd7
SM
9069 {
9070 if (isdigit (tmp[2]))
9071 break;
9072 else
9073 name = tmp + 2;
9074 }
14f9c5c9
AS
9075 }
9076
9077 if (name[0] == 'Q')
9078 {
14f9c5c9 9079 int v;
5b4ee69b 9080
14f9c5c9 9081 if (name[1] == 'U' || name[1] == 'W')
dda83cd7 9082 {
a7041de8
TT
9083 int offset = 2;
9084 if (name[1] == 'W' && name[2] == 'W')
9085 {
9086 /* Also handle the QWW case. */
9087 ++offset;
9088 }
9089 if (sscanf (name + offset, "%x", &v) != 1)
dda83cd7
SM
9090 return name;
9091 }
272560b5
TT
9092 else if (((name[1] >= '0' && name[1] <= '9')
9093 || (name[1] >= 'a' && name[1] <= 'z'))
9094 && name[2] == '\0')
9095 {
5f9febe0
TT
9096 storage = string_printf ("'%c'", name[1]);
9097 return storage.c_str ();
272560b5 9098 }
14f9c5c9 9099 else
dda83cd7 9100 return name;
14f9c5c9
AS
9101
9102 if (isascii (v) && isprint (v))
5f9febe0 9103 storage = string_printf ("'%c'", v);
14f9c5c9 9104 else if (name[1] == 'U')
a7041de8
TT
9105 storage = string_printf ("'[\"%02x\"]'", v);
9106 else if (name[2] != 'W')
9107 storage = string_printf ("'[\"%04x\"]'", v);
14f9c5c9 9108 else
a7041de8 9109 storage = string_printf ("'[\"%06x\"]'", v);
14f9c5c9 9110
5f9febe0 9111 return storage.c_str ();
14f9c5c9 9112 }
d2e4a39e 9113 else
4c4b4cd2 9114 {
c3e5cd34
PH
9115 tmp = strstr (name, "__");
9116 if (tmp == NULL)
9117 tmp = strstr (name, "$");
9118 if (tmp != NULL)
dda83cd7 9119 {
5f9febe0
TT
9120 storage = std::string (name, tmp - name);
9121 return storage.c_str ();
dda83cd7 9122 }
4c4b4cd2
PH
9123
9124 return name;
9125 }
14f9c5c9
AS
9126}
9127
013a623f
TT
9128/* If TYPE is a dynamic type, return the base type. Otherwise, if
9129 there is no parallel type, return nullptr. */
9130
9131static struct type *
9132find_base_type (struct type *type)
9133{
9134 struct type *raw_real_type
9135 = ada_check_typedef (ada_get_base_type (type));
9136
9137 /* No parallel XVS or XVE type. */
9138 if (type == raw_real_type
9139 && ada_find_parallel_type (type, "___XVE") == nullptr)
9140 return nullptr;
9141
9142 return raw_real_type;
9143}
9144
14f9c5c9 9145/* If VAL is wrapped in an aligner or subtype wrapper, return the
4c4b4cd2 9146 value it wraps. */
14f9c5c9 9147
d2e4a39e
AS
9148static struct value *
9149unwrap_value (struct value *val)
14f9c5c9 9150{
d0c97917 9151 struct type *type = ada_check_typedef (val->type ());
5b4ee69b 9152
14f9c5c9
AS
9153 if (ada_is_aligner_type (type))
9154 {
de4d072f 9155 struct value *v = ada_value_struct_elt (val, "F", 0);
d0c97917 9156 struct type *val_type = ada_check_typedef (v->type ());
5b4ee69b 9157
14f9c5c9 9158 if (ada_type_name (val_type) == NULL)
d0e39ea2 9159 val_type->set_name (ada_type_name (type));
14f9c5c9
AS
9160
9161 return unwrap_value (v);
9162 }
d2e4a39e 9163 else
14f9c5c9 9164 {
013a623f
TT
9165 struct type *raw_real_type = find_base_type (type);
9166 if (raw_real_type == nullptr)
5bf03f13 9167 return val;
14f9c5c9 9168
d2e4a39e 9169 return
dda83cd7
SM
9170 coerce_unspec_val_to_type
9171 (val, ada_to_fixed_type (raw_real_type, 0,
9feb2d07 9172 val->address (),
dda83cd7 9173 NULL, 1));
14f9c5c9
AS
9174 }
9175}
d2e4a39e 9176
d99dcf51
JB
9177/* Given two array types T1 and T2, return nonzero iff both arrays
9178 contain the same number of elements. */
9179
9180static int
9181ada_same_array_size_p (struct type *t1, struct type *t2)
9182{
9183 LONGEST lo1, hi1, lo2, hi2;
9184
9185 /* Get the array bounds in order to verify that the size of
9186 the two arrays match. */
9187 if (!get_array_bounds (t1, &lo1, &hi1)
9188 || !get_array_bounds (t2, &lo2, &hi2))
9189 error (_("unable to determine array bounds"));
9190
9191 /* To make things easier for size comparison, normalize a bit
9192 the case of empty arrays by making sure that the difference
9193 between upper bound and lower bound is always -1. */
9194 if (lo1 > hi1)
9195 hi1 = lo1 - 1;
9196 if (lo2 > hi2)
9197 hi2 = lo2 - 1;
9198
9199 return (hi1 - lo1 == hi2 - lo2);
9200}
9201
9202/* Assuming that VAL is an array of integrals, and TYPE represents
9203 an array with the same number of elements, but with wider integral
9204 elements, return an array "casted" to TYPE. In practice, this
9205 means that the returned array is built by casting each element
9206 of the original array into TYPE's (wider) element type. */
9207
9208static struct value *
9209ada_promote_array_of_integrals (struct type *type, struct value *val)
9210{
27710edb 9211 struct type *elt_type = type->target_type ();
d99dcf51 9212 LONGEST lo, hi;
d99dcf51
JB
9213 LONGEST i;
9214
9215 /* Verify that both val and type are arrays of scalars, and
9216 that the size of val's elements is smaller than the size
9217 of type's element. */
78134374 9218 gdb_assert (type->code () == TYPE_CODE_ARRAY);
27710edb 9219 gdb_assert (is_integral_type (type->target_type ()));
d0c97917
TT
9220 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9221 gdb_assert (is_integral_type (val->type ()->target_type ()));
df86565b 9222 gdb_assert (type->target_type ()->length ()
d0c97917 9223 > val->type ()->target_type ()->length ());
d99dcf51
JB
9224
9225 if (!get_array_bounds (type, &lo, &hi))
9226 error (_("unable to determine array bounds"));
9227
317c3ed9 9228 value *res = value::allocate (type);
bbe912ba 9229 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
d99dcf51
JB
9230
9231 /* Promote each array element. */
9232 for (i = 0; i < hi - lo + 1; i++)
9233 {
9234 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
df86565b 9235 int elt_len = elt_type->length ();
d99dcf51 9236
efaf1ae0 9237 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
d99dcf51
JB
9238 }
9239
9240 return res;
9241}
9242
4c4b4cd2
PH
9243/* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9244 return the converted value. */
9245
d2e4a39e
AS
9246static struct value *
9247coerce_for_assign (struct type *type, struct value *val)
14f9c5c9 9248{
d0c97917 9249 struct type *type2 = val->type ();
5b4ee69b 9250
14f9c5c9
AS
9251 if (type == type2)
9252 return val;
9253
61ee279c
PH
9254 type2 = ada_check_typedef (type2);
9255 type = ada_check_typedef (type);
14f9c5c9 9256
78134374
SM
9257 if (type2->code () == TYPE_CODE_PTR
9258 && type->code () == TYPE_CODE_ARRAY)
14f9c5c9
AS
9259 {
9260 val = ada_value_ind (val);
d0c97917 9261 type2 = val->type ();
14f9c5c9
AS
9262 }
9263
78134374
SM
9264 if (type2->code () == TYPE_CODE_ARRAY
9265 && type->code () == TYPE_CODE_ARRAY)
14f9c5c9 9266 {
d99dcf51
JB
9267 if (!ada_same_array_size_p (type, type2))
9268 error (_("cannot assign arrays of different length"));
9269
27710edb
SM
9270 if (is_integral_type (type->target_type ())
9271 && is_integral_type (type2->target_type ())
df86565b 9272 && type2->target_type ()->length () < type->target_type ()->length ())
d99dcf51
JB
9273 {
9274 /* Allow implicit promotion of the array elements to
9275 a wider type. */
9276 return ada_promote_array_of_integrals (type, val);
9277 }
9278
df86565b 9279 if (type2->target_type ()->length () != type->target_type ()->length ())
dda83cd7 9280 error (_("Incompatible types in assignment"));
81ae560c 9281 val->deprecated_set_type (type);
14f9c5c9 9282 }
d2e4a39e 9283 return val;
14f9c5c9
AS
9284}
9285
4c4b4cd2
PH
9286static struct value *
9287ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9288{
4c4b4cd2 9289 struct type *type1, *type2;
4c4b4cd2 9290
994b9211
AC
9291 arg1 = coerce_ref (arg1);
9292 arg2 = coerce_ref (arg2);
d0c97917
TT
9293 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9294 type2 = get_base_type (ada_check_typedef (arg2->type ()));
4c4b4cd2 9295
78134374
SM
9296 if (type1->code () != TYPE_CODE_INT
9297 || type2->code () != TYPE_CODE_INT)
4c4b4cd2
PH
9298 return value_binop (arg1, arg2, op);
9299
76a01679 9300 switch (op)
4c4b4cd2
PH
9301 {
9302 case BINOP_MOD:
9303 case BINOP_DIV:
9304 case BINOP_REM:
9305 break;
9306 default:
9307 return value_binop (arg1, arg2, op);
9308 }
9309
70050808
TT
9310 gdb_mpz v2 = value_as_mpz (arg2);
9311 if (v2.sgn () == 0)
b0f9164c
TT
9312 {
9313 const char *name;
9314 if (op == BINOP_MOD)
9315 name = "mod";
9316 else if (op == BINOP_DIV)
9317 name = "/";
9318 else
9319 {
9320 gdb_assert (op == BINOP_REM);
9321 name = "rem";
9322 }
9323
9324 error (_("second operand of %s must not be zero."), name);
9325 }
4c4b4cd2 9326
c6d940a9 9327 if (type1->is_unsigned () || op == BINOP_MOD)
4c4b4cd2
PH
9328 return value_binop (arg1, arg2, op);
9329
70050808
TT
9330 gdb_mpz v1 = value_as_mpz (arg1);
9331 gdb_mpz v;
4c4b4cd2
PH
9332 switch (op)
9333 {
9334 case BINOP_DIV:
9335 v = v1 / v2;
4c4b4cd2
PH
9336 break;
9337 case BINOP_REM:
9338 v = v1 % v2;
76a01679 9339 if (v * v1 < 0)
dda83cd7 9340 v -= v2;
4c4b4cd2
PH
9341 break;
9342 default:
9343 /* Should not reach this point. */
70050808 9344 gdb_assert_not_reached ("invalid operator");
4c4b4cd2
PH
9345 }
9346
70050808 9347 return value_from_mpz (type1, v);
4c4b4cd2
PH
9348}
9349
9350static int
9351ada_value_equal (struct value *arg1, struct value *arg2)
9352{
d0c97917
TT
9353 if (ada_is_direct_array_type (arg1->type ())
9354 || ada_is_direct_array_type (arg2->type ()))
4c4b4cd2 9355 {
79e8fcaa
JB
9356 struct type *arg1_type, *arg2_type;
9357
f58b38bf 9358 /* Automatically dereference any array reference before
dda83cd7 9359 we attempt to perform the comparison. */
f58b38bf
JB
9360 arg1 = ada_coerce_ref (arg1);
9361 arg2 = ada_coerce_ref (arg2);
79e8fcaa 9362
4c4b4cd2
PH
9363 arg1 = ada_coerce_to_simple_array (arg1);
9364 arg2 = ada_coerce_to_simple_array (arg2);
79e8fcaa 9365
d0c97917
TT
9366 arg1_type = ada_check_typedef (arg1->type ());
9367 arg2_type = ada_check_typedef (arg2->type ());
79e8fcaa 9368
78134374 9369 if (arg1_type->code () != TYPE_CODE_ARRAY
dda83cd7
SM
9370 || arg2_type->code () != TYPE_CODE_ARRAY)
9371 error (_("Attempt to compare array with non-array"));
4c4b4cd2 9372 /* FIXME: The following works only for types whose
dda83cd7
SM
9373 representations use all bits (no padding or undefined bits)
9374 and do not have user-defined equality. */
df86565b 9375 return (arg1_type->length () == arg2_type->length ()
efaf1ae0
TT
9376 && memcmp (arg1->contents ().data (),
9377 arg2->contents ().data (),
df86565b 9378 arg1_type->length ()) == 0);
4c4b4cd2
PH
9379 }
9380 return value_equal (arg1, arg2);
9381}
9382
d3c54a1c
TT
9383namespace expr
9384{
9385
9386bool
9387check_objfile (const std::unique_ptr<ada_component> &comp,
9388 struct objfile *objfile)
9389{
9390 return comp->uses_objfile (objfile);
9391}
9392
9393/* Assign the result of evaluating ARG starting at *POS to the INDEXth
9394 component of LHS (a simple array or a record). Does not modify the
9395 inferior's memory, nor does it modify LHS (unless LHS ==
9396 CONTAINER). */
52ce6436
PH
9397
9398static void
9399assign_component (struct value *container, struct value *lhs, LONGEST index,
d3c54a1c 9400 struct expression *exp, operation_up &arg)
52ce6436 9401{
d3c54a1c
TT
9402 scoped_value_mark mark;
9403
52ce6436 9404 struct value *elt;
d0c97917 9405 struct type *lhs_type = check_typedef (lhs->type ());
5b4ee69b 9406
78134374 9407 if (lhs_type->code () == TYPE_CODE_ARRAY)
52ce6436 9408 {
22601c15
UW
9409 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9410 struct value *index_val = value_from_longest (index_type, index);
5b4ee69b 9411
52ce6436
PH
9412 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9413 }
9414 else
9415 {
d0c97917 9416 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
c48db5ca 9417 elt = ada_to_fixed_value (elt);
52ce6436
PH
9418 }
9419
d3c54a1c
TT
9420 ada_aggregate_operation *ag_op
9421 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9422 if (ag_op != nullptr)
9423 ag_op->assign_aggregate (container, elt, exp);
52ce6436 9424 else
d3c54a1c
TT
9425 value_assign_to_component (container, elt,
9426 arg->evaluate (nullptr, exp,
9427 EVAL_NORMAL));
9428}
52ce6436 9429
d3c54a1c
TT
9430bool
9431ada_aggregate_component::uses_objfile (struct objfile *objfile)
9432{
9433 for (const auto &item : m_components)
9434 if (item->uses_objfile (objfile))
9435 return true;
9436 return false;
9437}
9438
9439void
9440ada_aggregate_component::dump (ui_file *stream, int depth)
9441{
6cb06a8c 9442 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
d3c54a1c
TT
9443 for (const auto &item : m_components)
9444 item->dump (stream, depth + 1);
9445}
9446
9447void
9448ada_aggregate_component::assign (struct value *container,
9449 struct value *lhs, struct expression *exp,
9450 std::vector<LONGEST> &indices,
9451 LONGEST low, LONGEST high)
9452{
9453 for (auto &item : m_components)
9454 item->assign (container, lhs, exp, indices, low, high);
52ce6436
PH
9455}
9456
207582c0 9457/* See ada-exp.h. */
52ce6436 9458
207582c0 9459value *
d3c54a1c
TT
9460ada_aggregate_operation::assign_aggregate (struct value *container,
9461 struct value *lhs,
9462 struct expression *exp)
52ce6436
PH
9463{
9464 struct type *lhs_type;
52ce6436 9465 LONGEST low_index, high_index;
52ce6436
PH
9466
9467 container = ada_coerce_ref (container);
d0c97917 9468 if (ada_is_direct_array_type (container->type ()))
52ce6436
PH
9469 container = ada_coerce_to_simple_array (container);
9470 lhs = ada_coerce_ref (lhs);
4b53ca88 9471 if (!lhs->deprecated_modifiable ())
52ce6436
PH
9472 error (_("Left operand of assignment is not a modifiable lvalue."));
9473
d0c97917 9474 lhs_type = check_typedef (lhs->type ());
52ce6436
PH
9475 if (ada_is_direct_array_type (lhs_type))
9476 {
9477 lhs = ada_coerce_to_simple_array (lhs);
d0c97917 9478 lhs_type = check_typedef (lhs->type ());
cf88be68
SM
9479 low_index = lhs_type->bounds ()->low.const_val ();
9480 high_index = lhs_type->bounds ()->high.const_val ();
52ce6436 9481 }
78134374 9482 else if (lhs_type->code () == TYPE_CODE_STRUCT)
52ce6436
PH
9483 {
9484 low_index = 0;
9485 high_index = num_visible_fields (lhs_type) - 1;
52ce6436
PH
9486 }
9487 else
9488 error (_("Left-hand side must be array or record."));
9489
cf608cc4 9490 std::vector<LONGEST> indices (4);
52ce6436
PH
9491 indices[0] = indices[1] = low_index - 1;
9492 indices[2] = indices[3] = high_index + 1;
52ce6436 9493
d3c54a1c
TT
9494 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9495 low_index, high_index);
207582c0
TT
9496
9497 return container;
d3c54a1c
TT
9498}
9499
9500bool
9501ada_positional_component::uses_objfile (struct objfile *objfile)
9502{
9503 return m_op->uses_objfile (objfile);
9504}
52ce6436 9505
d3c54a1c
TT
9506void
9507ada_positional_component::dump (ui_file *stream, int depth)
9508{
6cb06a8c
TT
9509 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9510 depth, "", m_index);
d3c54a1c 9511 m_op->dump (stream, depth + 1);
52ce6436 9512}
d3c54a1c 9513
52ce6436 9514/* Assign into the component of LHS indexed by the OP_POSITIONAL
d3c54a1c
TT
9515 construct, given that the positions are relative to lower bound
9516 LOW, where HIGH is the upper bound. Record the position in
9517 INDICES. CONTAINER is as for assign_aggregate. */
9518void
9519ada_positional_component::assign (struct value *container,
9520 struct value *lhs, struct expression *exp,
9521 std::vector<LONGEST> &indices,
9522 LONGEST low, LONGEST high)
52ce6436 9523{
d3c54a1c
TT
9524 LONGEST ind = m_index + low;
9525
52ce6436 9526 if (ind - 1 == high)
e1d5a0d2 9527 warning (_("Extra components in aggregate ignored."));
52ce6436
PH
9528 if (ind <= high)
9529 {
cf608cc4 9530 add_component_interval (ind, ind, indices);
d3c54a1c 9531 assign_component (container, lhs, ind, exp, m_op);
52ce6436 9532 }
52ce6436
PH
9533}
9534
d3c54a1c
TT
9535bool
9536ada_discrete_range_association::uses_objfile (struct objfile *objfile)
a88c4354
TT
9537{
9538 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9539}
9540
9541void
9542ada_discrete_range_association::dump (ui_file *stream, int depth)
9543{
6cb06a8c 9544 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
a88c4354
TT
9545 m_low->dump (stream, depth + 1);
9546 m_high->dump (stream, depth + 1);
9547}
9548
9549void
9550ada_discrete_range_association::assign (struct value *container,
9551 struct value *lhs,
9552 struct expression *exp,
9553 std::vector<LONGEST> &indices,
9554 LONGEST low, LONGEST high,
9555 operation_up &op)
9556{
9557 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9558 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9559
9560 if (lower <= upper && (lower < low || upper > high))
9561 error (_("Index in component association out of bounds."));
9562
9563 add_component_interval (lower, upper, indices);
9564 while (lower <= upper)
9565 {
9566 assign_component (container, lhs, lower, exp, op);
9567 lower += 1;
9568 }
9569}
9570
9571bool
9572ada_name_association::uses_objfile (struct objfile *objfile)
9573{
9574 return m_val->uses_objfile (objfile);
9575}
9576
9577void
9578ada_name_association::dump (ui_file *stream, int depth)
9579{
6cb06a8c 9580 gdb_printf (stream, _("%*sName:\n"), depth, "");
a88c4354
TT
9581 m_val->dump (stream, depth + 1);
9582}
9583
9584void
9585ada_name_association::assign (struct value *container,
9586 struct value *lhs,
9587 struct expression *exp,
9588 std::vector<LONGEST> &indices,
9589 LONGEST low, LONGEST high,
9590 operation_up &op)
9591{
9592 int index;
9593
d0c97917 9594 if (ada_is_direct_array_type (lhs->type ()))
a88c4354
TT
9595 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9596 EVAL_NORMAL)));
9597 else
9598 {
9599 ada_string_operation *strop
9600 = dynamic_cast<ada_string_operation *> (m_val.get ());
9601
9602 const char *name;
9603 if (strop != nullptr)
9604 name = strop->get_name ();
9605 else
9606 {
9607 ada_var_value_operation *vvo
9608 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
94c5098e 9609 if (vvo == nullptr)
a88c4354
TT
9610 error (_("Invalid record component association."));
9611 name = vvo->get_symbol ()->natural_name ();
94c5098e
TT
9612 /* In this scenario, the user wrote (name => expr), but
9613 write_name_assoc found some fully-qualified name and
9614 substituted it. This happens because, at parse time, the
9615 meaning of the expression isn't known; but here we know
9616 that just the base name was supplied and it refers to the
9617 name of a field. */
9618 name = ada_unqualified_name (name);
a88c4354
TT
9619 }
9620
9621 index = 0;
d0c97917 9622 if (! find_struct_field (name, lhs->type (), 0,
a88c4354
TT
9623 NULL, NULL, NULL, NULL, &index))
9624 error (_("Unknown component name: %s."), name);
9625 }
9626
9627 add_component_interval (index, index, indices);
9628 assign_component (container, lhs, index, exp, op);
9629}
9630
9631bool
9632ada_choices_component::uses_objfile (struct objfile *objfile)
9633{
9634 if (m_op->uses_objfile (objfile))
9635 return true;
9636 for (const auto &item : m_assocs)
9637 if (item->uses_objfile (objfile))
9638 return true;
9639 return false;
9640}
9641
9642void
9643ada_choices_component::dump (ui_file *stream, int depth)
9644{
6cb06a8c 9645 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
a88c4354
TT
9646 m_op->dump (stream, depth + 1);
9647 for (const auto &item : m_assocs)
9648 item->dump (stream, depth + 1);
9649}
9650
9651/* Assign into the components of LHS indexed by the OP_CHOICES
9652 construct at *POS, updating *POS past the construct, given that
9653 the allowable indices are LOW..HIGH. Record the indices assigned
9654 to in INDICES. CONTAINER is as for assign_aggregate. */
9655void
9656ada_choices_component::assign (struct value *container,
9657 struct value *lhs, struct expression *exp,
9658 std::vector<LONGEST> &indices,
9659 LONGEST low, LONGEST high)
9660{
9661 for (auto &item : m_assocs)
9662 item->assign (container, lhs, exp, indices, low, high, m_op);
9663}
9664
9665bool
9666ada_others_component::uses_objfile (struct objfile *objfile)
9667{
9668 return m_op->uses_objfile (objfile);
9669}
9670
9671void
9672ada_others_component::dump (ui_file *stream, int depth)
9673{
6cb06a8c 9674 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
a88c4354
TT
9675 m_op->dump (stream, depth + 1);
9676}
9677
9678/* Assign the value of the expression in the OP_OTHERS construct in
9679 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9680 have not been previously assigned. The index intervals already assigned
9681 are in INDICES. CONTAINER is as for assign_aggregate. */
9682void
9683ada_others_component::assign (struct value *container,
9684 struct value *lhs, struct expression *exp,
9685 std::vector<LONGEST> &indices,
9686 LONGEST low, LONGEST high)
9687{
9688 int num_indices = indices.size ();
9689 for (int i = 0; i < num_indices - 2; i += 2)
9690 {
9691 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9692 assign_component (container, lhs, ind, exp, m_op);
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
9733} /* namespace expr */
9734
cf608cc4
TT
9735/* Add the interval [LOW .. HIGH] to the sorted set of intervals
9736 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9737 overlap. */
52ce6436
PH
9738static void
9739add_component_interval (LONGEST low, LONGEST high,
cf608cc4 9740 std::vector<LONGEST> &indices)
52ce6436
PH
9741{
9742 int i, j;
5b4ee69b 9743
cf608cc4
TT
9744 int size = indices.size ();
9745 for (i = 0; i < size; i += 2) {
52ce6436
PH
9746 if (high >= indices[i] && low <= indices[i + 1])
9747 {
9748 int kh;
5b4ee69b 9749
cf608cc4 9750 for (kh = i + 2; kh < size; kh += 2)
52ce6436
PH
9751 if (high < indices[kh])
9752 break;
9753 if (low < indices[i])
9754 indices[i] = low;
9755 indices[i + 1] = indices[kh - 1];
9756 if (high > indices[i + 1])
9757 indices[i + 1] = high;
cf608cc4
TT
9758 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9759 indices.resize (kh - i - 2);
52ce6436
PH
9760 return;
9761 }
9762 else if (high < indices[i])
9763 break;
9764 }
9765
cf608cc4 9766 indices.resize (indices.size () + 2);
d4813f10 9767 for (j = indices.size () - 1; j >= i + 2; j -= 1)
52ce6436
PH
9768 indices[j] = indices[j - 2];
9769 indices[i] = low;
9770 indices[i + 1] = high;
9771}
9772
6e48bd2c
JB
9773/* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9774 is different. */
9775
9776static struct value *
b7e22850 9777ada_value_cast (struct type *type, struct value *arg2)
6e48bd2c 9778{
d0c97917 9779 if (type == ada_check_typedef (arg2->type ()))
6e48bd2c
JB
9780 return arg2;
9781
6e48bd2c
JB
9782 return value_cast (type, arg2);
9783}
9784
284614f0
JB
9785/* Evaluating Ada expressions, and printing their result.
9786 ------------------------------------------------------
9787
21649b50
JB
9788 1. Introduction:
9789 ----------------
9790
284614f0
JB
9791 We usually evaluate an Ada expression in order to print its value.
9792 We also evaluate an expression in order to print its type, which
9793 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9794 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9795 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9796 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9797 similar.
9798
9799 Evaluating expressions is a little more complicated for Ada entities
9800 than it is for entities in languages such as C. The main reason for
9801 this is that Ada provides types whose definition might be dynamic.
9802 One example of such types is variant records. Or another example
9803 would be an array whose bounds can only be known at run time.
9804
9805 The following description is a general guide as to what should be
9806 done (and what should NOT be done) in order to evaluate an expression
9807 involving such types, and when. This does not cover how the semantic
9808 information is encoded by GNAT as this is covered separatly. For the
9809 document used as the reference for the GNAT encoding, see exp_dbug.ads
9810 in the GNAT sources.
9811
9812 Ideally, we should embed each part of this description next to its
9813 associated code. Unfortunately, the amount of code is so vast right
9814 now that it's hard to see whether the code handling a particular
9815 situation might be duplicated or not. One day, when the code is
9816 cleaned up, this guide might become redundant with the comments
9817 inserted in the code, and we might want to remove it.
9818
21649b50
JB
9819 2. ``Fixing'' an Entity, the Simple Case:
9820 -----------------------------------------
9821
284614f0
JB
9822 When evaluating Ada expressions, the tricky issue is that they may
9823 reference entities whose type contents and size are not statically
9824 known. Consider for instance a variant record:
9825
9826 type Rec (Empty : Boolean := True) is record
dda83cd7
SM
9827 case Empty is
9828 when True => null;
9829 when False => Value : Integer;
9830 end case;
284614f0
JB
9831 end record;
9832 Yes : Rec := (Empty => False, Value => 1);
9833 No : Rec := (empty => True);
9834
9835 The size and contents of that record depends on the value of the
33b5899f 9836 discriminant (Rec.Empty). At this point, neither the debugging
284614f0
JB
9837 information nor the associated type structure in GDB are able to
9838 express such dynamic types. So what the debugger does is to create
9839 "fixed" versions of the type that applies to the specific object.
30baf67b 9840 We also informally refer to this operation as "fixing" an object,
284614f0
JB
9841 which means creating its associated fixed type.
9842
9843 Example: when printing the value of variable "Yes" above, its fixed
9844 type would look like this:
9845
9846 type Rec is record
dda83cd7
SM
9847 Empty : Boolean;
9848 Value : Integer;
284614f0
JB
9849 end record;
9850
9851 On the other hand, if we printed the value of "No", its fixed type
9852 would become:
9853
9854 type Rec is record
dda83cd7 9855 Empty : Boolean;
284614f0
JB
9856 end record;
9857
9858 Things become a little more complicated when trying to fix an entity
9859 with a dynamic type that directly contains another dynamic type,
9860 such as an array of variant records, for instance. There are
9861 two possible cases: Arrays, and records.
9862
21649b50
JB
9863 3. ``Fixing'' Arrays:
9864 ---------------------
9865
9866 The type structure in GDB describes an array in terms of its bounds,
9867 and the type of its elements. By design, all elements in the array
9868 have the same type and we cannot represent an array of variant elements
9869 using the current type structure in GDB. When fixing an array,
9870 we cannot fix the array element, as we would potentially need one
9871 fixed type per element of the array. As a result, the best we can do
9872 when fixing an array is to produce an array whose bounds and size
9873 are correct (allowing us to read it from memory), but without having
9874 touched its element type. Fixing each element will be done later,
9875 when (if) necessary.
9876
9877 Arrays are a little simpler to handle than records, because the same
9878 amount of memory is allocated for each element of the array, even if
1b536f04 9879 the amount of space actually used by each element differs from element
21649b50 9880 to element. Consider for instance the following array of type Rec:
284614f0
JB
9881
9882 type Rec_Array is array (1 .. 2) of Rec;
9883
1b536f04
JB
9884 The actual amount of memory occupied by each element might be different
9885 from element to element, depending on the value of their discriminant.
21649b50 9886 But the amount of space reserved for each element in the array remains
1b536f04 9887 fixed regardless. So we simply need to compute that size using
21649b50
JB
9888 the debugging information available, from which we can then determine
9889 the array size (we multiply the number of elements of the array by
9890 the size of each element).
9891
9892 The simplest case is when we have an array of a constrained element
9893 type. For instance, consider the following type declarations:
9894
dda83cd7
SM
9895 type Bounded_String (Max_Size : Integer) is
9896 Length : Integer;
9897 Buffer : String (1 .. Max_Size);
9898 end record;
9899 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
21649b50
JB
9900
9901 In this case, the compiler describes the array as an array of
9902 variable-size elements (identified by its XVS suffix) for which
9903 the size can be read in the parallel XVZ variable.
9904
9905 In the case of an array of an unconstrained element type, the compiler
9906 wraps the array element inside a private PAD type. This type should not
9907 be shown to the user, and must be "unwrap"'ed before printing. Note
284614f0
JB
9908 that we also use the adjective "aligner" in our code to designate
9909 these wrapper types.
9910
1b536f04 9911 In some cases, the size allocated for each element is statically
21649b50
JB
9912 known. In that case, the PAD type already has the correct size,
9913 and the array element should remain unfixed.
9914
9915 But there are cases when this size is not statically known.
9916 For instance, assuming that "Five" is an integer variable:
284614f0 9917
dda83cd7
SM
9918 type Dynamic is array (1 .. Five) of Integer;
9919 type Wrapper (Has_Length : Boolean := False) is record
9920 Data : Dynamic;
9921 case Has_Length is
9922 when True => Length : Integer;
9923 when False => null;
9924 end case;
9925 end record;
9926 type Wrapper_Array is array (1 .. 2) of Wrapper;
284614f0 9927
dda83cd7
SM
9928 Hello : Wrapper_Array := (others => (Has_Length => True,
9929 Data => (others => 17),
9930 Length => 1));
284614f0
JB
9931
9932
9933 The debugging info would describe variable Hello as being an
9934 array of a PAD type. The size of that PAD type is not statically
9935 known, but can be determined using a parallel XVZ variable.
9936 In that case, a copy of the PAD type with the correct size should
9937 be used for the fixed array.
9938
21649b50
JB
9939 3. ``Fixing'' record type objects:
9940 ----------------------------------
9941
9942 Things are slightly different from arrays in the case of dynamic
284614f0
JB
9943 record types. In this case, in order to compute the associated
9944 fixed type, we need to determine the size and offset of each of
9945 its components. This, in turn, requires us to compute the fixed
9946 type of each of these components.
9947
9948 Consider for instance the example:
9949
dda83cd7
SM
9950 type Bounded_String (Max_Size : Natural) is record
9951 Str : String (1 .. Max_Size);
9952 Length : Natural;
9953 end record;
9954 My_String : Bounded_String (Max_Size => 10);
284614f0
JB
9955
9956 In that case, the position of field "Length" depends on the size
9957 of field Str, which itself depends on the value of the Max_Size
21649b50 9958 discriminant. In order to fix the type of variable My_String,
284614f0
JB
9959 we need to fix the type of field Str. Therefore, fixing a variant
9960 record requires us to fix each of its components.
9961
9962 However, if a component does not have a dynamic size, the component
9963 should not be fixed. In particular, fields that use a PAD type
9964 should not fixed. Here is an example where this might happen
9965 (assuming type Rec above):
9966
9967 type Container (Big : Boolean) is record
dda83cd7
SM
9968 First : Rec;
9969 After : Integer;
9970 case Big is
9971 when True => Another : Integer;
9972 when False => null;
9973 end case;
284614f0
JB
9974 end record;
9975 My_Container : Container := (Big => False,
dda83cd7
SM
9976 First => (Empty => True),
9977 After => 42);
284614f0
JB
9978
9979 In that example, the compiler creates a PAD type for component First,
9980 whose size is constant, and then positions the component After just
9981 right after it. The offset of component After is therefore constant
9982 in this case.
9983
9984 The debugger computes the position of each field based on an algorithm
9985 that uses, among other things, the actual position and size of the field
21649b50
JB
9986 preceding it. Let's now imagine that the user is trying to print
9987 the value of My_Container. If the type fixing was recursive, we would
284614f0
JB
9988 end up computing the offset of field After based on the size of the
9989 fixed version of field First. And since in our example First has
9990 only one actual field, the size of the fixed type is actually smaller
9991 than the amount of space allocated to that field, and thus we would
9992 compute the wrong offset of field After.
9993
21649b50
JB
9994 To make things more complicated, we need to watch out for dynamic
9995 components of variant records (identified by the ___XVL suffix in
9996 the component name). Even if the target type is a PAD type, the size
9997 of that type might not be statically known. So the PAD type needs
9998 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9999 we might end up with the wrong size for our component. This can be
10000 observed with the following type declarations:
284614f0 10001
dda83cd7
SM
10002 type Octal is new Integer range 0 .. 7;
10003 type Octal_Array is array (Positive range <>) of Octal;
10004 pragma Pack (Octal_Array);
284614f0 10005
dda83cd7
SM
10006 type Octal_Buffer (Size : Positive) is record
10007 Buffer : Octal_Array (1 .. Size);
10008 Length : Integer;
10009 end record;
284614f0
JB
10010
10011 In that case, Buffer is a PAD type whose size is unset and needs
10012 to be computed by fixing the unwrapped type.
10013
21649b50
JB
10014 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10015 ----------------------------------------------------------
10016
10017 Lastly, when should the sub-elements of an entity that remained unfixed
284614f0
JB
10018 thus far, be actually fixed?
10019
10020 The answer is: Only when referencing that element. For instance
10021 when selecting one component of a record, this specific component
10022 should be fixed at that point in time. Or when printing the value
10023 of a record, each component should be fixed before its value gets
10024 printed. Similarly for arrays, the element of the array should be
10025 fixed when printing each element of the array, or when extracting
10026 one element out of that array. On the other hand, fixing should
10027 not be performed on the elements when taking a slice of an array!
10028
31432a67 10029 Note that one of the side effects of miscomputing the offset and
284614f0
JB
10030 size of each field is that we end up also miscomputing the size
10031 of the containing type. This can have adverse results when computing
10032 the value of an entity. GDB fetches the value of an entity based
10033 on the size of its type, and thus a wrong size causes GDB to fetch
10034 the wrong amount of memory. In the case where the computed size is
10035 too small, GDB fetches too little data to print the value of our
31432a67 10036 entity. Results in this case are unpredictable, as we usually read
284614f0
JB
10037 past the buffer containing the data =:-o. */
10038
62d4bd94
TT
10039/* A helper function for TERNOP_IN_RANGE. */
10040
10041static value *
10042eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10043 enum noside noside,
10044 value *arg1, value *arg2, value *arg3)
10045{
62d4bd94
TT
10046 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10047 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10048 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10049 return
10050 value_from_longest (type,
10051 (value_less (arg1, arg3)
10052 || value_equal (arg1, arg3))
10053 && (value_less (arg2, arg1)
10054 || value_equal (arg2, arg1)));
10055}
10056
82390ab8
TT
10057/* A helper function for UNOP_NEG. */
10058
7c15d377 10059value *
82390ab8
TT
10060ada_unop_neg (struct type *expect_type,
10061 struct expression *exp,
10062 enum noside noside, enum exp_opcode op,
10063 struct value *arg1)
10064{
82390ab8
TT
10065 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10066 return value_neg (arg1);
10067}
10068
7efc87ff
TT
10069/* A helper function for UNOP_IN_RANGE. */
10070
95d49dfb 10071value *
7efc87ff
TT
10072ada_unop_in_range (struct type *expect_type,
10073 struct expression *exp,
10074 enum noside noside, enum exp_opcode op,
10075 struct value *arg1, struct type *type)
10076{
7efc87ff
TT
10077 struct value *arg2, *arg3;
10078 switch (type->code ())
10079 {
10080 default:
10081 lim_warning (_("Membership test incompletely implemented; "
10082 "always returns true"));
10083 type = language_bool_type (exp->language_defn, exp->gdbarch);
66cf9350 10084 return value_from_longest (type, 1);
7efc87ff
TT
10085
10086 case TYPE_CODE_RANGE:
10087 arg2 = value_from_longest (type,
10088 type->bounds ()->low.const_val ());
10089 arg3 = value_from_longest (type,
10090 type->bounds ()->high.const_val ());
10091 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10092 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10093 type = language_bool_type (exp->language_defn, exp->gdbarch);
10094 return
10095 value_from_longest (type,
10096 (value_less (arg1, arg3)
10097 || value_equal (arg1, arg3))
10098 && (value_less (arg2, arg1)
10099 || value_equal (arg2, arg1)));
10100 }
10101}
10102
020dbabe
TT
10103/* A helper function for OP_ATR_TAG. */
10104
7c15d377 10105value *
020dbabe
TT
10106ada_atr_tag (struct type *expect_type,
10107 struct expression *exp,
10108 enum noside noside, enum exp_opcode op,
10109 struct value *arg1)
10110{
10111 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10112 return value::zero (ada_tag_type (arg1), not_lval);
020dbabe
TT
10113
10114 return ada_value_tag (arg1);
10115}
10116
68c75735
TT
10117/* A helper function for OP_ATR_SIZE. */
10118
7c15d377 10119value *
68c75735
TT
10120ada_atr_size (struct type *expect_type,
10121 struct expression *exp,
10122 enum noside noside, enum exp_opcode op,
10123 struct value *arg1)
10124{
d0c97917 10125 struct type *type = arg1->type ();
68c75735
TT
10126
10127 /* If the argument is a reference, then dereference its type, since
10128 the user is really asking for the size of the actual object,
10129 not the size of the pointer. */
10130 if (type->code () == TYPE_CODE_REF)
27710edb 10131 type = type->target_type ();
68c75735 10132
0b2b0b82 10133 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10134 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
68c75735
TT
10135 else
10136 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
df86565b 10137 TARGET_CHAR_BIT * type->length ());
68c75735
TT
10138}
10139
d05e24e6
TT
10140/* A helper function for UNOP_ABS. */
10141
7c15d377 10142value *
d05e24e6
TT
10143ada_abs (struct type *expect_type,
10144 struct expression *exp,
10145 enum noside noside, enum exp_opcode op,
10146 struct value *arg1)
10147{
10148 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
ee7bb294 10149 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
d05e24e6
TT
10150 return value_neg (arg1);
10151 else
10152 return arg1;
10153}
10154
faa1dfd7
TT
10155/* A helper function for BINOP_MUL. */
10156
d9e7db06 10157value *
faa1dfd7
TT
10158ada_mult_binop (struct type *expect_type,
10159 struct expression *exp,
10160 enum noside noside, enum exp_opcode op,
10161 struct value *arg1, struct value *arg2)
10162{
10163 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10164 {
10165 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
ee7bb294 10166 return value::zero (arg1->type (), not_lval);
faa1dfd7
TT
10167 }
10168 else
10169 {
10170 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10171 return ada_value_binop (arg1, arg2, op);
10172 }
10173}
10174
214b13ac
TT
10175/* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10176
6e8fb7b7 10177value *
214b13ac
TT
10178ada_equal_binop (struct type *expect_type,
10179 struct expression *exp,
10180 enum noside noside, enum exp_opcode op,
10181 struct value *arg1, struct value *arg2)
10182{
10183 int tem;
10184 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10185 tem = 0;
10186 else
10187 {
10188 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10189 tem = ada_value_equal (arg1, arg2);
10190 }
10191 if (op == BINOP_NOTEQUAL)
10192 tem = !tem;
10193 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
66cf9350 10194 return value_from_longest (type, tem);
214b13ac
TT
10195}
10196
5ce19db8
TT
10197/* A helper function for TERNOP_SLICE. */
10198
1b1ebfab 10199value *
5ce19db8
TT
10200ada_ternop_slice (struct expression *exp,
10201 enum noside noside,
10202 struct value *array, struct value *low_bound_val,
10203 struct value *high_bound_val)
10204{
10205 LONGEST low_bound;
10206 LONGEST high_bound;
10207
10208 low_bound_val = coerce_ref (low_bound_val);
10209 high_bound_val = coerce_ref (high_bound_val);
10210 low_bound = value_as_long (low_bound_val);
10211 high_bound = value_as_long (high_bound_val);
10212
10213 /* If this is a reference to an aligner type, then remove all
10214 the aligners. */
d0c97917
TT
10215 if (array->type ()->code () == TYPE_CODE_REF
10216 && ada_is_aligner_type (array->type ()->target_type ()))
10217 array->type ()->set_target_type
10218 (ada_aligned_type (array->type ()->target_type ()));
5ce19db8 10219
d0c97917 10220 if (ada_is_any_packed_array_type (array->type ()))
5ce19db8
TT
10221 error (_("cannot slice a packed array"));
10222
10223 /* If this is a reference to an array or an array lvalue,
10224 convert to a pointer. */
d0c97917
TT
10225 if (array->type ()->code () == TYPE_CODE_REF
10226 || (array->type ()->code () == TYPE_CODE_ARRAY
736355f2 10227 && array->lval () == lval_memory))
5ce19db8
TT
10228 array = value_addr (array);
10229
10230 if (noside == EVAL_AVOID_SIDE_EFFECTS
10231 && ada_is_array_descriptor_type (ada_check_typedef
d0c97917 10232 (array->type ())))
5ce19db8
TT
10233 return empty_array (ada_type_of_array (array, 0), low_bound,
10234 high_bound);
10235
10236 array = ada_coerce_to_simple_array_ptr (array);
10237
10238 /* If we have more than one level of pointer indirection,
10239 dereference the value until we get only one level. */
d0c97917
TT
10240 while (array->type ()->code () == TYPE_CODE_PTR
10241 && (array->type ()->target_type ()->code ()
5ce19db8
TT
10242 == TYPE_CODE_PTR))
10243 array = value_ind (array);
10244
10245 /* Make sure we really do have an array type before going further,
10246 to avoid a SEGV when trying to get the index type or the target
10247 type later down the road if the debug info generated by
10248 the compiler is incorrect or incomplete. */
d0c97917 10249 if (!ada_is_simple_array_type (array->type ()))
5ce19db8
TT
10250 error (_("cannot take slice of non-array"));
10251
d0c97917 10252 if (ada_check_typedef (array->type ())->code ()
5ce19db8
TT
10253 == TYPE_CODE_PTR)
10254 {
d0c97917 10255 struct type *type0 = ada_check_typedef (array->type ());
5ce19db8
TT
10256
10257 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
27710edb 10258 return empty_array (type0->target_type (), low_bound, high_bound);
5ce19db8
TT
10259 else
10260 {
10261 struct type *arr_type0 =
27710edb 10262 to_fixed_array_type (type0->target_type (), NULL, 1);
5ce19db8
TT
10263
10264 return ada_value_slice_from_ptr (array, arr_type0,
10265 longest_to_int (low_bound),
10266 longest_to_int (high_bound));
10267 }
10268 }
10269 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10270 return array;
10271 else if (high_bound < low_bound)
d0c97917 10272 return empty_array (array->type (), low_bound, high_bound);
5ce19db8
TT
10273 else
10274 return ada_value_slice (array, longest_to_int (low_bound),
10275 longest_to_int (high_bound));
10276}
10277
b467efaa
TT
10278/* A helper function for BINOP_IN_BOUNDS. */
10279
82c3886e 10280value *
b467efaa
TT
10281ada_binop_in_bounds (struct expression *exp, enum noside noside,
10282 struct value *arg1, struct value *arg2, int n)
10283{
10284 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10285 {
10286 struct type *type = language_bool_type (exp->language_defn,
10287 exp->gdbarch);
ee7bb294 10288 return value::zero (type, not_lval);
b467efaa
TT
10289 }
10290
d0c97917 10291 struct type *type = ada_index_type (arg2->type (), n, "range");
b467efaa 10292 if (!type)
d0c97917 10293 type = arg1->type ();
b467efaa
TT
10294
10295 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10296 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10297
10298 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10299 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10300 type = language_bool_type (exp->language_defn, exp->gdbarch);
10301 return value_from_longest (type,
10302 (value_less (arg1, arg3)
10303 || value_equal (arg1, arg3))
10304 && (value_less (arg2, arg1)
10305 || value_equal (arg2, arg1)));
10306}
10307
b84564fc
TT
10308/* A helper function for some attribute operations. */
10309
10310static value *
10311ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10312 struct value *arg1, struct type *type_arg, int tem)
10313{
1e5ae3d1
TT
10314 const char *attr_name = nullptr;
10315 if (op == OP_ATR_FIRST)
10316 attr_name = "first";
10317 else if (op == OP_ATR_LAST)
10318 attr_name = "last";
10319
b84564fc
TT
10320 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10321 {
10322 if (type_arg == NULL)
d0c97917 10323 type_arg = arg1->type ();
b84564fc
TT
10324
10325 if (ada_is_constrained_packed_array_type (type_arg))
10326 type_arg = decode_constrained_packed_array_type (type_arg);
10327
10328 if (!discrete_type_p (type_arg))
10329 {
10330 switch (op)
10331 {
10332 default: /* Should never happen. */
10333 error (_("unexpected attribute encountered"));
10334 case OP_ATR_FIRST:
10335 case OP_ATR_LAST:
10336 type_arg = ada_index_type (type_arg, tem,
1e5ae3d1 10337 attr_name);
b84564fc
TT
10338 break;
10339 case OP_ATR_LENGTH:
10340 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10341 break;
10342 }
10343 }
10344
ee7bb294 10345 return value::zero (type_arg, not_lval);
b84564fc
TT
10346 }
10347 else if (type_arg == NULL)
10348 {
10349 arg1 = ada_coerce_ref (arg1);
10350
d0c97917 10351 if (ada_is_constrained_packed_array_type (arg1->type ()))
b84564fc
TT
10352 arg1 = ada_coerce_to_simple_array (arg1);
10353
10354 struct type *type;
10355 if (op == OP_ATR_LENGTH)
10356 type = builtin_type (exp->gdbarch)->builtin_int;
10357 else
10358 {
d0c97917 10359 type = ada_index_type (arg1->type (), tem,
1e5ae3d1 10360 attr_name);
b84564fc
TT
10361 if (type == NULL)
10362 type = builtin_type (exp->gdbarch)->builtin_int;
10363 }
10364
10365 switch (op)
10366 {
10367 default: /* Should never happen. */
10368 error (_("unexpected attribute encountered"));
10369 case OP_ATR_FIRST:
10370 return value_from_longest
10371 (type, ada_array_bound (arg1, tem, 0));
10372 case OP_ATR_LAST:
10373 return value_from_longest
10374 (type, ada_array_bound (arg1, tem, 1));
10375 case OP_ATR_LENGTH:
10376 return value_from_longest
10377 (type, ada_array_length (arg1, tem));
10378 }
10379 }
10380 else if (discrete_type_p (type_arg))
10381 {
10382 struct type *range_type;
10383 const char *name = ada_type_name (type_arg);
10384
10385 range_type = NULL;
10386 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10387 range_type = to_fixed_range_type (type_arg, NULL);
10388 if (range_type == NULL)
10389 range_type = type_arg;
10390 switch (op)
10391 {
10392 default:
10393 error (_("unexpected attribute encountered"));
10394 case OP_ATR_FIRST:
10395 return value_from_longest
10396 (range_type, ada_discrete_type_low_bound (range_type));
10397 case OP_ATR_LAST:
10398 return value_from_longest
10399 (range_type, ada_discrete_type_high_bound (range_type));
10400 case OP_ATR_LENGTH:
10401 error (_("the 'length attribute applies only to array types"));
10402 }
10403 }
10404 else if (type_arg->code () == TYPE_CODE_FLT)
10405 error (_("unimplemented type attribute"));
10406 else
10407 {
10408 LONGEST low, high;
10409
10410 if (ada_is_constrained_packed_array_type (type_arg))
10411 type_arg = decode_constrained_packed_array_type (type_arg);
10412
10413 struct type *type;
10414 if (op == OP_ATR_LENGTH)
10415 type = builtin_type (exp->gdbarch)->builtin_int;
10416 else
10417 {
1e5ae3d1 10418 type = ada_index_type (type_arg, tem, attr_name);
b84564fc
TT
10419 if (type == NULL)
10420 type = builtin_type (exp->gdbarch)->builtin_int;
10421 }
10422
10423 switch (op)
10424 {
10425 default:
10426 error (_("unexpected attribute encountered"));
10427 case OP_ATR_FIRST:
10428 low = ada_array_bound_from_type (type_arg, tem, 0);
10429 return value_from_longest (type, low);
10430 case OP_ATR_LAST:
10431 high = ada_array_bound_from_type (type_arg, tem, 1);
10432 return value_from_longest (type, high);
10433 case OP_ATR_LENGTH:
10434 low = ada_array_bound_from_type (type_arg, tem, 0);
10435 high = ada_array_bound_from_type (type_arg, tem, 1);
10436 return value_from_longest (type, high - low + 1);
10437 }
10438 }
10439}
10440
38dc70cf
TT
10441/* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10442
6ad3b8bf 10443struct value *
38dc70cf
TT
10444ada_binop_minmax (struct type *expect_type,
10445 struct expression *exp,
10446 enum noside noside, enum exp_opcode op,
10447 struct value *arg1, struct value *arg2)
10448{
10449 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10450 return value::zero (arg1->type (), not_lval);
38dc70cf
TT
10451 else
10452 {
10453 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
0922dc84 10454 return value_binop (arg1, arg2, op);
38dc70cf
TT
10455 }
10456}
10457
dd5fd283
TT
10458/* A helper function for BINOP_EXP. */
10459
065ec826 10460struct value *
dd5fd283
TT
10461ada_binop_exp (struct type *expect_type,
10462 struct expression *exp,
10463 enum noside noside, enum exp_opcode op,
10464 struct value *arg1, struct value *arg2)
10465{
10466 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10467 return value::zero (arg1->type (), not_lval);
dd5fd283
TT
10468 else
10469 {
10470 /* For integer exponentiation operations,
10471 only promote the first argument. */
d0c97917 10472 if (is_integral_type (arg2->type ()))
dd5fd283
TT
10473 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10474 else
10475 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10476
10477 return value_binop (arg1, arg2, op);
10478 }
10479}
10480
03070ee9
TT
10481namespace expr
10482{
10483
8b12db26
TT
10484/* See ada-exp.h. */
10485
10486operation_up
10487ada_resolvable::replace (operation_up &&owner,
10488 struct expression *exp,
10489 bool deprocedure_p,
10490 bool parse_completion,
10491 innermost_block_tracker *tracker,
10492 struct type *context_type)
10493{
10494 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10495 return (make_operation<ada_funcall_operation>
10496 (std::move (owner),
10497 std::vector<operation_up> ()));
10498 return std::move (owner);
10499}
10500
c9f66f00 10501/* Convert the character literal whose value would be VAL to the
03adb248
TT
10502 appropriate value of type TYPE, if there is a translation.
10503 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10504 the literal 'A' (VAL == 65), returns 0. */
10505
10506static LONGEST
10507convert_char_literal (struct type *type, LONGEST val)
10508{
c9f66f00 10509 char name[12];
03adb248
TT
10510 int f;
10511
10512 if (type == NULL)
10513 return val;
10514 type = check_typedef (type);
10515 if (type->code () != TYPE_CODE_ENUM)
10516 return val;
10517
10518 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10519 xsnprintf (name, sizeof (name), "Q%c", (int) val);
c9f66f00
TT
10520 else if (val >= 0 && val < 256)
10521 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10522 else if (val >= 0 && val < 0x10000)
10523 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
03adb248 10524 else
c9f66f00 10525 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
03adb248
TT
10526 size_t len = strlen (name);
10527 for (f = 0; f < type->num_fields (); f += 1)
10528 {
10529 /* Check the suffix because an enum constant in a package will
10530 have a name like "pkg__QUxx". This is safe enough because we
10531 already have the correct type, and because mangling means
10532 there can't be clashes. */
33d16dd9 10533 const char *ename = type->field (f).name ();
03adb248
TT
10534 size_t elen = strlen (ename);
10535
10536 if (elen >= len && strcmp (name, ename + elen - len) == 0)
970db518 10537 return type->field (f).loc_enumval ();
03adb248
TT
10538 }
10539 return val;
10540}
10541
b1b9c411
TT
10542value *
10543ada_char_operation::evaluate (struct type *expect_type,
10544 struct expression *exp,
10545 enum noside noside)
10546{
10547 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10548 if (expect_type != nullptr)
10549 result = ada_value_cast (expect_type, result);
10550 return result;
10551}
10552
03adb248
TT
10553/* See ada-exp.h. */
10554
10555operation_up
10556ada_char_operation::replace (operation_up &&owner,
10557 struct expression *exp,
10558 bool deprocedure_p,
10559 bool parse_completion,
10560 innermost_block_tracker *tracker,
10561 struct type *context_type)
10562{
10563 operation_up result = std::move (owner);
10564
10565 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10566 {
5309ce2f 10567 LONGEST val = as_longest ();
03adb248
TT
10568 gdb_assert (result.get () == this);
10569 std::get<0> (m_storage) = context_type;
5309ce2f 10570 std::get<1> (m_storage) = convert_char_literal (context_type, val);
03adb248
TT
10571 }
10572
b1b9c411 10573 return result;
03adb248
TT
10574}
10575
03070ee9
TT
10576value *
10577ada_wrapped_operation::evaluate (struct type *expect_type,
10578 struct expression *exp,
10579 enum noside noside)
10580{
10581 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10582 if (noside == EVAL_NORMAL)
10583 result = unwrap_value (result);
10584
10585 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10586 then we need to perform the conversion manually, because
10587 evaluate_subexp_standard doesn't do it. This conversion is
10588 necessary in Ada because the different kinds of float/fixed
10589 types in Ada have different representations.
10590
10591 Similarly, we need to perform the conversion from OP_LONG
10592 ourselves. */
10593 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10594 result = ada_value_cast (expect_type, result);
10595
10596 return result;
10597}
10598
013a623f
TT
10599void
10600ada_wrapped_operation::do_generate_ax (struct expression *exp,
10601 struct agent_expr *ax,
10602 struct axs_value *value,
10603 struct type *cast_type)
10604{
10605 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10606
10607 struct type *type = value->type;
10608 if (ada_is_aligner_type (type))
10609 error (_("Aligner types cannot be handled in agent expressions"));
10610 else if (find_base_type (type) != nullptr)
10611 error (_("Dynamic types cannot be handled in agent expressions"));
10612}
10613
42fecb61
TT
10614value *
10615ada_string_operation::evaluate (struct type *expect_type,
10616 struct expression *exp,
10617 enum noside noside)
10618{
fc18a21b
TT
10619 struct type *char_type;
10620 if (expect_type != nullptr && ada_is_string_type (expect_type))
10621 char_type = ada_array_element_type (expect_type, 1);
10622 else
10623 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10624
10625 const std::string &str = std::get<0> (m_storage);
10626 const char *encoding;
df86565b 10627 switch (char_type->length ())
fc18a21b
TT
10628 {
10629 case 1:
10630 {
10631 /* Simply copy over the data -- this isn't perhaps strictly
10632 correct according to the encodings, but it is gdb's
10633 historical behavior. */
10634 struct type *stringtype
10635 = lookup_array_range_type (char_type, 1, str.length ());
317c3ed9 10636 struct value *val = value::allocate (stringtype);
bbe912ba 10637 memcpy (val->contents_raw ().data (), str.c_str (),
fc18a21b
TT
10638 str.length ());
10639 return val;
10640 }
10641
10642 case 2:
10643 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10644 encoding = "UTF-16BE";
10645 else
10646 encoding = "UTF-16LE";
10647 break;
10648
10649 case 4:
10650 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10651 encoding = "UTF-32BE";
10652 else
10653 encoding = "UTF-32LE";
10654 break;
10655
10656 default:
10657 error (_("unexpected character type size %s"),
df86565b 10658 pulongest (char_type->length ()));
fc18a21b
TT
10659 }
10660
10661 auto_obstack converted;
10662 convert_between_encodings (host_charset (), encoding,
10663 (const gdb_byte *) str.c_str (),
10664 str.length (), 1,
10665 &converted, translit_none);
10666
10667 struct type *stringtype
10668 = lookup_array_range_type (char_type, 1,
10669 obstack_object_size (&converted)
df86565b 10670 / char_type->length ());
317c3ed9 10671 struct value *val = value::allocate (stringtype);
bbe912ba 10672 memcpy (val->contents_raw ().data (),
fc18a21b
TT
10673 obstack_base (&converted),
10674 obstack_object_size (&converted));
10675 return val;
42fecb61
TT
10676}
10677
b1b9c411
TT
10678value *
10679ada_concat_operation::evaluate (struct type *expect_type,
10680 struct expression *exp,
10681 enum noside noside)
10682{
10683 /* If one side is a literal, evaluate the other side first so that
10684 the expected type can be set properly. */
10685 const operation_up &lhs_expr = std::get<0> (m_storage);
10686 const operation_up &rhs_expr = std::get<1> (m_storage);
10687
10688 value *lhs, *rhs;
10689 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10690 {
10691 rhs = rhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10692 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
b1b9c411
TT
10693 }
10694 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10695 {
10696 rhs = rhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10697 struct type *rhs_type = check_typedef (rhs->type ());
b1b9c411
TT
10698 struct type *elt_type = nullptr;
10699 if (rhs_type->code () == TYPE_CODE_ARRAY)
27710edb 10700 elt_type = rhs_type->target_type ();
b1b9c411
TT
10701 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10702 }
10703 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10704 {
10705 lhs = lhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10706 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
b1b9c411
TT
10707 }
10708 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10709 {
10710 lhs = lhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10711 struct type *lhs_type = check_typedef (lhs->type ());
b1b9c411
TT
10712 struct type *elt_type = nullptr;
10713 if (lhs_type->code () == TYPE_CODE_ARRAY)
27710edb 10714 elt_type = lhs_type->target_type ();
b1b9c411
TT
10715 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10716 }
10717 else
10718 return concat_operation::evaluate (expect_type, exp, noside);
10719
10720 return value_concat (lhs, rhs);
10721}
10722
cc6bd32e
TT
10723value *
10724ada_qual_operation::evaluate (struct type *expect_type,
10725 struct expression *exp,
10726 enum noside noside)
10727{
10728 struct type *type = std::get<1> (m_storage);
10729 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10730}
10731
fc715eb2
TT
10732value *
10733ada_ternop_range_operation::evaluate (struct type *expect_type,
10734 struct expression *exp,
10735 enum noside noside)
10736{
10737 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10738 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10739 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10740 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10741}
10742
73796c73
TT
10743value *
10744ada_binop_addsub_operation::evaluate (struct type *expect_type,
10745 struct expression *exp,
10746 enum noside noside)
10747{
10748 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10749 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10750
5bd5fecd 10751 auto do_op = [this] (LONGEST x, LONGEST y)
73796c73
TT
10752 {
10753 if (std::get<0> (m_storage) == BINOP_ADD)
10754 return x + y;
10755 return x - y;
10756 };
10757
d0c97917 10758 if (arg1->type ()->code () == TYPE_CODE_PTR)
73796c73 10759 return (value_from_longest
d0c97917 10760 (arg1->type (),
73796c73 10761 do_op (value_as_long (arg1), value_as_long (arg2))));
d0c97917 10762 if (arg2->type ()->code () == TYPE_CODE_PTR)
73796c73 10763 return (value_from_longest
d0c97917 10764 (arg2->type (),
73796c73
TT
10765 do_op (value_as_long (arg1), value_as_long (arg2))));
10766 /* Preserve the original type for use by the range case below.
10767 We cannot cast the result to a reference type, so if ARG1 is
10768 a reference type, find its underlying type. */
d0c97917 10769 struct type *type = arg1->type ();
73796c73 10770 while (type->code () == TYPE_CODE_REF)
27710edb 10771 type = type->target_type ();
73796c73
TT
10772 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10773 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10774 /* We need to special-case the result with a range.
10775 This is done for the benefit of "ptype". gdb's Ada support
10776 historically used the LHS to set the result type here, so
10777 preserve this behavior. */
10778 if (type->code () == TYPE_CODE_RANGE)
10779 arg1 = value_cast (type, arg1);
10780 return arg1;
10781}
10782
60fa02ca
TT
10783value *
10784ada_unop_atr_operation::evaluate (struct type *expect_type,
10785 struct expression *exp,
10786 enum noside noside)
10787{
10788 struct type *type_arg = nullptr;
10789 value *val = nullptr;
10790
10791 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10792 {
10793 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10794 EVAL_AVOID_SIDE_EFFECTS);
d0c97917 10795 type_arg = tem->type ();
60fa02ca
TT
10796 }
10797 else
10798 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10799
10800 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10801 val, type_arg, std::get<2> (m_storage));
10802}
10803
3f4a0053
TT
10804value *
10805ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10806 struct expression *exp,
10807 enum noside noside)
10808{
10809 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10810 return value::zero (expect_type, not_lval);
3f4a0053 10811
9c79936b
TT
10812 const bound_minimal_symbol &b = std::get<0> (m_storage);
10813 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
3f4a0053
TT
10814
10815 val = ada_value_cast (expect_type, val);
10816
10817 /* Follow the Ada language semantics that do not allow taking
10818 an address of the result of a cast (view conversion in Ada). */
736355f2 10819 if (val->lval () == lval_memory)
3f4a0053 10820 {
3ee3b270 10821 if (val->lazy ())
78259c36 10822 val->fetch_lazy ();
6f9c9d71 10823 val->set_lval (not_lval);
3f4a0053
TT
10824 }
10825 return val;
10826}
10827
99a3b1e7
TT
10828value *
10829ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10830 struct expression *exp,
10831 enum noside noside)
10832{
10833 value *val = evaluate_var_value (noside,
9e5e03df
TT
10834 std::get<0> (m_storage).block,
10835 std::get<0> (m_storage).symbol);
99a3b1e7
TT
10836
10837 val = ada_value_cast (expect_type, val);
10838
10839 /* Follow the Ada language semantics that do not allow taking
10840 an address of the result of a cast (view conversion in Ada). */
736355f2 10841 if (val->lval () == lval_memory)
99a3b1e7 10842 {
3ee3b270 10843 if (val->lazy ())
78259c36 10844 val->fetch_lazy ();
6f9c9d71 10845 val->set_lval (not_lval);
99a3b1e7
TT
10846 }
10847 return val;
10848}
10849
10850value *
10851ada_var_value_operation::evaluate (struct type *expect_type,
10852 struct expression *exp,
10853 enum noside noside)
10854{
9e5e03df 10855 symbol *sym = std::get<0> (m_storage).symbol;
99a3b1e7 10856
6c9c307c 10857 if (sym->domain () == UNDEF_DOMAIN)
99a3b1e7
TT
10858 /* Only encountered when an unresolved symbol occurs in a
10859 context other than a function call, in which case, it is
10860 invalid. */
10861 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10862 sym->print_name ());
10863
10864 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10865 {
5f9c5a63 10866 struct type *type = static_unwrap_type (sym->type ());
99a3b1e7
TT
10867 /* Check to see if this is a tagged type. We also need to handle
10868 the case where the type is a reference to a tagged type, but
10869 we have to be careful to exclude pointers to tagged types.
10870 The latter should be shown as usual (as a pointer), whereas
10871 a reference should mostly be transparent to the user. */
10872 if (ada_is_tagged_type (type, 0)
10873 || (type->code () == TYPE_CODE_REF
27710edb 10874 && ada_is_tagged_type (type->target_type (), 0)))
99a3b1e7
TT
10875 {
10876 /* Tagged types are a little special in the fact that the real
10877 type is dynamic and can only be determined by inspecting the
10878 object's tag. This means that we need to get the object's
10879 value first (EVAL_NORMAL) and then extract the actual object
10880 type from its tag.
10881
10882 Note that we cannot skip the final step where we extract
10883 the object type from its tag, because the EVAL_NORMAL phase
10884 results in dynamic components being resolved into fixed ones.
10885 This can cause problems when trying to print the type
10886 description of tagged types whose parent has a dynamic size:
10887 We use the type name of the "_parent" component in order
10888 to print the name of the ancestor type in the type description.
10889 If that component had a dynamic size, the resolution into
10890 a fixed type would result in the loss of that type name,
10891 thus preventing us from printing the name of the ancestor
10892 type in the type description. */
9863c3b5 10893 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
99a3b1e7
TT
10894
10895 if (type->code () != TYPE_CODE_REF)
10896 {
10897 struct type *actual_type;
10898
10899 actual_type = type_from_tag (ada_value_tag (arg1));
10900 if (actual_type == NULL)
10901 /* If, for some reason, we were unable to determine
10902 the actual type from the tag, then use the static
10903 approximation that we just computed as a fallback.
10904 This can happen if the debugging information is
10905 incomplete, for instance. */
10906 actual_type = type;
ee7bb294 10907 return value::zero (actual_type, not_lval);
99a3b1e7
TT
10908 }
10909 else
10910 {
10911 /* In the case of a ref, ada_coerce_ref takes care
10912 of determining the actual type. But the evaluation
10913 should return a ref as it should be valid to ask
10914 for its address; so rebuild a ref after coerce. */
10915 arg1 = ada_coerce_ref (arg1);
10916 return value_ref (arg1, TYPE_CODE_REF);
10917 }
10918 }
10919
10920 /* Records and unions for which GNAT encodings have been
10921 generated need to be statically fixed as well.
10922 Otherwise, non-static fixing produces a type where
10923 all dynamic properties are removed, which prevents "ptype"
10924 from being able to completely describe the type.
10925 For instance, a case statement in a variant record would be
10926 replaced by the relevant components based on the actual
10927 value of the discriminants. */
10928 if ((type->code () == TYPE_CODE_STRUCT
10929 && dynamic_template_type (type) != NULL)
10930 || (type->code () == TYPE_CODE_UNION
10931 && ada_find_parallel_type (type, "___XVU") != NULL))
ee7bb294 10932 return value::zero (to_static_fixed_type (type), not_lval);
99a3b1e7
TT
10933 }
10934
10935 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10936 return ada_to_fixed_value (arg1);
10937}
10938
d8a4ed8a
TT
10939bool
10940ada_var_value_operation::resolve (struct expression *exp,
10941 bool deprocedure_p,
10942 bool parse_completion,
10943 innermost_block_tracker *tracker,
10944 struct type *context_type)
10945{
9e5e03df 10946 symbol *sym = std::get<0> (m_storage).symbol;
6c9c307c 10947 if (sym->domain () == UNDEF_DOMAIN)
d8a4ed8a
TT
10948 {
10949 block_symbol resolved
9e5e03df 10950 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
d8a4ed8a
TT
10951 context_type, parse_completion,
10952 deprocedure_p, tracker);
9e5e03df 10953 std::get<0> (m_storage) = resolved;
d8a4ed8a
TT
10954 }
10955
10956 if (deprocedure_p
5f9c5a63 10957 && (std::get<0> (m_storage).symbol->type ()->code ()
9e5e03df 10958 == TYPE_CODE_FUNC))
d8a4ed8a
TT
10959 return true;
10960
10961 return false;
10962}
10963
013a623f
TT
10964void
10965ada_var_value_operation::do_generate_ax (struct expression *exp,
10966 struct agent_expr *ax,
10967 struct axs_value *value,
10968 struct type *cast_type)
10969{
10970 symbol *sym = std::get<0> (m_storage).symbol;
10971
10972 if (sym->domain () == UNDEF_DOMAIN)
10973 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10974 sym->print_name ());
10975
10976 struct type *type = static_unwrap_type (sym->type ());
10977 if (ada_is_tagged_type (type, 0)
10978 || (type->code () == TYPE_CODE_REF
10979 && ada_is_tagged_type (type->target_type (), 0)))
10980 error (_("Tagged types cannot be handled in agent expressions"));
10981
10982 if ((type->code () == TYPE_CODE_STRUCT
10983 && dynamic_template_type (type) != NULL)
10984 || (type->code () == TYPE_CODE_UNION
10985 && ada_find_parallel_type (type, "___XVU") != NULL))
10986 error (_("Dynamic types cannot be handled in agent expressions"));
10987
10988 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10989}
10990
e8c33fa1
TT
10991value *
10992ada_unop_ind_operation::evaluate (struct type *expect_type,
10993 struct expression *exp,
10994 enum noside noside)
10995{
10996 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10997
d0c97917 10998 struct type *type = ada_check_typedef (arg1->type ());
e8c33fa1
TT
10999 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11000 {
11001 if (ada_is_array_descriptor_type (type))
11002 /* GDB allows dereferencing GNAT array descriptors. */
11003 {
11004 struct type *arrType = ada_type_of_array (arg1, 0);
11005
11006 if (arrType == NULL)
11007 error (_("Attempt to dereference null array pointer."));
11008 return value_at_lazy (arrType, 0);
11009 }
11010 else if (type->code () == TYPE_CODE_PTR
11011 || type->code () == TYPE_CODE_REF
11012 /* In C you can dereference an array to get the 1st elt. */
11013 || type->code () == TYPE_CODE_ARRAY)
11014 {
11015 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11016 only be determined by inspecting the object's tag.
11017 This means that we need to evaluate completely the
11018 expression in order to get its type. */
11019
11020 if ((type->code () == TYPE_CODE_REF
11021 || type->code () == TYPE_CODE_PTR)
27710edb 11022 && ada_is_tagged_type (type->target_type (), 0))
e8c33fa1
TT
11023 {
11024 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11025 EVAL_NORMAL);
d0c97917 11026 type = ada_value_ind (arg1)->type ();
e8c33fa1
TT
11027 }
11028 else
11029 {
11030 type = to_static_fixed_type
11031 (ada_aligned_type
27710edb 11032 (ada_check_typedef (type->target_type ())));
e8c33fa1 11033 }
ee7bb294 11034 return value::zero (type, lval_memory);
e8c33fa1
TT
11035 }
11036 else if (type->code () == TYPE_CODE_INT)
11037 {
11038 /* GDB allows dereferencing an int. */
11039 if (expect_type == NULL)
ee7bb294 11040 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
e8c33fa1
TT
11041 lval_memory);
11042 else
11043 {
11044 expect_type =
11045 to_static_fixed_type (ada_aligned_type (expect_type));
ee7bb294 11046 return value::zero (expect_type, lval_memory);
e8c33fa1
TT
11047 }
11048 }
11049 else
11050 error (_("Attempt to take contents of a non-pointer value."));
11051 }
11052 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
d0c97917 11053 type = ada_check_typedef (arg1->type ());
e8c33fa1
TT
11054
11055 if (type->code () == TYPE_CODE_INT)
11056 /* GDB allows dereferencing an int. If we were given
11057 the expect_type, then use that as the target type.
11058 Otherwise, assume that the target type is an int. */
11059 {
11060 if (expect_type != NULL)
11061 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11062 arg1));
11063 else
11064 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11065 (CORE_ADDR) value_as_address (arg1));
11066 }
11067
11068 if (ada_is_array_descriptor_type (type))
11069 /* GDB allows dereferencing GNAT array descriptors. */
11070 return ada_coerce_to_simple_array (arg1);
11071 else
11072 return ada_value_ind (arg1);
11073}
11074
ebc06ad8
TT
11075value *
11076ada_structop_operation::evaluate (struct type *expect_type,
11077 struct expression *exp,
11078 enum noside noside)
11079{
11080 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11081 const char *str = std::get<1> (m_storage).c_str ();
11082 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11083 {
11084 struct type *type;
d0c97917 11085 struct type *type1 = arg1->type ();
ebc06ad8
TT
11086
11087 if (ada_is_tagged_type (type1, 1))
11088 {
11089 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11090
11091 /* If the field is not found, check if it exists in the
11092 extension of this object's type. This means that we
11093 need to evaluate completely the expression. */
11094
11095 if (type == NULL)
11096 {
11097 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11098 EVAL_NORMAL);
11099 arg1 = ada_value_struct_elt (arg1, str, 0);
11100 arg1 = unwrap_value (arg1);
d0c97917 11101 type = ada_to_fixed_value (arg1)->type ();
ebc06ad8
TT
11102 }
11103 }
11104 else
11105 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11106
ee7bb294 11107 return value::zero (ada_aligned_type (type), lval_memory);
ebc06ad8
TT
11108 }
11109 else
11110 {
11111 arg1 = ada_value_struct_elt (arg1, str, 0);
11112 arg1 = unwrap_value (arg1);
11113 return ada_to_fixed_value (arg1);
11114 }
11115}
11116
efe3af2f
TT
11117value *
11118ada_funcall_operation::evaluate (struct type *expect_type,
11119 struct expression *exp,
11120 enum noside noside)
11121{
11122 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11123 int nargs = args_up.size ();
11124 std::vector<value *> argvec (nargs);
11125 operation_up &callee_op = std::get<0> (m_storage);
11126
11127 ada_var_value_operation *avv
11128 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11129 if (avv != nullptr
6c9c307c 11130 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
efe3af2f
TT
11131 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11132 avv->get_symbol ()->print_name ());
11133
11134 value *callee = callee_op->evaluate (nullptr, exp, noside);
11135 for (int i = 0; i < args_up.size (); ++i)
11136 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11137
11138 if (ada_is_constrained_packed_array_type
d0c97917 11139 (desc_base_type (callee->type ())))
efe3af2f 11140 callee = ada_coerce_to_simple_array (callee);
d0c97917 11141 else if (callee->type ()->code () == TYPE_CODE_ARRAY
3757d2d4 11142 && callee->type ()->field (0).bitsize () != 0)
efe3af2f
TT
11143 /* This is a packed array that has already been fixed, and
11144 therefore already coerced to a simple array. Nothing further
11145 to do. */
11146 ;
d0c97917 11147 else if (callee->type ()->code () == TYPE_CODE_REF)
efe3af2f
TT
11148 {
11149 /* Make sure we dereference references so that all the code below
11150 feels like it's really handling the referenced value. Wrapping
11151 types (for alignment) may be there, so make sure we strip them as
11152 well. */
11153 callee = ada_to_fixed_value (coerce_ref (callee));
11154 }
d0c97917 11155 else if (callee->type ()->code () == TYPE_CODE_ARRAY
736355f2 11156 && callee->lval () == lval_memory)
efe3af2f
TT
11157 callee = value_addr (callee);
11158
d0c97917 11159 struct type *type = ada_check_typedef (callee->type ());
efe3af2f
TT
11160
11161 /* Ada allows us to implicitly dereference arrays when subscripting
11162 them. So, if this is an array typedef (encoding use for array
11163 access types encoded as fat pointers), strip it now. */
11164 if (type->code () == TYPE_CODE_TYPEDEF)
11165 type = ada_typedef_target_type (type);
11166
11167 if (type->code () == TYPE_CODE_PTR)
11168 {
27710edb 11169 switch (ada_check_typedef (type->target_type ())->code ())
efe3af2f
TT
11170 {
11171 case TYPE_CODE_FUNC:
27710edb 11172 type = ada_check_typedef (type->target_type ());
efe3af2f
TT
11173 break;
11174 case TYPE_CODE_ARRAY:
11175 break;
11176 case TYPE_CODE_STRUCT:
11177 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11178 callee = ada_value_ind (callee);
27710edb 11179 type = ada_check_typedef (type->target_type ());
efe3af2f
TT
11180 break;
11181 default:
11182 error (_("cannot subscript or call something of type `%s'"),
d0c97917 11183 ada_type_name (callee->type ()));
efe3af2f
TT
11184 break;
11185 }
11186 }
11187
11188 switch (type->code ())
11189 {
11190 case TYPE_CODE_FUNC:
11191 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11192 {
27710edb 11193 if (type->target_type () == NULL)
efe3af2f 11194 error_call_unknown_return_type (NULL);
317c3ed9 11195 return value::allocate (type->target_type ());
efe3af2f 11196 }
61f9fb1e 11197 return call_function_by_hand (callee, expect_type, argvec);
efe3af2f
TT
11198 case TYPE_CODE_INTERNAL_FUNCTION:
11199 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11200 /* We don't know anything about what the internal
11201 function might return, but we have to return
11202 something. */
ee7bb294 11203 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
efe3af2f
TT
11204 not_lval);
11205 else
11206 return call_internal_function (exp->gdbarch, exp->language_defn,
11207 callee, nargs,
11208 argvec.data ());
11209
d3c54a1c
TT
11210 case TYPE_CODE_STRUCT:
11211 {
11212 int arity;
4c4b4cd2 11213
d3c54a1c
TT
11214 arity = ada_array_arity (type);
11215 type = ada_array_element_type (type, nargs);
11216 if (type == NULL)
11217 error (_("cannot subscript or call a record"));
11218 if (arity != nargs)
11219 error (_("wrong number of subscripts; expecting %d"), arity);
11220 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 11221 return value::zero (ada_aligned_type (type), lval_memory);
d3c54a1c
TT
11222 return
11223 unwrap_value (ada_value_subscript
11224 (callee, nargs, argvec.data ()));
11225 }
11226 case TYPE_CODE_ARRAY:
14f9c5c9 11227 if (noside == EVAL_AVOID_SIDE_EFFECTS)
dda83cd7 11228 {
d3c54a1c
TT
11229 type = ada_array_element_type (type, nargs);
11230 if (type == NULL)
11231 error (_("element type of array unknown"));
dda83cd7 11232 else
ee7bb294 11233 return value::zero (ada_aligned_type (type), lval_memory);
dda83cd7 11234 }
d3c54a1c
TT
11235 return
11236 unwrap_value (ada_value_subscript
11237 (ada_coerce_to_simple_array (callee),
11238 nargs, argvec.data ()));
11239 case TYPE_CODE_PTR: /* Pointer to array */
11240 if (noside == EVAL_AVOID_SIDE_EFFECTS)
dda83cd7 11241 {
27710edb 11242 type = to_fixed_array_type (type->target_type (), NULL, 1);
d3c54a1c
TT
11243 type = ada_array_element_type (type, nargs);
11244 if (type == NULL)
11245 error (_("element type of array unknown"));
96967637 11246 else
ee7bb294 11247 return value::zero (ada_aligned_type (type), lval_memory);
dda83cd7 11248 }
d3c54a1c
TT
11249 return
11250 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11251 argvec.data ()));
6b0d7253 11252
d3c54a1c
TT
11253 default:
11254 error (_("Attempt to index or call something other than an "
11255 "array or function"));
11256 }
11257}
5b4ee69b 11258
d3c54a1c
TT
11259bool
11260ada_funcall_operation::resolve (struct expression *exp,
11261 bool deprocedure_p,
11262 bool parse_completion,
11263 innermost_block_tracker *tracker,
11264 struct type *context_type)
11265{
11266 operation_up &callee_op = std::get<0> (m_storage);
5ec18f2b 11267
d3c54a1c
TT
11268 ada_var_value_operation *avv
11269 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11270 if (avv == nullptr)
11271 return false;
5ec18f2b 11272
d3c54a1c 11273 symbol *sym = avv->get_symbol ();
6c9c307c 11274 if (sym->domain () != UNDEF_DOMAIN)
d3c54a1c 11275 return false;
dda83cd7 11276
d3c54a1c
TT
11277 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11278 int nargs = args_up.size ();
11279 std::vector<value *> argvec (nargs);
284614f0 11280
d3c54a1c
TT
11281 for (int i = 0; i < args_up.size (); ++i)
11282 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
52ce6436 11283
d3c54a1c
TT
11284 const block *block = avv->get_block ();
11285 block_symbol resolved
11286 = ada_resolve_funcall (sym, block,
11287 context_type, parse_completion,
11288 nargs, argvec.data (),
11289 tracker);
11290
11291 std::get<0> (m_storage)
9e5e03df 11292 = make_operation<ada_var_value_operation> (resolved);
d3c54a1c
TT
11293 return false;
11294}
11295
11296bool
11297ada_ternop_slice_operation::resolve (struct expression *exp,
11298 bool deprocedure_p,
11299 bool parse_completion,
11300 innermost_block_tracker *tracker,
11301 struct type *context_type)
11302{
11303 /* Historically this check was done during resolution, so we
11304 continue that here. */
11305 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11306 EVAL_AVOID_SIDE_EFFECTS);
d0c97917 11307 if (ada_is_any_packed_array_type (v->type ()))
d3c54a1c
TT
11308 error (_("cannot slice a packed array"));
11309 return false;
11310}
14f9c5c9 11311
14f9c5c9 11312}
d3c54a1c 11313
14f9c5c9 11314\f
d2e4a39e 11315
4c4b4cd2
PH
11316/* Return non-zero iff TYPE represents a System.Address type. */
11317
11318int
11319ada_is_system_address_type (struct type *type)
11320{
7d93a1e0 11321 return (type->name () && strcmp (type->name (), "system__address") == 0);
4c4b4cd2
PH
11322}
11323
14f9c5c9 11324\f
d2e4a39e 11325
dda83cd7 11326 /* Range types */
14f9c5c9
AS
11327
11328/* Scan STR beginning at position K for a discriminant name, and
11329 return the value of that discriminant field of DVAL in *PX. If
11330 PNEW_K is not null, put the position of the character beyond the
11331 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
4c4b4cd2 11332 not alter *PX and *PNEW_K if unsuccessful. */
14f9c5c9
AS
11333
11334static int
108d56a4 11335scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
dda83cd7 11336 int *pnew_k)
14f9c5c9 11337{
5f9febe0 11338 static std::string storage;
5da1a4d3 11339 const char *pstart, *pend, *bound;
d2e4a39e 11340 struct value *bound_val;
14f9c5c9
AS
11341
11342 if (dval == NULL || str == NULL || str[k] == '\0')
11343 return 0;
11344
5da1a4d3
SM
11345 pstart = str + k;
11346 pend = strstr (pstart, "__");
14f9c5c9
AS
11347 if (pend == NULL)
11348 {
5da1a4d3 11349 bound = pstart;
14f9c5c9
AS
11350 k += strlen (bound);
11351 }
d2e4a39e 11352 else
14f9c5c9 11353 {
5da1a4d3
SM
11354 int len = pend - pstart;
11355
11356 /* Strip __ and beyond. */
5f9febe0
TT
11357 storage = std::string (pstart, len);
11358 bound = storage.c_str ();
d2e4a39e 11359 k = pend - str;
14f9c5c9 11360 }
d2e4a39e 11361
d0c97917 11362 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
14f9c5c9
AS
11363 if (bound_val == NULL)
11364 return 0;
11365
11366 *px = value_as_long (bound_val);
11367 if (pnew_k != NULL)
11368 *pnew_k = k;
11369 return 1;
11370}
11371
25a1127b
TT
11372/* Value of variable named NAME. Only exact matches are considered.
11373 If no such variable found, then if ERR_MSG is null, returns 0, and
4c4b4cd2
PH
11374 otherwise causes an error with message ERR_MSG. */
11375
d2e4a39e 11376static struct value *
edb0c9cb 11377get_var_value (const char *name, const char *err_msg)
14f9c5c9 11378{
25a1127b
TT
11379 std::string quoted_name = add_angle_brackets (name);
11380
11381 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
14f9c5c9 11382
d1183b06
TT
11383 std::vector<struct block_symbol> syms
11384 = ada_lookup_symbol_list_worker (lookup_name,
11385 get_selected_block (0),
11386 VAR_DOMAIN, 1);
14f9c5c9 11387
d1183b06 11388 if (syms.size () != 1)
14f9c5c9
AS
11389 {
11390 if (err_msg == NULL)
dda83cd7 11391 return 0;
14f9c5c9 11392 else
dda83cd7 11393 error (("%s"), err_msg);
14f9c5c9
AS
11394 }
11395
54d343a2 11396 return value_of_variable (syms[0].symbol, syms[0].block);
14f9c5c9 11397}
d2e4a39e 11398
edb0c9cb
PA
11399/* Value of integer variable named NAME in the current environment.
11400 If no such variable is found, returns false. Otherwise, sets VALUE
11401 to the variable's value and returns true. */
4c4b4cd2 11402
edb0c9cb
PA
11403bool
11404get_int_var_value (const char *name, LONGEST &value)
14f9c5c9 11405{
4c4b4cd2 11406 struct value *var_val = get_var_value (name, 0);
d2e4a39e 11407
14f9c5c9 11408 if (var_val == 0)
edb0c9cb
PA
11409 return false;
11410
11411 value = value_as_long (var_val);
11412 return true;
14f9c5c9 11413}
d2e4a39e 11414
14f9c5c9
AS
11415
11416/* Return a range type whose base type is that of the range type named
11417 NAME in the current environment, and whose bounds are calculated
4c4b4cd2 11418 from NAME according to the GNAT range encoding conventions.
1ce677a4
UW
11419 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11420 corresponding range type from debug information; fall back to using it
11421 if symbol lookup fails. If a new type must be created, allocate it
11422 like ORIG_TYPE was. The bounds information, in general, is encoded
11423 in NAME, the base type given in the named range type. */
14f9c5c9 11424
d2e4a39e 11425static struct type *
28c85d6c 11426to_fixed_range_type (struct type *raw_type, struct value *dval)
14f9c5c9 11427{
0d5cff50 11428 const char *name;
14f9c5c9 11429 struct type *base_type;
108d56a4 11430 const char *subtype_info;
14f9c5c9 11431
28c85d6c 11432 gdb_assert (raw_type != NULL);
7d93a1e0 11433 gdb_assert (raw_type->name () != NULL);
dddfab26 11434
78134374 11435 if (raw_type->code () == TYPE_CODE_RANGE)
27710edb 11436 base_type = raw_type->target_type ();
14f9c5c9
AS
11437 else
11438 base_type = raw_type;
11439
7d93a1e0 11440 name = raw_type->name ();
14f9c5c9
AS
11441 subtype_info = strstr (name, "___XD");
11442 if (subtype_info == NULL)
690cc4eb 11443 {
43bbcdc2
PH
11444 LONGEST L = ada_discrete_type_low_bound (raw_type);
11445 LONGEST U = ada_discrete_type_high_bound (raw_type);
5b4ee69b 11446
690cc4eb
PH
11447 if (L < INT_MIN || U > INT_MAX)
11448 return raw_type;
11449 else
e727c536
TT
11450 {
11451 type_allocator alloc (raw_type);
11452 return create_static_range_type (alloc, raw_type, L, U);
11453 }
690cc4eb 11454 }
14f9c5c9
AS
11455 else
11456 {
14f9c5c9
AS
11457 int prefix_len = subtype_info - name;
11458 LONGEST L, U;
11459 struct type *type;
108d56a4 11460 const char *bounds_str;
14f9c5c9
AS
11461 int n;
11462
14f9c5c9
AS
11463 subtype_info += 5;
11464 bounds_str = strchr (subtype_info, '_');
11465 n = 1;
11466
d2e4a39e 11467 if (*subtype_info == 'L')
dda83cd7
SM
11468 {
11469 if (!ada_scan_number (bounds_str, n, &L, &n)
11470 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11471 return raw_type;
11472 if (bounds_str[n] == '_')
11473 n += 2;
11474 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11475 n += 1;
11476 subtype_info += 1;
11477 }
d2e4a39e 11478 else
dda83cd7 11479 {
5f9febe0
TT
11480 std::string name_buf = std::string (name, prefix_len) + "___L";
11481 if (!get_int_var_value (name_buf.c_str (), L))
dda83cd7
SM
11482 {
11483 lim_warning (_("Unknown lower bound, using 1."));
11484 L = 1;
11485 }
11486 }
14f9c5c9 11487
d2e4a39e 11488 if (*subtype_info == 'U')
dda83cd7
SM
11489 {
11490 if (!ada_scan_number (bounds_str, n, &U, &n)
11491 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11492 return raw_type;
11493 }
d2e4a39e 11494 else
dda83cd7 11495 {
5f9febe0
TT
11496 std::string name_buf = std::string (name, prefix_len) + "___U";
11497 if (!get_int_var_value (name_buf.c_str (), U))
dda83cd7
SM
11498 {
11499 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11500 U = L;
11501 }
11502 }
14f9c5c9 11503
e727c536
TT
11504 type_allocator alloc (raw_type);
11505 type = create_static_range_type (alloc, base_type, L, U);
f5a91472 11506 /* create_static_range_type alters the resulting type's length
dda83cd7
SM
11507 to match the size of the base_type, which is not what we want.
11508 Set it back to the original range type's length. */
df86565b 11509 type->set_length (raw_type->length ());
d0e39ea2 11510 type->set_name (name);
14f9c5c9
AS
11511 return type;
11512 }
11513}
11514
4c4b4cd2
PH
11515/* True iff NAME is the name of a range type. */
11516
14f9c5c9 11517int
d2e4a39e 11518ada_is_range_type_name (const char *name)
14f9c5c9
AS
11519{
11520 return (name != NULL && strstr (name, "___XD"));
d2e4a39e 11521}
14f9c5c9 11522\f
d2e4a39e 11523
dda83cd7 11524 /* Modular types */
4c4b4cd2
PH
11525
11526/* True iff TYPE is an Ada modular type. */
14f9c5c9 11527
14f9c5c9 11528int
d2e4a39e 11529ada_is_modular_type (struct type *type)
14f9c5c9 11530{
18af8284 11531 struct type *subranged_type = get_base_type (type);
14f9c5c9 11532
78134374 11533 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
dda83cd7
SM
11534 && subranged_type->code () == TYPE_CODE_INT
11535 && subranged_type->is_unsigned ());
14f9c5c9
AS
11536}
11537
4c4b4cd2
PH
11538/* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11539
61ee279c 11540ULONGEST
0056e4d5 11541ada_modulus (struct type *type)
14f9c5c9 11542{
5e500d33
SM
11543 const dynamic_prop &high = type->bounds ()->high;
11544
9c0fb734 11545 if (high.is_constant ())
5e500d33
SM
11546 return (ULONGEST) high.const_val () + 1;
11547
11548 /* If TYPE is unresolved, the high bound might be a location list. Return
11549 0, for lack of a better value to return. */
11550 return 0;
14f9c5c9 11551}
d2e4a39e 11552\f
f7f9143b
JB
11553
11554/* Ada exception catchpoint support:
11555 ---------------------------------
11556
11557 We support 3 kinds of exception catchpoints:
11558 . catchpoints on Ada exceptions
11559 . catchpoints on unhandled Ada exceptions
11560 . catchpoints on failed assertions
11561
11562 Exceptions raised during failed assertions, or unhandled exceptions
11563 could perfectly be caught with the general catchpoint on Ada exceptions.
11564 However, we can easily differentiate these two special cases, and having
11565 the option to distinguish these two cases from the rest can be useful
11566 to zero-in on certain situations.
11567
11568 Exception catchpoints are a specialized form of breakpoint,
11569 since they rely on inserting breakpoints inside known routines
11570 of the GNAT runtime. The implementation therefore uses a standard
11571 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11572 of breakpoint_ops.
11573
0259addd
JB
11574 Support in the runtime for exception catchpoints have been changed
11575 a few times already, and these changes affect the implementation
11576 of these catchpoints. In order to be able to support several
11577 variants of the runtime, we use a sniffer that will determine
28010a5d 11578 the runtime variant used by the program being debugged. */
f7f9143b 11579
82eacd52
JB
11580/* Ada's standard exceptions.
11581
11582 The Ada 83 standard also defined Numeric_Error. But there so many
11583 situations where it was unclear from the Ada 83 Reference Manual
11584 (RM) whether Constraint_Error or Numeric_Error should be raised,
11585 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11586 Interpretation saying that anytime the RM says that Numeric_Error
11587 should be raised, the implementation may raise Constraint_Error.
11588 Ada 95 went one step further and pretty much removed Numeric_Error
11589 from the list of standard exceptions (it made it a renaming of
11590 Constraint_Error, to help preserve compatibility when compiling
11591 an Ada83 compiler). As such, we do not include Numeric_Error from
11592 this list of standard exceptions. */
3d0b0fa3 11593
27087b7f 11594static const char * const standard_exc[] = {
3d0b0fa3
JB
11595 "constraint_error",
11596 "program_error",
11597 "storage_error",
11598 "tasking_error"
11599};
11600
0259addd
JB
11601typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11602
11603/* A structure that describes how to support exception catchpoints
11604 for a given executable. */
11605
11606struct exception_support_info
11607{
11608 /* The name of the symbol to break on in order to insert
11609 a catchpoint on exceptions. */
11610 const char *catch_exception_sym;
11611
11612 /* The name of the symbol to break on in order to insert
11613 a catchpoint on unhandled exceptions. */
11614 const char *catch_exception_unhandled_sym;
11615
11616 /* The name of the symbol to break on in order to insert
11617 a catchpoint on failed assertions. */
11618 const char *catch_assert_sym;
11619
9f757bf7
XR
11620 /* The name of the symbol to break on in order to insert
11621 a catchpoint on exception handling. */
11622 const char *catch_handlers_sym;
11623
0259addd
JB
11624 /* Assuming that the inferior just triggered an unhandled exception
11625 catchpoint, this function is responsible for returning the address
11626 in inferior memory where the name of that exception is stored.
11627 Return zero if the address could not be computed. */
11628 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11629};
11630
11631static CORE_ADDR ada_unhandled_exception_name_addr (void);
11632static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11633
11634/* The following exception support info structure describes how to
11635 implement exception catchpoints with the latest version of the
ca683e3a 11636 Ada runtime (as of 2019-08-??). */
0259addd
JB
11637
11638static const struct exception_support_info default_exception_support_info =
ca683e3a
AO
11639{
11640 "__gnat_debug_raise_exception", /* catch_exception_sym */
11641 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11642 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11643 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11644 ada_unhandled_exception_name_addr
11645};
11646
11647/* The following exception support info structure describes how to
11648 implement exception catchpoints with an earlier version of the
11649 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11650
11651static const struct exception_support_info exception_support_info_v0 =
0259addd
JB
11652{
11653 "__gnat_debug_raise_exception", /* catch_exception_sym */
11654 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11655 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
9f757bf7 11656 "__gnat_begin_handler", /* catch_handlers_sym */
0259addd
JB
11657 ada_unhandled_exception_name_addr
11658};
11659
11660/* The following exception support info structure describes how to
11661 implement exception catchpoints with a slightly older version
11662 of the Ada runtime. */
11663
11664static const struct exception_support_info exception_support_info_fallback =
11665{
11666 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11667 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11668 "system__assertions__raise_assert_failure", /* catch_assert_sym */
9f757bf7 11669 "__gnat_begin_handler", /* catch_handlers_sym */
0259addd
JB
11670 ada_unhandled_exception_name_addr_from_raise
11671};
11672
f17011e0
JB
11673/* Return nonzero if we can detect the exception support routines
11674 described in EINFO.
11675
11676 This function errors out if an abnormal situation is detected
11677 (for instance, if we find the exception support routines, but
11678 that support is found to be incomplete). */
11679
11680static int
11681ada_has_this_exception_support (const struct exception_support_info *einfo)
11682{
11683 struct symbol *sym;
11684
11685 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11686 that should be compiled with debugging information. As a result, we
11687 expect to find that symbol in the symtabs. */
11688
11689 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11690 if (sym == NULL)
a6af7abe
JB
11691 {
11692 /* Perhaps we did not find our symbol because the Ada runtime was
11693 compiled without debugging info, or simply stripped of it.
11694 It happens on some GNU/Linux distributions for instance, where
11695 users have to install a separate debug package in order to get
11696 the runtime's debugging info. In that situation, let the user
11697 know why we cannot insert an Ada exception catchpoint.
11698
11699 Note: Just for the purpose of inserting our Ada exception
11700 catchpoint, we could rely purely on the associated minimal symbol.
11701 But we would be operating in degraded mode anyway, since we are
11702 still lacking the debugging info needed later on to extract
11703 the name of the exception being raised (this name is printed in
11704 the catchpoint message, and is also used when trying to catch
11705 a specific exception). We do not handle this case for now. */
3b7344d5 11706 struct bound_minimal_symbol msym
1c8e84b0
JB
11707 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11708
60f62e2b 11709 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
a6af7abe
JB
11710 error (_("Your Ada runtime appears to be missing some debugging "
11711 "information.\nCannot insert Ada exception catchpoint "
11712 "in this configuration."));
11713
11714 return 0;
11715 }
f17011e0
JB
11716
11717 /* Make sure that the symbol we found corresponds to a function. */
11718
66d7f48f 11719 if (sym->aclass () != LOC_BLOCK)
fe043185
TT
11720 error (_("Symbol \"%s\" is not a function (class = %d)"),
11721 sym->linkage_name (), sym->aclass ());
ca683e3a
AO
11722
11723 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11724 if (sym == NULL)
11725 {
11726 struct bound_minimal_symbol msym
11727 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11728
60f62e2b 11729 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
ca683e3a
AO
11730 error (_("Your Ada runtime appears to be missing some debugging "
11731 "information.\nCannot insert Ada exception catchpoint "
11732 "in this configuration."));
11733
11734 return 0;
11735 }
11736
11737 /* Make sure that the symbol we found corresponds to a function. */
11738
66d7f48f 11739 if (sym->aclass () != LOC_BLOCK)
fe043185
TT
11740 error (_("Symbol \"%s\" is not a function (class = %d)"),
11741 sym->linkage_name (), sym->aclass ());
f17011e0
JB
11742
11743 return 1;
11744}
11745
0259addd
JB
11746/* Inspect the Ada runtime and determine which exception info structure
11747 should be used to provide support for exception catchpoints.
11748
3eecfa55
JB
11749 This function will always set the per-inferior exception_info,
11750 or raise an error. */
0259addd
JB
11751
11752static void
11753ada_exception_support_info_sniffer (void)
11754{
3eecfa55 11755 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
0259addd
JB
11756
11757 /* If the exception info is already known, then no need to recompute it. */
3eecfa55 11758 if (data->exception_info != NULL)
0259addd
JB
11759 return;
11760
11761 /* Check the latest (default) exception support info. */
f17011e0 11762 if (ada_has_this_exception_support (&default_exception_support_info))
0259addd 11763 {
3eecfa55 11764 data->exception_info = &default_exception_support_info;
0259addd
JB
11765 return;
11766 }
11767
ca683e3a
AO
11768 /* Try the v0 exception suport info. */
11769 if (ada_has_this_exception_support (&exception_support_info_v0))
11770 {
11771 data->exception_info = &exception_support_info_v0;
11772 return;
11773 }
11774
0259addd 11775 /* Try our fallback exception suport info. */
f17011e0 11776 if (ada_has_this_exception_support (&exception_support_info_fallback))
0259addd 11777 {
3eecfa55 11778 data->exception_info = &exception_support_info_fallback;
0259addd
JB
11779 return;
11780 }
11781
2c4c710f
TT
11782 throw_error (NOT_FOUND_ERROR,
11783 _("Could not find Ada runtime exception support"));
0259addd
JB
11784}
11785
f7f9143b
JB
11786/* True iff FRAME is very likely to be that of a function that is
11787 part of the runtime system. This is all very heuristic, but is
11788 intended to be used as advice as to what frames are uninteresting
11789 to most users. */
11790
11791static int
bd2b40ac 11792is_known_support_routine (frame_info_ptr frame)
f7f9143b 11793{
692465f1 11794 enum language func_lang;
f7f9143b 11795 int i;
f35a17b5 11796 const char *fullname;
f7f9143b 11797
4ed6b5be
JB
11798 /* If this code does not have any debugging information (no symtab),
11799 This cannot be any user code. */
f7f9143b 11800
51abb421 11801 symtab_and_line sal = find_frame_sal (frame);
f7f9143b
JB
11802 if (sal.symtab == NULL)
11803 return 1;
11804
4ed6b5be
JB
11805 /* If there is a symtab, but the associated source file cannot be
11806 located, then assume this is not user code: Selecting a frame
11807 for which we cannot display the code would not be very helpful
11808 for the user. This should also take care of case such as VxWorks
11809 where the kernel has some debugging info provided for a few units. */
f7f9143b 11810
f35a17b5
JK
11811 fullname = symtab_to_fullname (sal.symtab);
11812 if (access (fullname, R_OK) != 0)
f7f9143b
JB
11813 return 1;
11814
85102364 11815 /* Check the unit filename against the Ada runtime file naming.
4ed6b5be
JB
11816 We also check the name of the objfile against the name of some
11817 known system libraries that sometimes come with debugging info
11818 too. */
11819
f7f9143b
JB
11820 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11821 {
11822 re_comp (known_runtime_file_name_patterns[i]);
f69c91ad 11823 if (re_exec (lbasename (sal.symtab->filename)))
dda83cd7 11824 return 1;
3c86fae3
SM
11825 if (sal.symtab->compunit ()->objfile () != NULL
11826 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
dda83cd7 11827 return 1;
f7f9143b
JB
11828 }
11829
4ed6b5be 11830 /* Check whether the function is a GNAT-generated entity. */
f7f9143b 11831
c6dc63a1
TT
11832 gdb::unique_xmalloc_ptr<char> func_name
11833 = find_frame_funname (frame, &func_lang, NULL);
f7f9143b
JB
11834 if (func_name == NULL)
11835 return 1;
11836
11837 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11838 {
11839 re_comp (known_auxiliary_function_name_patterns[i]);
c6dc63a1
TT
11840 if (re_exec (func_name.get ()))
11841 return 1;
f7f9143b
JB
11842 }
11843
11844 return 0;
11845}
11846
11847/* Find the first frame that contains debugging information and that is not
11848 part of the Ada run-time, starting from FI and moving upward. */
11849
0ef643c8 11850void
bd2b40ac 11851ada_find_printable_frame (frame_info_ptr fi)
f7f9143b
JB
11852{
11853 for (; fi != NULL; fi = get_prev_frame (fi))
11854 {
11855 if (!is_known_support_routine (fi))
dda83cd7
SM
11856 {
11857 select_frame (fi);
11858 break;
11859 }
f7f9143b
JB
11860 }
11861
11862}
11863
11864/* Assuming that the inferior just triggered an unhandled exception
11865 catchpoint, return the address in inferior memory where the name
11866 of the exception is stored.
11867
11868 Return zero if the address could not be computed. */
11869
11870static CORE_ADDR
11871ada_unhandled_exception_name_addr (void)
0259addd
JB
11872{
11873 return parse_and_eval_address ("e.full_name");
11874}
11875
11876/* Same as ada_unhandled_exception_name_addr, except that this function
11877 should be used when the inferior uses an older version of the runtime,
11878 where the exception name needs to be extracted from a specific frame
11879 several frames up in the callstack. */
11880
11881static CORE_ADDR
11882ada_unhandled_exception_name_addr_from_raise (void)
f7f9143b
JB
11883{
11884 int frame_level;
bd2b40ac 11885 frame_info_ptr fi;
3eecfa55 11886 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
f7f9143b
JB
11887
11888 /* To determine the name of this exception, we need to select
11889 the frame corresponding to RAISE_SYM_NAME. This frame is
11890 at least 3 levels up, so we simply skip the first 3 frames
11891 without checking the name of their associated function. */
11892 fi = get_current_frame ();
11893 for (frame_level = 0; frame_level < 3; frame_level += 1)
11894 if (fi != NULL)
11895 fi = get_prev_frame (fi);
11896
11897 while (fi != NULL)
11898 {
692465f1
JB
11899 enum language func_lang;
11900
c6dc63a1
TT
11901 gdb::unique_xmalloc_ptr<char> func_name
11902 = find_frame_funname (fi, &func_lang, NULL);
55b87a52
KS
11903 if (func_name != NULL)
11904 {
dda83cd7 11905 if (strcmp (func_name.get (),
55b87a52
KS
11906 data->exception_info->catch_exception_sym) == 0)
11907 break; /* We found the frame we were looking for... */
55b87a52 11908 }
fb44b1a7 11909 fi = get_prev_frame (fi);
f7f9143b
JB
11910 }
11911
11912 if (fi == NULL)
11913 return 0;
11914
11915 select_frame (fi);
11916 return parse_and_eval_address ("id.full_name");
11917}
11918
11919/* Assuming the inferior just triggered an Ada exception catchpoint
11920 (of any type), return the address in inferior memory where the name
11921 of the exception is stored, if applicable.
11922
45db7c09
PA
11923 Assumes the selected frame is the current frame.
11924
f7f9143b
JB
11925 Return zero if the address could not be computed, or if not relevant. */
11926
11927static CORE_ADDR
7bd86313 11928ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
f7f9143b 11929{
3eecfa55
JB
11930 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11931
f7f9143b
JB
11932 switch (ex)
11933 {
761269c8 11934 case ada_catch_exception:
dda83cd7
SM
11935 return (parse_and_eval_address ("e.full_name"));
11936 break;
f7f9143b 11937
761269c8 11938 case ada_catch_exception_unhandled:
dda83cd7
SM
11939 return data->exception_info->unhandled_exception_name_addr ();
11940 break;
9f757bf7
XR
11941
11942 case ada_catch_handlers:
dda83cd7 11943 return 0; /* The runtimes does not provide access to the exception
9f757bf7 11944 name. */
dda83cd7 11945 break;
9f757bf7 11946
761269c8 11947 case ada_catch_assert:
dda83cd7
SM
11948 return 0; /* Exception name is not relevant in this case. */
11949 break;
f7f9143b
JB
11950
11951 default:
f34652de 11952 internal_error (_("unexpected catchpoint type"));
dda83cd7 11953 break;
f7f9143b
JB
11954 }
11955
11956 return 0; /* Should never be reached. */
11957}
11958
e547c119
JB
11959/* Assuming the inferior is stopped at an exception catchpoint,
11960 return the message which was associated to the exception, if
11961 available. Return NULL if the message could not be retrieved.
11962
e547c119
JB
11963 Note: The exception message can be associated to an exception
11964 either through the use of the Raise_Exception function, or
11965 more simply (Ada 2005 and later), via:
11966
11967 raise Exception_Name with "exception message";
11968
11969 */
11970
6f46ac85 11971static gdb::unique_xmalloc_ptr<char>
e547c119
JB
11972ada_exception_message_1 (void)
11973{
11974 struct value *e_msg_val;
e547c119 11975 int e_msg_len;
e547c119
JB
11976
11977 /* For runtimes that support this feature, the exception message
11978 is passed as an unbounded string argument called "message". */
11979 e_msg_val = parse_and_eval ("message");
11980 if (e_msg_val == NULL)
11981 return NULL; /* Exception message not supported. */
11982
11983 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11984 gdb_assert (e_msg_val != NULL);
d0c97917 11985 e_msg_len = e_msg_val->type ()->length ();
e547c119
JB
11986
11987 /* If the message string is empty, then treat it as if there was
11988 no exception message. */
11989 if (e_msg_len <= 0)
11990 return NULL;
11991
15f3b077 11992 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
9feb2d07 11993 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
15f3b077
TT
11994 e_msg_len);
11995 e_msg.get ()[e_msg_len] = '\0';
11996
11997 return e_msg;
e547c119
JB
11998}
11999
12000/* Same as ada_exception_message_1, except that all exceptions are
12001 contained here (returning NULL instead). */
12002
6f46ac85 12003static gdb::unique_xmalloc_ptr<char>
e547c119
JB
12004ada_exception_message (void)
12005{
6f46ac85 12006 gdb::unique_xmalloc_ptr<char> e_msg;
e547c119 12007
a70b8144 12008 try
e547c119
JB
12009 {
12010 e_msg = ada_exception_message_1 ();
12011 }
230d2906 12012 catch (const gdb_exception_error &e)
e547c119 12013 {
6f46ac85 12014 e_msg.reset (nullptr);
e547c119 12015 }
e547c119
JB
12016
12017 return e_msg;
12018}
12019
f7f9143b
JB
12020/* Same as ada_exception_name_addr_1, except that it intercepts and contains
12021 any error that ada_exception_name_addr_1 might cause to be thrown.
12022 When an error is intercepted, a warning with the error message is printed,
12023 and zero is returned. */
12024
12025static CORE_ADDR
7bd86313 12026ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
f7f9143b 12027{
f7f9143b
JB
12028 CORE_ADDR result = 0;
12029
a70b8144 12030 try
f7f9143b 12031 {
7bd86313 12032 result = ada_exception_name_addr_1 (ex);
f7f9143b
JB
12033 }
12034
230d2906 12035 catch (const gdb_exception_error &e)
f7f9143b 12036 {
3d6e9d23 12037 warning (_("failed to get exception name: %s"), e.what ());
f7f9143b
JB
12038 return 0;
12039 }
12040
12041 return result;
12042}
12043
cb7de75e 12044static std::string ada_exception_catchpoint_cond_string
9f757bf7
XR
12045 (const char *excep_string,
12046 enum ada_exception_catchpoint_kind ex);
28010a5d
PA
12047
12048/* Ada catchpoints.
12049
12050 In the case of catchpoints on Ada exceptions, the catchpoint will
12051 stop the target on every exception the program throws. When a user
12052 specifies the name of a specific exception, we translate this
12053 request into a condition expression (in text form), and then parse
12054 it into an expression stored in each of the catchpoint's locations.
12055 We then use this condition to check whether the exception that was
12056 raised is the one the user is interested in. If not, then the
12057 target is resumed again. We store the name of the requested
12058 exception, in order to be able to re-set the condition expression
12059 when symbols change. */
12060
c1fc2657 12061/* An instance of this type is used to represent an Ada catchpoint. */
28010a5d 12062
74421c0b 12063struct ada_catchpoint : public code_breakpoint
28010a5d 12064{
73063f51 12065 ada_catchpoint (struct gdbarch *gdbarch_,
bd21b6c9 12066 enum ada_exception_catchpoint_kind kind,
2c4c710f 12067 const char *cond_string,
bd21b6c9
PA
12068 bool tempflag,
12069 bool enabled,
898db0f7
TT
12070 bool from_tty,
12071 std::string &&excep_string_)
2c4c710f 12072 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
03f531ea 12073 m_excep_string (std::move (excep_string_)),
73063f51 12074 m_kind (kind)
37f6a7f4 12075 {
74421c0b 12076 /* Unlike most code_breakpoint types, Ada catchpoints are
bd21b6c9 12077 pspace-specific. */
2c4c710f 12078 pspace = current_program_space;
bd21b6c9 12079 enable_state = enabled ? bp_enabled : bp_disabled;
bd21b6c9 12080 language = language_ada;
95f2fe27
TT
12081
12082 re_set ();
37f6a7f4
TT
12083 }
12084
ae72050b
TT
12085 struct bp_location *allocate_location () override;
12086 void re_set () override;
12087 void check_status (struct bpstat *bs) override;
7bd86313 12088 enum print_stop_action print_it (const bpstat *bs) const override;
5e632eca 12089 bool print_one (const bp_location **) const override;
b713485d 12090 void print_mention () const override;
4d1ae558 12091 void print_recreate (struct ui_file *fp) const override;
ae72050b 12092
03f531ea
TT
12093private:
12094
971149cb
TT
12095 /* A helper function for check_status. Returns true if we should
12096 stop for this breakpoint hit. If the user specified a specific
12097 exception, we only want to cause a stop if the program thrown
12098 that exception. */
12099 bool should_stop_exception (const struct bp_location *bl) const;
12100
28010a5d 12101 /* The name of the specific exception the user specified. */
03f531ea 12102 std::string m_excep_string;
37f6a7f4
TT
12103
12104 /* What kind of catchpoint this is. */
12105 enum ada_exception_catchpoint_kind m_kind;
28010a5d
PA
12106};
12107
8cd0bf5e
PA
12108/* An instance of this type is used to represent an Ada catchpoint
12109 breakpoint location. */
12110
12111class ada_catchpoint_location : public bp_location
12112{
12113public:
12114 explicit ada_catchpoint_location (ada_catchpoint *owner)
12115 : bp_location (owner, bp_loc_software_breakpoint)
12116 {}
12117
12118 /* The condition that checks whether the exception that was raised
12119 is the specific exception the user specified on catchpoint
12120 creation. */
12121 expression_up excep_cond_expr;
12122};
12123
2c4c710f
TT
12124static struct symtab_and_line ada_exception_sal
12125 (enum ada_exception_catchpoint_kind ex);
12126
95f2fe27
TT
12127/* Implement the RE_SET method in the structure for all exception
12128 catchpoint kinds. */
28010a5d 12129
95f2fe27
TT
12130void
12131ada_catchpoint::re_set ()
28010a5d 12132{
2c4c710f
TT
12133 std::vector<symtab_and_line> sals;
12134 try
12135 {
12136 struct symtab_and_line sal = ada_exception_sal (m_kind);
12137 sals.push_back (sal);
12138 }
12139 catch (const gdb_exception_error &ex)
12140 {
12141 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12142 if (ex.error != NOT_FOUND_ERROR)
12143 throw;
12144 }
12145
12146 update_breakpoint_locations (this, pspace, sals, {});
95f2fe27
TT
12147
12148 /* Reparse the exception conditional expressions. One for each
12149 location. */
12150
28010a5d 12151 /* Nothing to do if there's no specific exception to catch. */
03f531ea 12152 if (m_excep_string.empty ())
28010a5d
PA
12153 return;
12154
12155 /* Same if there are no locations... */
95f2fe27 12156 if (!has_locations ())
28010a5d
PA
12157 return;
12158
fccf9de1 12159 /* Compute the condition expression in text form, from the specific
33b5899f 12160 exception we want to catch. */
fccf9de1 12161 std::string cond_string
03f531ea 12162 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
28010a5d 12163
fccf9de1
TT
12164 /* Iterate over all the catchpoint's locations, and parse an
12165 expression for each. */
95f2fe27 12166 for (bp_location &bl : locations ())
28010a5d 12167 {
b00b30b2
SM
12168 ada_catchpoint_location &ada_loc
12169 = static_cast<ada_catchpoint_location &> (bl);
4d01a485 12170 expression_up exp;
28010a5d 12171
b00b30b2 12172 if (!bl.shlib_disabled)
28010a5d 12173 {
bbc13ae3 12174 const char *s;
28010a5d 12175
cb7de75e 12176 s = cond_string.c_str ();
a70b8144 12177 try
28010a5d 12178 {
b00b30b2 12179 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
28010a5d 12180 }
230d2906 12181 catch (const gdb_exception_error &e)
849f2b52
JB
12182 {
12183 warning (_("failed to reevaluate internal exception condition "
12184 "for catchpoint %d: %s"),
95f2fe27 12185 number, e.what ());
849f2b52 12186 }
28010a5d
PA
12187 }
12188
b00b30b2 12189 ada_loc.excep_cond_expr = std::move (exp);
28010a5d 12190 }
28010a5d
PA
12191}
12192
ae72050b
TT
12193/* Implement the ALLOCATE_LOCATION method in the structure for all
12194 exception catchpoint kinds. */
28010a5d 12195
ae72050b
TT
12196struct bp_location *
12197ada_catchpoint::allocate_location ()
28010a5d 12198{
ae72050b 12199 return new ada_catchpoint_location (this);
28010a5d
PA
12200}
12201
971149cb 12202/* See declaration. */
28010a5d 12203
971149cb
TT
12204bool
12205ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
28010a5d 12206{
8e032233 12207 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
28010a5d
PA
12208 const struct ada_catchpoint_location *ada_loc
12209 = (const struct ada_catchpoint_location *) bl;
7ebaa5f7 12210 bool stop;
28010a5d 12211
37f6a7f4
TT
12212 struct internalvar *var = lookup_internalvar ("_ada_exception");
12213 if (c->m_kind == ada_catch_assert)
12214 clear_internalvar (var);
12215 else
12216 {
12217 try
12218 {
12219 const char *expr;
12220
12221 if (c->m_kind == ada_catch_handlers)
12222 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12223 ".all.occurrence.id");
12224 else
12225 expr = "e";
12226
12227 struct value *exc = parse_and_eval (expr);
12228 set_internalvar (var, exc);
12229 }
12230 catch (const gdb_exception_error &ex)
12231 {
12232 clear_internalvar (var);
12233 }
12234 }
12235
28010a5d 12236 /* With no specific exception, should always stop. */
03f531ea 12237 if (c->m_excep_string.empty ())
7ebaa5f7 12238 return true;
28010a5d
PA
12239
12240 if (ada_loc->excep_cond_expr == NULL)
12241 {
12242 /* We will have a NULL expression if back when we were creating
12243 the expressions, this location's had failed to parse. */
7ebaa5f7 12244 return true;
28010a5d
PA
12245 }
12246
7ebaa5f7 12247 stop = true;
a70b8144 12248 try
28010a5d 12249 {
65558ca5 12250 scoped_value_mark mark;
43048e46 12251 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
28010a5d 12252 }
b1ffd112 12253 catch (const gdb_exception_error &ex)
492d29ea
PA
12254 {
12255 exception_fprintf (gdb_stderr, ex,
12256 _("Error in testing exception condition:\n"));
12257 }
492d29ea 12258
28010a5d
PA
12259 return stop;
12260}
12261
ae72050b
TT
12262/* Implement the CHECK_STATUS method in the structure for all
12263 exception catchpoint kinds. */
28010a5d 12264
ae72050b
TT
12265void
12266ada_catchpoint::check_status (bpstat *bs)
28010a5d 12267{
b6433ede 12268 bs->stop = should_stop_exception (bs->bp_location_at.get ());
28010a5d
PA
12269}
12270
ae72050b
TT
12271/* Implement the PRINT_IT method in the structure for all exception
12272 catchpoint kinds. */
f7f9143b 12273
ae72050b 12274enum print_stop_action
7bd86313 12275ada_catchpoint::print_it (const bpstat *bs) const
f7f9143b 12276{
79a45e25 12277 struct ui_out *uiout = current_uiout;
348d480f 12278
ae72050b 12279 annotate_catchpoint (number);
f7f9143b 12280
112e8700 12281 if (uiout->is_mi_like_p ())
f7f9143b 12282 {
112e8700 12283 uiout->field_string ("reason",
956a9fb9 12284 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
ae72050b 12285 uiout->field_string ("disp", bpdisp_text (disposition));
f7f9143b
JB
12286 }
12287
ae72050b 12288 uiout->text (disposition == disp_del
112e8700 12289 ? "\nTemporary catchpoint " : "\nCatchpoint ");
78805ff8 12290 print_num_locno (bs, uiout);
112e8700 12291 uiout->text (", ");
f7f9143b 12292
45db7c09
PA
12293 /* ada_exception_name_addr relies on the selected frame being the
12294 current frame. Need to do this here because this function may be
12295 called more than once when printing a stop, and below, we'll
12296 select the first frame past the Ada run-time (see
12297 ada_find_printable_frame). */
12298 select_frame (get_current_frame ());
12299
ae72050b 12300 switch (m_kind)
f7f9143b 12301 {
761269c8
JB
12302 case ada_catch_exception:
12303 case ada_catch_exception_unhandled:
9f757bf7 12304 case ada_catch_handlers:
956a9fb9 12305 {
7bd86313 12306 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
956a9fb9
JB
12307 char exception_name[256];
12308
12309 if (addr != 0)
12310 {
c714b426
PA
12311 read_memory (addr, (gdb_byte *) exception_name,
12312 sizeof (exception_name) - 1);
956a9fb9
JB
12313 exception_name [sizeof (exception_name) - 1] = '\0';
12314 }
12315 else
12316 {
12317 /* For some reason, we were unable to read the exception
12318 name. This could happen if the Runtime was compiled
12319 without debugging info, for instance. In that case,
12320 just replace the exception name by the generic string
12321 "exception" - it will read as "an exception" in the
12322 notification we are about to print. */
967cff16 12323 memcpy (exception_name, "exception", sizeof ("exception"));
956a9fb9
JB
12324 }
12325 /* In the case of unhandled exception breakpoints, we print
12326 the exception name as "unhandled EXCEPTION_NAME", to make
12327 it clearer to the user which kind of catchpoint just got
12328 hit. We used ui_out_text to make sure that this extra
12329 info does not pollute the exception name in the MI case. */
ae72050b 12330 if (m_kind == ada_catch_exception_unhandled)
112e8700
SM
12331 uiout->text ("unhandled ");
12332 uiout->field_string ("exception-name", exception_name);
956a9fb9
JB
12333 }
12334 break;
761269c8 12335 case ada_catch_assert:
956a9fb9
JB
12336 /* In this case, the name of the exception is not really
12337 important. Just print "failed assertion" to make it clearer
12338 that his program just hit an assertion-failure catchpoint.
12339 We used ui_out_text because this info does not belong in
12340 the MI output. */
112e8700 12341 uiout->text ("failed assertion");
956a9fb9 12342 break;
f7f9143b 12343 }
e547c119 12344
6f46ac85 12345 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
e547c119
JB
12346 if (exception_message != NULL)
12347 {
e547c119 12348 uiout->text (" (");
6f46ac85 12349 uiout->field_string ("exception-message", exception_message.get ());
e547c119 12350 uiout->text (")");
e547c119
JB
12351 }
12352
112e8700 12353 uiout->text (" at ");
956a9fb9 12354 ada_find_printable_frame (get_current_frame ());
f7f9143b
JB
12355
12356 return PRINT_SRC_AND_LOC;
12357}
12358
ae72050b
TT
12359/* Implement the PRINT_ONE method in the structure for all exception
12360 catchpoint kinds. */
f7f9143b 12361
ae72050b 12362bool
5e632eca 12363ada_catchpoint::print_one (const bp_location **last_loc) const
f7f9143b 12364{
79a45e25 12365 struct ui_out *uiout = current_uiout;
79a45b7d
TT
12366 struct value_print_options opts;
12367
12368 get_user_print_options (&opts);
f06f1252 12369
79a45b7d 12370 if (opts.addressprint)
f06f1252 12371 uiout->field_skip ("addr");
f7f9143b
JB
12372
12373 annotate_field (5);
ae72050b 12374 switch (m_kind)
f7f9143b 12375 {
761269c8 12376 case ada_catch_exception:
03f531ea 12377 if (!m_excep_string.empty ())
dda83cd7 12378 {
bc18fbb5 12379 std::string msg = string_printf (_("`%s' Ada exception"),
03f531ea 12380 m_excep_string.c_str ());
28010a5d 12381
dda83cd7
SM
12382 uiout->field_string ("what", msg);
12383 }
12384 else
12385 uiout->field_string ("what", "all Ada exceptions");
12386
12387 break;
f7f9143b 12388
761269c8 12389 case ada_catch_exception_unhandled:
dda83cd7
SM
12390 uiout->field_string ("what", "unhandled Ada exceptions");
12391 break;
f7f9143b 12392
9f757bf7 12393 case ada_catch_handlers:
03f531ea 12394 if (!m_excep_string.empty ())
dda83cd7 12395 {
9f757bf7
XR
12396 uiout->field_fmt ("what",
12397 _("`%s' Ada exception handlers"),
03f531ea 12398 m_excep_string.c_str ());
dda83cd7
SM
12399 }
12400 else
9f757bf7 12401 uiout->field_string ("what", "all Ada exceptions handlers");
dda83cd7 12402 break;
9f757bf7 12403
761269c8 12404 case ada_catch_assert:
dda83cd7
SM
12405 uiout->field_string ("what", "failed Ada assertions");
12406 break;
f7f9143b
JB
12407
12408 default:
f34652de 12409 internal_error (_("unexpected catchpoint type"));
dda83cd7 12410 break;
f7f9143b 12411 }
c01e038b
TT
12412
12413 return true;
f7f9143b
JB
12414}
12415
12416/* Implement the PRINT_MENTION method in the breakpoint_ops structure
12417 for all exception catchpoint kinds. */
12418
ae72050b 12419void
b713485d 12420ada_catchpoint::print_mention () const
f7f9143b 12421{
79a45e25 12422 struct ui_out *uiout = current_uiout;
28010a5d 12423
ae72050b 12424 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
dda83cd7 12425 : _("Catchpoint "));
ae72050b 12426 uiout->field_signed ("bkptno", number);
112e8700 12427 uiout->text (": ");
00eb2c4a 12428
ae72050b 12429 switch (m_kind)
f7f9143b 12430 {
761269c8 12431 case ada_catch_exception:
03f531ea 12432 if (!m_excep_string.empty ())
00eb2c4a 12433 {
862d101a 12434 std::string info = string_printf (_("`%s' Ada exception"),
03f531ea 12435 m_excep_string.c_str ());
4915bfdc 12436 uiout->text (info);
00eb2c4a 12437 }
dda83cd7
SM
12438 else
12439 uiout->text (_("all Ada exceptions"));
12440 break;
f7f9143b 12441
761269c8 12442 case ada_catch_exception_unhandled:
dda83cd7
SM
12443 uiout->text (_("unhandled Ada exceptions"));
12444 break;
9f757bf7
XR
12445
12446 case ada_catch_handlers:
03f531ea 12447 if (!m_excep_string.empty ())
9f757bf7
XR
12448 {
12449 std::string info
12450 = string_printf (_("`%s' Ada exception handlers"),
03f531ea 12451 m_excep_string.c_str ());
4915bfdc 12452 uiout->text (info);
9f757bf7 12453 }
dda83cd7
SM
12454 else
12455 uiout->text (_("all Ada exceptions handlers"));
12456 break;
9f757bf7 12457
761269c8 12458 case ada_catch_assert:
dda83cd7
SM
12459 uiout->text (_("failed Ada assertions"));
12460 break;
f7f9143b
JB
12461
12462 default:
f34652de 12463 internal_error (_("unexpected catchpoint type"));
dda83cd7 12464 break;
f7f9143b
JB
12465 }
12466}
12467
ae72050b
TT
12468/* Implement the PRINT_RECREATE method in the structure for all
12469 exception catchpoint kinds. */
6149aea9 12470
ae72050b 12471void
4d1ae558 12472ada_catchpoint::print_recreate (struct ui_file *fp) const
6149aea9 12473{
ae72050b 12474 switch (m_kind)
6149aea9 12475 {
761269c8 12476 case ada_catch_exception:
6cb06a8c 12477 gdb_printf (fp, "catch exception");
03f531ea
TT
12478 if (!m_excep_string.empty ())
12479 gdb_printf (fp, " %s", m_excep_string.c_str ());
6149aea9
PA
12480 break;
12481
761269c8 12482 case ada_catch_exception_unhandled:
6cb06a8c 12483 gdb_printf (fp, "catch exception unhandled");
6149aea9
PA
12484 break;
12485
9f757bf7 12486 case ada_catch_handlers:
6cb06a8c 12487 gdb_printf (fp, "catch handlers");
9f757bf7
XR
12488 break;
12489
761269c8 12490 case ada_catch_assert:
6cb06a8c 12491 gdb_printf (fp, "catch assert");
6149aea9
PA
12492 break;
12493
12494 default:
f34652de 12495 internal_error (_("unexpected catchpoint type"));
6149aea9 12496 }
04d0163c 12497 print_recreate_thread (fp);
6149aea9
PA
12498}
12499
f06f1252
TT
12500/* See ada-lang.h. */
12501
12502bool
12503is_ada_exception_catchpoint (breakpoint *bp)
12504{
ae72050b 12505 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
f06f1252
TT
12506}
12507
f7f9143b
JB
12508/* Split the arguments specified in a "catch exception" command.
12509 Set EX to the appropriate catchpoint type.
28010a5d 12510 Set EXCEP_STRING to the name of the specific exception if
5845583d 12511 specified by the user.
9f757bf7
XR
12512 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12513 "catch handlers" command. False otherwise.
5845583d
JB
12514 If a condition is found at the end of the arguments, the condition
12515 expression is stored in COND_STRING (memory must be deallocated
12516 after use). Otherwise COND_STRING is set to NULL. */
f7f9143b
JB
12517
12518static void
a121b7c1 12519catch_ada_exception_command_split (const char *args,
9f757bf7 12520 bool is_catch_handlers_cmd,
dda83cd7 12521 enum ada_exception_catchpoint_kind *ex,
bc18fbb5
TT
12522 std::string *excep_string,
12523 std::string *cond_string)
f7f9143b 12524{
bc18fbb5 12525 std::string exception_name;
f7f9143b 12526
bc18fbb5
TT
12527 exception_name = extract_arg (&args);
12528 if (exception_name == "if")
5845583d
JB
12529 {
12530 /* This is not an exception name; this is the start of a condition
12531 expression for a catchpoint on all exceptions. So, "un-get"
12532 this token, and set exception_name to NULL. */
bc18fbb5 12533 exception_name.clear ();
5845583d
JB
12534 args -= 2;
12535 }
f7f9143b 12536
5845583d 12537 /* Check to see if we have a condition. */
f7f9143b 12538
f1735a53 12539 args = skip_spaces (args);
61012eef 12540 if (startswith (args, "if")
5845583d
JB
12541 && (isspace (args[2]) || args[2] == '\0'))
12542 {
12543 args += 2;
f1735a53 12544 args = skip_spaces (args);
5845583d
JB
12545
12546 if (args[0] == '\0')
dda83cd7 12547 error (_("Condition missing after `if' keyword"));
bc18fbb5 12548 *cond_string = args;
5845583d
JB
12549
12550 args += strlen (args);
12551 }
12552
12553 /* Check that we do not have any more arguments. Anything else
12554 is unexpected. */
f7f9143b
JB
12555
12556 if (args[0] != '\0')
12557 error (_("Junk at end of expression"));
12558
9f757bf7
XR
12559 if (is_catch_handlers_cmd)
12560 {
12561 /* Catch handling of exceptions. */
12562 *ex = ada_catch_handlers;
12563 *excep_string = exception_name;
12564 }
bc18fbb5 12565 else if (exception_name.empty ())
f7f9143b
JB
12566 {
12567 /* Catch all exceptions. */
761269c8 12568 *ex = ada_catch_exception;
bc18fbb5 12569 excep_string->clear ();
f7f9143b 12570 }
bc18fbb5 12571 else if (exception_name == "unhandled")
f7f9143b
JB
12572 {
12573 /* Catch unhandled exceptions. */
761269c8 12574 *ex = ada_catch_exception_unhandled;
bc18fbb5 12575 excep_string->clear ();
f7f9143b
JB
12576 }
12577 else
12578 {
12579 /* Catch a specific exception. */
761269c8 12580 *ex = ada_catch_exception;
28010a5d 12581 *excep_string = exception_name;
f7f9143b
JB
12582 }
12583}
12584
12585/* Return the name of the symbol on which we should break in order to
12586 implement a catchpoint of the EX kind. */
12587
12588static const char *
761269c8 12589ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
f7f9143b 12590{
3eecfa55
JB
12591 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12592
12593 gdb_assert (data->exception_info != NULL);
0259addd 12594
f7f9143b
JB
12595 switch (ex)
12596 {
761269c8 12597 case ada_catch_exception:
dda83cd7
SM
12598 return (data->exception_info->catch_exception_sym);
12599 break;
761269c8 12600 case ada_catch_exception_unhandled:
dda83cd7
SM
12601 return (data->exception_info->catch_exception_unhandled_sym);
12602 break;
761269c8 12603 case ada_catch_assert:
dda83cd7
SM
12604 return (data->exception_info->catch_assert_sym);
12605 break;
9f757bf7 12606 case ada_catch_handlers:
dda83cd7
SM
12607 return (data->exception_info->catch_handlers_sym);
12608 break;
f7f9143b 12609 default:
f34652de 12610 internal_error (_("unexpected catchpoint kind (%d)"), ex);
f7f9143b
JB
12611 }
12612}
12613
f7f9143b
JB
12614/* Return the condition that will be used to match the current exception
12615 being raised with the exception that the user wants to catch. This
12616 assumes that this condition is used when the inferior just triggered
12617 an exception catchpoint.
cb7de75e 12618 EX: the type of catchpoints used for catching Ada exceptions. */
f7f9143b 12619
cb7de75e 12620static std::string
9f757bf7 12621ada_exception_catchpoint_cond_string (const char *excep_string,
dda83cd7 12622 enum ada_exception_catchpoint_kind ex)
f7f9143b 12623{
fccf9de1 12624 bool is_standard_exc = false;
cb7de75e 12625 std::string result;
9f757bf7
XR
12626
12627 if (ex == ada_catch_handlers)
12628 {
12629 /* For exception handlers catchpoints, the condition string does
dda83cd7 12630 not use the same parameter as for the other exceptions. */
fccf9de1
TT
12631 result = ("long_integer (GNAT_GCC_exception_Access"
12632 "(gcc_exception).all.occurrence.id)");
9f757bf7
XR
12633 }
12634 else
fccf9de1 12635 result = "long_integer (e)";
3d0b0fa3 12636
0963b4bd 12637 /* The standard exceptions are a special case. They are defined in
3d0b0fa3 12638 runtime units that have been compiled without debugging info; if
28010a5d 12639 EXCEP_STRING is the not-fully-qualified name of a standard
3d0b0fa3
JB
12640 exception (e.g. "constraint_error") then, during the evaluation
12641 of the condition expression, the symbol lookup on this name would
0963b4bd 12642 *not* return this standard exception. The catchpoint condition
3d0b0fa3
JB
12643 may then be set only on user-defined exceptions which have the
12644 same not-fully-qualified name (e.g. my_package.constraint_error).
12645
12646 To avoid this unexcepted behavior, these standard exceptions are
0963b4bd 12647 systematically prefixed by "standard". This means that "catch
3d0b0fa3
JB
12648 exception constraint_error" is rewritten into "catch exception
12649 standard.constraint_error".
12650
85102364 12651 If an exception named constraint_error is defined in another package of
3d0b0fa3
JB
12652 the inferior program, then the only way to specify this exception as a
12653 breakpoint condition is to use its fully-qualified named:
fccf9de1 12654 e.g. my_package.constraint_error. */
3d0b0fa3 12655
696d6f4d 12656 for (const char *name : standard_exc)
3d0b0fa3 12657 {
696d6f4d 12658 if (strcmp (name, excep_string) == 0)
3d0b0fa3 12659 {
fccf9de1 12660 is_standard_exc = true;
9f757bf7 12661 break;
3d0b0fa3
JB
12662 }
12663 }
9f757bf7 12664
fccf9de1
TT
12665 result += " = ";
12666
12667 if (is_standard_exc)
12668 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12669 else
12670 string_appendf (result, "long_integer (&%s)", excep_string);
9f757bf7 12671
9f757bf7 12672 return result;
f7f9143b
JB
12673}
12674
2c4c710f
TT
12675/* Return the symtab_and_line that should be used to insert an
12676 exception catchpoint of the TYPE kind. */
f7f9143b
JB
12677
12678static struct symtab_and_line
2c4c710f 12679ada_exception_sal (enum ada_exception_catchpoint_kind ex)
f7f9143b
JB
12680{
12681 const char *sym_name;
12682 struct symbol *sym;
f7f9143b 12683
0259addd
JB
12684 /* First, find out which exception support info to use. */
12685 ada_exception_support_info_sniffer ();
12686
12687 /* Then lookup the function on which we will break in order to catch
f7f9143b 12688 the Ada exceptions requested by the user. */
f7f9143b
JB
12689 sym_name = ada_exception_sym_name (ex);
12690 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12691
57aff202 12692 if (sym == NULL)
2c4c710f
TT
12693 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12694 sym_name);
57aff202 12695
66d7f48f 12696 if (sym->aclass () != LOC_BLOCK)
57aff202 12697 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
f7f9143b 12698
f17011e0 12699 return find_function_start_sal (sym, 1);
f7f9143b
JB
12700}
12701
b4a5b78b 12702/* Create an Ada exception catchpoint.
f7f9143b 12703
b4a5b78b 12704 EX_KIND is the kind of exception catchpoint to be created.
5845583d 12705
bc18fbb5 12706 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
2df4d1d5 12707 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
bc18fbb5 12708 of the exception to which this catchpoint applies.
2df4d1d5 12709
bc18fbb5 12710 COND_STRING, if not empty, is the catchpoint condition.
f7f9143b 12711
b4a5b78b
JB
12712 TEMPFLAG, if nonzero, means that the underlying breakpoint
12713 should be temporary.
28010a5d 12714
b4a5b78b 12715 FROM_TTY is the usual argument passed to all commands implementations. */
28010a5d 12716
349774ef 12717void
28010a5d 12718create_ada_exception_catchpoint (struct gdbarch *gdbarch,
761269c8 12719 enum ada_exception_catchpoint_kind ex_kind,
898db0f7 12720 std::string &&excep_string,
56ecd069 12721 const std::string &cond_string,
28010a5d 12722 int tempflag,
12d67b37 12723 int enabled,
28010a5d
PA
12724 int from_tty)
12725{
bd21b6c9 12726 std::unique_ptr<ada_catchpoint> c
2c4c710f
TT
12727 (new ada_catchpoint (gdbarch, ex_kind,
12728 cond_string.empty () ? nullptr : cond_string.c_str (),
898db0f7
TT
12729 tempflag, enabled, from_tty,
12730 std::move (excep_string)));
b270e6f9 12731 install_breakpoint (0, std::move (c), 1);
f7f9143b
JB
12732}
12733
9ac4176b
PA
12734/* Implement the "catch exception" command. */
12735
12736static void
eb4c3f4a 12737catch_ada_exception_command (const char *arg_entry, int from_tty,
9ac4176b
PA
12738 struct cmd_list_element *command)
12739{
a121b7c1 12740 const char *arg = arg_entry;
9ac4176b
PA
12741 struct gdbarch *gdbarch = get_current_arch ();
12742 int tempflag;
761269c8 12743 enum ada_exception_catchpoint_kind ex_kind;
bc18fbb5 12744 std::string excep_string;
56ecd069 12745 std::string cond_string;
9ac4176b 12746
0f8e2034 12747 tempflag = command->context () == CATCH_TEMPORARY;
9ac4176b
PA
12748
12749 if (!arg)
12750 arg = "";
9f757bf7 12751 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
bc18fbb5 12752 &cond_string);
9f757bf7 12753 create_ada_exception_catchpoint (gdbarch, ex_kind,
898db0f7 12754 std::move (excep_string), cond_string,
9f757bf7
XR
12755 tempflag, 1 /* enabled */,
12756 from_tty);
12757}
12758
12759/* Implement the "catch handlers" command. */
12760
12761static void
12762catch_ada_handlers_command (const char *arg_entry, int from_tty,
12763 struct cmd_list_element *command)
12764{
12765 const char *arg = arg_entry;
12766 struct gdbarch *gdbarch = get_current_arch ();
12767 int tempflag;
12768 enum ada_exception_catchpoint_kind ex_kind;
bc18fbb5 12769 std::string excep_string;
56ecd069 12770 std::string cond_string;
9f757bf7 12771
0f8e2034 12772 tempflag = command->context () == CATCH_TEMPORARY;
9f757bf7
XR
12773
12774 if (!arg)
12775 arg = "";
12776 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
bc18fbb5 12777 &cond_string);
b4a5b78b 12778 create_ada_exception_catchpoint (gdbarch, ex_kind,
898db0f7 12779 std::move (excep_string), cond_string,
349774ef
JB
12780 tempflag, 1 /* enabled */,
12781 from_tty);
9ac4176b
PA
12782}
12783
71bed2db
TT
12784/* Completion function for the Ada "catch" commands. */
12785
12786static void
12787catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12788 const char *text, const char *word)
12789{
12790 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12791
12792 for (const ada_exc_info &info : exceptions)
12793 {
12794 if (startswith (info.name, word))
b02f78f9 12795 tracker.add_completion (make_unique_xstrdup (info.name));
71bed2db
TT
12796 }
12797}
12798
b4a5b78b 12799/* Split the arguments specified in a "catch assert" command.
5845583d 12800
b4a5b78b
JB
12801 ARGS contains the command's arguments (or the empty string if
12802 no arguments were passed).
5845583d
JB
12803
12804 If ARGS contains a condition, set COND_STRING to that condition
b4a5b78b 12805 (the memory needs to be deallocated after use). */
5845583d 12806
b4a5b78b 12807static void
56ecd069 12808catch_ada_assert_command_split (const char *args, std::string &cond_string)
f7f9143b 12809{
f1735a53 12810 args = skip_spaces (args);
f7f9143b 12811
5845583d 12812 /* Check whether a condition was provided. */
61012eef 12813 if (startswith (args, "if")
5845583d 12814 && (isspace (args[2]) || args[2] == '\0'))
f7f9143b 12815 {
5845583d 12816 args += 2;
f1735a53 12817 args = skip_spaces (args);
5845583d 12818 if (args[0] == '\0')
dda83cd7 12819 error (_("condition missing after `if' keyword"));
56ecd069 12820 cond_string.assign (args);
f7f9143b
JB
12821 }
12822
5845583d
JB
12823 /* Otherwise, there should be no other argument at the end of
12824 the command. */
12825 else if (args[0] != '\0')
12826 error (_("Junk at end of arguments."));
f7f9143b
JB
12827}
12828
9ac4176b
PA
12829/* Implement the "catch assert" command. */
12830
12831static void
eb4c3f4a 12832catch_assert_command (const char *arg_entry, int from_tty,
9ac4176b
PA
12833 struct cmd_list_element *command)
12834{
a121b7c1 12835 const char *arg = arg_entry;
9ac4176b
PA
12836 struct gdbarch *gdbarch = get_current_arch ();
12837 int tempflag;
56ecd069 12838 std::string cond_string;
9ac4176b 12839
0f8e2034 12840 tempflag = command->context () == CATCH_TEMPORARY;
9ac4176b
PA
12841
12842 if (!arg)
12843 arg = "";
56ecd069 12844 catch_ada_assert_command_split (arg, cond_string);
761269c8 12845 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
898db0f7 12846 {}, cond_string,
349774ef
JB
12847 tempflag, 1 /* enabled */,
12848 from_tty);
9ac4176b 12849}
778865d3
JB
12850
12851/* Return non-zero if the symbol SYM is an Ada exception object. */
12852
12853static int
12854ada_is_exception_sym (struct symbol *sym)
12855{
5f9c5a63 12856 const char *type_name = sym->type ()->name ();
778865d3 12857
66d7f48f
SM
12858 return (sym->aclass () != LOC_TYPEDEF
12859 && sym->aclass () != LOC_BLOCK
12860 && sym->aclass () != LOC_CONST
12861 && sym->aclass () != LOC_UNRESOLVED
dda83cd7 12862 && type_name != NULL && strcmp (type_name, "exception") == 0);
778865d3
JB
12863}
12864
12865/* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12866 Ada exception object. This matches all exceptions except the ones
12867 defined by the Ada language. */
12868
12869static int
12870ada_is_non_standard_exception_sym (struct symbol *sym)
12871{
778865d3
JB
12872 if (!ada_is_exception_sym (sym))
12873 return 0;
12874
696d6f4d
TT
12875 for (const char *name : standard_exc)
12876 if (strcmp (sym->linkage_name (), name) == 0)
778865d3
JB
12877 return 0; /* A standard exception. */
12878
12879 /* Numeric_Error is also a standard exception, so exclude it.
12880 See the STANDARD_EXC description for more details as to why
12881 this exception is not listed in that array. */
987012b8 12882 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
778865d3
JB
12883 return 0;
12884
12885 return 1;
12886}
12887
ab816a27 12888/* A helper function for std::sort, comparing two struct ada_exc_info
778865d3
JB
12889 objects.
12890
12891 The comparison is determined first by exception name, and then
12892 by exception address. */
12893
ab816a27 12894bool
cc536b21 12895ada_exc_info::operator< (const ada_exc_info &other) const
778865d3 12896{
778865d3
JB
12897 int result;
12898
ab816a27
TT
12899 result = strcmp (name, other.name);
12900 if (result < 0)
12901 return true;
12902 if (result == 0 && addr < other.addr)
12903 return true;
12904 return false;
12905}
778865d3 12906
ab816a27 12907bool
cc536b21 12908ada_exc_info::operator== (const ada_exc_info &other) const
ab816a27
TT
12909{
12910 return addr == other.addr && strcmp (name, other.name) == 0;
778865d3
JB
12911}
12912
12913/* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12914 routine, but keeping the first SKIP elements untouched.
12915
12916 All duplicates are also removed. */
12917
12918static void
ab816a27 12919sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
778865d3
JB
12920 int skip)
12921{
ab816a27
TT
12922 std::sort (exceptions->begin () + skip, exceptions->end ());
12923 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12924 exceptions->end ());
778865d3
JB
12925}
12926
778865d3
JB
12927/* Add all exceptions defined by the Ada standard whose name match
12928 a regular expression.
12929
12930 If PREG is not NULL, then this regexp_t object is used to
12931 perform the symbol name matching. Otherwise, no name-based
12932 filtering is performed.
12933
12934 EXCEPTIONS is a vector of exceptions to which matching exceptions
12935 gets pushed. */
12936
12937static void
2d7cc5c7 12938ada_add_standard_exceptions (compiled_regex *preg,
ab816a27 12939 std::vector<ada_exc_info> *exceptions)
778865d3 12940{
696d6f4d 12941 for (const char *name : standard_exc)
778865d3 12942 {
696d6f4d 12943 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
778865d3 12944 {
4326580d
MM
12945 symbol_name_match_type match_type = name_match_type_from_name (name);
12946 lookup_name_info lookup_name (name, match_type);
778865d3 12947
4326580d
MM
12948 symbol_name_matcher_ftype *match_name
12949 = ada_get_symbol_name_matcher (lookup_name);
778865d3 12950
4326580d
MM
12951 /* Iterate over all objfiles irrespective of scope or linker
12952 namespaces so we get all exceptions anywhere in the
12953 progspace. */
12954 for (objfile *objfile : current_program_space->objfiles ())
12955 {
12956 for (minimal_symbol *msymbol : objfile->msymbols ())
12957 {
12958 if (match_name (msymbol->linkage_name (), lookup_name,
12959 nullptr)
12960 && msymbol->type () != mst_solib_trampoline)
12961 {
12962 ada_exc_info info
12963 = {name, msymbol->value_address (objfile)};
12964
12965 exceptions->push_back (info);
12966 }
12967 }
778865d3
JB
12968 }
12969 }
12970 }
12971}
12972
12973/* Add all Ada exceptions defined locally and accessible from the given
12974 FRAME.
12975
12976 If PREG is not NULL, then this regexp_t object is used to
12977 perform the symbol name matching. Otherwise, no name-based
12978 filtering is performed.
12979
12980 EXCEPTIONS is a vector of exceptions to which matching exceptions
12981 gets pushed. */
12982
12983static void
2d7cc5c7 12984ada_add_exceptions_from_frame (compiled_regex *preg,
bd2b40ac 12985 frame_info_ptr frame,
ab816a27 12986 std::vector<ada_exc_info> *exceptions)
778865d3 12987{
3977b71f 12988 const struct block *block = get_frame_block (frame, 0);
778865d3
JB
12989
12990 while (block != 0)
12991 {
548a89df 12992 for (struct symbol *sym : block_iterator_range (block))
778865d3 12993 {
66d7f48f 12994 switch (sym->aclass ())
778865d3
JB
12995 {
12996 case LOC_TYPEDEF:
12997 case LOC_BLOCK:
12998 case LOC_CONST:
12999 break;
13000 default:
13001 if (ada_is_exception_sym (sym))
13002 {
987012b8 13003 struct ada_exc_info info = {sym->print_name (),
4aeddc50 13004 sym->value_address ()};
778865d3 13005
ab816a27 13006 exceptions->push_back (info);
778865d3
JB
13007 }
13008 }
13009 }
6c00f721 13010 if (block->function () != NULL)
778865d3 13011 break;
f135fe72 13012 block = block->superblock ();
778865d3
JB
13013 }
13014}
13015
14bc53a8
PA
13016/* Return true if NAME matches PREG or if PREG is NULL. */
13017
13018static bool
2d7cc5c7 13019name_matches_regex (const char *name, compiled_regex *preg)
14bc53a8
PA
13020{
13021 return (preg == NULL
f945dedf 13022 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
14bc53a8
PA
13023}
13024
778865d3
JB
13025/* Add all exceptions defined globally whose name name match
13026 a regular expression, excluding standard exceptions.
13027
13028 The reason we exclude standard exceptions is that they need
13029 to be handled separately: Standard exceptions are defined inside
13030 a runtime unit which is normally not compiled with debugging info,
13031 and thus usually do not show up in our symbol search. However,
13032 if the unit was in fact built with debugging info, we need to
13033 exclude them because they would duplicate the entry we found
13034 during the special loop that specifically searches for those
13035 standard exceptions.
13036
13037 If PREG is not NULL, then this regexp_t object is used to
13038 perform the symbol name matching. Otherwise, no name-based
13039 filtering is performed.
13040
13041 EXCEPTIONS is a vector of exceptions to which matching exceptions
13042 gets pushed. */
13043
13044static void
2d7cc5c7 13045ada_add_global_exceptions (compiled_regex *preg,
ab816a27 13046 std::vector<ada_exc_info> *exceptions)
778865d3 13047{
14bc53a8
PA
13048 /* In Ada, the symbol "search name" is a linkage name, whereas the
13049 regular expression used to do the matching refers to the natural
13050 name. So match against the decoded name. */
13051 expand_symtabs_matching (NULL,
b5ec771e 13052 lookup_name_info::match_any (),
14bc53a8
PA
13053 [&] (const char *search_name)
13054 {
f945dedf
CB
13055 std::string decoded = ada_decode (search_name);
13056 return name_matches_regex (decoded.c_str (), preg);
14bc53a8
PA
13057 },
13058 NULL,
03a8ea51 13059 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
14bc53a8 13060 VARIABLES_DOMAIN);
778865d3 13061
4326580d
MM
13062 /* Iterate over all objfiles irrespective of scope or linker namespaces
13063 so we get all exceptions anywhere in the progspace. */
2030c079 13064 for (objfile *objfile : current_program_space->objfiles ())
778865d3 13065 {
b669c953 13066 for (compunit_symtab *s : objfile->compunits ())
778865d3 13067 {
af39c5c8 13068 const struct blockvector *bv = s->blockvector ();
d8aeb77f 13069 int i;
778865d3 13070
d8aeb77f
TT
13071 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13072 {
63d609de 13073 const struct block *b = bv->block (i);
778865d3 13074
548a89df 13075 for (struct symbol *sym : block_iterator_range (b))
d8aeb77f 13076 if (ada_is_non_standard_exception_sym (sym)
987012b8 13077 && name_matches_regex (sym->natural_name (), preg))
d8aeb77f
TT
13078 {
13079 struct ada_exc_info info
4aeddc50 13080 = {sym->print_name (), sym->value_address ()};
d8aeb77f
TT
13081
13082 exceptions->push_back (info);
13083 }
13084 }
778865d3
JB
13085 }
13086 }
13087}
13088
13089/* Implements ada_exceptions_list with the regular expression passed
13090 as a regex_t, rather than a string.
13091
13092 If not NULL, PREG is used to filter out exceptions whose names
13093 do not match. Otherwise, all exceptions are listed. */
13094
ab816a27 13095static std::vector<ada_exc_info>
2d7cc5c7 13096ada_exceptions_list_1 (compiled_regex *preg)
778865d3 13097{
ab816a27 13098 std::vector<ada_exc_info> result;
778865d3
JB
13099 int prev_len;
13100
13101 /* First, list the known standard exceptions. These exceptions
13102 need to be handled separately, as they are usually defined in
13103 runtime units that have been compiled without debugging info. */
13104
13105 ada_add_standard_exceptions (preg, &result);
13106
13107 /* Next, find all exceptions whose scope is local and accessible
13108 from the currently selected frame. */
13109
13110 if (has_stack_frames ())
13111 {
ab816a27 13112 prev_len = result.size ();
778865d3
JB
13113 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13114 &result);
ab816a27 13115 if (result.size () > prev_len)
778865d3
JB
13116 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13117 }
13118
13119 /* Add all exceptions whose scope is global. */
13120
ab816a27 13121 prev_len = result.size ();
778865d3 13122 ada_add_global_exceptions (preg, &result);
ab816a27 13123 if (result.size () > prev_len)
778865d3
JB
13124 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13125
778865d3
JB
13126 return result;
13127}
13128
13129/* Return a vector of ada_exc_info.
13130
13131 If REGEXP is NULL, all exceptions are included in the result.
13132 Otherwise, it should contain a valid regular expression,
13133 and only the exceptions whose names match that regular expression
13134 are included in the result.
13135
13136 The exceptions are sorted in the following order:
13137 - Standard exceptions (defined by the Ada language), in
13138 alphabetical order;
13139 - Exceptions only visible from the current frame, in
13140 alphabetical order;
13141 - Exceptions whose scope is global, in alphabetical order. */
13142
ab816a27 13143std::vector<ada_exc_info>
778865d3
JB
13144ada_exceptions_list (const char *regexp)
13145{
2d7cc5c7
PA
13146 if (regexp == NULL)
13147 return ada_exceptions_list_1 (NULL);
778865d3 13148
2d7cc5c7
PA
13149 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13150 return ada_exceptions_list_1 (&reg);
778865d3
JB
13151}
13152
13153/* Implement the "info exceptions" command. */
13154
13155static void
1d12d88f 13156info_exceptions_command (const char *regexp, int from_tty)
778865d3 13157{
778865d3 13158 struct gdbarch *gdbarch = get_current_arch ();
778865d3 13159
ab816a27 13160 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
778865d3
JB
13161
13162 if (regexp != NULL)
6cb06a8c 13163 gdb_printf
778865d3
JB
13164 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13165 else
6cb06a8c 13166 gdb_printf (_("All defined Ada exceptions:\n"));
778865d3 13167
ab816a27 13168 for (const ada_exc_info &info : exceptions)
6cb06a8c 13169 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
778865d3
JB
13170}
13171
6c038f32
PH
13172\f
13173 /* Language vector */
13174
b5ec771e
PA
13175/* symbol_name_matcher_ftype adapter for wild_match. */
13176
13177static bool
13178do_wild_match (const char *symbol_search_name,
13179 const lookup_name_info &lookup_name,
a207cff2 13180 completion_match_result *comp_match_res)
b5ec771e
PA
13181{
13182 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13183}
13184
13185/* symbol_name_matcher_ftype adapter for full_match. */
13186
13187static bool
13188do_full_match (const char *symbol_search_name,
13189 const lookup_name_info &lookup_name,
a207cff2 13190 completion_match_result *comp_match_res)
b5ec771e 13191{
959d6a67
TT
13192 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13193
13194 /* If both symbols start with "_ada_", just let the loop below
13195 handle the comparison. However, if only the symbol name starts
13196 with "_ada_", skip the prefix and let the match proceed as
13197 usual. */
13198 if (startswith (symbol_search_name, "_ada_")
13199 && !startswith (lname, "_ada"))
86b44259 13200 symbol_search_name += 5;
81eaa506
TT
13201 /* Likewise for ghost entities. */
13202 if (startswith (symbol_search_name, "___ghost_")
13203 && !startswith (lname, "___ghost_"))
13204 symbol_search_name += 9;
86b44259 13205
86b44259
TT
13206 int uscore_count = 0;
13207 while (*lname != '\0')
13208 {
13209 if (*symbol_search_name != *lname)
13210 {
13211 if (*symbol_search_name == 'B' && uscore_count == 2
13212 && symbol_search_name[1] == '_')
13213 {
13214 symbol_search_name += 2;
13215 while (isdigit (*symbol_search_name))
13216 ++symbol_search_name;
13217 if (symbol_search_name[0] == '_'
13218 && symbol_search_name[1] == '_')
13219 {
13220 symbol_search_name += 2;
13221 continue;
13222 }
13223 }
13224 return false;
13225 }
13226
13227 if (*symbol_search_name == '_')
13228 ++uscore_count;
13229 else
13230 uscore_count = 0;
13231
13232 ++symbol_search_name;
13233 ++lname;
13234 }
13235
13236 return is_name_suffix (symbol_search_name);
b5ec771e
PA
13237}
13238
a2cd4f14
JB
13239/* symbol_name_matcher_ftype for exact (verbatim) matches. */
13240
13241static bool
13242do_exact_match (const char *symbol_search_name,
13243 const lookup_name_info &lookup_name,
13244 completion_match_result *comp_match_res)
13245{
13246 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13247}
13248
b5ec771e
PA
13249/* Build the Ada lookup name for LOOKUP_NAME. */
13250
13251ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13252{
e0802d59 13253 gdb::string_view user_name = lookup_name.name ();
b5ec771e 13254
6a780b67 13255 if (!user_name.empty () && user_name[0] == '<')
b5ec771e
PA
13256 {
13257 if (user_name.back () == '>')
e0802d59 13258 m_encoded_name
5ac58899 13259 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
b5ec771e 13260 else
e0802d59 13261 m_encoded_name
5ac58899 13262 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
b5ec771e
PA
13263 m_encoded_p = true;
13264 m_verbatim_p = true;
13265 m_wild_match_p = false;
13266 m_standard_p = false;
13267 }
13268 else
13269 {
13270 m_verbatim_p = false;
13271
e0802d59 13272 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
b5ec771e
PA
13273
13274 if (!m_encoded_p)
13275 {
e0802d59 13276 const char *folded = ada_fold_name (user_name);
5c4258f4
TT
13277 m_encoded_name = ada_encode_1 (folded, false);
13278 if (m_encoded_name.empty ())
5ac58899 13279 m_encoded_name = gdb::to_string (user_name);
b5ec771e
PA
13280 }
13281 else
5ac58899 13282 m_encoded_name = gdb::to_string (user_name);
b5ec771e
PA
13283
13284 /* Handle the 'package Standard' special case. See description
13285 of m_standard_p. */
13286 if (startswith (m_encoded_name.c_str (), "standard__"))
13287 {
13288 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13289 m_standard_p = true;
13290 }
13291 else
13292 m_standard_p = false;
74ccd7f5 13293
b5ec771e
PA
13294 /* If the name contains a ".", then the user is entering a fully
13295 qualified entity name, and the match must not be done in wild
13296 mode. Similarly, if the user wants to complete what looks
13297 like an encoded name, the match must not be done in wild
13298 mode. Also, in the standard__ special case always do
13299 non-wild matching. */
13300 m_wild_match_p
13301 = (lookup_name.match_type () != symbol_name_match_type::FULL
13302 && !m_encoded_p
13303 && !m_standard_p
13304 && user_name.find ('.') == std::string::npos);
13305 }
13306}
13307
13308/* symbol_name_matcher_ftype method for Ada. This only handles
13309 completion mode. */
13310
13311static bool
13312ada_symbol_name_matches (const char *symbol_search_name,
13313 const lookup_name_info &lookup_name,
a207cff2 13314 completion_match_result *comp_match_res)
74ccd7f5 13315{
b5ec771e
PA
13316 return lookup_name.ada ().matches (symbol_search_name,
13317 lookup_name.match_type (),
a207cff2 13318 comp_match_res);
b5ec771e
PA
13319}
13320
de63c46b
PA
13321/* A name matcher that matches the symbol name exactly, with
13322 strcmp. */
13323
13324static bool
13325literal_symbol_name_matcher (const char *symbol_search_name,
13326 const lookup_name_info &lookup_name,
13327 completion_match_result *comp_match_res)
13328{
e0802d59 13329 gdb::string_view name_view = lookup_name.name ();
de63c46b 13330
e0802d59
TT
13331 if (lookup_name.completion_mode ()
13332 ? (strncmp (symbol_search_name, name_view.data (),
13333 name_view.size ()) == 0)
13334 : symbol_search_name == name_view)
de63c46b
PA
13335 {
13336 if (comp_match_res != NULL)
13337 comp_match_res->set_match (symbol_search_name);
13338 return true;
13339 }
13340 else
13341 return false;
13342}
13343
c9debfb9 13344/* Implement the "get_symbol_name_matcher" language_defn method for
b5ec771e
PA
13345 Ada. */
13346
13347static symbol_name_matcher_ftype *
13348ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13349{
de63c46b
PA
13350 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13351 return literal_symbol_name_matcher;
13352
b5ec771e
PA
13353 if (lookup_name.completion_mode ())
13354 return ada_symbol_name_matches;
74ccd7f5 13355 else
b5ec771e
PA
13356 {
13357 if (lookup_name.ada ().wild_match_p ())
13358 return do_wild_match;
a2cd4f14
JB
13359 else if (lookup_name.ada ().verbatim_p ())
13360 return do_exact_match;
b5ec771e
PA
13361 else
13362 return do_full_match;
13363 }
74ccd7f5
JB
13364}
13365
0874fd07
AB
13366/* Class representing the Ada language. */
13367
13368class ada_language : public language_defn
13369{
13370public:
13371 ada_language ()
0e25e767 13372 : language_defn (language_ada)
0874fd07 13373 { /* Nothing. */ }
5bd40f2a 13374
6f7664a9
AB
13375 /* See language.h. */
13376
13377 const char *name () const override
13378 { return "ada"; }
13379
13380 /* See language.h. */
13381
13382 const char *natural_name () const override
13383 { return "Ada"; }
13384
e171d6f1
AB
13385 /* See language.h. */
13386
13387 const std::vector<const char *> &filename_extensions () const override
13388 {
13389 static const std::vector<const char *> extensions
13390 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13391 return extensions;
13392 }
13393
5bd40f2a
AB
13394 /* Print an array element index using the Ada syntax. */
13395
13396 void print_array_index (struct type *index_type,
13397 LONGEST index,
13398 struct ui_file *stream,
13399 const value_print_options *options) const override
13400 {
13401 struct value *index_value = val_atr (index_type, index);
13402
00c696a6 13403 value_print (index_value, stream, options);
6cb06a8c 13404 gdb_printf (stream, " => ");
5bd40f2a 13405 }
15e5fd35
AB
13406
13407 /* Implement the "read_var_value" language_defn method for Ada. */
13408
13409 struct value *read_var_value (struct symbol *var,
13410 const struct block *var_block,
bd2b40ac 13411 frame_info_ptr frame) const override
15e5fd35
AB
13412 {
13413 /* The only case where default_read_var_value is not sufficient
13414 is when VAR is a renaming... */
13415 if (frame != nullptr)
13416 {
13417 const struct block *frame_block = get_frame_block (frame, NULL);
13418 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13419 return ada_read_renaming_var_value (var, frame_block);
13420 }
13421
13422 /* This is a typical case where we expect the default_read_var_value
13423 function to work. */
13424 return language_defn::read_var_value (var, var_block, frame);
13425 }
1fb314aa 13426
2c71f639 13427 /* See language.h. */
496feb16 13428 bool symbol_printing_suppressed (struct symbol *symbol) const override
2c71f639 13429 {
496feb16 13430 return symbol->is_artificial ();
2c71f639
TV
13431 }
13432
baab3753
AB
13433 /* See language.h. */
13434 struct value *value_string (struct gdbarch *gdbarch,
13435 const char *ptr, ssize_t len) const override
13436 {
13437 struct type *type = language_string_char_type (this, gdbarch);
13438 value *val = ::value_string (ptr, len, type);
13439 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13440 strings that are arrays of characters, so fix the type now. */
13441 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13442 val->type ()->set_code (TYPE_CODE_ARRAY);
13443 return val;
13444 }
13445
1fb314aa
AB
13446 /* See language.h. */
13447 void language_arch_info (struct gdbarch *gdbarch,
13448 struct language_arch_info *lai) const override
13449 {
13450 const struct builtin_type *builtin = builtin_type (gdbarch);
13451
7bea47f0
AB
13452 /* Helper function to allow shorter lines below. */
13453 auto add = [&] (struct type *t)
13454 {
13455 lai->add_primitive_type (t);
13456 };
13457
cc495054 13458 type_allocator alloc (gdbarch);
2d39ccd3 13459 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0 13460 0, "integer"));
2d39ccd3 13461 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
7bea47f0 13462 0, "long_integer"));
2d39ccd3 13463 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
7bea47f0 13464 0, "short_integer"));
f50b437c 13465 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
c9f66f00 13466 1, "character");
7bea47f0
AB
13467 lai->set_string_char_type (char_type);
13468 add (char_type);
f50b437c
TT
13469 add (init_character_type (alloc, 16, 1, "wide_character"));
13470 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
77c5f496 13471 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
7bea47f0 13472 "float", gdbarch_float_format (gdbarch)));
77c5f496 13473 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
7bea47f0 13474 "long_float", gdbarch_double_format (gdbarch)));
2d39ccd3 13475 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
7bea47f0 13476 0, "long_long_integer"));
e49831ba
TT
13477 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13478 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
77c5f496 13479 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
7bea47f0
AB
13480 "long_long_float",
13481 gdbarch_long_double_format (gdbarch)));
2d39ccd3 13482 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0 13483 0, "natural"));
2d39ccd3 13484 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0
AB
13485 0, "positive"));
13486 add (builtin->builtin_void);
13487
13488 struct type *system_addr_ptr
cc495054
TT
13489 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13490 "void"));
7bea47f0
AB
13491 system_addr_ptr->set_name ("system__address");
13492 add (system_addr_ptr);
1fb314aa
AB
13493
13494 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13495 type. This is a signed integral type whose size is the same as
13496 the size of addresses. */
df86565b 13497 unsigned int addr_length = system_addr_ptr->length ();
2d39ccd3 13498 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
7bea47f0 13499 "storage_offset"));
1fb314aa 13500
7bea47f0 13501 lai->set_bool_type (builtin->builtin_bool);
1fb314aa 13502 }
4009ee92
AB
13503
13504 /* See language.h. */
13505
13506 bool iterate_over_symbols
13507 (const struct block *block, const lookup_name_info &name,
13508 domain_enum domain,
13509 gdb::function_view<symbol_found_callback_ftype> callback) const override
13510 {
d1183b06
TT
13511 std::vector<struct block_symbol> results
13512 = ada_lookup_symbol_list_worker (name, block, domain, 0);
4009ee92
AB
13513 for (block_symbol &sym : results)
13514 {
13515 if (!callback (&sym))
13516 return false;
13517 }
13518
13519 return true;
13520 }
6f827019
AB
13521
13522 /* See language.h. */
3456e70c
TT
13523 bool sniff_from_mangled_name
13524 (const char *mangled,
13525 gdb::unique_xmalloc_ptr<char> *out) const override
6f827019
AB
13526 {
13527 std::string demangled = ada_decode (mangled);
13528
13529 *out = NULL;
13530
13531 if (demangled != mangled && demangled[0] != '<')
13532 {
13533 /* Set the gsymbol language to Ada, but still return 0.
13534 Two reasons for that:
13535
13536 1. For Ada, we prefer computing the symbol's decoded name
13537 on the fly rather than pre-compute it, in order to save
13538 memory (Ada projects are typically very large).
13539
13540 2. There are some areas in the definition of the GNAT
13541 encoding where, with a bit of bad luck, we might be able
13542 to decode a non-Ada symbol, generating an incorrect
13543 demangled name (Eg: names ending with "TB" for instance
13544 are identified as task bodies and so stripped from
13545 the decoded name returned).
13546
13547 Returning true, here, but not setting *DEMANGLED, helps us get
13548 a little bit of the best of both worlds. Because we're last,
13549 we should not affect any of the other languages that were
13550 able to demangle the symbol before us; we get to correctly
13551 tag Ada symbols as such; and even if we incorrectly tagged a
13552 non-Ada symbol, which should be rare, any routing through the
13553 Ada language should be transparent (Ada tries to behave much
13554 like C/C++ with non-Ada symbols). */
13555 return true;
13556 }
13557
13558 return false;
13559 }
fbfb0a46
AB
13560
13561 /* See language.h. */
13562
3456e70c
TT
13563 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13564 int options) const override
0a50df5d 13565 {
3456e70c 13566 return make_unique_xstrdup (ada_decode (mangled).c_str ());
0a50df5d
AB
13567 }
13568
13569 /* See language.h. */
13570
fbfb0a46
AB
13571 void print_type (struct type *type, const char *varstring,
13572 struct ui_file *stream, int show, int level,
13573 const struct type_print_options *flags) const override
13574 {
13575 ada_print_type (type, varstring, stream, show, level, flags);
13576 }
c9debfb9 13577
53fc67f8
AB
13578 /* See language.h. */
13579
13580 const char *word_break_characters (void) const override
13581 {
13582 return ada_completer_word_break_characters;
13583 }
13584
7e56227d
AB
13585 /* See language.h. */
13586
13587 void collect_symbol_completion_matches (completion_tracker &tracker,
13588 complete_symbol_mode mode,
13589 symbol_name_match_type name_match_type,
13590 const char *text, const char *word,
13591 enum type_code code) const override
13592 {
7e56227d 13593 const struct block *b, *surrounding_static_block = 0;
7e56227d
AB
13594
13595 gdb_assert (code == TYPE_CODE_UNDEF);
13596
13597 lookup_name_info lookup_name (text, name_match_type, true);
13598
13599 /* First, look at the partial symtab symbols. */
13600 expand_symtabs_matching (NULL,
13601 lookup_name,
13602 NULL,
13603 NULL,
03a8ea51 13604 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
7e56227d
AB
13605 ALL_DOMAIN);
13606
13607 /* At this point scan through the misc symbol vectors and add each
13608 symbol you find to the list. Eventually we want to ignore
13609 anything that isn't a text symbol (everything else will be
13610 handled by the psymtab code above). */
13611
13612 for (objfile *objfile : current_program_space->objfiles ())
13613 {
13614 for (minimal_symbol *msymbol : objfile->msymbols ())
13615 {
13616 QUIT;
13617
13618 if (completion_skip_symbol (mode, msymbol))
13619 continue;
13620
13621 language symbol_language = msymbol->language ();
13622
13623 /* Ada minimal symbols won't have their language set to Ada. If
13624 we let completion_list_add_name compare using the
13625 default/C-like matcher, then when completing e.g., symbols in a
13626 package named "pck", we'd match internal Ada symbols like
13627 "pckS", which are invalid in an Ada expression, unless you wrap
13628 them in '<' '>' to request a verbatim match.
13629
13630 Unfortunately, some Ada encoded names successfully demangle as
13631 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13632 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13633 with the wrong language set. Paper over that issue here. */
129bce36 13634 if (symbol_language == language_unknown
7e56227d
AB
13635 || symbol_language == language_cplus)
13636 symbol_language = language_ada;
13637
13638 completion_list_add_name (tracker,
13639 symbol_language,
13640 msymbol->linkage_name (),
13641 lookup_name, text, word);
13642 }
13643 }
13644
13645 /* Search upwards from currently selected frame (so that we can
13646 complete on local vars. */
13647
f135fe72 13648 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
7e56227d 13649 {
f135fe72 13650 if (!b->superblock ())
7e56227d
AB
13651 surrounding_static_block = b; /* For elmin of dups */
13652
548a89df 13653 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13654 {
13655 if (completion_skip_symbol (mode, sym))
13656 continue;
13657
13658 completion_list_add_name (tracker,
13659 sym->language (),
13660 sym->linkage_name (),
13661 lookup_name, text, word);
13662 }
13663 }
13664
13665 /* Go through the symtabs and check the externs and statics for
13666 symbols which match. */
13667
13668 for (objfile *objfile : current_program_space->objfiles ())
13669 {
13670 for (compunit_symtab *s : objfile->compunits ())
13671 {
13672 QUIT;
63d609de 13673 b = s->blockvector ()->global_block ();
548a89df 13674 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13675 {
13676 if (completion_skip_symbol (mode, sym))
13677 continue;
13678
13679 completion_list_add_name (tracker,
13680 sym->language (),
13681 sym->linkage_name (),
13682 lookup_name, text, word);
13683 }
13684 }
13685 }
13686
13687 for (objfile *objfile : current_program_space->objfiles ())
13688 {
13689 for (compunit_symtab *s : objfile->compunits ())
13690 {
13691 QUIT;
63d609de 13692 b = s->blockvector ()->static_block ();
7e56227d
AB
13693 /* Don't do this block twice. */
13694 if (b == surrounding_static_block)
13695 continue;
548a89df 13696 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13697 {
13698 if (completion_skip_symbol (mode, sym))
13699 continue;
13700
13701 completion_list_add_name (tracker,
13702 sym->language (),
13703 sym->linkage_name (),
13704 lookup_name, text, word);
13705 }
13706 }
13707 }
13708 }
13709
f16a9f57
AB
13710 /* See language.h. */
13711
13712 gdb::unique_xmalloc_ptr<char> watch_location_expression
13713 (struct type *type, CORE_ADDR addr) const override
13714 {
27710edb 13715 type = check_typedef (check_typedef (type)->target_type ());
f16a9f57 13716 std::string name = type_to_string (type);
8579fd13 13717 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
f16a9f57
AB
13718 }
13719
a1d1fa3e
AB
13720 /* See language.h. */
13721
13722 void value_print (struct value *val, struct ui_file *stream,
13723 const struct value_print_options *options) const override
13724 {
13725 return ada_value_print (val, stream, options);
13726 }
13727
ebe2334e
AB
13728 /* See language.h. */
13729
13730 void value_print_inner
13731 (struct value *val, struct ui_file *stream, int recurse,
13732 const struct value_print_options *options) const override
13733 {
13734 return ada_value_print_inner (val, stream, recurse, options);
13735 }
13736
a78a19b1
AB
13737 /* See language.h. */
13738
13739 struct block_symbol lookup_symbol_nonlocal
13740 (const char *name, const struct block *block,
13741 const domain_enum domain) const override
13742 {
13743 struct block_symbol sym;
13744
78004096
TT
13745 sym = ada_lookup_symbol (name,
13746 (block == nullptr
13747 ? nullptr
d24e14a0 13748 : block->static_block ()),
78004096 13749 domain);
a78a19b1
AB
13750 if (sym.symbol != NULL)
13751 return sym;
13752
13753 /* If we haven't found a match at this point, try the primitive
13754 types. In other languages, this search is performed before
13755 searching for global symbols in order to short-circuit that
13756 global-symbol search if it happens that the name corresponds
13757 to a primitive type. But we cannot do the same in Ada, because
13758 it is perfectly legitimate for a program to declare a type which
13759 has the same name as a standard type. If looking up a type in
13760 that situation, we have traditionally ignored the primitive type
13761 in favor of user-defined types. This is why, unlike most other
13762 languages, we search the primitive types this late and only after
13763 having searched the global symbols without success. */
13764
13765 if (domain == VAR_DOMAIN)
13766 {
13767 struct gdbarch *gdbarch;
13768
13769 if (block == NULL)
99d9c3b9 13770 gdbarch = current_inferior ()->arch ();
a78a19b1 13771 else
7f5937df 13772 gdbarch = block->gdbarch ();
a78a19b1
AB
13773 sym.symbol
13774 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13775 if (sym.symbol != NULL)
13776 return sym;
13777 }
13778
13779 return {};
13780 }
13781
87afa652
AB
13782 /* See language.h. */
13783
13784 int parser (struct parser_state *ps) const override
13785 {
13786 warnings_issued = 0;
13787 return ada_parse (ps);
13788 }
13789
ec8cec5b
AB
13790 /* See language.h. */
13791
13792 void emitchar (int ch, struct type *chtype,
13793 struct ui_file *stream, int quoter) const override
13794 {
13795 ada_emit_char (ch, chtype, stream, quoter, 1);
13796 }
13797
52b50f2c
AB
13798 /* See language.h. */
13799
13800 void printchar (int ch, struct type *chtype,
13801 struct ui_file *stream) const override
13802 {
13803 ada_printchar (ch, chtype, stream);
13804 }
13805
d711ee67
AB
13806 /* See language.h. */
13807
13808 void printstr (struct ui_file *stream, struct type *elttype,
13809 const gdb_byte *string, unsigned int length,
13810 const char *encoding, int force_ellipses,
13811 const struct value_print_options *options) const override
13812 {
13813 ada_printstr (stream, elttype, string, length, encoding,
13814 force_ellipses, options);
13815 }
13816
4ffc13fb
AB
13817 /* See language.h. */
13818
13819 void print_typedef (struct type *type, struct symbol *new_symbol,
13820 struct ui_file *stream) const override
13821 {
13822 ada_print_typedef (type, new_symbol, stream);
13823 }
13824
39e7ecca
AB
13825 /* See language.h. */
13826
13827 bool is_string_type_p (struct type *type) const override
13828 {
13829 return ada_is_string_type (type);
13830 }
13831
22e3f3ed
AB
13832 /* See language.h. */
13833
26733fc7
TT
13834 bool is_array_like (struct type *type) const override
13835 {
13836 return (ada_is_constrained_packed_array_type (type)
13837 || ada_is_array_descriptor_type (type));
13838 }
13839
13840 /* See language.h. */
13841
13842 struct value *to_array (struct value *val) const override
13843 { return ada_coerce_to_simple_array (val); }
13844
13845 /* See language.h. */
13846
22e3f3ed
AB
13847 const char *struct_too_deep_ellipsis () const override
13848 { return "(...)"; }
39e7ecca 13849
67bd3fd5
AB
13850 /* See language.h. */
13851
13852 bool c_style_arrays_p () const override
13853 { return false; }
13854
d3355e4d
AB
13855 /* See language.h. */
13856
13857 bool store_sym_names_in_linkage_form_p () const override
13858 { return true; }
13859
b63a3f3f
AB
13860 /* See language.h. */
13861
13862 const struct lang_varobj_ops *varobj_ops () const override
13863 { return &ada_varobj_ops; }
13864
c9debfb9
AB
13865protected:
13866 /* See language.h. */
13867
13868 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13869 (const lookup_name_info &lookup_name) const override
13870 {
13871 return ada_get_symbol_name_matcher (lookup_name);
13872 }
0874fd07
AB
13873};
13874
13875/* Single instance of the Ada language class. */
13876
13877static ada_language ada_language_defn;
13878
5bf03f13
JB
13879/* Command-list for the "set/show ada" prefix command. */
13880static struct cmd_list_element *set_ada_list;
13881static struct cmd_list_element *show_ada_list;
13882
3d9434b5
JB
13883/* This module's 'new_objfile' observer. */
13884
13885static void
13886ada_new_objfile_observer (struct objfile *objfile)
13887{
74daa597 13888 ada_clear_symbol_cache (objfile->pspace);
3d9434b5
JB
13889}
13890
13891/* This module's 'free_objfile' observer. */
13892
13893static void
13894ada_free_objfile_observer (struct objfile *objfile)
13895{
74daa597 13896 ada_clear_symbol_cache (objfile->pspace);
3d9434b5
JB
13897}
13898
315e4ebb
TT
13899/* Charsets known to GNAT. */
13900static const char * const gnat_source_charsets[] =
13901{
13902 /* Note that code below assumes that the default comes first.
13903 Latin-1 is the default here, because that is also GNAT's
13904 default. */
13905 "ISO-8859-1",
13906 "ISO-8859-2",
13907 "ISO-8859-3",
13908 "ISO-8859-4",
13909 "ISO-8859-5",
13910 "ISO-8859-15",
13911 "CP437",
13912 "CP850",
13913 /* Note that this value is special-cased in the encoder and
13914 decoder. */
13915 ada_utf8,
13916 nullptr
13917};
13918
6c265988 13919void _initialize_ada_language ();
d2e4a39e 13920void
6c265988 13921_initialize_ada_language ()
14f9c5c9 13922{
f54bdb6d
SM
13923 add_setshow_prefix_cmd
13924 ("ada", no_class,
13925 _("Prefix command for changing Ada-specific settings."),
13926 _("Generic command for showing Ada-specific settings."),
13927 &set_ada_list, &show_ada_list,
13928 &setlist, &showlist);
5bf03f13
JB
13929
13930 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
dda83cd7 13931 &trust_pad_over_xvs, _("\
590042fc
PW
13932Enable or disable an optimization trusting PAD types over XVS types."), _("\
13933Show whether an optimization trusting PAD types over XVS types is activated."),
dda83cd7 13934 _("\
5bf03f13
JB
13935This is related to the encoding used by the GNAT compiler. The debugger\n\
13936should normally trust the contents of PAD types, but certain older versions\n\
13937of GNAT have a bug that sometimes causes the information in the PAD type\n\
13938to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13939work around this bug. It is always safe to turn this option \"off\", but\n\
13940this incurs a slight performance penalty, so it is recommended to NOT change\n\
13941this option to \"off\" unless necessary."),
dda83cd7 13942 NULL, NULL, &set_ada_list, &show_ada_list);
5bf03f13 13943
d72413e6
PMR
13944 add_setshow_boolean_cmd ("print-signatures", class_vars,
13945 &print_signatures, _("\
13946Enable or disable the output of formal and return types for functions in the \
590042fc 13947overloads selection menu."), _("\
d72413e6 13948Show whether the output of formal and return types for functions in the \
590042fc 13949overloads selection menu is activated."),
d72413e6
PMR
13950 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13951
315e4ebb
TT
13952 ada_source_charset = gnat_source_charsets[0];
13953 add_setshow_enum_cmd ("source-charset", class_files,
13954 gnat_source_charsets,
13955 &ada_source_charset, _("\
13956Set the Ada source character set."), _("\
13957Show the Ada source character set."), _("\
13958The character set used for Ada source files.\n\
13959This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13960 nullptr, nullptr,
13961 &set_ada_list, &show_ada_list);
13962
9ac4176b
PA
13963 add_catch_command ("exception", _("\
13964Catch Ada exceptions, when raised.\n\
9bf7038b 13965Usage: catch exception [ARG] [if CONDITION]\n\
60a90376
JB
13966Without any argument, stop when any Ada exception is raised.\n\
13967If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13968being raised does not have a handler (and will therefore lead to the task's\n\
13969termination).\n\
13970Otherwise, the catchpoint only stops when the name of the exception being\n\
9bf7038b
TT
13971raised is the same as ARG.\n\
13972CONDITION is a boolean expression that is evaluated to see whether the\n\
13973exception should cause a stop."),
9ac4176b 13974 catch_ada_exception_command,
71bed2db 13975 catch_ada_completer,
9ac4176b
PA
13976 CATCH_PERMANENT,
13977 CATCH_TEMPORARY);
9f757bf7
XR
13978
13979 add_catch_command ("handlers", _("\
13980Catch Ada exceptions, when handled.\n\
9bf7038b
TT
13981Usage: catch handlers [ARG] [if CONDITION]\n\
13982Without any argument, stop when any Ada exception is handled.\n\
13983With an argument, catch only exceptions with the given name.\n\
13984CONDITION is a boolean expression that is evaluated to see whether the\n\
13985exception should cause a stop."),
9f757bf7 13986 catch_ada_handlers_command,
dda83cd7 13987 catch_ada_completer,
9f757bf7
XR
13988 CATCH_PERMANENT,
13989 CATCH_TEMPORARY);
9ac4176b
PA
13990 add_catch_command ("assert", _("\
13991Catch failed Ada assertions, when raised.\n\
9bf7038b
TT
13992Usage: catch assert [if CONDITION]\n\
13993CONDITION is a boolean expression that is evaluated to see whether the\n\
13994exception should cause a stop."),
9ac4176b 13995 catch_assert_command,
dda83cd7 13996 NULL,
9ac4176b
PA
13997 CATCH_PERMANENT,
13998 CATCH_TEMPORARY);
13999
778865d3
JB
14000 add_info ("exceptions", info_exceptions_command,
14001 _("\
14002List all Ada exception names.\n\
9bf7038b 14003Usage: info exceptions [REGEXP]\n\
778865d3
JB
14004If a regular expression is passed as an argument, only those matching\n\
14005the regular expression are listed."));
14006
f54bdb6d
SM
14007 add_setshow_prefix_cmd ("ada", class_maintenance,
14008 _("Set Ada maintenance-related variables."),
14009 _("Show Ada maintenance-related variables."),
14010 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14011 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
c6044dd1
JB
14012
14013 add_setshow_boolean_cmd
14014 ("ignore-descriptive-types", class_maintenance,
14015 &ada_ignore_descriptive_types_p,
14016 _("Set whether descriptive types generated by GNAT should be ignored."),
14017 _("Show whether descriptive types generated by GNAT should be ignored."),
14018 _("\
14019When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14020DWARF attribute."),
14021 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14022
2698f5ea
TT
14023 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14024 htab_eq_string,
459a2e4c 14025 NULL, xcalloc, xfree);
6b69afc4 14026
3d9434b5 14027 /* The ada-lang observers. */
c90e7d63 14028 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
74daa597
SM
14029 gdb::observers::all_objfiles_removed.attach (ada_clear_symbol_cache,
14030 "ada-lang");
c90e7d63
SM
14031 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14032 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
033bc52b
TT
14033
14034#ifdef GDB_SELF_TEST
14035 selftests::register_test ("ada-decode", ada_decode_tests);
14036#endif
14f9c5c9 14037}