]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/ada-lang.c
gdb: move set_target_gdbarch to inferior::set_arch
[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
MM
4916 gdbarch_iterate_over_objfiles_in_search_order
4917 (objfile != NULL ? objfile->arch () : target_gdbarch (),
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),
6451 target_gdbarch(), "storage_offset");
6452 ptr_type = lookup_pointer_type (offset_type);
b50d69b5
JG
6453 val = value_cast (ptr_type, tag);
6454 if (!val)
6455 return obj;
6456
6457 /* It is perfectly possible that an exception be raised while
6458 trying to determine the base address, just like for the tag;
6459 see ada_tag_name for more details. We do not print the error
6460 message for the same reason. */
6461
a70b8144 6462 try
b50d69b5
JG
6463 {
6464 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6465 }
6466
230d2906 6467 catch (const gdb_exception_error &e)
492d29ea
PA
6468 {
6469 return obj;
6470 }
b50d69b5
JG
6471
6472 /* If offset is null, nothing to do. */
6473
6474 if (offset_to_top == 0)
6475 return obj;
6476
6477 /* -1 is a special case in Ada.Tags; however, what should be done
6478 is not quite clear from the documentation. So do nothing for
6479 now. */
6480
6481 if (offset_to_top == -1)
6482 return obj;
6483
d537777d
TT
6484 /* Storage_Offset'Last is used to indicate that a dynamic offset to
6485 top is used. In this situation the offset is stored just after
6486 the tag, in the object itself. */
df86565b 6487 ULONGEST last = (((ULONGEST) 1) << (8 * offset_type->length () - 1)) - 1;
d537777d
TT
6488 if (offset_to_top == last)
6489 {
6490 struct value *tem = value_addr (tag);
6491 tem = value_ptradd (tem, 1);
6492 tem = value_cast (ptr_type, tem);
6493 offset_to_top = value_as_long (value_ind (tem));
6494 }
05527d8c
TV
6495
6496 if (offset_to_top > 0)
d537777d
TT
6497 {
6498 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6499 from the base address. This was however incompatible with
6500 C++ dispatch table: C++ uses a *negative* value to *add*
6501 to the base address. Ada's convention has therefore been
6502 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6503 use the same convention. Here, we support both cases by
6504 checking the sign of OFFSET_TO_TOP. */
6505 offset_to_top = -offset_to_top;
6506 }
08f49010 6507
9feb2d07 6508 base_address = obj->address () + offset_to_top;
b50d69b5
JG
6509 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6510
6511 /* Make sure that we have a proper tag at the new address.
6512 Otherwise, offset_to_top is bogus (which can happen when
6513 the object is not initialized yet). */
6514
6515 if (!tag)
6516 return obj;
6517
6518 obj_type = type_from_tag (tag);
6519
6520 if (!obj_type)
6521 return obj;
6522
6523 return value_from_contents_and_address (obj_type, NULL, base_address);
6524}
6525
1b611343
JB
6526/* Return the "ada__tags__type_specific_data" type. */
6527
6528static struct type *
6529ada_get_tsd_type (struct inferior *inf)
963a6417 6530{
1b611343 6531 struct ada_inferior_data *data = get_ada_inferior_data (inf);
4c4b4cd2 6532
1b611343
JB
6533 if (data->tsd_type == 0)
6534 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6535 return data->tsd_type;
6536}
529cad9c 6537
1b611343
JB
6538/* Return the TSD (type-specific data) associated to the given TAG.
6539 TAG is assumed to be the tag of a tagged-type entity.
529cad9c 6540
1b611343 6541 May return NULL if we are unable to get the TSD. */
4c4b4cd2 6542
1b611343
JB
6543static struct value *
6544ada_get_tsd_from_tag (struct value *tag)
4c4b4cd2 6545{
4c4b4cd2 6546 struct value *val;
1b611343 6547 struct type *type;
5b4ee69b 6548
1b611343
JB
6549 /* First option: The TSD is simply stored as a field of our TAG.
6550 Only older versions of GNAT would use this format, but we have
6551 to test it first, because there are no visible markers for
6552 the current approach except the absence of that field. */
529cad9c 6553
1b611343
JB
6554 val = ada_value_struct_elt (tag, "tsd", 1);
6555 if (val)
6556 return val;
e802dbe0 6557
1b611343
JB
6558 /* Try the second representation for the dispatch table (in which
6559 there is no explicit 'tsd' field in the referent of the tag pointer,
6560 and instead the tsd pointer is stored just before the dispatch
6561 table. */
e802dbe0 6562
1b611343
JB
6563 type = ada_get_tsd_type (current_inferior());
6564 if (type == NULL)
6565 return NULL;
6566 type = lookup_pointer_type (lookup_pointer_type (type));
6567 val = value_cast (type, tag);
6568 if (val == NULL)
6569 return NULL;
6570 return value_ind (value_ptradd (val, -1));
e802dbe0
JB
6571}
6572
1b611343
JB
6573/* Given the TSD of a tag (type-specific data), return a string
6574 containing the name of the associated type.
6575
f5272a3b 6576 May return NULL if we are unable to determine the tag name. */
1b611343 6577
f5272a3b 6578static gdb::unique_xmalloc_ptr<char>
1b611343 6579ada_tag_name_from_tsd (struct value *tsd)
529cad9c 6580{
1b611343 6581 struct value *val;
529cad9c 6582
1b611343 6583 val = ada_value_struct_elt (tsd, "expanded_name", 1);
4c4b4cd2 6584 if (val == NULL)
1b611343 6585 return NULL;
66920317
TT
6586 gdb::unique_xmalloc_ptr<char> buffer
6587 = target_read_string (value_as_address (val), INT_MAX);
6588 if (buffer == nullptr)
f5272a3b
TT
6589 return nullptr;
6590
315e4ebb 6591 try
f5272a3b 6592 {
315e4ebb
TT
6593 /* Let this throw an exception on error. If the data is
6594 uninitialized, we'd rather not have the user see a
6595 warning. */
6596 const char *folded = ada_fold_name (buffer.get (), true);
6597 return make_unique_xstrdup (folded);
6598 }
6599 catch (const gdb_exception &)
6600 {
6601 return nullptr;
f5272a3b 6602 }
4c4b4cd2
PH
6603}
6604
6605/* The type name of the dynamic type denoted by the 'tag value TAG, as
1b611343
JB
6606 a C string.
6607
6608 Return NULL if the TAG is not an Ada tag, or if we were unable to
f5272a3b 6609 determine the name of that tag. */
4c4b4cd2 6610
f5272a3b 6611gdb::unique_xmalloc_ptr<char>
4c4b4cd2
PH
6612ada_tag_name (struct value *tag)
6613{
f5272a3b 6614 gdb::unique_xmalloc_ptr<char> name;
5b4ee69b 6615
d0c97917 6616 if (!ada_is_tag_type (tag->type ()))
4c4b4cd2 6617 return NULL;
1b611343
JB
6618
6619 /* It is perfectly possible that an exception be raised while trying
6620 to determine the TAG's name, even under normal circumstances:
6621 The associated variable may be uninitialized or corrupted, for
6622 instance. We do not let any exception propagate past this point.
6623 instead we return NULL.
6624
6625 We also do not print the error message either (which often is very
6626 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6627 the caller print a more meaningful message if necessary. */
a70b8144 6628 try
1b611343
JB
6629 {
6630 struct value *tsd = ada_get_tsd_from_tag (tag);
6631
6632 if (tsd != NULL)
6633 name = ada_tag_name_from_tsd (tsd);
6634 }
230d2906 6635 catch (const gdb_exception_error &e)
492d29ea
PA
6636 {
6637 }
1b611343
JB
6638
6639 return name;
4c4b4cd2
PH
6640}
6641
6642/* The parent type of TYPE, or NULL if none. */
14f9c5c9 6643
d2e4a39e 6644struct type *
ebf56fd3 6645ada_parent_type (struct type *type)
14f9c5c9
AS
6646{
6647 int i;
6648
61ee279c 6649 type = ada_check_typedef (type);
14f9c5c9 6650
78134374 6651 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
14f9c5c9
AS
6652 return NULL;
6653
1f704f76 6654 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 6655 if (ada_is_parent_field (type, i))
0c1f74cf 6656 {
dda83cd7 6657 struct type *parent_type = type->field (i).type ();
0c1f74cf 6658
dda83cd7
SM
6659 /* If the _parent field is a pointer, then dereference it. */
6660 if (parent_type->code () == TYPE_CODE_PTR)
27710edb 6661 parent_type = parent_type->target_type ();
dda83cd7
SM
6662 /* If there is a parallel XVS type, get the actual base type. */
6663 parent_type = ada_get_base_type (parent_type);
0c1f74cf 6664
dda83cd7 6665 return ada_check_typedef (parent_type);
0c1f74cf 6666 }
14f9c5c9
AS
6667
6668 return NULL;
6669}
6670
4c4b4cd2
PH
6671/* True iff field number FIELD_NUM of structure type TYPE contains the
6672 parent-type (inherited) fields of a derived type. Assumes TYPE is
6673 a structure type with at least FIELD_NUM+1 fields. */
14f9c5c9
AS
6674
6675int
ebf56fd3 6676ada_is_parent_field (struct type *type, int field_num)
14f9c5c9 6677{
33d16dd9 6678 const char *name = ada_check_typedef (type)->field (field_num).name ();
5b4ee69b 6679
4c4b4cd2 6680 return (name != NULL
dda83cd7
SM
6681 && (startswith (name, "PARENT")
6682 || startswith (name, "_parent")));
14f9c5c9
AS
6683}
6684
4c4b4cd2 6685/* True iff field number FIELD_NUM of structure type TYPE is a
14f9c5c9 6686 transparent wrapper field (which should be silently traversed when doing
4c4b4cd2 6687 field selection and flattened when printing). Assumes TYPE is a
14f9c5c9 6688 structure type with at least FIELD_NUM+1 fields. Such fields are always
4c4b4cd2 6689 structures. */
14f9c5c9
AS
6690
6691int
ebf56fd3 6692ada_is_wrapper_field (struct type *type, int field_num)
14f9c5c9 6693{
33d16dd9 6694 const char *name = type->field (field_num).name ();
5b4ee69b 6695
dddc0e16
JB
6696 if (name != NULL && strcmp (name, "RETVAL") == 0)
6697 {
6698 /* This happens in functions with "out" or "in out" parameters
6699 which are passed by copy. For such functions, GNAT describes
6700 the function's return type as being a struct where the return
6701 value is in a field called RETVAL, and where the other "out"
6702 or "in out" parameters are fields of that struct. This is not
6703 a wrapper. */
6704 return 0;
6705 }
6706
d2e4a39e 6707 return (name != NULL
dda83cd7
SM
6708 && (startswith (name, "PARENT")
6709 || strcmp (name, "REP") == 0
6710 || startswith (name, "_parent")
6711 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
14f9c5c9
AS
6712}
6713
4c4b4cd2
PH
6714/* True iff field number FIELD_NUM of structure or union type TYPE
6715 is a variant wrapper. Assumes TYPE is a structure type with at least
6716 FIELD_NUM+1 fields. */
14f9c5c9
AS
6717
6718int
ebf56fd3 6719ada_is_variant_part (struct type *type, int field_num)
14f9c5c9 6720{
8ecb59f8
TT
6721 /* Only Ada types are eligible. */
6722 if (!ADA_TYPE_P (type))
6723 return 0;
6724
940da03e 6725 struct type *field_type = type->field (field_num).type ();
5b4ee69b 6726
78134374
SM
6727 return (field_type->code () == TYPE_CODE_UNION
6728 || (is_dynamic_field (type, field_num)
27710edb 6729 && (field_type->target_type ()->code ()
c3e5cd34 6730 == TYPE_CODE_UNION)));
14f9c5c9
AS
6731}
6732
6733/* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
4c4b4cd2 6734 whose discriminants are contained in the record type OUTER_TYPE,
7c964f07
UW
6735 returns the type of the controlling discriminant for the variant.
6736 May return NULL if the type could not be found. */
14f9c5c9 6737
d2e4a39e 6738struct type *
ebf56fd3 6739ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
14f9c5c9 6740{
a121b7c1 6741 const char *name = ada_variant_discrim_name (var_type);
5b4ee69b 6742
988f6b3d 6743 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
14f9c5c9
AS
6744}
6745
4c4b4cd2 6746/* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
14f9c5c9 6747 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
4c4b4cd2 6748 represents a 'when others' clause; otherwise 0. */
14f9c5c9 6749
de93309a 6750static int
ebf56fd3 6751ada_is_others_clause (struct type *type, int field_num)
14f9c5c9 6752{
33d16dd9 6753 const char *name = type->field (field_num).name ();
5b4ee69b 6754
14f9c5c9
AS
6755 return (name != NULL && name[0] == 'O');
6756}
6757
6758/* Assuming that TYPE0 is the type of the variant part of a record,
4c4b4cd2
PH
6759 returns the name of the discriminant controlling the variant.
6760 The value is valid until the next call to ada_variant_discrim_name. */
14f9c5c9 6761
a121b7c1 6762const char *
ebf56fd3 6763ada_variant_discrim_name (struct type *type0)
14f9c5c9 6764{
5f9febe0 6765 static std::string result;
d2e4a39e
AS
6766 struct type *type;
6767 const char *name;
6768 const char *discrim_end;
6769 const char *discrim_start;
14f9c5c9 6770
78134374 6771 if (type0->code () == TYPE_CODE_PTR)
27710edb 6772 type = type0->target_type ();
14f9c5c9
AS
6773 else
6774 type = type0;
6775
6776 name = ada_type_name (type);
6777
6778 if (name == NULL || name[0] == '\000')
6779 return "";
6780
6781 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
6782 discrim_end -= 1)
6783 {
61012eef 6784 if (startswith (discrim_end, "___XVN"))
dda83cd7 6785 break;
14f9c5c9
AS
6786 }
6787 if (discrim_end == name)
6788 return "";
6789
d2e4a39e 6790 for (discrim_start = discrim_end; discrim_start != name + 3;
14f9c5c9
AS
6791 discrim_start -= 1)
6792 {
d2e4a39e 6793 if (discrim_start == name + 1)
dda83cd7 6794 return "";
76a01679 6795 if ((discrim_start > name + 3
dda83cd7
SM
6796 && startswith (discrim_start - 3, "___"))
6797 || discrim_start[-1] == '.')
6798 break;
14f9c5c9
AS
6799 }
6800
5f9febe0
TT
6801 result = std::string (discrim_start, discrim_end - discrim_start);
6802 return result.c_str ();
14f9c5c9
AS
6803}
6804
4c4b4cd2
PH
6805/* Scan STR for a subtype-encoded number, beginning at position K.
6806 Put the position of the character just past the number scanned in
6807 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
6808 Return 1 if there was a valid number at the given position, and 0
6809 otherwise. A "subtype-encoded" number consists of the absolute value
6810 in decimal, followed by the letter 'm' to indicate a negative number.
6811 Assumes 0m does not occur. */
14f9c5c9
AS
6812
6813int
d2e4a39e 6814ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
14f9c5c9
AS
6815{
6816 ULONGEST RU;
6817
d2e4a39e 6818 if (!isdigit (str[k]))
14f9c5c9
AS
6819 return 0;
6820
4c4b4cd2 6821 /* Do it the hard way so as not to make any assumption about
14f9c5c9 6822 the relationship of unsigned long (%lu scan format code) and
4c4b4cd2 6823 LONGEST. */
14f9c5c9
AS
6824 RU = 0;
6825 while (isdigit (str[k]))
6826 {
d2e4a39e 6827 RU = RU * 10 + (str[k] - '0');
14f9c5c9
AS
6828 k += 1;
6829 }
6830
d2e4a39e 6831 if (str[k] == 'm')
14f9c5c9
AS
6832 {
6833 if (R != NULL)
dda83cd7 6834 *R = (-(LONGEST) (RU - 1)) - 1;
14f9c5c9
AS
6835 k += 1;
6836 }
6837 else if (R != NULL)
6838 *R = (LONGEST) RU;
6839
4c4b4cd2 6840 /* NOTE on the above: Technically, C does not say what the results of
14f9c5c9
AS
6841 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
6842 number representable as a LONGEST (although either would probably work
6843 in most implementations). When RU>0, the locution in the then branch
4c4b4cd2 6844 above is always equivalent to the negative of RU. */
14f9c5c9
AS
6845
6846 if (new_k != NULL)
6847 *new_k = k;
6848 return 1;
6849}
6850
4c4b4cd2
PH
6851/* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
6852 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
6853 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
14f9c5c9 6854
de93309a 6855static int
ebf56fd3 6856ada_in_variant (LONGEST val, struct type *type, int field_num)
14f9c5c9 6857{
33d16dd9 6858 const char *name = type->field (field_num).name ();
14f9c5c9
AS
6859 int p;
6860
6861 p = 0;
6862 while (1)
6863 {
d2e4a39e 6864 switch (name[p])
dda83cd7
SM
6865 {
6866 case '\0':
6867 return 0;
6868 case 'S':
6869 {
6870 LONGEST W;
6871
6872 if (!ada_scan_number (name, p + 1, &W, &p))
6873 return 0;
6874 if (val == W)
6875 return 1;
6876 break;
6877 }
6878 case 'R':
6879 {
6880 LONGEST L, U;
6881
6882 if (!ada_scan_number (name, p + 1, &L, &p)
6883 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
6884 return 0;
6885 if (val >= L && val <= U)
6886 return 1;
6887 break;
6888 }
6889 case 'O':
6890 return 1;
6891 default:
6892 return 0;
6893 }
4c4b4cd2
PH
6894 }
6895}
6896
0963b4bd 6897/* FIXME: Lots of redundancy below. Try to consolidate. */
4c4b4cd2
PH
6898
6899/* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
6900 ARG_TYPE, extract and return the value of one of its (non-static)
6901 fields. FIELDNO says which field. Differs from value_primitive_field
6902 only in that it can handle packed values of arbitrary type. */
14f9c5c9 6903
5eb68a39 6904struct value *
d2e4a39e 6905ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
dda83cd7 6906 struct type *arg_type)
14f9c5c9 6907{
14f9c5c9
AS
6908 struct type *type;
6909
61ee279c 6910 arg_type = ada_check_typedef (arg_type);
940da03e 6911 type = arg_type->field (fieldno).type ();
14f9c5c9 6912
4504bbde
TT
6913 /* Handle packed fields. It might be that the field is not packed
6914 relative to its containing structure, but the structure itself is
6915 packed; in this case we must take the bit-field path. */
3757d2d4 6916 if (arg_type->field (fieldno).bitsize () != 0 || arg1->bitpos () != 0)
14f9c5c9 6917 {
b610c045 6918 int bit_pos = arg_type->field (fieldno).loc_bitpos ();
3757d2d4 6919 int bit_size = arg_type->field (fieldno).bitsize ();
d2e4a39e 6920
50888e42 6921 return ada_value_primitive_packed_val (arg1,
efaf1ae0 6922 arg1->contents ().data (),
dda83cd7
SM
6923 offset + bit_pos / 8,
6924 bit_pos % 8, bit_size, type);
14f9c5c9
AS
6925 }
6926 else
6c49729e 6927 return arg1->primitive_field (offset, fieldno, arg_type);
14f9c5c9
AS
6928}
6929
52ce6436
PH
6930/* Find field with name NAME in object of type TYPE. If found,
6931 set the following for each argument that is non-null:
6932 - *FIELD_TYPE_P to the field's type;
6933 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
6934 an object of that type;
6935 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
6936 - *BIT_SIZE_P to its size in bits if the field is packed, and
6937 0 otherwise;
6938 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
6939 fields up to but not including the desired field, or by the total
6940 number of fields if not found. A NULL value of NAME never
6941 matches; the function just counts visible fields in this case.
6942
828d5846
XR
6943 Notice that we need to handle when a tagged record hierarchy
6944 has some components with the same name, like in this scenario:
6945
6946 type Top_T is tagged record
dda83cd7
SM
6947 N : Integer := 1;
6948 U : Integer := 974;
6949 A : Integer := 48;
828d5846
XR
6950 end record;
6951
6952 type Middle_T is new Top.Top_T with record
dda83cd7
SM
6953 N : Character := 'a';
6954 C : Integer := 3;
828d5846
XR
6955 end record;
6956
6957 type Bottom_T is new Middle.Middle_T with record
dda83cd7
SM
6958 N : Float := 4.0;
6959 C : Character := '5';
6960 X : Integer := 6;
6961 A : Character := 'J';
828d5846
XR
6962 end record;
6963
6964 Let's say we now have a variable declared and initialized as follow:
6965
6966 TC : Top_A := new Bottom_T;
6967
6968 And then we use this variable to call this function
6969
6970 procedure Assign (Obj: in out Top_T; TV : Integer);
6971
6972 as follow:
6973
6974 Assign (Top_T (B), 12);
6975
6976 Now, we're in the debugger, and we're inside that procedure
6977 then and we want to print the value of obj.c:
6978
6979 Usually, the tagged record or one of the parent type owns the
6980 component to print and there's no issue but in this particular
6981 case, what does it mean to ask for Obj.C? Since the actual
6982 type for object is type Bottom_T, it could mean two things: type
6983 component C from the Middle_T view, but also component C from
6984 Bottom_T. So in that "undefined" case, when the component is
6985 not found in the non-resolved type (which includes all the
6986 components of the parent type), then resolve it and see if we
6987 get better luck once expanded.
6988
6989 In the case of homonyms in the derived tagged type, we don't
6990 guaranty anything, and pick the one that's easiest for us
6991 to program.
6992
0963b4bd 6993 Returns 1 if found, 0 otherwise. */
52ce6436 6994
4c4b4cd2 6995static int
0d5cff50 6996find_struct_field (const char *name, struct type *type, int offset,
dda83cd7
SM
6997 struct type **field_type_p,
6998 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
52ce6436 6999 int *index_p)
4c4b4cd2
PH
7000{
7001 int i;
828d5846 7002 int parent_offset = -1;
4c4b4cd2 7003
61ee279c 7004 type = ada_check_typedef (type);
76a01679 7005
52ce6436
PH
7006 if (field_type_p != NULL)
7007 *field_type_p = NULL;
7008 if (byte_offset_p != NULL)
d5d6fca5 7009 *byte_offset_p = 0;
52ce6436
PH
7010 if (bit_offset_p != NULL)
7011 *bit_offset_p = 0;
7012 if (bit_size_p != NULL)
7013 *bit_size_p = 0;
7014
1f704f76 7015 for (i = 0; i < type->num_fields (); i += 1)
4c4b4cd2 7016 {
4d1795ac
TT
7017 /* These can't be computed using TYPE_FIELD_BITPOS for a dynamic
7018 type. However, we only need the values to be correct when
7019 the caller asks for them. */
7020 int bit_pos = 0, fld_offset = 0;
7021 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7022 {
b610c045 7023 bit_pos = type->field (i).loc_bitpos ();
4d1795ac
TT
7024 fld_offset = offset + bit_pos / 8;
7025 }
7026
33d16dd9 7027 const char *t_field_name = type->field (i).name ();
76a01679 7028
4c4b4cd2 7029 if (t_field_name == NULL)
dda83cd7 7030 continue;
4c4b4cd2 7031
828d5846 7032 else if (ada_is_parent_field (type, i))
dda83cd7 7033 {
828d5846
XR
7034 /* This is a field pointing us to the parent type of a tagged
7035 type. As hinted in this function's documentation, we give
7036 preference to fields in the current record first, so what
7037 we do here is just record the index of this field before
7038 we skip it. If it turns out we couldn't find our field
7039 in the current record, then we'll get back to it and search
7040 inside it whether the field might exist in the parent. */
7041
dda83cd7
SM
7042 parent_offset = i;
7043 continue;
7044 }
828d5846 7045
52ce6436 7046 else if (name != NULL && field_name_match (t_field_name, name))
dda83cd7 7047 {
3757d2d4 7048 int bit_size = type->field (i).bitsize ();
5b4ee69b 7049
52ce6436 7050 if (field_type_p != NULL)
940da03e 7051 *field_type_p = type->field (i).type ();
52ce6436
PH
7052 if (byte_offset_p != NULL)
7053 *byte_offset_p = fld_offset;
7054 if (bit_offset_p != NULL)
7055 *bit_offset_p = bit_pos % 8;
7056 if (bit_size_p != NULL)
7057 *bit_size_p = bit_size;
dda83cd7
SM
7058 return 1;
7059 }
4c4b4cd2 7060 else if (ada_is_wrapper_field (type, i))
dda83cd7 7061 {
940da03e 7062 if (find_struct_field (name, type->field (i).type (), fld_offset,
52ce6436
PH
7063 field_type_p, byte_offset_p, bit_offset_p,
7064 bit_size_p, index_p))
dda83cd7
SM
7065 return 1;
7066 }
4c4b4cd2 7067 else if (ada_is_variant_part (type, i))
dda83cd7 7068 {
52ce6436
PH
7069 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7070 fixed type?? */
dda83cd7
SM
7071 int j;
7072 struct type *field_type
940da03e 7073 = ada_check_typedef (type->field (i).type ());
4c4b4cd2 7074
dda83cd7
SM
7075 for (j = 0; j < field_type->num_fields (); j += 1)
7076 {
7077 if (find_struct_field (name, field_type->field (j).type (),
7078 fld_offset
b610c045 7079 + field_type->field (j).loc_bitpos () / 8,
dda83cd7
SM
7080 field_type_p, byte_offset_p,
7081 bit_offset_p, bit_size_p, index_p))
7082 return 1;
7083 }
7084 }
52ce6436
PH
7085 else if (index_p != NULL)
7086 *index_p += 1;
4c4b4cd2 7087 }
828d5846
XR
7088
7089 /* Field not found so far. If this is a tagged type which
7090 has a parent, try finding that field in the parent now. */
7091
7092 if (parent_offset != -1)
7093 {
4d1795ac
TT
7094 /* As above, only compute the offset when truly needed. */
7095 int fld_offset = offset;
7096 if (byte_offset_p != nullptr || bit_offset_p != nullptr)
7097 {
b610c045 7098 int bit_pos = type->field (parent_offset).loc_bitpos ();
4d1795ac
TT
7099 fld_offset += bit_pos / 8;
7100 }
828d5846 7101
940da03e 7102 if (find_struct_field (name, type->field (parent_offset).type (),
dda83cd7
SM
7103 fld_offset, field_type_p, byte_offset_p,
7104 bit_offset_p, bit_size_p, index_p))
7105 return 1;
828d5846
XR
7106 }
7107
4c4b4cd2
PH
7108 return 0;
7109}
7110
0963b4bd 7111/* Number of user-visible fields in record type TYPE. */
4c4b4cd2 7112
52ce6436
PH
7113static int
7114num_visible_fields (struct type *type)
7115{
7116 int n;
5b4ee69b 7117
52ce6436
PH
7118 n = 0;
7119 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7120 return n;
7121}
14f9c5c9 7122
4c4b4cd2 7123/* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
14f9c5c9
AS
7124 and search in it assuming it has (class) type TYPE.
7125 If found, return value, else return NULL.
7126
828d5846
XR
7127 Searches recursively through wrapper fields (e.g., '_parent').
7128
7129 In the case of homonyms in the tagged types, please refer to the
7130 long explanation in find_struct_field's function documentation. */
14f9c5c9 7131
4c4b4cd2 7132static struct value *
108d56a4 7133ada_search_struct_field (const char *name, struct value *arg, int offset,
dda83cd7 7134 struct type *type)
14f9c5c9
AS
7135{
7136 int i;
828d5846 7137 int parent_offset = -1;
14f9c5c9 7138
5b4ee69b 7139 type = ada_check_typedef (type);
1f704f76 7140 for (i = 0; i < type->num_fields (); i += 1)
14f9c5c9 7141 {
33d16dd9 7142 const char *t_field_name = type->field (i).name ();
14f9c5c9
AS
7143
7144 if (t_field_name == NULL)
dda83cd7 7145 continue;
14f9c5c9 7146
828d5846 7147 else if (ada_is_parent_field (type, i))
dda83cd7 7148 {
828d5846
XR
7149 /* This is a field pointing us to the parent type of a tagged
7150 type. As hinted in this function's documentation, we give
7151 preference to fields in the current record first, so what
7152 we do here is just record the index of this field before
7153 we skip it. If it turns out we couldn't find our field
7154 in the current record, then we'll get back to it and search
7155 inside it whether the field might exist in the parent. */
7156
dda83cd7
SM
7157 parent_offset = i;
7158 continue;
7159 }
828d5846 7160
14f9c5c9 7161 else if (field_name_match (t_field_name, name))
dda83cd7 7162 return ada_value_primitive_field (arg, offset, i, type);
14f9c5c9
AS
7163
7164 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7165 {
7166 struct value *v = /* Do not let indent join lines here. */
7167 ada_search_struct_field (name, arg,
b610c045 7168 offset + type->field (i).loc_bitpos () / 8,
dda83cd7 7169 type->field (i).type ());
5b4ee69b 7170
dda83cd7
SM
7171 if (v != NULL)
7172 return v;
7173 }
14f9c5c9
AS
7174
7175 else if (ada_is_variant_part (type, i))
dda83cd7 7176 {
0963b4bd 7177 /* PNH: Do we ever get here? See find_struct_field. */
dda83cd7
SM
7178 int j;
7179 struct type *field_type = ada_check_typedef (type->field (i).type ());
b610c045 7180 int var_offset = offset + type->field (i).loc_bitpos () / 8;
4c4b4cd2 7181
dda83cd7
SM
7182 for (j = 0; j < field_type->num_fields (); j += 1)
7183 {
7184 struct value *v = ada_search_struct_field /* Force line
0963b4bd 7185 break. */
dda83cd7 7186 (name, arg,
b610c045 7187 var_offset + field_type->field (j).loc_bitpos () / 8,
dda83cd7 7188 field_type->field (j).type ());
5b4ee69b 7189
dda83cd7
SM
7190 if (v != NULL)
7191 return v;
7192 }
7193 }
14f9c5c9 7194 }
828d5846
XR
7195
7196 /* Field not found so far. If this is a tagged type which
7197 has a parent, try finding that field in the parent now. */
7198
7199 if (parent_offset != -1)
7200 {
7201 struct value *v = ada_search_struct_field (
b610c045 7202 name, arg, offset + type->field (parent_offset).loc_bitpos () / 8,
940da03e 7203 type->field (parent_offset).type ());
828d5846
XR
7204
7205 if (v != NULL)
dda83cd7 7206 return v;
828d5846
XR
7207 }
7208
14f9c5c9
AS
7209 return NULL;
7210}
d2e4a39e 7211
52ce6436
PH
7212static struct value *ada_index_struct_field_1 (int *, struct value *,
7213 int, struct type *);
7214
7215
7216/* Return field #INDEX in ARG, where the index is that returned by
7217 * find_struct_field through its INDEX_P argument. Adjust the address
7218 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
0963b4bd 7219 * If found, return value, else return NULL. */
52ce6436
PH
7220
7221static struct value *
7222ada_index_struct_field (int index, struct value *arg, int offset,
7223 struct type *type)
7224{
7225 return ada_index_struct_field_1 (&index, arg, offset, type);
7226}
7227
7228
7229/* Auxiliary function for ada_index_struct_field. Like
7230 * ada_index_struct_field, but takes index from *INDEX_P and modifies
0963b4bd 7231 * *INDEX_P. */
52ce6436
PH
7232
7233static struct value *
7234ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7235 struct type *type)
7236{
7237 int i;
7238 type = ada_check_typedef (type);
7239
1f704f76 7240 for (i = 0; i < type->num_fields (); i += 1)
52ce6436 7241 {
33d16dd9 7242 if (type->field (i).name () == NULL)
dda83cd7 7243 continue;
52ce6436 7244 else if (ada_is_wrapper_field (type, i))
dda83cd7
SM
7245 {
7246 struct value *v = /* Do not let indent join lines here. */
7247 ada_index_struct_field_1 (index_p, arg,
b610c045 7248 offset + type->field (i).loc_bitpos () / 8,
940da03e 7249 type->field (i).type ());
5b4ee69b 7250
dda83cd7
SM
7251 if (v != NULL)
7252 return v;
7253 }
52ce6436
PH
7254
7255 else if (ada_is_variant_part (type, i))
dda83cd7 7256 {
52ce6436 7257 /* PNH: Do we ever get here? See ada_search_struct_field,
0963b4bd 7258 find_struct_field. */
52ce6436 7259 error (_("Cannot assign this kind of variant record"));
dda83cd7 7260 }
52ce6436 7261 else if (*index_p == 0)
dda83cd7 7262 return ada_value_primitive_field (arg, offset, i, type);
52ce6436
PH
7263 else
7264 *index_p -= 1;
7265 }
7266 return NULL;
7267}
7268
3b4de39c 7269/* Return a string representation of type TYPE. */
99bbb428 7270
3b4de39c 7271static std::string
99bbb428
PA
7272type_as_string (struct type *type)
7273{
d7e74731 7274 string_file tmp_stream;
99bbb428 7275
d7e74731 7276 type_print (type, "", &tmp_stream, -1);
99bbb428 7277
5d10a204 7278 return tmp_stream.release ();
99bbb428
PA
7279}
7280
14f9c5c9 7281/* Given a type TYPE, look up the type of the component of type named NAME.
14f9c5c9
AS
7282
7283 Matches any field whose name has NAME as a prefix, possibly
4c4b4cd2 7284 followed by "___".
14f9c5c9 7285
0963b4bd 7286 TYPE can be either a struct or union. If REFOK, TYPE may also
4c4b4cd2
PH
7287 be a (pointer or reference)+ to a struct or union, and the
7288 ultimate target type will be searched.
14f9c5c9
AS
7289
7290 Looks recursively into variant clauses and parent types.
7291
828d5846
XR
7292 In the case of homonyms in the tagged types, please refer to the
7293 long explanation in find_struct_field's function documentation.
7294
4c4b4cd2
PH
7295 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7296 TYPE is not a type of the right kind. */
14f9c5c9 7297
4c4b4cd2 7298static struct type *
a121b7c1 7299ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
dda83cd7 7300 int noerr)
14f9c5c9 7301{
14f9c5c9
AS
7302 if (name == NULL)
7303 goto BadName;
7304
76a01679 7305 if (refok && type != NULL)
4c4b4cd2
PH
7306 while (1)
7307 {
dda83cd7
SM
7308 type = ada_check_typedef (type);
7309 if (type->code () != TYPE_CODE_PTR && type->code () != TYPE_CODE_REF)
7310 break;
27710edb 7311 type = type->target_type ();
4c4b4cd2 7312 }
14f9c5c9 7313
76a01679 7314 if (type == NULL
78134374
SM
7315 || (type->code () != TYPE_CODE_STRUCT
7316 && type->code () != TYPE_CODE_UNION))
14f9c5c9 7317 {
4c4b4cd2 7318 if (noerr)
dda83cd7 7319 return NULL;
99bbb428 7320
3b4de39c
PA
7321 error (_("Type %s is not a structure or union type"),
7322 type != NULL ? type_as_string (type).c_str () : _("(null)"));
14f9c5c9
AS
7323 }
7324
7325 type = to_static_fixed_type (type);
7326
f0874f41
TT
7327 struct type *result;
7328 find_struct_field (name, type, 0, &result, nullptr, nullptr, nullptr,
7329 nullptr);
7330 if (result != nullptr)
7331 return result;
828d5846 7332
14f9c5c9 7333BadName:
d2e4a39e 7334 if (!noerr)
14f9c5c9 7335 {
2b2798cc 7336 const char *name_str = name != NULL ? name : _("<null>");
99bbb428
PA
7337
7338 error (_("Type %s has no component named %s"),
3b4de39c 7339 type_as_string (type).c_str (), name_str);
14f9c5c9
AS
7340 }
7341
7342 return NULL;
7343}
7344
b1f33ddd
JB
7345/* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7346 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7347 represents an unchecked union (that is, the variant part of a
0963b4bd 7348 record that is named in an Unchecked_Union pragma). */
b1f33ddd
JB
7349
7350static int
7351is_unchecked_variant (struct type *var_type, struct type *outer_type)
7352{
a121b7c1 7353 const char *discrim_name = ada_variant_discrim_name (var_type);
5b4ee69b 7354
988f6b3d 7355 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
b1f33ddd
JB
7356}
7357
7358
14f9c5c9 7359/* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
d8af9068 7360 within OUTER, determine which variant clause (field number in VAR_TYPE,
4c4b4cd2 7361 numbering from 0) is applicable. Returns -1 if none are. */
14f9c5c9 7362
d2e4a39e 7363int
d8af9068 7364ada_which_variant_applies (struct type *var_type, struct value *outer)
14f9c5c9
AS
7365{
7366 int others_clause;
7367 int i;
a121b7c1 7368 const char *discrim_name = ada_variant_discrim_name (var_type);
0c281816 7369 struct value *discrim;
14f9c5c9
AS
7370 LONGEST discrim_val;
7371
012370f6
TT
7372 /* Using plain value_from_contents_and_address here causes problems
7373 because we will end up trying to resolve a type that is currently
7374 being constructed. */
0c281816
JB
7375 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7376 if (discrim == NULL)
14f9c5c9 7377 return -1;
0c281816 7378 discrim_val = value_as_long (discrim);
14f9c5c9
AS
7379
7380 others_clause = -1;
1f704f76 7381 for (i = 0; i < var_type->num_fields (); i += 1)
14f9c5c9
AS
7382 {
7383 if (ada_is_others_clause (var_type, i))
dda83cd7 7384 others_clause = i;
14f9c5c9 7385 else if (ada_in_variant (discrim_val, var_type, i))
dda83cd7 7386 return i;
14f9c5c9
AS
7387 }
7388
7389 return others_clause;
7390}
d2e4a39e 7391\f
14f9c5c9
AS
7392
7393
dda83cd7 7394 /* Dynamic-Sized Records */
14f9c5c9
AS
7395
7396/* Strategy: The type ostensibly attached to a value with dynamic size
7397 (i.e., a size that is not statically recorded in the debugging
7398 data) does not accurately reflect the size or layout of the value.
7399 Our strategy is to convert these values to values with accurate,
4c4b4cd2 7400 conventional types that are constructed on the fly. */
14f9c5c9
AS
7401
7402/* There is a subtle and tricky problem here. In general, we cannot
7403 determine the size of dynamic records without its data. However,
7404 the 'struct value' data structure, which GDB uses to represent
7405 quantities in the inferior process (the target), requires the size
7406 of the type at the time of its allocation in order to reserve space
7407 for GDB's internal copy of the data. That's why the
7408 'to_fixed_xxx_type' routines take (target) addresses as parameters,
4c4b4cd2 7409 rather than struct value*s.
14f9c5c9
AS
7410
7411 However, GDB's internal history variables ($1, $2, etc.) are
7412 struct value*s containing internal copies of the data that are not, in
7413 general, the same as the data at their corresponding addresses in
7414 the target. Fortunately, the types we give to these values are all
7415 conventional, fixed-size types (as per the strategy described
7416 above), so that we don't usually have to perform the
7417 'to_fixed_xxx_type' conversions to look at their values.
7418 Unfortunately, there is one exception: if one of the internal
7419 history variables is an array whose elements are unconstrained
7420 records, then we will need to create distinct fixed types for each
7421 element selected. */
7422
7423/* The upshot of all of this is that many routines take a (type, host
7424 address, target address) triple as arguments to represent a value.
7425 The host address, if non-null, is supposed to contain an internal
7426 copy of the relevant data; otherwise, the program is to consult the
4c4b4cd2 7427 target at the target address. */
14f9c5c9
AS
7428
7429/* Assuming that VAL0 represents a pointer value, the result of
7430 dereferencing it. Differs from value_ind in its treatment of
4c4b4cd2 7431 dynamic-sized types. */
14f9c5c9 7432
d2e4a39e
AS
7433struct value *
7434ada_value_ind (struct value *val0)
14f9c5c9 7435{
c48db5ca 7436 struct value *val = value_ind (val0);
5b4ee69b 7437
d0c97917 7438 if (ada_is_tagged_type (val->type (), 0))
b50d69b5
JG
7439 val = ada_tag_value_at_base_address (val);
7440
4c4b4cd2 7441 return ada_to_fixed_value (val);
14f9c5c9
AS
7442}
7443
7444/* The value resulting from dereferencing any "reference to"
4c4b4cd2
PH
7445 qualifiers on VAL0. */
7446
d2e4a39e
AS
7447static struct value *
7448ada_coerce_ref (struct value *val0)
7449{
d0c97917 7450 if (val0->type ()->code () == TYPE_CODE_REF)
d2e4a39e
AS
7451 {
7452 struct value *val = val0;
5b4ee69b 7453
994b9211 7454 val = coerce_ref (val);
b50d69b5 7455
d0c97917 7456 if (ada_is_tagged_type (val->type (), 0))
b50d69b5
JG
7457 val = ada_tag_value_at_base_address (val);
7458
4c4b4cd2 7459 return ada_to_fixed_value (val);
d2e4a39e
AS
7460 }
7461 else
14f9c5c9
AS
7462 return val0;
7463}
7464
4c4b4cd2 7465/* Return the bit alignment required for field #F of template type TYPE. */
14f9c5c9
AS
7466
7467static unsigned int
ebf56fd3 7468field_alignment (struct type *type, int f)
14f9c5c9 7469{
33d16dd9 7470 const char *name = type->field (f).name ();
64a1bf19 7471 int len;
14f9c5c9
AS
7472 int align_offset;
7473
64a1bf19
JB
7474 /* The field name should never be null, unless the debugging information
7475 is somehow malformed. In this case, we assume the field does not
7476 require any alignment. */
7477 if (name == NULL)
7478 return 1;
7479
7480 len = strlen (name);
7481
4c4b4cd2
PH
7482 if (!isdigit (name[len - 1]))
7483 return 1;
14f9c5c9 7484
d2e4a39e 7485 if (isdigit (name[len - 2]))
14f9c5c9
AS
7486 align_offset = len - 2;
7487 else
7488 align_offset = len - 1;
7489
61012eef 7490 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
14f9c5c9
AS
7491 return TARGET_CHAR_BIT;
7492
4c4b4cd2
PH
7493 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7494}
7495
852dff6c 7496/* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
4c4b4cd2 7497
852dff6c
JB
7498static struct symbol *
7499ada_find_any_type_symbol (const char *name)
4c4b4cd2
PH
7500{
7501 struct symbol *sym;
7502
7503 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
66d7f48f 7504 if (sym != NULL && sym->aclass () == LOC_TYPEDEF)
4c4b4cd2
PH
7505 return sym;
7506
4186eb54
KS
7507 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7508 return sym;
14f9c5c9
AS
7509}
7510
dddfab26
UW
7511/* Find a type named NAME. Ignores ambiguity. This routine will look
7512 solely for types defined by debug info, it will not search the GDB
7513 primitive types. */
4c4b4cd2 7514
852dff6c 7515static struct type *
ebf56fd3 7516ada_find_any_type (const char *name)
14f9c5c9 7517{
852dff6c 7518 struct symbol *sym = ada_find_any_type_symbol (name);
14f9c5c9 7519
14f9c5c9 7520 if (sym != NULL)
5f9c5a63 7521 return sym->type ();
14f9c5c9 7522
dddfab26 7523 return NULL;
14f9c5c9
AS
7524}
7525
739593e0
JB
7526/* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7527 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7528 symbol, in which case it is returned. Otherwise, this looks for
7529 symbols whose name is that of NAME_SYM suffixed with "___XR".
7530 Return symbol if found, and NULL otherwise. */
4c4b4cd2 7531
c0e70c62
TT
7532static bool
7533ada_is_renaming_symbol (struct symbol *name_sym)
aeb5907d 7534{
987012b8 7535 const char *name = name_sym->linkage_name ();
c0e70c62 7536 return strstr (name, "___XR") != NULL;
4c4b4cd2
PH
7537}
7538
14f9c5c9 7539/* Because of GNAT encoding conventions, several GDB symbols may match a
4c4b4cd2 7540 given type name. If the type denoted by TYPE0 is to be preferred to
14f9c5c9 7541 that of TYPE1 for purposes of type printing, return non-zero;
4c4b4cd2
PH
7542 otherwise return 0. */
7543
14f9c5c9 7544int
d2e4a39e 7545ada_prefer_type (struct type *type0, struct type *type1)
14f9c5c9
AS
7546{
7547 if (type1 == NULL)
7548 return 1;
7549 else if (type0 == NULL)
7550 return 0;
78134374 7551 else if (type1->code () == TYPE_CODE_VOID)
14f9c5c9 7552 return 1;
78134374 7553 else if (type0->code () == TYPE_CODE_VOID)
14f9c5c9 7554 return 0;
7d93a1e0 7555 else if (type1->name () == NULL && type0->name () != NULL)
4c4b4cd2 7556 return 1;
ad82864c 7557 else if (ada_is_constrained_packed_array_type (type0))
14f9c5c9 7558 return 1;
4c4b4cd2 7559 else if (ada_is_array_descriptor_type (type0)
dda83cd7 7560 && !ada_is_array_descriptor_type (type1))
14f9c5c9 7561 return 1;
aeb5907d
JB
7562 else
7563 {
7d93a1e0
SM
7564 const char *type0_name = type0->name ();
7565 const char *type1_name = type1->name ();
aeb5907d
JB
7566
7567 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
7568 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
7569 return 1;
7570 }
14f9c5c9
AS
7571 return 0;
7572}
7573
e86ca25f
TT
7574/* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
7575 null. */
4c4b4cd2 7576
0d5cff50 7577const char *
d2e4a39e 7578ada_type_name (struct type *type)
14f9c5c9 7579{
d2e4a39e 7580 if (type == NULL)
14f9c5c9 7581 return NULL;
7d93a1e0 7582 return type->name ();
14f9c5c9
AS
7583}
7584
b4ba55a1
JB
7585/* Search the list of "descriptive" types associated to TYPE for a type
7586 whose name is NAME. */
7587
7588static struct type *
7589find_parallel_type_by_descriptive_type (struct type *type, const char *name)
7590{
931e5bc3 7591 struct type *result, *tmp;
b4ba55a1 7592
c6044dd1
JB
7593 if (ada_ignore_descriptive_types_p)
7594 return NULL;
7595
b4ba55a1
JB
7596 /* If there no descriptive-type info, then there is no parallel type
7597 to be found. */
7598 if (!HAVE_GNAT_AUX_INFO (type))
7599 return NULL;
7600
7601 result = TYPE_DESCRIPTIVE_TYPE (type);
7602 while (result != NULL)
7603 {
0d5cff50 7604 const char *result_name = ada_type_name (result);
b4ba55a1
JB
7605
7606 if (result_name == NULL)
dda83cd7
SM
7607 {
7608 warning (_("unexpected null name on descriptive type"));
7609 return NULL;
7610 }
b4ba55a1
JB
7611
7612 /* If the names match, stop. */
7613 if (strcmp (result_name, name) == 0)
7614 break;
7615
7616 /* Otherwise, look at the next item on the list, if any. */
7617 if (HAVE_GNAT_AUX_INFO (result))
931e5bc3
JG
7618 tmp = TYPE_DESCRIPTIVE_TYPE (result);
7619 else
7620 tmp = NULL;
7621
7622 /* If not found either, try after having resolved the typedef. */
7623 if (tmp != NULL)
7624 result = tmp;
b4ba55a1 7625 else
931e5bc3 7626 {
f168693b 7627 result = check_typedef (result);
931e5bc3
JG
7628 if (HAVE_GNAT_AUX_INFO (result))
7629 result = TYPE_DESCRIPTIVE_TYPE (result);
7630 else
7631 result = NULL;
7632 }
b4ba55a1
JB
7633 }
7634
7635 /* If we didn't find a match, see whether this is a packed array. With
7636 older compilers, the descriptive type information is either absent or
7637 irrelevant when it comes to packed arrays so the above lookup fails.
7638 Fall back to using a parallel lookup by name in this case. */
12ab9e09 7639 if (result == NULL && ada_is_constrained_packed_array_type (type))
b4ba55a1
JB
7640 return ada_find_any_type (name);
7641
7642 return result;
7643}
7644
7645/* Find a parallel type to TYPE with the specified NAME, using the
7646 descriptive type taken from the debugging information, if available,
7647 and otherwise using the (slower) name-based method. */
7648
7649static struct type *
7650ada_find_parallel_type_with_name (struct type *type, const char *name)
7651{
7652 struct type *result = NULL;
7653
7654 if (HAVE_GNAT_AUX_INFO (type))
7655 result = find_parallel_type_by_descriptive_type (type, name);
7656 else
7657 result = ada_find_any_type (name);
7658
7659 return result;
7660}
7661
7662/* Same as above, but specify the name of the parallel type by appending
4c4b4cd2 7663 SUFFIX to the name of TYPE. */
14f9c5c9 7664
d2e4a39e 7665struct type *
ebf56fd3 7666ada_find_parallel_type (struct type *type, const char *suffix)
14f9c5c9 7667{
0d5cff50 7668 char *name;
fe978cb0 7669 const char *type_name = ada_type_name (type);
14f9c5c9 7670 int len;
d2e4a39e 7671
fe978cb0 7672 if (type_name == NULL)
14f9c5c9
AS
7673 return NULL;
7674
fe978cb0 7675 len = strlen (type_name);
14f9c5c9 7676
b4ba55a1 7677 name = (char *) alloca (len + strlen (suffix) + 1);
14f9c5c9 7678
fe978cb0 7679 strcpy (name, type_name);
14f9c5c9
AS
7680 strcpy (name + len, suffix);
7681
b4ba55a1 7682 return ada_find_parallel_type_with_name (type, name);
14f9c5c9
AS
7683}
7684
14f9c5c9 7685/* If TYPE is a variable-size record type, return the corresponding template
4c4b4cd2 7686 type describing its fields. Otherwise, return NULL. */
14f9c5c9 7687
d2e4a39e
AS
7688static struct type *
7689dynamic_template_type (struct type *type)
14f9c5c9 7690{
61ee279c 7691 type = ada_check_typedef (type);
14f9c5c9 7692
78134374 7693 if (type == NULL || type->code () != TYPE_CODE_STRUCT
d2e4a39e 7694 || ada_type_name (type) == NULL)
14f9c5c9 7695 return NULL;
d2e4a39e 7696 else
14f9c5c9
AS
7697 {
7698 int len = strlen (ada_type_name (type));
5b4ee69b 7699
4c4b4cd2 7700 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
dda83cd7 7701 return type;
14f9c5c9 7702 else
dda83cd7 7703 return ada_find_parallel_type (type, "___XVE");
14f9c5c9
AS
7704 }
7705}
7706
7707/* Assuming that TEMPL_TYPE is a union or struct type, returns
4c4b4cd2 7708 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
14f9c5c9 7709
d2e4a39e
AS
7710static int
7711is_dynamic_field (struct type *templ_type, int field_num)
14f9c5c9 7712{
33d16dd9 7713 const char *name = templ_type->field (field_num).name ();
5b4ee69b 7714
d2e4a39e 7715 return name != NULL
940da03e 7716 && templ_type->field (field_num).type ()->code () == TYPE_CODE_PTR
14f9c5c9
AS
7717 && strstr (name, "___XVL") != NULL;
7718}
7719
4c4b4cd2
PH
7720/* The index of the variant field of TYPE, or -1 if TYPE does not
7721 represent a variant record type. */
14f9c5c9 7722
d2e4a39e 7723static int
4c4b4cd2 7724variant_field_index (struct type *type)
14f9c5c9
AS
7725{
7726 int f;
7727
78134374 7728 if (type == NULL || type->code () != TYPE_CODE_STRUCT)
4c4b4cd2
PH
7729 return -1;
7730
1f704f76 7731 for (f = 0; f < type->num_fields (); f += 1)
4c4b4cd2
PH
7732 {
7733 if (ada_is_variant_part (type, f))
dda83cd7 7734 return f;
4c4b4cd2
PH
7735 }
7736 return -1;
14f9c5c9
AS
7737}
7738
4c4b4cd2
PH
7739/* A record type with no fields. */
7740
d2e4a39e 7741static struct type *
fe978cb0 7742empty_record (struct type *templ)
14f9c5c9 7743{
9fa83a7a 7744 struct type *type = type_allocator (templ).new_type ();
5b4ee69b 7745
67607e24 7746 type->set_code (TYPE_CODE_STRUCT);
8ecb59f8 7747 INIT_NONE_SPECIFIC (type);
d0e39ea2 7748 type->set_name ("<empty>");
b6cdbc9a 7749 type->set_length (0);
14f9c5c9
AS
7750 return type;
7751}
7752
7753/* An ordinary record type (with fixed-length fields) that describes
4c4b4cd2
PH
7754 the value of type TYPE at VALADDR or ADDRESS (see comments at
7755 the beginning of this section) VAL according to GNAT conventions.
7756 DVAL0 should describe the (portion of a) record that contains any
d0c97917 7757 necessary discriminants. It should be NULL if VAL->type () is
14f9c5c9
AS
7758 an outer-level type (i.e., as opposed to a branch of a variant.) A
7759 variant field (unless unchecked) is replaced by a particular branch
4c4b4cd2 7760 of the variant.
14f9c5c9 7761
4c4b4cd2
PH
7762 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
7763 length are not statically known are discarded. As a consequence,
7764 VALADDR, ADDRESS and DVAL0 are ignored.
7765
7766 NOTE: Limitations: For now, we assume that dynamic fields and
7767 variants occupy whole numbers of bytes. However, they need not be
7768 byte-aligned. */
7769
7770struct type *
10a2c479 7771ada_template_to_fixed_record_type_1 (struct type *type,
fc1a4b47 7772 const gdb_byte *valaddr,
dda83cd7
SM
7773 CORE_ADDR address, struct value *dval0,
7774 int keep_dynamic_fields)
14f9c5c9 7775{
d2e4a39e
AS
7776 struct value *dval;
7777 struct type *rtype;
14f9c5c9 7778 int nfields, bit_len;
4c4b4cd2 7779 int variant_field;
14f9c5c9 7780 long off;
d94e4f4f 7781 int fld_bit_len;
14f9c5c9
AS
7782 int f;
7783
65558ca5
TT
7784 scoped_value_mark mark;
7785
4c4b4cd2
PH
7786 /* Compute the number of fields in this record type that are going
7787 to be processed: unless keep_dynamic_fields, this includes only
7788 fields whose position and length are static will be processed. */
7789 if (keep_dynamic_fields)
1f704f76 7790 nfields = type->num_fields ();
4c4b4cd2
PH
7791 else
7792 {
7793 nfields = 0;
1f704f76 7794 while (nfields < type->num_fields ()
dda83cd7
SM
7795 && !ada_is_variant_part (type, nfields)
7796 && !is_dynamic_field (type, nfields))
7797 nfields++;
4c4b4cd2
PH
7798 }
7799
9fa83a7a 7800 rtype = type_allocator (type).new_type ();
67607e24 7801 rtype->set_code (TYPE_CODE_STRUCT);
8ecb59f8 7802 INIT_NONE_SPECIFIC (rtype);
2774f2da 7803 rtype->alloc_fields (nfields);
d0e39ea2 7804 rtype->set_name (ada_type_name (type));
9cdd0d12 7805 rtype->set_is_fixed_instance (true);
14f9c5c9 7806
d2e4a39e
AS
7807 off = 0;
7808 bit_len = 0;
4c4b4cd2
PH
7809 variant_field = -1;
7810
14f9c5c9
AS
7811 for (f = 0; f < nfields; f += 1)
7812 {
a89febbd 7813 off = align_up (off, field_alignment (type, f))
b610c045 7814 + type->field (f).loc_bitpos ();
cd3f655c 7815 rtype->field (f).set_loc_bitpos (off);
886176b8 7816 rtype->field (f).set_bitsize (0);
14f9c5c9 7817
d2e4a39e 7818 if (ada_is_variant_part (type, f))
dda83cd7
SM
7819 {
7820 variant_field = f;
7821 fld_bit_len = 0;
7822 }
14f9c5c9 7823 else if (is_dynamic_field (type, f))
dda83cd7 7824 {
284614f0
JB
7825 const gdb_byte *field_valaddr = valaddr;
7826 CORE_ADDR field_address = address;
27710edb 7827 struct type *field_type = type->field (f).type ()->target_type ();
284614f0 7828
dda83cd7 7829 if (dval0 == NULL)
b5304971 7830 {
012370f6
TT
7831 /* Using plain value_from_contents_and_address here
7832 causes problems because we will end up trying to
7833 resolve a type that is currently being
7834 constructed. */
7835 dval = value_from_contents_and_address_unresolved (rtype,
7836 valaddr,
7837 address);
d0c97917 7838 rtype = dval->type ();
b5304971 7839 }
dda83cd7
SM
7840 else
7841 dval = dval0;
4c4b4cd2 7842
284614f0
JB
7843 /* If the type referenced by this field is an aligner type, we need
7844 to unwrap that aligner type, because its size might not be set.
7845 Keeping the aligner type would cause us to compute the wrong
7846 size for this field, impacting the offset of the all the fields
7847 that follow this one. */
7848 if (ada_is_aligner_type (field_type))
7849 {
b610c045 7850 long field_offset = type->field (f).loc_bitpos ();
284614f0
JB
7851
7852 field_valaddr = cond_offset_host (field_valaddr, field_offset);
7853 field_address = cond_offset_target (field_address, field_offset);
7854 field_type = ada_aligned_type (field_type);
7855 }
7856
7857 field_valaddr = cond_offset_host (field_valaddr,
7858 off / TARGET_CHAR_BIT);
7859 field_address = cond_offset_target (field_address,
7860 off / TARGET_CHAR_BIT);
7861
7862 /* Get the fixed type of the field. Note that, in this case,
7863 we do not want to get the real type out of the tag: if
7864 the current field is the parent part of a tagged record,
7865 we will get the tag of the object. Clearly wrong: the real
7866 type of the parent is not the real type of the child. We
7867 would end up in an infinite loop. */
7868 field_type = ada_get_base_type (field_type);
7869 field_type = ada_to_fixed_type (field_type, field_valaddr,
7870 field_address, dval, 0);
7871
5d14b6e5 7872 rtype->field (f).set_type (field_type);
33d16dd9 7873 rtype->field (f).set_name (type->field (f).name ());
27f2a97b
JB
7874 /* The multiplication can potentially overflow. But because
7875 the field length has been size-checked just above, and
7876 assuming that the maximum size is a reasonable value,
7877 an overflow should not happen in practice. So rather than
7878 adding overflow recovery code to this already complex code,
7879 we just assume that it's not going to happen. */
df86565b 7880 fld_bit_len = rtype->field (f).type ()->length () * TARGET_CHAR_BIT;
dda83cd7 7881 }
14f9c5c9 7882 else
dda83cd7 7883 {
5ded5331
JB
7884 /* Note: If this field's type is a typedef, it is important
7885 to preserve the typedef layer.
7886
7887 Otherwise, we might be transforming a typedef to a fat
7888 pointer (encoding a pointer to an unconstrained array),
7889 into a basic fat pointer (encoding an unconstrained
7890 array). As both types are implemented using the same
7891 structure, the typedef is the only clue which allows us
7892 to distinguish between the two options. Stripping it
7893 would prevent us from printing this field appropriately. */
dda83cd7 7894 rtype->field (f).set_type (type->field (f).type ());
33d16dd9 7895 rtype->field (f).set_name (type->field (f).name ());
3757d2d4 7896 if (type->field (f).bitsize () > 0)
886176b8 7897 {
3757d2d4 7898 fld_bit_len = type->field (f).bitsize ();
886176b8
SM
7899 rtype->field (f).set_bitsize (fld_bit_len);
7900 }
dda83cd7 7901 else
5ded5331 7902 {
940da03e 7903 struct type *field_type = type->field (f).type ();
5ded5331
JB
7904
7905 /* We need to be careful of typedefs when computing
7906 the length of our field. If this is a typedef,
7907 get the length of the target type, not the length
7908 of the typedef. */
78134374 7909 if (field_type->code () == TYPE_CODE_TYPEDEF)
5ded5331
JB
7910 field_type = ada_typedef_target_type (field_type);
7911
dda83cd7 7912 fld_bit_len =
df86565b 7913 ada_check_typedef (field_type)->length () * TARGET_CHAR_BIT;
5ded5331 7914 }
dda83cd7 7915 }
14f9c5c9 7916 if (off + fld_bit_len > bit_len)
dda83cd7 7917 bit_len = off + fld_bit_len;
d94e4f4f 7918 off += fld_bit_len;
b6cdbc9a 7919 rtype->set_length (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
14f9c5c9 7920 }
4c4b4cd2
PH
7921
7922 /* We handle the variant part, if any, at the end because of certain
b1f33ddd 7923 odd cases in which it is re-ordered so as NOT to be the last field of
4c4b4cd2
PH
7924 the record. This can happen in the presence of representation
7925 clauses. */
7926 if (variant_field >= 0)
7927 {
7928 struct type *branch_type;
7929
b610c045 7930 off = rtype->field (variant_field).loc_bitpos ();
4c4b4cd2
PH
7931
7932 if (dval0 == NULL)
9f1f738a 7933 {
012370f6
TT
7934 /* Using plain value_from_contents_and_address here causes
7935 problems because we will end up trying to resolve a type
7936 that is currently being constructed. */
7937 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
7938 address);
d0c97917 7939 rtype = dval->type ();
9f1f738a 7940 }
4c4b4cd2 7941 else
dda83cd7 7942 dval = dval0;
4c4b4cd2
PH
7943
7944 branch_type =
dda83cd7
SM
7945 to_fixed_variant_branch_type
7946 (type->field (variant_field).type (),
7947 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
7948 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
4c4b4cd2 7949 if (branch_type == NULL)
dda83cd7
SM
7950 {
7951 for (f = variant_field + 1; f < rtype->num_fields (); f += 1)
7952 rtype->field (f - 1) = rtype->field (f);
5e33d5f4 7953 rtype->set_num_fields (rtype->num_fields () - 1);
dda83cd7 7954 }
4c4b4cd2 7955 else
dda83cd7
SM
7956 {
7957 rtype->field (variant_field).set_type (branch_type);
d3fd12df 7958 rtype->field (variant_field).set_name ("S");
dda83cd7 7959 fld_bit_len =
df86565b 7960 rtype->field (variant_field).type ()->length () * TARGET_CHAR_BIT;
dda83cd7
SM
7961 if (off + fld_bit_len > bit_len)
7962 bit_len = off + fld_bit_len;
b6cdbc9a
SM
7963
7964 rtype->set_length
7965 (align_up (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT);
dda83cd7 7966 }
4c4b4cd2
PH
7967 }
7968
714e53ab
PH
7969 /* According to exp_dbug.ads, the size of TYPE for variable-size records
7970 should contain the alignment of that record, which should be a strictly
7971 positive value. If null or negative, then something is wrong, most
7972 probably in the debug info. In that case, we don't round up the size
0963b4bd 7973 of the resulting type. If this record is not part of another structure,
714e53ab 7974 the current RTYPE length might be good enough for our purposes. */
df86565b 7975 if (type->length () <= 0)
714e53ab 7976 {
7d93a1e0 7977 if (rtype->name ())
cc1defb1 7978 warning (_("Invalid type size for `%s' detected: %s."),
df86565b 7979 rtype->name (), pulongest (type->length ()));
323e0a4a 7980 else
cc1defb1 7981 warning (_("Invalid type size for <unnamed> detected: %s."),
df86565b 7982 pulongest (type->length ()));
714e53ab
PH
7983 }
7984 else
df86565b 7985 rtype->set_length (align_up (rtype->length (), type->length ()));
14f9c5c9 7986
14f9c5c9
AS
7987 return rtype;
7988}
7989
4c4b4cd2
PH
7990/* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
7991 of 1. */
14f9c5c9 7992
d2e4a39e 7993static struct type *
fc1a4b47 7994template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
dda83cd7 7995 CORE_ADDR address, struct value *dval0)
4c4b4cd2
PH
7996{
7997 return ada_template_to_fixed_record_type_1 (type, valaddr,
dda83cd7 7998 address, dval0, 1);
4c4b4cd2
PH
7999}
8000
8001/* An ordinary record type in which ___XVL-convention fields and
8002 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8003 static approximations, containing all possible fields. Uses
8004 no runtime values. Useless for use in values, but that's OK,
8005 since the results are used only for type determinations. Works on both
8006 structs and unions. Representation note: to save space, we memorize
27710edb 8007 the result of this function in the type::target_type of the
4c4b4cd2
PH
8008 template type. */
8009
8010static struct type *
8011template_to_static_fixed_type (struct type *type0)
14f9c5c9
AS
8012{
8013 struct type *type;
8014 int nfields;
8015 int f;
8016
9e195661 8017 /* No need no do anything if the input type is already fixed. */
22c4c60c 8018 if (type0->is_fixed_instance ())
9e195661
PMR
8019 return type0;
8020
8021 /* Likewise if we already have computed the static approximation. */
27710edb
SM
8022 if (type0->target_type () != NULL)
8023 return type0->target_type ();
4c4b4cd2 8024
9e195661 8025 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
4c4b4cd2 8026 type = type0;
1f704f76 8027 nfields = type0->num_fields ();
9e195661
PMR
8028
8029 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8030 recompute all over next time. */
8a50fdce 8031 type0->set_target_type (type);
14f9c5c9
AS
8032
8033 for (f = 0; f < nfields; f += 1)
8034 {
940da03e 8035 struct type *field_type = type0->field (f).type ();
4c4b4cd2 8036 struct type *new_type;
14f9c5c9 8037
4c4b4cd2 8038 if (is_dynamic_field (type0, f))
460efde1
JB
8039 {
8040 field_type = ada_check_typedef (field_type);
27710edb 8041 new_type = to_static_fixed_type (field_type->target_type ());
460efde1 8042 }
14f9c5c9 8043 else
dda83cd7 8044 new_type = static_unwrap_type (field_type);
9e195661
PMR
8045
8046 if (new_type != field_type)
8047 {
8048 /* Clone TYPE0 only the first time we get a new field type. */
8049 if (type == type0)
8050 {
9fa83a7a 8051 type = type_allocator (type0).new_type ();
8a50fdce 8052 type0->set_target_type (type);
78134374 8053 type->set_code (type0->code ());
8ecb59f8 8054 INIT_NONE_SPECIFIC (type);
3cabb6b0 8055
2774f2da 8056 type->copy_fields (type0);
3cabb6b0 8057
d0e39ea2 8058 type->set_name (ada_type_name (type0));
9cdd0d12 8059 type->set_is_fixed_instance (true);
b6cdbc9a 8060 type->set_length (0);
9e195661 8061 }
5d14b6e5 8062 type->field (f).set_type (new_type);
33d16dd9 8063 type->field (f).set_name (type0->field (f).name ());
9e195661 8064 }
14f9c5c9 8065 }
9e195661 8066
14f9c5c9
AS
8067 return type;
8068}
8069
4c4b4cd2 8070/* Given an object of type TYPE whose contents are at VALADDR and
5823c3ef
JB
8071 whose address in memory is ADDRESS, returns a revision of TYPE,
8072 which should be a non-dynamic-sized record, in which the variant
8073 part, if any, is replaced with the appropriate branch. Looks
4c4b4cd2
PH
8074 for discriminant values in DVAL0, which can be NULL if the record
8075 contains the necessary discriminant values. */
8076
d2e4a39e 8077static struct type *
fc1a4b47 8078to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
dda83cd7 8079 CORE_ADDR address, struct value *dval0)
14f9c5c9 8080{
4c4b4cd2 8081 struct value *dval;
d2e4a39e 8082 struct type *rtype;
14f9c5c9 8083 struct type *branch_type;
1f704f76 8084 int nfields = type->num_fields ();
4c4b4cd2 8085 int variant_field = variant_field_index (type);
14f9c5c9 8086
4c4b4cd2 8087 if (variant_field == -1)
14f9c5c9
AS
8088 return type;
8089
65558ca5 8090 scoped_value_mark mark;
4c4b4cd2 8091 if (dval0 == NULL)
9f1f738a
SA
8092 {
8093 dval = value_from_contents_and_address (type, valaddr, address);
d0c97917 8094 type = dval->type ();
9f1f738a 8095 }
4c4b4cd2
PH
8096 else
8097 dval = dval0;
8098
9fa83a7a 8099 rtype = type_allocator (type).new_type ();
67607e24 8100 rtype->set_code (TYPE_CODE_STRUCT);
8ecb59f8 8101 INIT_NONE_SPECIFIC (rtype);
2774f2da 8102 rtype->copy_fields (type);
3cabb6b0 8103
d0e39ea2 8104 rtype->set_name (ada_type_name (type));
9cdd0d12 8105 rtype->set_is_fixed_instance (true);
df86565b 8106 rtype->set_length (type->length ());
14f9c5c9 8107
4c4b4cd2 8108 branch_type = to_fixed_variant_branch_type
940da03e 8109 (type->field (variant_field).type (),
d2e4a39e 8110 cond_offset_host (valaddr,
b610c045 8111 type->field (variant_field).loc_bitpos ()
dda83cd7 8112 / TARGET_CHAR_BIT),
d2e4a39e 8113 cond_offset_target (address,
b610c045 8114 type->field (variant_field).loc_bitpos ()
dda83cd7 8115 / TARGET_CHAR_BIT), dval);
d2e4a39e 8116 if (branch_type == NULL)
14f9c5c9 8117 {
4c4b4cd2 8118 int f;
5b4ee69b 8119
4c4b4cd2 8120 for (f = variant_field + 1; f < nfields; f += 1)
dda83cd7 8121 rtype->field (f - 1) = rtype->field (f);
5e33d5f4 8122 rtype->set_num_fields (rtype->num_fields () - 1);
14f9c5c9
AS
8123 }
8124 else
8125 {
5d14b6e5 8126 rtype->field (variant_field).set_type (branch_type);
d3fd12df 8127 rtype->field (variant_field).set_name ("S");
886176b8 8128 rtype->field (variant_field).set_bitsize (0);
df86565b 8129 rtype->set_length (rtype->length () + branch_type->length ());
14f9c5c9 8130 }
b6cdbc9a 8131
df86565b
SM
8132 rtype->set_length (rtype->length ()
8133 - type->field (variant_field).type ()->length ());
d2e4a39e 8134
14f9c5c9
AS
8135 return rtype;
8136}
8137
8138/* An ordinary record type (with fixed-length fields) that describes
8139 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8140 beginning of this section]. Any necessary discriminants' values
4c4b4cd2
PH
8141 should be in DVAL, a record value; it may be NULL if the object
8142 at ADDR itself contains any necessary discriminant values.
8143 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8144 values from the record are needed. Except in the case that DVAL,
8145 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8146 unchecked) is replaced by a particular branch of the variant.
8147
8148 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8149 is questionable and may be removed. It can arise during the
8150 processing of an unconstrained-array-of-record type where all the
8151 variant branches have exactly the same size. This is because in
8152 such cases, the compiler does not bother to use the XVS convention
8153 when encoding the record. I am currently dubious of this
8154 shortcut and suspect the compiler should be altered. FIXME. */
14f9c5c9 8155
d2e4a39e 8156static struct type *
fc1a4b47 8157to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
dda83cd7 8158 CORE_ADDR address, struct value *dval)
14f9c5c9 8159{
d2e4a39e 8160 struct type *templ_type;
14f9c5c9 8161
22c4c60c 8162 if (type0->is_fixed_instance ())
4c4b4cd2
PH
8163 return type0;
8164
d2e4a39e 8165 templ_type = dynamic_template_type (type0);
14f9c5c9
AS
8166
8167 if (templ_type != NULL)
8168 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
4c4b4cd2
PH
8169 else if (variant_field_index (type0) >= 0)
8170 {
8171 if (dval == NULL && valaddr == NULL && address == 0)
dda83cd7 8172 return type0;
4c4b4cd2 8173 return to_record_with_fixed_variant_part (type0, valaddr, address,
dda83cd7 8174 dval);
4c4b4cd2 8175 }
14f9c5c9
AS
8176 else
8177 {
9cdd0d12 8178 type0->set_is_fixed_instance (true);
14f9c5c9
AS
8179 return type0;
8180 }
8181
8182}
8183
8184/* An ordinary record type (with fixed-length fields) that describes
8185 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8186 union type. Any necessary discriminants' values should be in DVAL,
8187 a record value. That is, this routine selects the appropriate
8188 branch of the union at ADDR according to the discriminant value
b1f33ddd 8189 indicated in the union's type name. Returns VAR_TYPE0 itself if
0963b4bd 8190 it represents a variant subject to a pragma Unchecked_Union. */
14f9c5c9 8191
d2e4a39e 8192static struct type *
fc1a4b47 8193to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
dda83cd7 8194 CORE_ADDR address, struct value *dval)
14f9c5c9
AS
8195{
8196 int which;
d2e4a39e
AS
8197 struct type *templ_type;
8198 struct type *var_type;
14f9c5c9 8199
78134374 8200 if (var_type0->code () == TYPE_CODE_PTR)
27710edb 8201 var_type = var_type0->target_type ();
d2e4a39e 8202 else
14f9c5c9
AS
8203 var_type = var_type0;
8204
8205 templ_type = ada_find_parallel_type (var_type, "___XVU");
8206
8207 if (templ_type != NULL)
8208 var_type = templ_type;
8209
d0c97917 8210 if (is_unchecked_variant (var_type, dval->type ()))
b1f33ddd 8211 return var_type0;
d8af9068 8212 which = ada_which_variant_applies (var_type, dval);
14f9c5c9
AS
8213
8214 if (which < 0)
e9bb382b 8215 return empty_record (var_type);
14f9c5c9 8216 else if (is_dynamic_field (var_type, which))
4c4b4cd2 8217 return to_fixed_record_type
27710edb 8218 (var_type->field (which).type ()->target_type(), valaddr, address, dval);
940da03e 8219 else if (variant_field_index (var_type->field (which).type ()) >= 0)
d2e4a39e
AS
8220 return
8221 to_fixed_record_type
940da03e 8222 (var_type->field (which).type (), valaddr, address, dval);
14f9c5c9 8223 else
940da03e 8224 return var_type->field (which).type ();
14f9c5c9
AS
8225}
8226
8908fca5
JB
8227/* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8228 ENCODING_TYPE, a type following the GNAT conventions for discrete
8229 type encodings, only carries redundant information. */
8230
8231static int
8232ada_is_redundant_range_encoding (struct type *range_type,
8233 struct type *encoding_type)
8234{
108d56a4 8235 const char *bounds_str;
8908fca5
JB
8236 int n;
8237 LONGEST lo, hi;
8238
78134374 8239 gdb_assert (range_type->code () == TYPE_CODE_RANGE);
8908fca5 8240
78134374
SM
8241 if (get_base_type (range_type)->code ()
8242 != get_base_type (encoding_type)->code ())
005e2509
JB
8243 {
8244 /* The compiler probably used a simple base type to describe
8245 the range type instead of the range's actual base type,
8246 expecting us to get the real base type from the encoding
8247 anyway. In this situation, the encoding cannot be ignored
8248 as redundant. */
8249 return 0;
8250 }
8251
8908fca5
JB
8252 if (is_dynamic_type (range_type))
8253 return 0;
8254
7d93a1e0 8255 if (encoding_type->name () == NULL)
8908fca5
JB
8256 return 0;
8257
7d93a1e0 8258 bounds_str = strstr (encoding_type->name (), "___XDLU_");
8908fca5
JB
8259 if (bounds_str == NULL)
8260 return 0;
8261
8262 n = 8; /* Skip "___XDLU_". */
8263 if (!ada_scan_number (bounds_str, n, &lo, &n))
8264 return 0;
5537ddd0 8265 if (range_type->bounds ()->low.const_val () != lo)
8908fca5
JB
8266 return 0;
8267
8268 n += 2; /* Skip the "__" separator between the two bounds. */
8269 if (!ada_scan_number (bounds_str, n, &hi, &n))
8270 return 0;
5537ddd0 8271 if (range_type->bounds ()->high.const_val () != hi)
8908fca5
JB
8272 return 0;
8273
8274 return 1;
8275}
8276
8277/* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8278 a type following the GNAT encoding for describing array type
8279 indices, only carries redundant information. */
8280
8281static int
8282ada_is_redundant_index_type_desc (struct type *array_type,
8283 struct type *desc_type)
8284{
8285 struct type *this_layer = check_typedef (array_type);
8286 int i;
8287
1f704f76 8288 for (i = 0; i < desc_type->num_fields (); i++)
8908fca5 8289 {
3d967001 8290 if (!ada_is_redundant_range_encoding (this_layer->index_type (),
940da03e 8291 desc_type->field (i).type ()))
8908fca5 8292 return 0;
27710edb 8293 this_layer = check_typedef (this_layer->target_type ());
8908fca5
JB
8294 }
8295
8296 return 1;
8297}
8298
14f9c5c9
AS
8299/* Assuming that TYPE0 is an array type describing the type of a value
8300 at ADDR, and that DVAL describes a record containing any
8301 discriminants used in TYPE0, returns a type for the value that
8302 contains no dynamic components (that is, no components whose sizes
8303 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8304 true, gives an error message if the resulting type's size is over
4c4b4cd2 8305 varsize_limit. */
14f9c5c9 8306
d2e4a39e
AS
8307static struct type *
8308to_fixed_array_type (struct type *type0, struct value *dval,
dda83cd7 8309 int ignore_too_big)
14f9c5c9 8310{
d2e4a39e
AS
8311 struct type *index_type_desc;
8312 struct type *result;
ad82864c 8313 int constrained_packed_array_p;
931e5bc3 8314 static const char *xa_suffix = "___XA";
14f9c5c9 8315
b0dd7688 8316 type0 = ada_check_typedef (type0);
22c4c60c 8317 if (type0->is_fixed_instance ())
4c4b4cd2 8318 return type0;
14f9c5c9 8319
ad82864c
JB
8320 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8321 if (constrained_packed_array_p)
75fd6a26
TT
8322 {
8323 type0 = decode_constrained_packed_array_type (type0);
8324 if (type0 == nullptr)
8325 error (_("could not decode constrained packed array type"));
8326 }
284614f0 8327
931e5bc3
JG
8328 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8329
8330 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8331 encoding suffixed with 'P' may still be generated. If so,
8332 it should be used to find the XA type. */
8333
8334 if (index_type_desc == NULL)
8335 {
1da0522e 8336 const char *type_name = ada_type_name (type0);
931e5bc3 8337
1da0522e 8338 if (type_name != NULL)
931e5bc3 8339 {
1da0522e 8340 const int len = strlen (type_name);
931e5bc3
JG
8341 char *name = (char *) alloca (len + strlen (xa_suffix));
8342
1da0522e 8343 if (type_name[len - 1] == 'P')
931e5bc3 8344 {
1da0522e 8345 strcpy (name, type_name);
931e5bc3
JG
8346 strcpy (name + len - 1, xa_suffix);
8347 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8348 }
8349 }
8350 }
8351
28c85d6c 8352 ada_fixup_array_indexes_type (index_type_desc);
8908fca5
JB
8353 if (index_type_desc != NULL
8354 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8355 {
8356 /* Ignore this ___XA parallel type, as it does not bring any
8357 useful information. This allows us to avoid creating fixed
8358 versions of the array's index types, which would be identical
8359 to the original ones. This, in turn, can also help avoid
8360 the creation of fixed versions of the array itself. */
8361 index_type_desc = NULL;
8362 }
8363
14f9c5c9
AS
8364 if (index_type_desc == NULL)
8365 {
27710edb 8366 struct type *elt_type0 = ada_check_typedef (type0->target_type ());
5b4ee69b 8367
14f9c5c9 8368 /* NOTE: elt_type---the fixed version of elt_type0---should never
dda83cd7
SM
8369 depend on the contents of the array in properly constructed
8370 debugging data. */
529cad9c 8371 /* Create a fixed version of the array element type.
dda83cd7
SM
8372 We're not providing the address of an element here,
8373 and thus the actual object value cannot be inspected to do
8374 the conversion. This should not be a problem, since arrays of
8375 unconstrained objects are not allowed. In particular, all
8376 the elements of an array of a tagged type should all be of
8377 the same type specified in the debugging info. No need to
8378 consult the object tag. */
1ed6ede0 8379 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
14f9c5c9 8380
284614f0
JB
8381 /* Make sure we always create a new array type when dealing with
8382 packed array types, since we're going to fix-up the array
8383 type length and element bitsize a little further down. */
ad82864c 8384 if (elt_type0 == elt_type && !constrained_packed_array_p)
dda83cd7 8385 result = type0;
14f9c5c9 8386 else
9e76b17a
TT
8387 {
8388 type_allocator alloc (type0);
8389 result = create_array_type (alloc, elt_type, type0->index_type ());
8390 }
14f9c5c9
AS
8391 }
8392 else
8393 {
8394 int i;
8395 struct type *elt_type0;
8396
8397 elt_type0 = type0;
1f704f76 8398 for (i = index_type_desc->num_fields (); i > 0; i -= 1)
27710edb 8399 elt_type0 = elt_type0->target_type ();
14f9c5c9
AS
8400
8401 /* NOTE: result---the fixed version of elt_type0---should never
dda83cd7
SM
8402 depend on the contents of the array in properly constructed
8403 debugging data. */
529cad9c 8404 /* Create a fixed version of the array element type.
dda83cd7
SM
8405 We're not providing the address of an element here,
8406 and thus the actual object value cannot be inspected to do
8407 the conversion. This should not be a problem, since arrays of
8408 unconstrained objects are not allowed. In particular, all
8409 the elements of an array of a tagged type should all be of
8410 the same type specified in the debugging info. No need to
8411 consult the object tag. */
1ed6ede0 8412 result =
dda83cd7 8413 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
1ce677a4
UW
8414
8415 elt_type0 = type0;
1f704f76 8416 for (i = index_type_desc->num_fields () - 1; i >= 0; i -= 1)
dda83cd7
SM
8417 {
8418 struct type *range_type =
8419 to_fixed_range_type (index_type_desc->field (i).type (), dval);
5b4ee69b 8420
9e76b17a
TT
8421 type_allocator alloc (elt_type0);
8422 result = create_array_type (alloc, result, range_type);
27710edb 8423 elt_type0 = elt_type0->target_type ();
dda83cd7 8424 }
14f9c5c9
AS
8425 }
8426
2e6fda7d
JB
8427 /* We want to preserve the type name. This can be useful when
8428 trying to get the type name of a value that has already been
8429 printed (for instance, if the user did "print VAR; whatis $". */
7d93a1e0 8430 result->set_name (type0->name ());
2e6fda7d 8431
ad82864c 8432 if (constrained_packed_array_p)
284614f0
JB
8433 {
8434 /* So far, the resulting type has been created as if the original
8435 type was a regular (non-packed) array type. As a result, the
8436 bitsize of the array elements needs to be set again, and the array
8437 length needs to be recomputed based on that bitsize. */
df86565b 8438 int len = result->length () / result->target_type ()->length ();
3757d2d4 8439 int elt_bitsize = type0->field (0).bitsize ();
284614f0 8440
3757d2d4 8441 result->field (0).set_bitsize (elt_bitsize);
b6cdbc9a 8442 result->set_length (len * elt_bitsize / HOST_CHAR_BIT);
df86565b
SM
8443 if (result->length () * HOST_CHAR_BIT < len * elt_bitsize)
8444 result->set_length (result->length () + 1);
284614f0
JB
8445 }
8446
9cdd0d12 8447 result->set_is_fixed_instance (true);
14f9c5c9 8448 return result;
d2e4a39e 8449}
14f9c5c9
AS
8450
8451
8452/* A standard type (containing no dynamically sized components)
8453 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
8454 DVAL describes a record containing any discriminants used in TYPE0,
4c4b4cd2 8455 and may be NULL if there are none, or if the object of type TYPE at
529cad9c
PH
8456 ADDRESS or in VALADDR contains these discriminants.
8457
1ed6ede0
JB
8458 If CHECK_TAG is not null, in the case of tagged types, this function
8459 attempts to locate the object's tag and use it to compute the actual
8460 type. However, when ADDRESS is null, we cannot use it to determine the
8461 location of the tag, and therefore compute the tagged type's actual type.
8462 So we return the tagged type without consulting the tag. */
529cad9c 8463
f192137b
JB
8464static struct type *
8465ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
dda83cd7 8466 CORE_ADDR address, struct value *dval, int check_tag)
14f9c5c9 8467{
61ee279c 8468 type = ada_check_typedef (type);
8ecb59f8
TT
8469
8470 /* Only un-fixed types need to be handled here. */
8471 if (!HAVE_GNAT_AUX_INFO (type))
8472 return type;
8473
78134374 8474 switch (type->code ())
d2e4a39e
AS
8475 {
8476 default:
14f9c5c9 8477 return type;
d2e4a39e 8478 case TYPE_CODE_STRUCT:
4c4b4cd2 8479 {
dda83cd7
SM
8480 struct type *static_type = to_static_fixed_type (type);
8481 struct type *fixed_record_type =
8482 to_fixed_record_type (type, valaddr, address, NULL);
8483
8484 /* If STATIC_TYPE is a tagged type and we know the object's address,
8485 then we can determine its tag, and compute the object's actual
8486 type from there. Note that we have to use the fixed record
8487 type (the parent part of the record may have dynamic fields
8488 and the way the location of _tag is expressed may depend on
8489 them). */
8490
8491 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
8492 {
b50d69b5
JG
8493 struct value *tag =
8494 value_tag_from_contents_and_address
8495 (fixed_record_type,
8496 valaddr,
8497 address);
8498 struct type *real_type = type_from_tag (tag);
8499 struct value *obj =
8500 value_from_contents_and_address (fixed_record_type,
8501 valaddr,
8502 address);
d0c97917 8503 fixed_record_type = obj->type ();
dda83cd7
SM
8504 if (real_type != NULL)
8505 return to_fixed_record_type
b50d69b5 8506 (real_type, NULL,
9feb2d07 8507 ada_tag_value_at_base_address (obj)->address (), NULL);
dda83cd7
SM
8508 }
8509
8510 /* Check to see if there is a parallel ___XVZ variable.
8511 If there is, then it provides the actual size of our type. */
8512 else if (ada_type_name (fixed_record_type) != NULL)
8513 {
8514 const char *name = ada_type_name (fixed_record_type);
8515 char *xvz_name
224c3ddb 8516 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
eccab96d 8517 bool xvz_found = false;
dda83cd7 8518 LONGEST size;
4af88198 8519
dda83cd7 8520 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
a70b8144 8521 try
eccab96d
JB
8522 {
8523 xvz_found = get_int_var_value (xvz_name, size);
8524 }
230d2906 8525 catch (const gdb_exception_error &except)
eccab96d
JB
8526 {
8527 /* We found the variable, but somehow failed to read
8528 its value. Rethrow the same error, but with a little
8529 bit more information, to help the user understand
8530 what went wrong (Eg: the variable might have been
8531 optimized out). */
8532 throw_error (except.error,
8533 _("unable to read value of %s (%s)"),
3d6e9d23 8534 xvz_name, except.what ());
eccab96d 8535 }
eccab96d 8536
df86565b 8537 if (xvz_found && fixed_record_type->length () != size)
dda83cd7
SM
8538 {
8539 fixed_record_type = copy_type (fixed_record_type);
b6cdbc9a 8540 fixed_record_type->set_length (size);
dda83cd7
SM
8541
8542 /* The FIXED_RECORD_TYPE may have be a stub. We have
8543 observed this when the debugging info is STABS, and
8544 apparently it is something that is hard to fix.
8545
8546 In practice, we don't need the actual type definition
8547 at all, because the presence of the XVZ variable allows us
8548 to assume that there must be a XVS type as well, which we
8549 should be able to use later, when we need the actual type
8550 definition.
8551
8552 In the meantime, pretend that the "fixed" type we are
8553 returning is NOT a stub, because this can cause trouble
8554 when using this type to create new types targeting it.
8555 Indeed, the associated creation routines often check
8556 whether the target type is a stub and will try to replace
8557 it, thus using a type with the wrong size. This, in turn,
8558 might cause the new type to have the wrong size too.
8559 Consider the case of an array, for instance, where the size
8560 of the array is computed from the number of elements in
8561 our array multiplied by the size of its element. */
b4b73759 8562 fixed_record_type->set_is_stub (false);
dda83cd7
SM
8563 }
8564 }
8565 return fixed_record_type;
4c4b4cd2 8566 }
d2e4a39e 8567 case TYPE_CODE_ARRAY:
4c4b4cd2 8568 return to_fixed_array_type (type, dval, 1);
d2e4a39e
AS
8569 case TYPE_CODE_UNION:
8570 if (dval == NULL)
dda83cd7 8571 return type;
d2e4a39e 8572 else
dda83cd7 8573 return to_fixed_variant_branch_type (type, valaddr, address, dval);
d2e4a39e 8574 }
14f9c5c9
AS
8575}
8576
f192137b
JB
8577/* The same as ada_to_fixed_type_1, except that it preserves the type
8578 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
96dbd2c1
JB
8579
8580 The typedef layer needs be preserved in order to differentiate between
8581 arrays and array pointers when both types are implemented using the same
8582 fat pointer. In the array pointer case, the pointer is encoded as
8583 a typedef of the pointer type. For instance, considering:
8584
8585 type String_Access is access String;
8586 S1 : String_Access := null;
8587
8588 To the debugger, S1 is defined as a typedef of type String. But
8589 to the user, it is a pointer. So if the user tries to print S1,
8590 we should not dereference the array, but print the array address
8591 instead.
8592
8593 If we didn't preserve the typedef layer, we would lose the fact that
8594 the type is to be presented as a pointer (needs de-reference before
8595 being printed). And we would also use the source-level type name. */
f192137b
JB
8596
8597struct type *
8598ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
dda83cd7 8599 CORE_ADDR address, struct value *dval, int check_tag)
f192137b
JB
8600
8601{
8602 struct type *fixed_type =
8603 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
8604
96dbd2c1
JB
8605 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
8606 then preserve the typedef layer.
8607
8608 Implementation note: We can only check the main-type portion of
8609 the TYPE and FIXED_TYPE, because eliminating the typedef layer
8610 from TYPE now returns a type that has the same instance flags
8611 as TYPE. For instance, if TYPE is a "typedef const", and its
8612 target type is a "struct", then the typedef elimination will return
8613 a "const" version of the target type. See check_typedef for more
8614 details about how the typedef layer elimination is done.
8615
8616 brobecker/2010-11-19: It seems to me that the only case where it is
8617 useful to preserve the typedef layer is when dealing with fat pointers.
8618 Perhaps, we could add a check for that and preserve the typedef layer
85102364 8619 only in that situation. But this seems unnecessary so far, probably
96dbd2c1
JB
8620 because we call check_typedef/ada_check_typedef pretty much everywhere.
8621 */
78134374 8622 if (type->code () == TYPE_CODE_TYPEDEF
720d1a40 8623 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
96dbd2c1 8624 == TYPE_MAIN_TYPE (fixed_type)))
f192137b
JB
8625 return type;
8626
8627 return fixed_type;
8628}
8629
14f9c5c9 8630/* A standard (static-sized) type corresponding as well as possible to
4c4b4cd2 8631 TYPE0, but based on no runtime data. */
14f9c5c9 8632
d2e4a39e
AS
8633static struct type *
8634to_static_fixed_type (struct type *type0)
14f9c5c9 8635{
d2e4a39e 8636 struct type *type;
14f9c5c9
AS
8637
8638 if (type0 == NULL)
8639 return NULL;
8640
22c4c60c 8641 if (type0->is_fixed_instance ())
4c4b4cd2
PH
8642 return type0;
8643
61ee279c 8644 type0 = ada_check_typedef (type0);
d2e4a39e 8645
78134374 8646 switch (type0->code ())
14f9c5c9
AS
8647 {
8648 default:
8649 return type0;
8650 case TYPE_CODE_STRUCT:
8651 type = dynamic_template_type (type0);
d2e4a39e 8652 if (type != NULL)
dda83cd7 8653 return template_to_static_fixed_type (type);
4c4b4cd2 8654 else
dda83cd7 8655 return template_to_static_fixed_type (type0);
14f9c5c9
AS
8656 case TYPE_CODE_UNION:
8657 type = ada_find_parallel_type (type0, "___XVU");
8658 if (type != NULL)
dda83cd7 8659 return template_to_static_fixed_type (type);
4c4b4cd2 8660 else
dda83cd7 8661 return template_to_static_fixed_type (type0);
14f9c5c9
AS
8662 }
8663}
8664
4c4b4cd2
PH
8665/* A static approximation of TYPE with all type wrappers removed. */
8666
d2e4a39e
AS
8667static struct type *
8668static_unwrap_type (struct type *type)
14f9c5c9
AS
8669{
8670 if (ada_is_aligner_type (type))
8671 {
940da03e 8672 struct type *type1 = ada_check_typedef (type)->field (0).type ();
14f9c5c9 8673 if (ada_type_name (type1) == NULL)
d0e39ea2 8674 type1->set_name (ada_type_name (type));
14f9c5c9
AS
8675
8676 return static_unwrap_type (type1);
8677 }
d2e4a39e 8678 else
14f9c5c9 8679 {
d2e4a39e 8680 struct type *raw_real_type = ada_get_base_type (type);
5b4ee69b 8681
d2e4a39e 8682 if (raw_real_type == type)
dda83cd7 8683 return type;
14f9c5c9 8684 else
dda83cd7 8685 return to_static_fixed_type (raw_real_type);
14f9c5c9
AS
8686 }
8687}
8688
8689/* In some cases, incomplete and private types require
4c4b4cd2 8690 cross-references that are not resolved as records (for example,
14f9c5c9
AS
8691 type Foo;
8692 type FooP is access Foo;
8693 V: FooP;
8694 type Foo is array ...;
4c4b4cd2 8695 ). In these cases, since there is no mechanism for producing
14f9c5c9
AS
8696 cross-references to such types, we instead substitute for FooP a
8697 stub enumeration type that is nowhere resolved, and whose tag is
4c4b4cd2 8698 the name of the actual type. Call these types "non-record stubs". */
14f9c5c9
AS
8699
8700/* A type equivalent to TYPE that is not a non-record stub, if one
4c4b4cd2
PH
8701 exists, otherwise TYPE. */
8702
d2e4a39e 8703struct type *
61ee279c 8704ada_check_typedef (struct type *type)
14f9c5c9 8705{
727e3d2e
JB
8706 if (type == NULL)
8707 return NULL;
8708
736ade86
XR
8709 /* If our type is an access to an unconstrained array, which is encoded
8710 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
720d1a40
JB
8711 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
8712 what allows us to distinguish between fat pointers that represent
8713 array types, and fat pointers that represent array access types
8714 (in both cases, the compiler implements them as fat pointers). */
736ade86 8715 if (ada_is_access_to_unconstrained_array (type))
720d1a40
JB
8716 return type;
8717
f168693b 8718 type = check_typedef (type);
78134374 8719 if (type == NULL || type->code () != TYPE_CODE_ENUM
e46d3488 8720 || !type->is_stub ()
7d93a1e0 8721 || type->name () == NULL)
14f9c5c9 8722 return type;
d2e4a39e 8723 else
14f9c5c9 8724 {
7d93a1e0 8725 const char *name = type->name ();
d2e4a39e 8726 struct type *type1 = ada_find_any_type (name);
5b4ee69b 8727
05e522ef 8728 if (type1 == NULL)
dda83cd7 8729 return type;
05e522ef
JB
8730
8731 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
8732 stubs pointing to arrays, as we don't create symbols for array
3a867c22
JB
8733 types, only for the typedef-to-array types). If that's the case,
8734 strip the typedef layer. */
78134374 8735 if (type1->code () == TYPE_CODE_TYPEDEF)
3a867c22
JB
8736 type1 = ada_check_typedef (type1);
8737
8738 return type1;
14f9c5c9
AS
8739 }
8740}
8741
8742/* A value representing the data at VALADDR/ADDRESS as described by
8743 type TYPE0, but with a standard (static-sized) type that correctly
8744 describes it. If VAL0 is not NULL and TYPE0 already is a standard
8745 type, then return VAL0 [this feature is simply to avoid redundant
4c4b4cd2 8746 creation of struct values]. */
14f9c5c9 8747
4c4b4cd2
PH
8748static struct value *
8749ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
dda83cd7 8750 struct value *val0)
14f9c5c9 8751{
1ed6ede0 8752 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
5b4ee69b 8753
14f9c5c9
AS
8754 if (type == type0 && val0 != NULL)
8755 return val0;
cc0e770c 8756
736355f2 8757 if (val0->lval () != lval_memory)
cc0e770c
JB
8758 {
8759 /* Our value does not live in memory; it could be a convenience
8760 variable, for instance. Create a not_lval value using val0's
8761 contents. */
efaf1ae0 8762 return value_from_contents (type, val0->contents ().data ());
cc0e770c
JB
8763 }
8764
8765 return value_from_contents_and_address (type, 0, address);
4c4b4cd2
PH
8766}
8767
8768/* A value representing VAL, but with a standard (static-sized) type
8769 that correctly describes it. Does not necessarily create a new
8770 value. */
8771
0c3acc09 8772struct value *
4c4b4cd2
PH
8773ada_to_fixed_value (struct value *val)
8774{
c48db5ca 8775 val = unwrap_value (val);
9feb2d07 8776 val = ada_to_fixed_value_create (val->type (), val->address (), val);
c48db5ca 8777 return val;
14f9c5c9 8778}
d2e4a39e 8779\f
14f9c5c9 8780
14f9c5c9
AS
8781/* Attributes */
8782
4c4b4cd2 8783/* Evaluate the 'POS attribute applied to ARG. */
14f9c5c9 8784
4c4b4cd2
PH
8785static LONGEST
8786pos_atr (struct value *arg)
14f9c5c9 8787{
24209737 8788 struct value *val = coerce_ref (arg);
d0c97917 8789 struct type *type = val->type ();
14f9c5c9 8790
d2e4a39e 8791 if (!discrete_type_p (type))
323e0a4a 8792 error (_("'POS only defined on discrete types"));
14f9c5c9 8793
6244c119
SM
8794 gdb::optional<LONGEST> result = discrete_position (type, value_as_long (val));
8795 if (!result.has_value ())
aa715135 8796 error (_("enumeration value is invalid: can't find 'POS"));
14f9c5c9 8797
6244c119 8798 return *result;
4c4b4cd2
PH
8799}
8800
7631cf6c 8801struct value *
7992accc
TT
8802ada_pos_atr (struct type *expect_type,
8803 struct expression *exp,
8804 enum noside noside, enum exp_opcode op,
8805 struct value *arg)
4c4b4cd2 8806{
7992accc
TT
8807 struct type *type = builtin_type (exp->gdbarch)->builtin_int;
8808 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 8809 return value::zero (type, not_lval);
3cb382c9 8810 return value_from_longest (type, pos_atr (arg));
14f9c5c9
AS
8811}
8812
4c4b4cd2 8813/* Evaluate the TYPE'VAL attribute applied to ARG. */
14f9c5c9 8814
d2e4a39e 8815static struct value *
53a47a3e 8816val_atr (struct type *type, LONGEST val)
14f9c5c9 8817{
53a47a3e 8818 gdb_assert (discrete_type_p (type));
0bc2354b 8819 if (type->code () == TYPE_CODE_RANGE)
27710edb 8820 type = type->target_type ();
78134374 8821 if (type->code () == TYPE_CODE_ENUM)
14f9c5c9 8822 {
53a47a3e 8823 if (val < 0 || val >= type->num_fields ())
dda83cd7 8824 error (_("argument to 'VAL out of range"));
970db518 8825 val = type->field (val).loc_enumval ();
14f9c5c9 8826 }
53a47a3e
TT
8827 return value_from_longest (type, val);
8828}
8829
9e99f48f 8830struct value *
22f6f797
TT
8831ada_val_atr (struct expression *exp, enum noside noside, struct type *type,
8832 struct value *arg)
53a47a3e 8833{
3848abd6 8834 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 8835 return value::zero (type, not_lval);
3848abd6 8836
53a47a3e
TT
8837 if (!discrete_type_p (type))
8838 error (_("'VAL only defined on discrete types"));
d0c97917 8839 if (!integer_type_p (arg->type ()))
53a47a3e
TT
8840 error (_("'VAL requires integral argument"));
8841
8842 return val_atr (type, value_as_long (arg));
14f9c5c9 8843}
22f6f797
TT
8844
8845/* Implementation of the enum_rep attribute. */
8846struct value *
8847ada_atr_enum_rep (struct expression *exp, enum noside noside, struct type *type,
8848 struct value *arg)
8849{
8850 struct type *inttype = builtin_type (exp->gdbarch)->builtin_int;
8851 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8852 return value::zero (inttype, not_lval);
8853
8854 if (type->code () == TYPE_CODE_RANGE)
8855 type = type->target_type ();
8856 if (type->code () != TYPE_CODE_ENUM)
8857 error (_("'Enum_Rep only defined on enum types"));
8858 if (!types_equal (type, arg->type ()))
8859 error (_("'Enum_Rep requires argument to have same type as enum"));
8860
8861 return value_cast (inttype, arg);
8862}
8863
8864/* Implementation of the enum_val attribute. */
8865struct value *
8866ada_atr_enum_val (struct expression *exp, enum noside noside, struct type *type,
8867 struct value *arg)
8868{
8869 struct type *original_type = type;
8870 if (noside == EVAL_AVOID_SIDE_EFFECTS)
8871 return value::zero (original_type, not_lval);
8872
8873 if (type->code () == TYPE_CODE_RANGE)
8874 type = type->target_type ();
8875 if (type->code () != TYPE_CODE_ENUM)
8876 error (_("'Enum_Val only defined on enum types"));
8877 if (!integer_type_p (arg->type ()))
8878 error (_("'Enum_Val requires integral argument"));
8879
8880 LONGEST value = value_as_long (arg);
8881 for (int i = 0; i < type->num_fields (); ++i)
8882 {
8883 if (type->field (i).loc_enumval () == value)
8884 return value_from_longest (original_type, value);
8885 }
8886
8887 error (_("value %s not found in enum"), plongest (value));
8888}
8889
14f9c5c9 8890\f
d2e4a39e 8891
dda83cd7 8892 /* Evaluation */
14f9c5c9 8893
4c4b4cd2
PH
8894/* True if TYPE appears to be an Ada character type.
8895 [At the moment, this is true only for Character and Wide_Character;
8896 It is a heuristic test that could stand improvement]. */
14f9c5c9 8897
fc913e53 8898bool
d2e4a39e 8899ada_is_character_type (struct type *type)
14f9c5c9 8900{
7b9f71f2
JB
8901 const char *name;
8902
8903 /* If the type code says it's a character, then assume it really is,
8904 and don't check any further. */
78134374 8905 if (type->code () == TYPE_CODE_CHAR)
fc913e53 8906 return true;
7b9f71f2
JB
8907
8908 /* Otherwise, assume it's a character type iff it is a discrete type
8909 with a known character type name. */
8910 name = ada_type_name (type);
8911 return (name != NULL
dda83cd7
SM
8912 && (type->code () == TYPE_CODE_INT
8913 || type->code () == TYPE_CODE_RANGE)
8914 && (strcmp (name, "character") == 0
8915 || strcmp (name, "wide_character") == 0
8916 || strcmp (name, "wide_wide_character") == 0
8917 || strcmp (name, "unsigned char") == 0));
14f9c5c9
AS
8918}
8919
4c4b4cd2 8920/* True if TYPE appears to be an Ada string type. */
14f9c5c9 8921
fc913e53 8922bool
ebf56fd3 8923ada_is_string_type (struct type *type)
14f9c5c9 8924{
61ee279c 8925 type = ada_check_typedef (type);
d2e4a39e 8926 if (type != NULL
78134374 8927 && type->code () != TYPE_CODE_PTR
76a01679 8928 && (ada_is_simple_array_type (type)
dda83cd7 8929 || ada_is_array_descriptor_type (type))
14f9c5c9
AS
8930 && ada_array_arity (type) == 1)
8931 {
8932 struct type *elttype = ada_array_element_type (type, 1);
8933
8934 return ada_is_character_type (elttype);
8935 }
d2e4a39e 8936 else
fc913e53 8937 return false;
14f9c5c9
AS
8938}
8939
5bf03f13
JB
8940/* The compiler sometimes provides a parallel XVS type for a given
8941 PAD type. Normally, it is safe to follow the PAD type directly,
8942 but older versions of the compiler have a bug that causes the offset
8943 of its "F" field to be wrong. Following that field in that case
8944 would lead to incorrect results, but this can be worked around
8945 by ignoring the PAD type and using the associated XVS type instead.
8946
8947 Set to True if the debugger should trust the contents of PAD types.
8948 Otherwise, ignore the PAD type if there is a parallel XVS type. */
491144b5 8949static bool trust_pad_over_xvs = true;
14f9c5c9
AS
8950
8951/* True if TYPE is a struct type introduced by the compiler to force the
8952 alignment of a value. Such types have a single field with a
4c4b4cd2 8953 distinctive name. */
14f9c5c9
AS
8954
8955int
ebf56fd3 8956ada_is_aligner_type (struct type *type)
14f9c5c9 8957{
61ee279c 8958 type = ada_check_typedef (type);
714e53ab 8959
5bf03f13 8960 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
714e53ab
PH
8961 return 0;
8962
78134374 8963 return (type->code () == TYPE_CODE_STRUCT
dda83cd7 8964 && type->num_fields () == 1
33d16dd9 8965 && strcmp (type->field (0).name (), "F") == 0);
14f9c5c9
AS
8966}
8967
8968/* If there is an ___XVS-convention type parallel to SUBTYPE, return
4c4b4cd2 8969 the parallel type. */
14f9c5c9 8970
d2e4a39e
AS
8971struct type *
8972ada_get_base_type (struct type *raw_type)
14f9c5c9 8973{
d2e4a39e
AS
8974 struct type *real_type_namer;
8975 struct type *raw_real_type;
14f9c5c9 8976
78134374 8977 if (raw_type == NULL || raw_type->code () != TYPE_CODE_STRUCT)
14f9c5c9
AS
8978 return raw_type;
8979
284614f0
JB
8980 if (ada_is_aligner_type (raw_type))
8981 /* The encoding specifies that we should always use the aligner type.
8982 So, even if this aligner type has an associated XVS type, we should
8983 simply ignore it.
8984
8985 According to the compiler gurus, an XVS type parallel to an aligner
8986 type may exist because of a stabs limitation. In stabs, aligner
8987 types are empty because the field has a variable-sized type, and
8988 thus cannot actually be used as an aligner type. As a result,
8989 we need the associated parallel XVS type to decode the type.
8990 Since the policy in the compiler is to not change the internal
8991 representation based on the debugging info format, we sometimes
8992 end up having a redundant XVS type parallel to the aligner type. */
8993 return raw_type;
8994
14f9c5c9 8995 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
d2e4a39e 8996 if (real_type_namer == NULL
78134374 8997 || real_type_namer->code () != TYPE_CODE_STRUCT
1f704f76 8998 || real_type_namer->num_fields () != 1)
14f9c5c9
AS
8999 return raw_type;
9000
940da03e 9001 if (real_type_namer->field (0).type ()->code () != TYPE_CODE_REF)
f80d3ff2
JB
9002 {
9003 /* This is an older encoding form where the base type needs to be
85102364 9004 looked up by name. We prefer the newer encoding because it is
f80d3ff2 9005 more efficient. */
33d16dd9 9006 raw_real_type = ada_find_any_type (real_type_namer->field (0).name ());
f80d3ff2
JB
9007 if (raw_real_type == NULL)
9008 return raw_type;
9009 else
9010 return raw_real_type;
9011 }
9012
9013 /* The field in our XVS type is a reference to the base type. */
27710edb 9014 return real_type_namer->field (0).type ()->target_type ();
d2e4a39e 9015}
14f9c5c9 9016
4c4b4cd2 9017/* The type of value designated by TYPE, with all aligners removed. */
14f9c5c9 9018
d2e4a39e
AS
9019struct type *
9020ada_aligned_type (struct type *type)
14f9c5c9
AS
9021{
9022 if (ada_is_aligner_type (type))
940da03e 9023 return ada_aligned_type (type->field (0).type ());
14f9c5c9
AS
9024 else
9025 return ada_get_base_type (type);
9026}
9027
9028
9029/* The address of the aligned value in an object at address VALADDR
4c4b4cd2 9030 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
14f9c5c9 9031
fc1a4b47
AC
9032const gdb_byte *
9033ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
14f9c5c9 9034{
d2e4a39e 9035 if (ada_is_aligner_type (type))
b610c045
SM
9036 return ada_aligned_value_addr
9037 (type->field (0).type (),
9038 valaddr + type->field (0).loc_bitpos () / TARGET_CHAR_BIT);
14f9c5c9
AS
9039 else
9040 return valaddr;
9041}
9042
4c4b4cd2
PH
9043
9044
14f9c5c9 9045/* The printed representation of an enumeration literal with encoded
4c4b4cd2 9046 name NAME. The value is good to the next call of ada_enum_name. */
d2e4a39e
AS
9047const char *
9048ada_enum_name (const char *name)
14f9c5c9 9049{
5f9febe0 9050 static std::string storage;
e6a959d6 9051 const char *tmp;
14f9c5c9 9052
4c4b4cd2
PH
9053 /* First, unqualify the enumeration name:
9054 1. Search for the last '.' character. If we find one, then skip
177b42fe 9055 all the preceding characters, the unqualified name starts
76a01679 9056 right after that dot.
4c4b4cd2 9057 2. Otherwise, we may be debugging on a target where the compiler
76a01679
JB
9058 translates dots into "__". Search forward for double underscores,
9059 but stop searching when we hit an overloading suffix, which is
9060 of the form "__" followed by digits. */
4c4b4cd2 9061
c3e5cd34
PH
9062 tmp = strrchr (name, '.');
9063 if (tmp != NULL)
4c4b4cd2
PH
9064 name = tmp + 1;
9065 else
14f9c5c9 9066 {
4c4b4cd2 9067 while ((tmp = strstr (name, "__")) != NULL)
dda83cd7
SM
9068 {
9069 if (isdigit (tmp[2]))
9070 break;
9071 else
9072 name = tmp + 2;
9073 }
14f9c5c9
AS
9074 }
9075
9076 if (name[0] == 'Q')
9077 {
14f9c5c9 9078 int v;
5b4ee69b 9079
14f9c5c9 9080 if (name[1] == 'U' || name[1] == 'W')
dda83cd7 9081 {
a7041de8
TT
9082 int offset = 2;
9083 if (name[1] == 'W' && name[2] == 'W')
9084 {
9085 /* Also handle the QWW case. */
9086 ++offset;
9087 }
9088 if (sscanf (name + offset, "%x", &v) != 1)
dda83cd7
SM
9089 return name;
9090 }
272560b5
TT
9091 else if (((name[1] >= '0' && name[1] <= '9')
9092 || (name[1] >= 'a' && name[1] <= 'z'))
9093 && name[2] == '\0')
9094 {
5f9febe0
TT
9095 storage = string_printf ("'%c'", name[1]);
9096 return storage.c_str ();
272560b5 9097 }
14f9c5c9 9098 else
dda83cd7 9099 return name;
14f9c5c9
AS
9100
9101 if (isascii (v) && isprint (v))
5f9febe0 9102 storage = string_printf ("'%c'", v);
14f9c5c9 9103 else if (name[1] == 'U')
a7041de8
TT
9104 storage = string_printf ("'[\"%02x\"]'", v);
9105 else if (name[2] != 'W')
9106 storage = string_printf ("'[\"%04x\"]'", v);
14f9c5c9 9107 else
a7041de8 9108 storage = string_printf ("'[\"%06x\"]'", v);
14f9c5c9 9109
5f9febe0 9110 return storage.c_str ();
14f9c5c9 9111 }
d2e4a39e 9112 else
4c4b4cd2 9113 {
c3e5cd34
PH
9114 tmp = strstr (name, "__");
9115 if (tmp == NULL)
9116 tmp = strstr (name, "$");
9117 if (tmp != NULL)
dda83cd7 9118 {
5f9febe0
TT
9119 storage = std::string (name, tmp - name);
9120 return storage.c_str ();
dda83cd7 9121 }
4c4b4cd2
PH
9122
9123 return name;
9124 }
14f9c5c9
AS
9125}
9126
013a623f
TT
9127/* If TYPE is a dynamic type, return the base type. Otherwise, if
9128 there is no parallel type, return nullptr. */
9129
9130static struct type *
9131find_base_type (struct type *type)
9132{
9133 struct type *raw_real_type
9134 = ada_check_typedef (ada_get_base_type (type));
9135
9136 /* No parallel XVS or XVE type. */
9137 if (type == raw_real_type
9138 && ada_find_parallel_type (type, "___XVE") == nullptr)
9139 return nullptr;
9140
9141 return raw_real_type;
9142}
9143
14f9c5c9 9144/* If VAL is wrapped in an aligner or subtype wrapper, return the
4c4b4cd2 9145 value it wraps. */
14f9c5c9 9146
d2e4a39e
AS
9147static struct value *
9148unwrap_value (struct value *val)
14f9c5c9 9149{
d0c97917 9150 struct type *type = ada_check_typedef (val->type ());
5b4ee69b 9151
14f9c5c9
AS
9152 if (ada_is_aligner_type (type))
9153 {
de4d072f 9154 struct value *v = ada_value_struct_elt (val, "F", 0);
d0c97917 9155 struct type *val_type = ada_check_typedef (v->type ());
5b4ee69b 9156
14f9c5c9 9157 if (ada_type_name (val_type) == NULL)
d0e39ea2 9158 val_type->set_name (ada_type_name (type));
14f9c5c9
AS
9159
9160 return unwrap_value (v);
9161 }
d2e4a39e 9162 else
14f9c5c9 9163 {
013a623f
TT
9164 struct type *raw_real_type = find_base_type (type);
9165 if (raw_real_type == nullptr)
5bf03f13 9166 return val;
14f9c5c9 9167
d2e4a39e 9168 return
dda83cd7
SM
9169 coerce_unspec_val_to_type
9170 (val, ada_to_fixed_type (raw_real_type, 0,
9feb2d07 9171 val->address (),
dda83cd7 9172 NULL, 1));
14f9c5c9
AS
9173 }
9174}
d2e4a39e 9175
d99dcf51
JB
9176/* Given two array types T1 and T2, return nonzero iff both arrays
9177 contain the same number of elements. */
9178
9179static int
9180ada_same_array_size_p (struct type *t1, struct type *t2)
9181{
9182 LONGEST lo1, hi1, lo2, hi2;
9183
9184 /* Get the array bounds in order to verify that the size of
9185 the two arrays match. */
9186 if (!get_array_bounds (t1, &lo1, &hi1)
9187 || !get_array_bounds (t2, &lo2, &hi2))
9188 error (_("unable to determine array bounds"));
9189
9190 /* To make things easier for size comparison, normalize a bit
9191 the case of empty arrays by making sure that the difference
9192 between upper bound and lower bound is always -1. */
9193 if (lo1 > hi1)
9194 hi1 = lo1 - 1;
9195 if (lo2 > hi2)
9196 hi2 = lo2 - 1;
9197
9198 return (hi1 - lo1 == hi2 - lo2);
9199}
9200
9201/* Assuming that VAL is an array of integrals, and TYPE represents
9202 an array with the same number of elements, but with wider integral
9203 elements, return an array "casted" to TYPE. In practice, this
9204 means that the returned array is built by casting each element
9205 of the original array into TYPE's (wider) element type. */
9206
9207static struct value *
9208ada_promote_array_of_integrals (struct type *type, struct value *val)
9209{
27710edb 9210 struct type *elt_type = type->target_type ();
d99dcf51 9211 LONGEST lo, hi;
d99dcf51
JB
9212 LONGEST i;
9213
9214 /* Verify that both val and type are arrays of scalars, and
9215 that the size of val's elements is smaller than the size
9216 of type's element. */
78134374 9217 gdb_assert (type->code () == TYPE_CODE_ARRAY);
27710edb 9218 gdb_assert (is_integral_type (type->target_type ()));
d0c97917
TT
9219 gdb_assert (val->type ()->code () == TYPE_CODE_ARRAY);
9220 gdb_assert (is_integral_type (val->type ()->target_type ()));
df86565b 9221 gdb_assert (type->target_type ()->length ()
d0c97917 9222 > val->type ()->target_type ()->length ());
d99dcf51
JB
9223
9224 if (!get_array_bounds (type, &lo, &hi))
9225 error (_("unable to determine array bounds"));
9226
317c3ed9 9227 value *res = value::allocate (type);
bbe912ba 9228 gdb::array_view<gdb_byte> res_contents = res->contents_writeable ();
d99dcf51
JB
9229
9230 /* Promote each array element. */
9231 for (i = 0; i < hi - lo + 1; i++)
9232 {
9233 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
df86565b 9234 int elt_len = elt_type->length ();
d99dcf51 9235
efaf1ae0 9236 copy (elt->contents_all (), res_contents.slice (elt_len * i, elt_len));
d99dcf51
JB
9237 }
9238
9239 return res;
9240}
9241
4c4b4cd2
PH
9242/* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9243 return the converted value. */
9244
d2e4a39e
AS
9245static struct value *
9246coerce_for_assign (struct type *type, struct value *val)
14f9c5c9 9247{
d0c97917 9248 struct type *type2 = val->type ();
5b4ee69b 9249
14f9c5c9
AS
9250 if (type == type2)
9251 return val;
9252
61ee279c
PH
9253 type2 = ada_check_typedef (type2);
9254 type = ada_check_typedef (type);
14f9c5c9 9255
78134374
SM
9256 if (type2->code () == TYPE_CODE_PTR
9257 && type->code () == TYPE_CODE_ARRAY)
14f9c5c9
AS
9258 {
9259 val = ada_value_ind (val);
d0c97917 9260 type2 = val->type ();
14f9c5c9
AS
9261 }
9262
78134374
SM
9263 if (type2->code () == TYPE_CODE_ARRAY
9264 && type->code () == TYPE_CODE_ARRAY)
14f9c5c9 9265 {
d99dcf51
JB
9266 if (!ada_same_array_size_p (type, type2))
9267 error (_("cannot assign arrays of different length"));
9268
27710edb
SM
9269 if (is_integral_type (type->target_type ())
9270 && is_integral_type (type2->target_type ())
df86565b 9271 && type2->target_type ()->length () < type->target_type ()->length ())
d99dcf51
JB
9272 {
9273 /* Allow implicit promotion of the array elements to
9274 a wider type. */
9275 return ada_promote_array_of_integrals (type, val);
9276 }
9277
df86565b 9278 if (type2->target_type ()->length () != type->target_type ()->length ())
dda83cd7 9279 error (_("Incompatible types in assignment"));
81ae560c 9280 val->deprecated_set_type (type);
14f9c5c9 9281 }
d2e4a39e 9282 return val;
14f9c5c9
AS
9283}
9284
4c4b4cd2
PH
9285static struct value *
9286ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9287{
4c4b4cd2 9288 struct type *type1, *type2;
4c4b4cd2 9289
994b9211
AC
9290 arg1 = coerce_ref (arg1);
9291 arg2 = coerce_ref (arg2);
d0c97917
TT
9292 type1 = get_base_type (ada_check_typedef (arg1->type ()));
9293 type2 = get_base_type (ada_check_typedef (arg2->type ()));
4c4b4cd2 9294
78134374
SM
9295 if (type1->code () != TYPE_CODE_INT
9296 || type2->code () != TYPE_CODE_INT)
4c4b4cd2
PH
9297 return value_binop (arg1, arg2, op);
9298
76a01679 9299 switch (op)
4c4b4cd2
PH
9300 {
9301 case BINOP_MOD:
9302 case BINOP_DIV:
9303 case BINOP_REM:
9304 break;
9305 default:
9306 return value_binop (arg1, arg2, op);
9307 }
9308
70050808
TT
9309 gdb_mpz v2 = value_as_mpz (arg2);
9310 if (v2.sgn () == 0)
b0f9164c
TT
9311 {
9312 const char *name;
9313 if (op == BINOP_MOD)
9314 name = "mod";
9315 else if (op == BINOP_DIV)
9316 name = "/";
9317 else
9318 {
9319 gdb_assert (op == BINOP_REM);
9320 name = "rem";
9321 }
9322
9323 error (_("second operand of %s must not be zero."), name);
9324 }
4c4b4cd2 9325
c6d940a9 9326 if (type1->is_unsigned () || op == BINOP_MOD)
4c4b4cd2
PH
9327 return value_binop (arg1, arg2, op);
9328
70050808
TT
9329 gdb_mpz v1 = value_as_mpz (arg1);
9330 gdb_mpz v;
4c4b4cd2
PH
9331 switch (op)
9332 {
9333 case BINOP_DIV:
9334 v = v1 / v2;
4c4b4cd2
PH
9335 break;
9336 case BINOP_REM:
9337 v = v1 % v2;
76a01679 9338 if (v * v1 < 0)
dda83cd7 9339 v -= v2;
4c4b4cd2
PH
9340 break;
9341 default:
9342 /* Should not reach this point. */
70050808 9343 gdb_assert_not_reached ("invalid operator");
4c4b4cd2
PH
9344 }
9345
70050808 9346 return value_from_mpz (type1, v);
4c4b4cd2
PH
9347}
9348
9349static int
9350ada_value_equal (struct value *arg1, struct value *arg2)
9351{
d0c97917
TT
9352 if (ada_is_direct_array_type (arg1->type ())
9353 || ada_is_direct_array_type (arg2->type ()))
4c4b4cd2 9354 {
79e8fcaa
JB
9355 struct type *arg1_type, *arg2_type;
9356
f58b38bf 9357 /* Automatically dereference any array reference before
dda83cd7 9358 we attempt to perform the comparison. */
f58b38bf
JB
9359 arg1 = ada_coerce_ref (arg1);
9360 arg2 = ada_coerce_ref (arg2);
79e8fcaa 9361
4c4b4cd2
PH
9362 arg1 = ada_coerce_to_simple_array (arg1);
9363 arg2 = ada_coerce_to_simple_array (arg2);
79e8fcaa 9364
d0c97917
TT
9365 arg1_type = ada_check_typedef (arg1->type ());
9366 arg2_type = ada_check_typedef (arg2->type ());
79e8fcaa 9367
78134374 9368 if (arg1_type->code () != TYPE_CODE_ARRAY
dda83cd7
SM
9369 || arg2_type->code () != TYPE_CODE_ARRAY)
9370 error (_("Attempt to compare array with non-array"));
4c4b4cd2 9371 /* FIXME: The following works only for types whose
dda83cd7
SM
9372 representations use all bits (no padding or undefined bits)
9373 and do not have user-defined equality. */
df86565b 9374 return (arg1_type->length () == arg2_type->length ()
efaf1ae0
TT
9375 && memcmp (arg1->contents ().data (),
9376 arg2->contents ().data (),
df86565b 9377 arg1_type->length ()) == 0);
4c4b4cd2
PH
9378 }
9379 return value_equal (arg1, arg2);
9380}
9381
d3c54a1c
TT
9382namespace expr
9383{
9384
9385bool
9386check_objfile (const std::unique_ptr<ada_component> &comp,
9387 struct objfile *objfile)
9388{
9389 return comp->uses_objfile (objfile);
9390}
9391
9392/* Assign the result of evaluating ARG starting at *POS to the INDEXth
9393 component of LHS (a simple array or a record). Does not modify the
9394 inferior's memory, nor does it modify LHS (unless LHS ==
9395 CONTAINER). */
52ce6436
PH
9396
9397static void
9398assign_component (struct value *container, struct value *lhs, LONGEST index,
d3c54a1c 9399 struct expression *exp, operation_up &arg)
52ce6436 9400{
d3c54a1c
TT
9401 scoped_value_mark mark;
9402
52ce6436 9403 struct value *elt;
d0c97917 9404 struct type *lhs_type = check_typedef (lhs->type ());
5b4ee69b 9405
78134374 9406 if (lhs_type->code () == TYPE_CODE_ARRAY)
52ce6436 9407 {
22601c15
UW
9408 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9409 struct value *index_val = value_from_longest (index_type, index);
5b4ee69b 9410
52ce6436
PH
9411 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9412 }
9413 else
9414 {
d0c97917 9415 elt = ada_index_struct_field (index, lhs, 0, lhs->type ());
c48db5ca 9416 elt = ada_to_fixed_value (elt);
52ce6436
PH
9417 }
9418
d3c54a1c
TT
9419 ada_aggregate_operation *ag_op
9420 = dynamic_cast<ada_aggregate_operation *> (arg.get ());
9421 if (ag_op != nullptr)
9422 ag_op->assign_aggregate (container, elt, exp);
52ce6436 9423 else
d3c54a1c
TT
9424 value_assign_to_component (container, elt,
9425 arg->evaluate (nullptr, exp,
9426 EVAL_NORMAL));
9427}
52ce6436 9428
d3c54a1c
TT
9429bool
9430ada_aggregate_component::uses_objfile (struct objfile *objfile)
9431{
9432 for (const auto &item : m_components)
9433 if (item->uses_objfile (objfile))
9434 return true;
9435 return false;
9436}
9437
9438void
9439ada_aggregate_component::dump (ui_file *stream, int depth)
9440{
6cb06a8c 9441 gdb_printf (stream, _("%*sAggregate\n"), depth, "");
d3c54a1c
TT
9442 for (const auto &item : m_components)
9443 item->dump (stream, depth + 1);
9444}
9445
9446void
9447ada_aggregate_component::assign (struct value *container,
9448 struct value *lhs, struct expression *exp,
9449 std::vector<LONGEST> &indices,
9450 LONGEST low, LONGEST high)
9451{
9452 for (auto &item : m_components)
9453 item->assign (container, lhs, exp, indices, low, high);
52ce6436
PH
9454}
9455
207582c0 9456/* See ada-exp.h. */
52ce6436 9457
207582c0 9458value *
d3c54a1c
TT
9459ada_aggregate_operation::assign_aggregate (struct value *container,
9460 struct value *lhs,
9461 struct expression *exp)
52ce6436
PH
9462{
9463 struct type *lhs_type;
52ce6436 9464 LONGEST low_index, high_index;
52ce6436
PH
9465
9466 container = ada_coerce_ref (container);
d0c97917 9467 if (ada_is_direct_array_type (container->type ()))
52ce6436
PH
9468 container = ada_coerce_to_simple_array (container);
9469 lhs = ada_coerce_ref (lhs);
4b53ca88 9470 if (!lhs->deprecated_modifiable ())
52ce6436
PH
9471 error (_("Left operand of assignment is not a modifiable lvalue."));
9472
d0c97917 9473 lhs_type = check_typedef (lhs->type ());
52ce6436
PH
9474 if (ada_is_direct_array_type (lhs_type))
9475 {
9476 lhs = ada_coerce_to_simple_array (lhs);
d0c97917 9477 lhs_type = check_typedef (lhs->type ());
cf88be68
SM
9478 low_index = lhs_type->bounds ()->low.const_val ();
9479 high_index = lhs_type->bounds ()->high.const_val ();
52ce6436 9480 }
78134374 9481 else if (lhs_type->code () == TYPE_CODE_STRUCT)
52ce6436
PH
9482 {
9483 low_index = 0;
9484 high_index = num_visible_fields (lhs_type) - 1;
52ce6436
PH
9485 }
9486 else
9487 error (_("Left-hand side must be array or record."));
9488
cf608cc4 9489 std::vector<LONGEST> indices (4);
52ce6436
PH
9490 indices[0] = indices[1] = low_index - 1;
9491 indices[2] = indices[3] = high_index + 1;
52ce6436 9492
d3c54a1c
TT
9493 std::get<0> (m_storage)->assign (container, lhs, exp, indices,
9494 low_index, high_index);
207582c0
TT
9495
9496 return container;
d3c54a1c
TT
9497}
9498
9499bool
9500ada_positional_component::uses_objfile (struct objfile *objfile)
9501{
9502 return m_op->uses_objfile (objfile);
9503}
52ce6436 9504
d3c54a1c
TT
9505void
9506ada_positional_component::dump (ui_file *stream, int depth)
9507{
6cb06a8c
TT
9508 gdb_printf (stream, _("%*sPositional, index = %d\n"),
9509 depth, "", m_index);
d3c54a1c 9510 m_op->dump (stream, depth + 1);
52ce6436 9511}
d3c54a1c 9512
52ce6436 9513/* Assign into the component of LHS indexed by the OP_POSITIONAL
d3c54a1c
TT
9514 construct, given that the positions are relative to lower bound
9515 LOW, where HIGH is the upper bound. Record the position in
9516 INDICES. CONTAINER is as for assign_aggregate. */
9517void
9518ada_positional_component::assign (struct value *container,
9519 struct value *lhs, struct expression *exp,
9520 std::vector<LONGEST> &indices,
9521 LONGEST low, LONGEST high)
52ce6436 9522{
d3c54a1c
TT
9523 LONGEST ind = m_index + low;
9524
52ce6436 9525 if (ind - 1 == high)
e1d5a0d2 9526 warning (_("Extra components in aggregate ignored."));
52ce6436
PH
9527 if (ind <= high)
9528 {
cf608cc4 9529 add_component_interval (ind, ind, indices);
d3c54a1c 9530 assign_component (container, lhs, ind, exp, m_op);
52ce6436 9531 }
52ce6436
PH
9532}
9533
d3c54a1c
TT
9534bool
9535ada_discrete_range_association::uses_objfile (struct objfile *objfile)
a88c4354
TT
9536{
9537 return m_low->uses_objfile (objfile) || m_high->uses_objfile (objfile);
9538}
9539
9540void
9541ada_discrete_range_association::dump (ui_file *stream, int depth)
9542{
6cb06a8c 9543 gdb_printf (stream, _("%*sDiscrete range:\n"), depth, "");
a88c4354
TT
9544 m_low->dump (stream, depth + 1);
9545 m_high->dump (stream, depth + 1);
9546}
9547
9548void
9549ada_discrete_range_association::assign (struct value *container,
9550 struct value *lhs,
9551 struct expression *exp,
9552 std::vector<LONGEST> &indices,
9553 LONGEST low, LONGEST high,
9554 operation_up &op)
9555{
9556 LONGEST lower = value_as_long (m_low->evaluate (nullptr, exp, EVAL_NORMAL));
9557 LONGEST upper = value_as_long (m_high->evaluate (nullptr, exp, EVAL_NORMAL));
9558
9559 if (lower <= upper && (lower < low || upper > high))
9560 error (_("Index in component association out of bounds."));
9561
9562 add_component_interval (lower, upper, indices);
9563 while (lower <= upper)
9564 {
9565 assign_component (container, lhs, lower, exp, op);
9566 lower += 1;
9567 }
9568}
9569
9570bool
9571ada_name_association::uses_objfile (struct objfile *objfile)
9572{
9573 return m_val->uses_objfile (objfile);
9574}
9575
9576void
9577ada_name_association::dump (ui_file *stream, int depth)
9578{
6cb06a8c 9579 gdb_printf (stream, _("%*sName:\n"), depth, "");
a88c4354
TT
9580 m_val->dump (stream, depth + 1);
9581}
9582
9583void
9584ada_name_association::assign (struct value *container,
9585 struct value *lhs,
9586 struct expression *exp,
9587 std::vector<LONGEST> &indices,
9588 LONGEST low, LONGEST high,
9589 operation_up &op)
9590{
9591 int index;
9592
d0c97917 9593 if (ada_is_direct_array_type (lhs->type ()))
a88c4354
TT
9594 index = longest_to_int (value_as_long (m_val->evaluate (nullptr, exp,
9595 EVAL_NORMAL)));
9596 else
9597 {
9598 ada_string_operation *strop
9599 = dynamic_cast<ada_string_operation *> (m_val.get ());
9600
9601 const char *name;
9602 if (strop != nullptr)
9603 name = strop->get_name ();
9604 else
9605 {
9606 ada_var_value_operation *vvo
9607 = dynamic_cast<ada_var_value_operation *> (m_val.get ());
94c5098e 9608 if (vvo == nullptr)
a88c4354
TT
9609 error (_("Invalid record component association."));
9610 name = vvo->get_symbol ()->natural_name ();
94c5098e
TT
9611 /* In this scenario, the user wrote (name => expr), but
9612 write_name_assoc found some fully-qualified name and
9613 substituted it. This happens because, at parse time, the
9614 meaning of the expression isn't known; but here we know
9615 that just the base name was supplied and it refers to the
9616 name of a field. */
9617 name = ada_unqualified_name (name);
a88c4354
TT
9618 }
9619
9620 index = 0;
d0c97917 9621 if (! find_struct_field (name, lhs->type (), 0,
a88c4354
TT
9622 NULL, NULL, NULL, NULL, &index))
9623 error (_("Unknown component name: %s."), name);
9624 }
9625
9626 add_component_interval (index, index, indices);
9627 assign_component (container, lhs, index, exp, op);
9628}
9629
9630bool
9631ada_choices_component::uses_objfile (struct objfile *objfile)
9632{
9633 if (m_op->uses_objfile (objfile))
9634 return true;
9635 for (const auto &item : m_assocs)
9636 if (item->uses_objfile (objfile))
9637 return true;
9638 return false;
9639}
9640
9641void
9642ada_choices_component::dump (ui_file *stream, int depth)
9643{
6cb06a8c 9644 gdb_printf (stream, _("%*sChoices:\n"), depth, "");
a88c4354
TT
9645 m_op->dump (stream, depth + 1);
9646 for (const auto &item : m_assocs)
9647 item->dump (stream, depth + 1);
9648}
9649
9650/* Assign into the components of LHS indexed by the OP_CHOICES
9651 construct at *POS, updating *POS past the construct, given that
9652 the allowable indices are LOW..HIGH. Record the indices assigned
9653 to in INDICES. CONTAINER is as for assign_aggregate. */
9654void
9655ada_choices_component::assign (struct value *container,
9656 struct value *lhs, struct expression *exp,
9657 std::vector<LONGEST> &indices,
9658 LONGEST low, LONGEST high)
9659{
9660 for (auto &item : m_assocs)
9661 item->assign (container, lhs, exp, indices, low, high, m_op);
9662}
9663
9664bool
9665ada_others_component::uses_objfile (struct objfile *objfile)
9666{
9667 return m_op->uses_objfile (objfile);
9668}
9669
9670void
9671ada_others_component::dump (ui_file *stream, int depth)
9672{
6cb06a8c 9673 gdb_printf (stream, _("%*sOthers:\n"), depth, "");
a88c4354
TT
9674 m_op->dump (stream, depth + 1);
9675}
9676
9677/* Assign the value of the expression in the OP_OTHERS construct in
9678 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
9679 have not been previously assigned. The index intervals already assigned
9680 are in INDICES. CONTAINER is as for assign_aggregate. */
9681void
9682ada_others_component::assign (struct value *container,
9683 struct value *lhs, struct expression *exp,
9684 std::vector<LONGEST> &indices,
9685 LONGEST low, LONGEST high)
9686{
9687 int num_indices = indices.size ();
9688 for (int i = 0; i < num_indices - 2; i += 2)
9689 {
9690 for (LONGEST ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
9691 assign_component (container, lhs, ind, exp, m_op);
9692 }
9693}
9694
9695struct value *
9696ada_assign_operation::evaluate (struct type *expect_type,
9697 struct expression *exp,
9698 enum noside noside)
9699{
9700 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
b3a27d2f 9701 scoped_restore save_lhs = make_scoped_restore (&m_current, arg1);
a88c4354
TT
9702
9703 ada_aggregate_operation *ag_op
9704 = dynamic_cast<ada_aggregate_operation *> (std::get<1> (m_storage).get ());
9705 if (ag_op != nullptr)
9706 {
9707 if (noside != EVAL_NORMAL)
9708 return arg1;
9709
207582c0 9710 arg1 = ag_op->assign_aggregate (arg1, arg1, exp);
a88c4354
TT
9711 return ada_value_assign (arg1, arg1);
9712 }
9713 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
9714 except if the lhs of our assignment is a convenience variable.
9715 In the case of assigning to a convenience variable, the lhs
9716 should be exactly the result of the evaluation of the rhs. */
d0c97917 9717 struct type *type = arg1->type ();
736355f2 9718 if (arg1->lval () == lval_internalvar)
a88c4354
TT
9719 type = NULL;
9720 value *arg2 = std::get<1> (m_storage)->evaluate (type, exp, noside);
0b2b0b82 9721 if (noside == EVAL_AVOID_SIDE_EFFECTS)
a88c4354 9722 return arg1;
736355f2 9723 if (arg1->lval () == lval_internalvar)
a88c4354
TT
9724 {
9725 /* Nothing. */
9726 }
9727 else
d0c97917 9728 arg2 = coerce_for_assign (arg1->type (), arg2);
a88c4354
TT
9729 return ada_value_assign (arg1, arg2);
9730}
9731
9732} /* namespace expr */
9733
cf608cc4
TT
9734/* Add the interval [LOW .. HIGH] to the sorted set of intervals
9735 [ INDICES[0] .. INDICES[1] ],... The resulting intervals do not
9736 overlap. */
52ce6436
PH
9737static void
9738add_component_interval (LONGEST low, LONGEST high,
cf608cc4 9739 std::vector<LONGEST> &indices)
52ce6436
PH
9740{
9741 int i, j;
5b4ee69b 9742
cf608cc4
TT
9743 int size = indices.size ();
9744 for (i = 0; i < size; i += 2) {
52ce6436
PH
9745 if (high >= indices[i] && low <= indices[i + 1])
9746 {
9747 int kh;
5b4ee69b 9748
cf608cc4 9749 for (kh = i + 2; kh < size; kh += 2)
52ce6436
PH
9750 if (high < indices[kh])
9751 break;
9752 if (low < indices[i])
9753 indices[i] = low;
9754 indices[i + 1] = indices[kh - 1];
9755 if (high > indices[i + 1])
9756 indices[i + 1] = high;
cf608cc4
TT
9757 memcpy (indices.data () + i + 2, indices.data () + kh, size - kh);
9758 indices.resize (kh - i - 2);
52ce6436
PH
9759 return;
9760 }
9761 else if (high < indices[i])
9762 break;
9763 }
9764
cf608cc4 9765 indices.resize (indices.size () + 2);
d4813f10 9766 for (j = indices.size () - 1; j >= i + 2; j -= 1)
52ce6436
PH
9767 indices[j] = indices[j - 2];
9768 indices[i] = low;
9769 indices[i + 1] = high;
9770}
9771
6e48bd2c
JB
9772/* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
9773 is different. */
9774
9775static struct value *
b7e22850 9776ada_value_cast (struct type *type, struct value *arg2)
6e48bd2c 9777{
d0c97917 9778 if (type == ada_check_typedef (arg2->type ()))
6e48bd2c
JB
9779 return arg2;
9780
6e48bd2c
JB
9781 return value_cast (type, arg2);
9782}
9783
284614f0
JB
9784/* Evaluating Ada expressions, and printing their result.
9785 ------------------------------------------------------
9786
21649b50
JB
9787 1. Introduction:
9788 ----------------
9789
284614f0
JB
9790 We usually evaluate an Ada expression in order to print its value.
9791 We also evaluate an expression in order to print its type, which
9792 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
9793 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
9794 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
9795 the evaluation compared to the EVAL_NORMAL, but is otherwise very
9796 similar.
9797
9798 Evaluating expressions is a little more complicated for Ada entities
9799 than it is for entities in languages such as C. The main reason for
9800 this is that Ada provides types whose definition might be dynamic.
9801 One example of such types is variant records. Or another example
9802 would be an array whose bounds can only be known at run time.
9803
9804 The following description is a general guide as to what should be
9805 done (and what should NOT be done) in order to evaluate an expression
9806 involving such types, and when. This does not cover how the semantic
9807 information is encoded by GNAT as this is covered separatly. For the
9808 document used as the reference for the GNAT encoding, see exp_dbug.ads
9809 in the GNAT sources.
9810
9811 Ideally, we should embed each part of this description next to its
9812 associated code. Unfortunately, the amount of code is so vast right
9813 now that it's hard to see whether the code handling a particular
9814 situation might be duplicated or not. One day, when the code is
9815 cleaned up, this guide might become redundant with the comments
9816 inserted in the code, and we might want to remove it.
9817
21649b50
JB
9818 2. ``Fixing'' an Entity, the Simple Case:
9819 -----------------------------------------
9820
284614f0
JB
9821 When evaluating Ada expressions, the tricky issue is that they may
9822 reference entities whose type contents and size are not statically
9823 known. Consider for instance a variant record:
9824
9825 type Rec (Empty : Boolean := True) is record
dda83cd7
SM
9826 case Empty is
9827 when True => null;
9828 when False => Value : Integer;
9829 end case;
284614f0
JB
9830 end record;
9831 Yes : Rec := (Empty => False, Value => 1);
9832 No : Rec := (empty => True);
9833
9834 The size and contents of that record depends on the value of the
33b5899f 9835 discriminant (Rec.Empty). At this point, neither the debugging
284614f0
JB
9836 information nor the associated type structure in GDB are able to
9837 express such dynamic types. So what the debugger does is to create
9838 "fixed" versions of the type that applies to the specific object.
30baf67b 9839 We also informally refer to this operation as "fixing" an object,
284614f0
JB
9840 which means creating its associated fixed type.
9841
9842 Example: when printing the value of variable "Yes" above, its fixed
9843 type would look like this:
9844
9845 type Rec is record
dda83cd7
SM
9846 Empty : Boolean;
9847 Value : Integer;
284614f0
JB
9848 end record;
9849
9850 On the other hand, if we printed the value of "No", its fixed type
9851 would become:
9852
9853 type Rec is record
dda83cd7 9854 Empty : Boolean;
284614f0
JB
9855 end record;
9856
9857 Things become a little more complicated when trying to fix an entity
9858 with a dynamic type that directly contains another dynamic type,
9859 such as an array of variant records, for instance. There are
9860 two possible cases: Arrays, and records.
9861
21649b50
JB
9862 3. ``Fixing'' Arrays:
9863 ---------------------
9864
9865 The type structure in GDB describes an array in terms of its bounds,
9866 and the type of its elements. By design, all elements in the array
9867 have the same type and we cannot represent an array of variant elements
9868 using the current type structure in GDB. When fixing an array,
9869 we cannot fix the array element, as we would potentially need one
9870 fixed type per element of the array. As a result, the best we can do
9871 when fixing an array is to produce an array whose bounds and size
9872 are correct (allowing us to read it from memory), but without having
9873 touched its element type. Fixing each element will be done later,
9874 when (if) necessary.
9875
9876 Arrays are a little simpler to handle than records, because the same
9877 amount of memory is allocated for each element of the array, even if
1b536f04 9878 the amount of space actually used by each element differs from element
21649b50 9879 to element. Consider for instance the following array of type Rec:
284614f0
JB
9880
9881 type Rec_Array is array (1 .. 2) of Rec;
9882
1b536f04
JB
9883 The actual amount of memory occupied by each element might be different
9884 from element to element, depending on the value of their discriminant.
21649b50 9885 But the amount of space reserved for each element in the array remains
1b536f04 9886 fixed regardless. So we simply need to compute that size using
21649b50
JB
9887 the debugging information available, from which we can then determine
9888 the array size (we multiply the number of elements of the array by
9889 the size of each element).
9890
9891 The simplest case is when we have an array of a constrained element
9892 type. For instance, consider the following type declarations:
9893
dda83cd7
SM
9894 type Bounded_String (Max_Size : Integer) is
9895 Length : Integer;
9896 Buffer : String (1 .. Max_Size);
9897 end record;
9898 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
21649b50
JB
9899
9900 In this case, the compiler describes the array as an array of
9901 variable-size elements (identified by its XVS suffix) for which
9902 the size can be read in the parallel XVZ variable.
9903
9904 In the case of an array of an unconstrained element type, the compiler
9905 wraps the array element inside a private PAD type. This type should not
9906 be shown to the user, and must be "unwrap"'ed before printing. Note
284614f0
JB
9907 that we also use the adjective "aligner" in our code to designate
9908 these wrapper types.
9909
1b536f04 9910 In some cases, the size allocated for each element is statically
21649b50
JB
9911 known. In that case, the PAD type already has the correct size,
9912 and the array element should remain unfixed.
9913
9914 But there are cases when this size is not statically known.
9915 For instance, assuming that "Five" is an integer variable:
284614f0 9916
dda83cd7
SM
9917 type Dynamic is array (1 .. Five) of Integer;
9918 type Wrapper (Has_Length : Boolean := False) is record
9919 Data : Dynamic;
9920 case Has_Length is
9921 when True => Length : Integer;
9922 when False => null;
9923 end case;
9924 end record;
9925 type Wrapper_Array is array (1 .. 2) of Wrapper;
284614f0 9926
dda83cd7
SM
9927 Hello : Wrapper_Array := (others => (Has_Length => True,
9928 Data => (others => 17),
9929 Length => 1));
284614f0
JB
9930
9931
9932 The debugging info would describe variable Hello as being an
9933 array of a PAD type. The size of that PAD type is not statically
9934 known, but can be determined using a parallel XVZ variable.
9935 In that case, a copy of the PAD type with the correct size should
9936 be used for the fixed array.
9937
21649b50
JB
9938 3. ``Fixing'' record type objects:
9939 ----------------------------------
9940
9941 Things are slightly different from arrays in the case of dynamic
284614f0
JB
9942 record types. In this case, in order to compute the associated
9943 fixed type, we need to determine the size and offset of each of
9944 its components. This, in turn, requires us to compute the fixed
9945 type of each of these components.
9946
9947 Consider for instance the example:
9948
dda83cd7
SM
9949 type Bounded_String (Max_Size : Natural) is record
9950 Str : String (1 .. Max_Size);
9951 Length : Natural;
9952 end record;
9953 My_String : Bounded_String (Max_Size => 10);
284614f0
JB
9954
9955 In that case, the position of field "Length" depends on the size
9956 of field Str, which itself depends on the value of the Max_Size
21649b50 9957 discriminant. In order to fix the type of variable My_String,
284614f0
JB
9958 we need to fix the type of field Str. Therefore, fixing a variant
9959 record requires us to fix each of its components.
9960
9961 However, if a component does not have a dynamic size, the component
9962 should not be fixed. In particular, fields that use a PAD type
9963 should not fixed. Here is an example where this might happen
9964 (assuming type Rec above):
9965
9966 type Container (Big : Boolean) is record
dda83cd7
SM
9967 First : Rec;
9968 After : Integer;
9969 case Big is
9970 when True => Another : Integer;
9971 when False => null;
9972 end case;
284614f0
JB
9973 end record;
9974 My_Container : Container := (Big => False,
dda83cd7
SM
9975 First => (Empty => True),
9976 After => 42);
284614f0
JB
9977
9978 In that example, the compiler creates a PAD type for component First,
9979 whose size is constant, and then positions the component After just
9980 right after it. The offset of component After is therefore constant
9981 in this case.
9982
9983 The debugger computes the position of each field based on an algorithm
9984 that uses, among other things, the actual position and size of the field
21649b50
JB
9985 preceding it. Let's now imagine that the user is trying to print
9986 the value of My_Container. If the type fixing was recursive, we would
284614f0
JB
9987 end up computing the offset of field After based on the size of the
9988 fixed version of field First. And since in our example First has
9989 only one actual field, the size of the fixed type is actually smaller
9990 than the amount of space allocated to that field, and thus we would
9991 compute the wrong offset of field After.
9992
21649b50
JB
9993 To make things more complicated, we need to watch out for dynamic
9994 components of variant records (identified by the ___XVL suffix in
9995 the component name). Even if the target type is a PAD type, the size
9996 of that type might not be statically known. So the PAD type needs
9997 to be unwrapped and the resulting type needs to be fixed. Otherwise,
9998 we might end up with the wrong size for our component. This can be
9999 observed with the following type declarations:
284614f0 10000
dda83cd7
SM
10001 type Octal is new Integer range 0 .. 7;
10002 type Octal_Array is array (Positive range <>) of Octal;
10003 pragma Pack (Octal_Array);
284614f0 10004
dda83cd7
SM
10005 type Octal_Buffer (Size : Positive) is record
10006 Buffer : Octal_Array (1 .. Size);
10007 Length : Integer;
10008 end record;
284614f0
JB
10009
10010 In that case, Buffer is a PAD type whose size is unset and needs
10011 to be computed by fixing the unwrapped type.
10012
21649b50
JB
10013 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10014 ----------------------------------------------------------
10015
10016 Lastly, when should the sub-elements of an entity that remained unfixed
284614f0
JB
10017 thus far, be actually fixed?
10018
10019 The answer is: Only when referencing that element. For instance
10020 when selecting one component of a record, this specific component
10021 should be fixed at that point in time. Or when printing the value
10022 of a record, each component should be fixed before its value gets
10023 printed. Similarly for arrays, the element of the array should be
10024 fixed when printing each element of the array, or when extracting
10025 one element out of that array. On the other hand, fixing should
10026 not be performed on the elements when taking a slice of an array!
10027
31432a67 10028 Note that one of the side effects of miscomputing the offset and
284614f0
JB
10029 size of each field is that we end up also miscomputing the size
10030 of the containing type. This can have adverse results when computing
10031 the value of an entity. GDB fetches the value of an entity based
10032 on the size of its type, and thus a wrong size causes GDB to fetch
10033 the wrong amount of memory. In the case where the computed size is
10034 too small, GDB fetches too little data to print the value of our
31432a67 10035 entity. Results in this case are unpredictable, as we usually read
284614f0
JB
10036 past the buffer containing the data =:-o. */
10037
62d4bd94
TT
10038/* A helper function for TERNOP_IN_RANGE. */
10039
10040static value *
10041eval_ternop_in_range (struct type *expect_type, struct expression *exp,
10042 enum noside noside,
10043 value *arg1, value *arg2, value *arg3)
10044{
62d4bd94
TT
10045 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10046 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10047 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
10048 return
10049 value_from_longest (type,
10050 (value_less (arg1, arg3)
10051 || value_equal (arg1, arg3))
10052 && (value_less (arg2, arg1)
10053 || value_equal (arg2, arg1)));
10054}
10055
82390ab8
TT
10056/* A helper function for UNOP_NEG. */
10057
7c15d377 10058value *
82390ab8
TT
10059ada_unop_neg (struct type *expect_type,
10060 struct expression *exp,
10061 enum noside noside, enum exp_opcode op,
10062 struct value *arg1)
10063{
82390ab8
TT
10064 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10065 return value_neg (arg1);
10066}
10067
7efc87ff
TT
10068/* A helper function for UNOP_IN_RANGE. */
10069
95d49dfb 10070value *
7efc87ff
TT
10071ada_unop_in_range (struct type *expect_type,
10072 struct expression *exp,
10073 enum noside noside, enum exp_opcode op,
10074 struct value *arg1, struct type *type)
10075{
7efc87ff
TT
10076 struct value *arg2, *arg3;
10077 switch (type->code ())
10078 {
10079 default:
10080 lim_warning (_("Membership test incompletely implemented; "
10081 "always returns true"));
10082 type = language_bool_type (exp->language_defn, exp->gdbarch);
66cf9350 10083 return value_from_longest (type, 1);
7efc87ff
TT
10084
10085 case TYPE_CODE_RANGE:
10086 arg2 = value_from_longest (type,
10087 type->bounds ()->low.const_val ());
10088 arg3 = value_from_longest (type,
10089 type->bounds ()->high.const_val ());
10090 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10091 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10092 type = language_bool_type (exp->language_defn, exp->gdbarch);
10093 return
10094 value_from_longest (type,
10095 (value_less (arg1, arg3)
10096 || value_equal (arg1, arg3))
10097 && (value_less (arg2, arg1)
10098 || value_equal (arg2, arg1)));
10099 }
10100}
10101
020dbabe
TT
10102/* A helper function for OP_ATR_TAG. */
10103
7c15d377 10104value *
020dbabe
TT
10105ada_atr_tag (struct type *expect_type,
10106 struct expression *exp,
10107 enum noside noside, enum exp_opcode op,
10108 struct value *arg1)
10109{
10110 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10111 return value::zero (ada_tag_type (arg1), not_lval);
020dbabe
TT
10112
10113 return ada_value_tag (arg1);
10114}
10115
68c75735
TT
10116/* A helper function for OP_ATR_SIZE. */
10117
7c15d377 10118value *
68c75735
TT
10119ada_atr_size (struct type *expect_type,
10120 struct expression *exp,
10121 enum noside noside, enum exp_opcode op,
10122 struct value *arg1)
10123{
d0c97917 10124 struct type *type = arg1->type ();
68c75735
TT
10125
10126 /* If the argument is a reference, then dereference its type, since
10127 the user is really asking for the size of the actual object,
10128 not the size of the pointer. */
10129 if (type->code () == TYPE_CODE_REF)
27710edb 10130 type = type->target_type ();
68c75735 10131
0b2b0b82 10132 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10133 return value::zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
68c75735
TT
10134 else
10135 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
df86565b 10136 TARGET_CHAR_BIT * type->length ());
68c75735
TT
10137}
10138
d05e24e6
TT
10139/* A helper function for UNOP_ABS. */
10140
7c15d377 10141value *
d05e24e6
TT
10142ada_abs (struct type *expect_type,
10143 struct expression *exp,
10144 enum noside noside, enum exp_opcode op,
10145 struct value *arg1)
10146{
10147 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
ee7bb294 10148 if (value_less (arg1, value::zero (arg1->type (), not_lval)))
d05e24e6
TT
10149 return value_neg (arg1);
10150 else
10151 return arg1;
10152}
10153
faa1dfd7
TT
10154/* A helper function for BINOP_MUL. */
10155
d9e7db06 10156value *
faa1dfd7
TT
10157ada_mult_binop (struct type *expect_type,
10158 struct expression *exp,
10159 enum noside noside, enum exp_opcode op,
10160 struct value *arg1, struct value *arg2)
10161{
10162 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10163 {
10164 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
ee7bb294 10165 return value::zero (arg1->type (), not_lval);
faa1dfd7
TT
10166 }
10167 else
10168 {
10169 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10170 return ada_value_binop (arg1, arg2, op);
10171 }
10172}
10173
214b13ac
TT
10174/* A helper function for BINOP_EQUAL and BINOP_NOTEQUAL. */
10175
6e8fb7b7 10176value *
214b13ac
TT
10177ada_equal_binop (struct type *expect_type,
10178 struct expression *exp,
10179 enum noside noside, enum exp_opcode op,
10180 struct value *arg1, struct value *arg2)
10181{
10182 int tem;
10183 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10184 tem = 0;
10185 else
10186 {
10187 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10188 tem = ada_value_equal (arg1, arg2);
10189 }
10190 if (op == BINOP_NOTEQUAL)
10191 tem = !tem;
10192 struct type *type = language_bool_type (exp->language_defn, exp->gdbarch);
66cf9350 10193 return value_from_longest (type, tem);
214b13ac
TT
10194}
10195
5ce19db8
TT
10196/* A helper function for TERNOP_SLICE. */
10197
1b1ebfab 10198value *
5ce19db8
TT
10199ada_ternop_slice (struct expression *exp,
10200 enum noside noside,
10201 struct value *array, struct value *low_bound_val,
10202 struct value *high_bound_val)
10203{
10204 LONGEST low_bound;
10205 LONGEST high_bound;
10206
10207 low_bound_val = coerce_ref (low_bound_val);
10208 high_bound_val = coerce_ref (high_bound_val);
10209 low_bound = value_as_long (low_bound_val);
10210 high_bound = value_as_long (high_bound_val);
10211
10212 /* If this is a reference to an aligner type, then remove all
10213 the aligners. */
d0c97917
TT
10214 if (array->type ()->code () == TYPE_CODE_REF
10215 && ada_is_aligner_type (array->type ()->target_type ()))
10216 array->type ()->set_target_type
10217 (ada_aligned_type (array->type ()->target_type ()));
5ce19db8 10218
d0c97917 10219 if (ada_is_any_packed_array_type (array->type ()))
5ce19db8
TT
10220 error (_("cannot slice a packed array"));
10221
10222 /* If this is a reference to an array or an array lvalue,
10223 convert to a pointer. */
d0c97917
TT
10224 if (array->type ()->code () == TYPE_CODE_REF
10225 || (array->type ()->code () == TYPE_CODE_ARRAY
736355f2 10226 && array->lval () == lval_memory))
5ce19db8
TT
10227 array = value_addr (array);
10228
10229 if (noside == EVAL_AVOID_SIDE_EFFECTS
10230 && ada_is_array_descriptor_type (ada_check_typedef
d0c97917 10231 (array->type ())))
5ce19db8
TT
10232 return empty_array (ada_type_of_array (array, 0), low_bound,
10233 high_bound);
10234
10235 array = ada_coerce_to_simple_array_ptr (array);
10236
10237 /* If we have more than one level of pointer indirection,
10238 dereference the value until we get only one level. */
d0c97917
TT
10239 while (array->type ()->code () == TYPE_CODE_PTR
10240 && (array->type ()->target_type ()->code ()
5ce19db8
TT
10241 == TYPE_CODE_PTR))
10242 array = value_ind (array);
10243
10244 /* Make sure we really do have an array type before going further,
10245 to avoid a SEGV when trying to get the index type or the target
10246 type later down the road if the debug info generated by
10247 the compiler is incorrect or incomplete. */
d0c97917 10248 if (!ada_is_simple_array_type (array->type ()))
5ce19db8
TT
10249 error (_("cannot take slice of non-array"));
10250
d0c97917 10251 if (ada_check_typedef (array->type ())->code ()
5ce19db8
TT
10252 == TYPE_CODE_PTR)
10253 {
d0c97917 10254 struct type *type0 = ada_check_typedef (array->type ());
5ce19db8
TT
10255
10256 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
27710edb 10257 return empty_array (type0->target_type (), low_bound, high_bound);
5ce19db8
TT
10258 else
10259 {
10260 struct type *arr_type0 =
27710edb 10261 to_fixed_array_type (type0->target_type (), NULL, 1);
5ce19db8
TT
10262
10263 return ada_value_slice_from_ptr (array, arr_type0,
10264 longest_to_int (low_bound),
10265 longest_to_int (high_bound));
10266 }
10267 }
10268 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10269 return array;
10270 else if (high_bound < low_bound)
d0c97917 10271 return empty_array (array->type (), low_bound, high_bound);
5ce19db8
TT
10272 else
10273 return ada_value_slice (array, longest_to_int (low_bound),
10274 longest_to_int (high_bound));
10275}
10276
b467efaa
TT
10277/* A helper function for BINOP_IN_BOUNDS. */
10278
82c3886e 10279value *
b467efaa
TT
10280ada_binop_in_bounds (struct expression *exp, enum noside noside,
10281 struct value *arg1, struct value *arg2, int n)
10282{
10283 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10284 {
10285 struct type *type = language_bool_type (exp->language_defn,
10286 exp->gdbarch);
ee7bb294 10287 return value::zero (type, not_lval);
b467efaa
TT
10288 }
10289
d0c97917 10290 struct type *type = ada_index_type (arg2->type (), n, "range");
b467efaa 10291 if (!type)
d0c97917 10292 type = arg1->type ();
b467efaa
TT
10293
10294 value *arg3 = value_from_longest (type, ada_array_bound (arg2, n, 1));
10295 arg2 = value_from_longest (type, ada_array_bound (arg2, n, 0));
10296
10297 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10298 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10299 type = language_bool_type (exp->language_defn, exp->gdbarch);
10300 return value_from_longest (type,
10301 (value_less (arg1, arg3)
10302 || value_equal (arg1, arg3))
10303 && (value_less (arg2, arg1)
10304 || value_equal (arg2, arg1)));
10305}
10306
b84564fc
TT
10307/* A helper function for some attribute operations. */
10308
10309static value *
10310ada_unop_atr (struct expression *exp, enum noside noside, enum exp_opcode op,
10311 struct value *arg1, struct type *type_arg, int tem)
10312{
1e5ae3d1
TT
10313 const char *attr_name = nullptr;
10314 if (op == OP_ATR_FIRST)
10315 attr_name = "first";
10316 else if (op == OP_ATR_LAST)
10317 attr_name = "last";
10318
b84564fc
TT
10319 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10320 {
10321 if (type_arg == NULL)
d0c97917 10322 type_arg = arg1->type ();
b84564fc
TT
10323
10324 if (ada_is_constrained_packed_array_type (type_arg))
10325 type_arg = decode_constrained_packed_array_type (type_arg);
10326
10327 if (!discrete_type_p (type_arg))
10328 {
10329 switch (op)
10330 {
10331 default: /* Should never happen. */
10332 error (_("unexpected attribute encountered"));
10333 case OP_ATR_FIRST:
10334 case OP_ATR_LAST:
10335 type_arg = ada_index_type (type_arg, tem,
1e5ae3d1 10336 attr_name);
b84564fc
TT
10337 break;
10338 case OP_ATR_LENGTH:
10339 type_arg = builtin_type (exp->gdbarch)->builtin_int;
10340 break;
10341 }
10342 }
10343
ee7bb294 10344 return value::zero (type_arg, not_lval);
b84564fc
TT
10345 }
10346 else if (type_arg == NULL)
10347 {
10348 arg1 = ada_coerce_ref (arg1);
10349
d0c97917 10350 if (ada_is_constrained_packed_array_type (arg1->type ()))
b84564fc
TT
10351 arg1 = ada_coerce_to_simple_array (arg1);
10352
10353 struct type *type;
10354 if (op == OP_ATR_LENGTH)
10355 type = builtin_type (exp->gdbarch)->builtin_int;
10356 else
10357 {
d0c97917 10358 type = ada_index_type (arg1->type (), tem,
1e5ae3d1 10359 attr_name);
b84564fc
TT
10360 if (type == NULL)
10361 type = builtin_type (exp->gdbarch)->builtin_int;
10362 }
10363
10364 switch (op)
10365 {
10366 default: /* Should never happen. */
10367 error (_("unexpected attribute encountered"));
10368 case OP_ATR_FIRST:
10369 return value_from_longest
10370 (type, ada_array_bound (arg1, tem, 0));
10371 case OP_ATR_LAST:
10372 return value_from_longest
10373 (type, ada_array_bound (arg1, tem, 1));
10374 case OP_ATR_LENGTH:
10375 return value_from_longest
10376 (type, ada_array_length (arg1, tem));
10377 }
10378 }
10379 else if (discrete_type_p (type_arg))
10380 {
10381 struct type *range_type;
10382 const char *name = ada_type_name (type_arg);
10383
10384 range_type = NULL;
10385 if (name != NULL && type_arg->code () != TYPE_CODE_ENUM)
10386 range_type = to_fixed_range_type (type_arg, NULL);
10387 if (range_type == NULL)
10388 range_type = type_arg;
10389 switch (op)
10390 {
10391 default:
10392 error (_("unexpected attribute encountered"));
10393 case OP_ATR_FIRST:
10394 return value_from_longest
10395 (range_type, ada_discrete_type_low_bound (range_type));
10396 case OP_ATR_LAST:
10397 return value_from_longest
10398 (range_type, ada_discrete_type_high_bound (range_type));
10399 case OP_ATR_LENGTH:
10400 error (_("the 'length attribute applies only to array types"));
10401 }
10402 }
10403 else if (type_arg->code () == TYPE_CODE_FLT)
10404 error (_("unimplemented type attribute"));
10405 else
10406 {
10407 LONGEST low, high;
10408
10409 if (ada_is_constrained_packed_array_type (type_arg))
10410 type_arg = decode_constrained_packed_array_type (type_arg);
10411
10412 struct type *type;
10413 if (op == OP_ATR_LENGTH)
10414 type = builtin_type (exp->gdbarch)->builtin_int;
10415 else
10416 {
1e5ae3d1 10417 type = ada_index_type (type_arg, tem, attr_name);
b84564fc
TT
10418 if (type == NULL)
10419 type = builtin_type (exp->gdbarch)->builtin_int;
10420 }
10421
10422 switch (op)
10423 {
10424 default:
10425 error (_("unexpected attribute encountered"));
10426 case OP_ATR_FIRST:
10427 low = ada_array_bound_from_type (type_arg, tem, 0);
10428 return value_from_longest (type, low);
10429 case OP_ATR_LAST:
10430 high = ada_array_bound_from_type (type_arg, tem, 1);
10431 return value_from_longest (type, high);
10432 case OP_ATR_LENGTH:
10433 low = ada_array_bound_from_type (type_arg, tem, 0);
10434 high = ada_array_bound_from_type (type_arg, tem, 1);
10435 return value_from_longest (type, high - low + 1);
10436 }
10437 }
10438}
10439
38dc70cf
TT
10440/* A helper function for OP_ATR_MIN and OP_ATR_MAX. */
10441
6ad3b8bf 10442struct value *
38dc70cf
TT
10443ada_binop_minmax (struct type *expect_type,
10444 struct expression *exp,
10445 enum noside noside, enum exp_opcode op,
10446 struct value *arg1, struct value *arg2)
10447{
10448 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10449 return value::zero (arg1->type (), not_lval);
38dc70cf
TT
10450 else
10451 {
10452 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
0922dc84 10453 return value_binop (arg1, arg2, op);
38dc70cf
TT
10454 }
10455}
10456
dd5fd283
TT
10457/* A helper function for BINOP_EXP. */
10458
065ec826 10459struct value *
dd5fd283
TT
10460ada_binop_exp (struct type *expect_type,
10461 struct expression *exp,
10462 enum noside noside, enum exp_opcode op,
10463 struct value *arg1, struct value *arg2)
10464{
10465 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10466 return value::zero (arg1->type (), not_lval);
dd5fd283
TT
10467 else
10468 {
10469 /* For integer exponentiation operations,
10470 only promote the first argument. */
d0c97917 10471 if (is_integral_type (arg2->type ()))
dd5fd283
TT
10472 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10473 else
10474 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10475
10476 return value_binop (arg1, arg2, op);
10477 }
10478}
10479
03070ee9
TT
10480namespace expr
10481{
10482
8b12db26
TT
10483/* See ada-exp.h. */
10484
10485operation_up
10486ada_resolvable::replace (operation_up &&owner,
10487 struct expression *exp,
10488 bool deprocedure_p,
10489 bool parse_completion,
10490 innermost_block_tracker *tracker,
10491 struct type *context_type)
10492{
10493 if (resolve (exp, deprocedure_p, parse_completion, tracker, context_type))
10494 return (make_operation<ada_funcall_operation>
10495 (std::move (owner),
10496 std::vector<operation_up> ()));
10497 return std::move (owner);
10498}
10499
c9f66f00 10500/* Convert the character literal whose value would be VAL to the
03adb248
TT
10501 appropriate value of type TYPE, if there is a translation.
10502 Otherwise return VAL. Hence, in an enumeration type ('A', 'B'),
10503 the literal 'A' (VAL == 65), returns 0. */
10504
10505static LONGEST
10506convert_char_literal (struct type *type, LONGEST val)
10507{
c9f66f00 10508 char name[12];
03adb248
TT
10509 int f;
10510
10511 if (type == NULL)
10512 return val;
10513 type = check_typedef (type);
10514 if (type->code () != TYPE_CODE_ENUM)
10515 return val;
10516
10517 if ((val >= 'a' && val <= 'z') || (val >= '0' && val <= '9'))
10518 xsnprintf (name, sizeof (name), "Q%c", (int) val);
c9f66f00
TT
10519 else if (val >= 0 && val < 256)
10520 xsnprintf (name, sizeof (name), "QU%02x", (unsigned) val);
10521 else if (val >= 0 && val < 0x10000)
10522 xsnprintf (name, sizeof (name), "QW%04x", (unsigned) val);
03adb248 10523 else
c9f66f00 10524 xsnprintf (name, sizeof (name), "QWW%08lx", (unsigned long) val);
03adb248
TT
10525 size_t len = strlen (name);
10526 for (f = 0; f < type->num_fields (); f += 1)
10527 {
10528 /* Check the suffix because an enum constant in a package will
10529 have a name like "pkg__QUxx". This is safe enough because we
10530 already have the correct type, and because mangling means
10531 there can't be clashes. */
33d16dd9 10532 const char *ename = type->field (f).name ();
03adb248
TT
10533 size_t elen = strlen (ename);
10534
10535 if (elen >= len && strcmp (name, ename + elen - len) == 0)
970db518 10536 return type->field (f).loc_enumval ();
03adb248
TT
10537 }
10538 return val;
10539}
10540
b1b9c411
TT
10541value *
10542ada_char_operation::evaluate (struct type *expect_type,
10543 struct expression *exp,
10544 enum noside noside)
10545{
10546 value *result = long_const_operation::evaluate (expect_type, exp, noside);
10547 if (expect_type != nullptr)
10548 result = ada_value_cast (expect_type, result);
10549 return result;
10550}
10551
03adb248
TT
10552/* See ada-exp.h. */
10553
10554operation_up
10555ada_char_operation::replace (operation_up &&owner,
10556 struct expression *exp,
10557 bool deprocedure_p,
10558 bool parse_completion,
10559 innermost_block_tracker *tracker,
10560 struct type *context_type)
10561{
10562 operation_up result = std::move (owner);
10563
10564 if (context_type != nullptr && context_type->code () == TYPE_CODE_ENUM)
10565 {
5309ce2f 10566 LONGEST val = as_longest ();
03adb248
TT
10567 gdb_assert (result.get () == this);
10568 std::get<0> (m_storage) = context_type;
5309ce2f 10569 std::get<1> (m_storage) = convert_char_literal (context_type, val);
03adb248
TT
10570 }
10571
b1b9c411 10572 return result;
03adb248
TT
10573}
10574
03070ee9
TT
10575value *
10576ada_wrapped_operation::evaluate (struct type *expect_type,
10577 struct expression *exp,
10578 enum noside noside)
10579{
10580 value *result = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10581 if (noside == EVAL_NORMAL)
10582 result = unwrap_value (result);
10583
10584 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10585 then we need to perform the conversion manually, because
10586 evaluate_subexp_standard doesn't do it. This conversion is
10587 necessary in Ada because the different kinds of float/fixed
10588 types in Ada have different representations.
10589
10590 Similarly, we need to perform the conversion from OP_LONG
10591 ourselves. */
10592 if ((opcode () == OP_FLOAT || opcode () == OP_LONG) && expect_type != NULL)
10593 result = ada_value_cast (expect_type, result);
10594
10595 return result;
10596}
10597
013a623f
TT
10598void
10599ada_wrapped_operation::do_generate_ax (struct expression *exp,
10600 struct agent_expr *ax,
10601 struct axs_value *value,
10602 struct type *cast_type)
10603{
10604 std::get<0> (m_storage)->generate_ax (exp, ax, value, cast_type);
10605
10606 struct type *type = value->type;
10607 if (ada_is_aligner_type (type))
10608 error (_("Aligner types cannot be handled in agent expressions"));
10609 else if (find_base_type (type) != nullptr)
10610 error (_("Dynamic types cannot be handled in agent expressions"));
10611}
10612
42fecb61
TT
10613value *
10614ada_string_operation::evaluate (struct type *expect_type,
10615 struct expression *exp,
10616 enum noside noside)
10617{
fc18a21b
TT
10618 struct type *char_type;
10619 if (expect_type != nullptr && ada_is_string_type (expect_type))
10620 char_type = ada_array_element_type (expect_type, 1);
10621 else
10622 char_type = language_string_char_type (exp->language_defn, exp->gdbarch);
10623
10624 const std::string &str = std::get<0> (m_storage);
10625 const char *encoding;
df86565b 10626 switch (char_type->length ())
fc18a21b
TT
10627 {
10628 case 1:
10629 {
10630 /* Simply copy over the data -- this isn't perhaps strictly
10631 correct according to the encodings, but it is gdb's
10632 historical behavior. */
10633 struct type *stringtype
10634 = lookup_array_range_type (char_type, 1, str.length ());
317c3ed9 10635 struct value *val = value::allocate (stringtype);
bbe912ba 10636 memcpy (val->contents_raw ().data (), str.c_str (),
fc18a21b
TT
10637 str.length ());
10638 return val;
10639 }
10640
10641 case 2:
10642 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10643 encoding = "UTF-16BE";
10644 else
10645 encoding = "UTF-16LE";
10646 break;
10647
10648 case 4:
10649 if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
10650 encoding = "UTF-32BE";
10651 else
10652 encoding = "UTF-32LE";
10653 break;
10654
10655 default:
10656 error (_("unexpected character type size %s"),
df86565b 10657 pulongest (char_type->length ()));
fc18a21b
TT
10658 }
10659
10660 auto_obstack converted;
10661 convert_between_encodings (host_charset (), encoding,
10662 (const gdb_byte *) str.c_str (),
10663 str.length (), 1,
10664 &converted, translit_none);
10665
10666 struct type *stringtype
10667 = lookup_array_range_type (char_type, 1,
10668 obstack_object_size (&converted)
df86565b 10669 / char_type->length ());
317c3ed9 10670 struct value *val = value::allocate (stringtype);
bbe912ba 10671 memcpy (val->contents_raw ().data (),
fc18a21b
TT
10672 obstack_base (&converted),
10673 obstack_object_size (&converted));
10674 return val;
42fecb61
TT
10675}
10676
b1b9c411
TT
10677value *
10678ada_concat_operation::evaluate (struct type *expect_type,
10679 struct expression *exp,
10680 enum noside noside)
10681{
10682 /* If one side is a literal, evaluate the other side first so that
10683 the expected type can be set properly. */
10684 const operation_up &lhs_expr = std::get<0> (m_storage);
10685 const operation_up &rhs_expr = std::get<1> (m_storage);
10686
10687 value *lhs, *rhs;
10688 if (dynamic_cast<ada_string_operation *> (lhs_expr.get ()) != nullptr)
10689 {
10690 rhs = rhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10691 lhs = lhs_expr->evaluate (rhs->type (), exp, noside);
b1b9c411
TT
10692 }
10693 else if (dynamic_cast<ada_char_operation *> (lhs_expr.get ()) != nullptr)
10694 {
10695 rhs = rhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10696 struct type *rhs_type = check_typedef (rhs->type ());
b1b9c411
TT
10697 struct type *elt_type = nullptr;
10698 if (rhs_type->code () == TYPE_CODE_ARRAY)
27710edb 10699 elt_type = rhs_type->target_type ();
b1b9c411
TT
10700 lhs = lhs_expr->evaluate (elt_type, exp, noside);
10701 }
10702 else if (dynamic_cast<ada_string_operation *> (rhs_expr.get ()) != nullptr)
10703 {
10704 lhs = lhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10705 rhs = rhs_expr->evaluate (lhs->type (), exp, noside);
b1b9c411
TT
10706 }
10707 else if (dynamic_cast<ada_char_operation *> (rhs_expr.get ()) != nullptr)
10708 {
10709 lhs = lhs_expr->evaluate (nullptr, exp, noside);
d0c97917 10710 struct type *lhs_type = check_typedef (lhs->type ());
b1b9c411
TT
10711 struct type *elt_type = nullptr;
10712 if (lhs_type->code () == TYPE_CODE_ARRAY)
27710edb 10713 elt_type = lhs_type->target_type ();
b1b9c411
TT
10714 rhs = rhs_expr->evaluate (elt_type, exp, noside);
10715 }
10716 else
10717 return concat_operation::evaluate (expect_type, exp, noside);
10718
10719 return value_concat (lhs, rhs);
10720}
10721
cc6bd32e
TT
10722value *
10723ada_qual_operation::evaluate (struct type *expect_type,
10724 struct expression *exp,
10725 enum noside noside)
10726{
10727 struct type *type = std::get<1> (m_storage);
10728 return std::get<0> (m_storage)->evaluate (type, exp, noside);
10729}
10730
fc715eb2
TT
10731value *
10732ada_ternop_range_operation::evaluate (struct type *expect_type,
10733 struct expression *exp,
10734 enum noside noside)
10735{
10736 value *arg0 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10737 value *arg1 = std::get<1> (m_storage)->evaluate (nullptr, exp, noside);
10738 value *arg2 = std::get<2> (m_storage)->evaluate (nullptr, exp, noside);
10739 return eval_ternop_in_range (expect_type, exp, noside, arg0, arg1, arg2);
10740}
10741
73796c73
TT
10742value *
10743ada_binop_addsub_operation::evaluate (struct type *expect_type,
10744 struct expression *exp,
10745 enum noside noside)
10746{
10747 value *arg1 = std::get<1> (m_storage)->evaluate_with_coercion (exp, noside);
10748 value *arg2 = std::get<2> (m_storage)->evaluate_with_coercion (exp, noside);
10749
5bd5fecd 10750 auto do_op = [this] (LONGEST x, LONGEST y)
73796c73
TT
10751 {
10752 if (std::get<0> (m_storage) == BINOP_ADD)
10753 return x + y;
10754 return x - y;
10755 };
10756
d0c97917 10757 if (arg1->type ()->code () == TYPE_CODE_PTR)
73796c73 10758 return (value_from_longest
d0c97917 10759 (arg1->type (),
73796c73 10760 do_op (value_as_long (arg1), value_as_long (arg2))));
d0c97917 10761 if (arg2->type ()->code () == TYPE_CODE_PTR)
73796c73 10762 return (value_from_longest
d0c97917 10763 (arg2->type (),
73796c73
TT
10764 do_op (value_as_long (arg1), value_as_long (arg2))));
10765 /* Preserve the original type for use by the range case below.
10766 We cannot cast the result to a reference type, so if ARG1 is
10767 a reference type, find its underlying type. */
d0c97917 10768 struct type *type = arg1->type ();
73796c73 10769 while (type->code () == TYPE_CODE_REF)
27710edb 10770 type = type->target_type ();
73796c73
TT
10771 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10772 arg1 = value_binop (arg1, arg2, std::get<0> (m_storage));
10773 /* We need to special-case the result with a range.
10774 This is done for the benefit of "ptype". gdb's Ada support
10775 historically used the LHS to set the result type here, so
10776 preserve this behavior. */
10777 if (type->code () == TYPE_CODE_RANGE)
10778 arg1 = value_cast (type, arg1);
10779 return arg1;
10780}
10781
60fa02ca
TT
10782value *
10783ada_unop_atr_operation::evaluate (struct type *expect_type,
10784 struct expression *exp,
10785 enum noside noside)
10786{
10787 struct type *type_arg = nullptr;
10788 value *val = nullptr;
10789
10790 if (std::get<0> (m_storage)->opcode () == OP_TYPE)
10791 {
10792 value *tem = std::get<0> (m_storage)->evaluate (nullptr, exp,
10793 EVAL_AVOID_SIDE_EFFECTS);
d0c97917 10794 type_arg = tem->type ();
60fa02ca
TT
10795 }
10796 else
10797 val = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
10798
10799 return ada_unop_atr (exp, noside, std::get<1> (m_storage),
10800 val, type_arg, std::get<2> (m_storage));
10801}
10802
3f4a0053
TT
10803value *
10804ada_var_msym_value_operation::evaluate_for_cast (struct type *expect_type,
10805 struct expression *exp,
10806 enum noside noside)
10807{
10808 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 10809 return value::zero (expect_type, not_lval);
3f4a0053 10810
9c79936b
TT
10811 const bound_minimal_symbol &b = std::get<0> (m_storage);
10812 value *val = evaluate_var_msym_value (noside, b.objfile, b.minsym);
3f4a0053
TT
10813
10814 val = ada_value_cast (expect_type, val);
10815
10816 /* Follow the Ada language semantics that do not allow taking
10817 an address of the result of a cast (view conversion in Ada). */
736355f2 10818 if (val->lval () == lval_memory)
3f4a0053 10819 {
3ee3b270 10820 if (val->lazy ())
78259c36 10821 val->fetch_lazy ();
6f9c9d71 10822 val->set_lval (not_lval);
3f4a0053
TT
10823 }
10824 return val;
10825}
10826
99a3b1e7
TT
10827value *
10828ada_var_value_operation::evaluate_for_cast (struct type *expect_type,
10829 struct expression *exp,
10830 enum noside noside)
10831{
10832 value *val = evaluate_var_value (noside,
9e5e03df
TT
10833 std::get<0> (m_storage).block,
10834 std::get<0> (m_storage).symbol);
99a3b1e7
TT
10835
10836 val = ada_value_cast (expect_type, val);
10837
10838 /* Follow the Ada language semantics that do not allow taking
10839 an address of the result of a cast (view conversion in Ada). */
736355f2 10840 if (val->lval () == lval_memory)
99a3b1e7 10841 {
3ee3b270 10842 if (val->lazy ())
78259c36 10843 val->fetch_lazy ();
6f9c9d71 10844 val->set_lval (not_lval);
99a3b1e7
TT
10845 }
10846 return val;
10847}
10848
10849value *
10850ada_var_value_operation::evaluate (struct type *expect_type,
10851 struct expression *exp,
10852 enum noside noside)
10853{
9e5e03df 10854 symbol *sym = std::get<0> (m_storage).symbol;
99a3b1e7 10855
6c9c307c 10856 if (sym->domain () == UNDEF_DOMAIN)
99a3b1e7
TT
10857 /* Only encountered when an unresolved symbol occurs in a
10858 context other than a function call, in which case, it is
10859 invalid. */
10860 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10861 sym->print_name ());
10862
10863 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10864 {
5f9c5a63 10865 struct type *type = static_unwrap_type (sym->type ());
99a3b1e7
TT
10866 /* Check to see if this is a tagged type. We also need to handle
10867 the case where the type is a reference to a tagged type, but
10868 we have to be careful to exclude pointers to tagged types.
10869 The latter should be shown as usual (as a pointer), whereas
10870 a reference should mostly be transparent to the user. */
10871 if (ada_is_tagged_type (type, 0)
10872 || (type->code () == TYPE_CODE_REF
27710edb 10873 && ada_is_tagged_type (type->target_type (), 0)))
99a3b1e7
TT
10874 {
10875 /* Tagged types are a little special in the fact that the real
10876 type is dynamic and can only be determined by inspecting the
10877 object's tag. This means that we need to get the object's
10878 value first (EVAL_NORMAL) and then extract the actual object
10879 type from its tag.
10880
10881 Note that we cannot skip the final step where we extract
10882 the object type from its tag, because the EVAL_NORMAL phase
10883 results in dynamic components being resolved into fixed ones.
10884 This can cause problems when trying to print the type
10885 description of tagged types whose parent has a dynamic size:
10886 We use the type name of the "_parent" component in order
10887 to print the name of the ancestor type in the type description.
10888 If that component had a dynamic size, the resolution into
10889 a fixed type would result in the loss of that type name,
10890 thus preventing us from printing the name of the ancestor
10891 type in the type description. */
9863c3b5 10892 value *arg1 = evaluate (nullptr, exp, EVAL_NORMAL);
99a3b1e7
TT
10893
10894 if (type->code () != TYPE_CODE_REF)
10895 {
10896 struct type *actual_type;
10897
10898 actual_type = type_from_tag (ada_value_tag (arg1));
10899 if (actual_type == NULL)
10900 /* If, for some reason, we were unable to determine
10901 the actual type from the tag, then use the static
10902 approximation that we just computed as a fallback.
10903 This can happen if the debugging information is
10904 incomplete, for instance. */
10905 actual_type = type;
ee7bb294 10906 return value::zero (actual_type, not_lval);
99a3b1e7
TT
10907 }
10908 else
10909 {
10910 /* In the case of a ref, ada_coerce_ref takes care
10911 of determining the actual type. But the evaluation
10912 should return a ref as it should be valid to ask
10913 for its address; so rebuild a ref after coerce. */
10914 arg1 = ada_coerce_ref (arg1);
10915 return value_ref (arg1, TYPE_CODE_REF);
10916 }
10917 }
10918
10919 /* Records and unions for which GNAT encodings have been
10920 generated need to be statically fixed as well.
10921 Otherwise, non-static fixing produces a type where
10922 all dynamic properties are removed, which prevents "ptype"
10923 from being able to completely describe the type.
10924 For instance, a case statement in a variant record would be
10925 replaced by the relevant components based on the actual
10926 value of the discriminants. */
10927 if ((type->code () == TYPE_CODE_STRUCT
10928 && dynamic_template_type (type) != NULL)
10929 || (type->code () == TYPE_CODE_UNION
10930 && ada_find_parallel_type (type, "___XVU") != NULL))
ee7bb294 10931 return value::zero (to_static_fixed_type (type), not_lval);
99a3b1e7
TT
10932 }
10933
10934 value *arg1 = var_value_operation::evaluate (expect_type, exp, noside);
10935 return ada_to_fixed_value (arg1);
10936}
10937
d8a4ed8a
TT
10938bool
10939ada_var_value_operation::resolve (struct expression *exp,
10940 bool deprocedure_p,
10941 bool parse_completion,
10942 innermost_block_tracker *tracker,
10943 struct type *context_type)
10944{
9e5e03df 10945 symbol *sym = std::get<0> (m_storage).symbol;
6c9c307c 10946 if (sym->domain () == UNDEF_DOMAIN)
d8a4ed8a
TT
10947 {
10948 block_symbol resolved
9e5e03df 10949 = ada_resolve_variable (sym, std::get<0> (m_storage).block,
d8a4ed8a
TT
10950 context_type, parse_completion,
10951 deprocedure_p, tracker);
9e5e03df 10952 std::get<0> (m_storage) = resolved;
d8a4ed8a
TT
10953 }
10954
10955 if (deprocedure_p
5f9c5a63 10956 && (std::get<0> (m_storage).symbol->type ()->code ()
9e5e03df 10957 == TYPE_CODE_FUNC))
d8a4ed8a
TT
10958 return true;
10959
10960 return false;
10961}
10962
013a623f
TT
10963void
10964ada_var_value_operation::do_generate_ax (struct expression *exp,
10965 struct agent_expr *ax,
10966 struct axs_value *value,
10967 struct type *cast_type)
10968{
10969 symbol *sym = std::get<0> (m_storage).symbol;
10970
10971 if (sym->domain () == UNDEF_DOMAIN)
10972 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10973 sym->print_name ());
10974
10975 struct type *type = static_unwrap_type (sym->type ());
10976 if (ada_is_tagged_type (type, 0)
10977 || (type->code () == TYPE_CODE_REF
10978 && ada_is_tagged_type (type->target_type (), 0)))
10979 error (_("Tagged types cannot be handled in agent expressions"));
10980
10981 if ((type->code () == TYPE_CODE_STRUCT
10982 && dynamic_template_type (type) != NULL)
10983 || (type->code () == TYPE_CODE_UNION
10984 && ada_find_parallel_type (type, "___XVU") != NULL))
10985 error (_("Dynamic types cannot be handled in agent expressions"));
10986
10987 var_value_operation::do_generate_ax (exp, ax, value, cast_type);
10988}
10989
e8c33fa1
TT
10990value *
10991ada_unop_ind_operation::evaluate (struct type *expect_type,
10992 struct expression *exp,
10993 enum noside noside)
10994{
10995 value *arg1 = std::get<0> (m_storage)->evaluate (expect_type, exp, noside);
10996
d0c97917 10997 struct type *type = ada_check_typedef (arg1->type ());
e8c33fa1
TT
10998 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10999 {
11000 if (ada_is_array_descriptor_type (type))
11001 /* GDB allows dereferencing GNAT array descriptors. */
11002 {
11003 struct type *arrType = ada_type_of_array (arg1, 0);
11004
11005 if (arrType == NULL)
11006 error (_("Attempt to dereference null array pointer."));
11007 return value_at_lazy (arrType, 0);
11008 }
11009 else if (type->code () == TYPE_CODE_PTR
11010 || type->code () == TYPE_CODE_REF
11011 /* In C you can dereference an array to get the 1st elt. */
11012 || type->code () == TYPE_CODE_ARRAY)
11013 {
11014 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11015 only be determined by inspecting the object's tag.
11016 This means that we need to evaluate completely the
11017 expression in order to get its type. */
11018
11019 if ((type->code () == TYPE_CODE_REF
11020 || type->code () == TYPE_CODE_PTR)
27710edb 11021 && ada_is_tagged_type (type->target_type (), 0))
e8c33fa1
TT
11022 {
11023 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11024 EVAL_NORMAL);
d0c97917 11025 type = ada_value_ind (arg1)->type ();
e8c33fa1
TT
11026 }
11027 else
11028 {
11029 type = to_static_fixed_type
11030 (ada_aligned_type
27710edb 11031 (ada_check_typedef (type->target_type ())));
e8c33fa1 11032 }
ee7bb294 11033 return value::zero (type, lval_memory);
e8c33fa1
TT
11034 }
11035 else if (type->code () == TYPE_CODE_INT)
11036 {
11037 /* GDB allows dereferencing an int. */
11038 if (expect_type == NULL)
ee7bb294 11039 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
e8c33fa1
TT
11040 lval_memory);
11041 else
11042 {
11043 expect_type =
11044 to_static_fixed_type (ada_aligned_type (expect_type));
ee7bb294 11045 return value::zero (expect_type, lval_memory);
e8c33fa1
TT
11046 }
11047 }
11048 else
11049 error (_("Attempt to take contents of a non-pointer value."));
11050 }
11051 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
d0c97917 11052 type = ada_check_typedef (arg1->type ());
e8c33fa1
TT
11053
11054 if (type->code () == TYPE_CODE_INT)
11055 /* GDB allows dereferencing an int. If we were given
11056 the expect_type, then use that as the target type.
11057 Otherwise, assume that the target type is an int. */
11058 {
11059 if (expect_type != NULL)
11060 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11061 arg1));
11062 else
11063 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11064 (CORE_ADDR) value_as_address (arg1));
11065 }
11066
11067 if (ada_is_array_descriptor_type (type))
11068 /* GDB allows dereferencing GNAT array descriptors. */
11069 return ada_coerce_to_simple_array (arg1);
11070 else
11071 return ada_value_ind (arg1);
11072}
11073
ebc06ad8
TT
11074value *
11075ada_structop_operation::evaluate (struct type *expect_type,
11076 struct expression *exp,
11077 enum noside noside)
11078{
11079 value *arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp, noside);
11080 const char *str = std::get<1> (m_storage).c_str ();
11081 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11082 {
11083 struct type *type;
d0c97917 11084 struct type *type1 = arg1->type ();
ebc06ad8
TT
11085
11086 if (ada_is_tagged_type (type1, 1))
11087 {
11088 type = ada_lookup_struct_elt_type (type1, str, 1, 1);
11089
11090 /* If the field is not found, check if it exists in the
11091 extension of this object's type. This means that we
11092 need to evaluate completely the expression. */
11093
11094 if (type == NULL)
11095 {
11096 arg1 = std::get<0> (m_storage)->evaluate (nullptr, exp,
11097 EVAL_NORMAL);
11098 arg1 = ada_value_struct_elt (arg1, str, 0);
11099 arg1 = unwrap_value (arg1);
d0c97917 11100 type = ada_to_fixed_value (arg1)->type ();
ebc06ad8
TT
11101 }
11102 }
11103 else
11104 type = ada_lookup_struct_elt_type (type1, str, 1, 0);
11105
ee7bb294 11106 return value::zero (ada_aligned_type (type), lval_memory);
ebc06ad8
TT
11107 }
11108 else
11109 {
11110 arg1 = ada_value_struct_elt (arg1, str, 0);
11111 arg1 = unwrap_value (arg1);
11112 return ada_to_fixed_value (arg1);
11113 }
11114}
11115
efe3af2f
TT
11116value *
11117ada_funcall_operation::evaluate (struct type *expect_type,
11118 struct expression *exp,
11119 enum noside noside)
11120{
11121 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11122 int nargs = args_up.size ();
11123 std::vector<value *> argvec (nargs);
11124 operation_up &callee_op = std::get<0> (m_storage);
11125
11126 ada_var_value_operation *avv
11127 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11128 if (avv != nullptr
6c9c307c 11129 && avv->get_symbol ()->domain () == UNDEF_DOMAIN)
efe3af2f
TT
11130 error (_("Unexpected unresolved symbol, %s, during evaluation"),
11131 avv->get_symbol ()->print_name ());
11132
11133 value *callee = callee_op->evaluate (nullptr, exp, noside);
11134 for (int i = 0; i < args_up.size (); ++i)
11135 argvec[i] = args_up[i]->evaluate (nullptr, exp, noside);
11136
11137 if (ada_is_constrained_packed_array_type
d0c97917 11138 (desc_base_type (callee->type ())))
efe3af2f 11139 callee = ada_coerce_to_simple_array (callee);
d0c97917 11140 else if (callee->type ()->code () == TYPE_CODE_ARRAY
3757d2d4 11141 && callee->type ()->field (0).bitsize () != 0)
efe3af2f
TT
11142 /* This is a packed array that has already been fixed, and
11143 therefore already coerced to a simple array. Nothing further
11144 to do. */
11145 ;
d0c97917 11146 else if (callee->type ()->code () == TYPE_CODE_REF)
efe3af2f
TT
11147 {
11148 /* Make sure we dereference references so that all the code below
11149 feels like it's really handling the referenced value. Wrapping
11150 types (for alignment) may be there, so make sure we strip them as
11151 well. */
11152 callee = ada_to_fixed_value (coerce_ref (callee));
11153 }
d0c97917 11154 else if (callee->type ()->code () == TYPE_CODE_ARRAY
736355f2 11155 && callee->lval () == lval_memory)
efe3af2f
TT
11156 callee = value_addr (callee);
11157
d0c97917 11158 struct type *type = ada_check_typedef (callee->type ());
efe3af2f
TT
11159
11160 /* Ada allows us to implicitly dereference arrays when subscripting
11161 them. So, if this is an array typedef (encoding use for array
11162 access types encoded as fat pointers), strip it now. */
11163 if (type->code () == TYPE_CODE_TYPEDEF)
11164 type = ada_typedef_target_type (type);
11165
11166 if (type->code () == TYPE_CODE_PTR)
11167 {
27710edb 11168 switch (ada_check_typedef (type->target_type ())->code ())
efe3af2f
TT
11169 {
11170 case TYPE_CODE_FUNC:
27710edb 11171 type = ada_check_typedef (type->target_type ());
efe3af2f
TT
11172 break;
11173 case TYPE_CODE_ARRAY:
11174 break;
11175 case TYPE_CODE_STRUCT:
11176 if (noside != EVAL_AVOID_SIDE_EFFECTS)
11177 callee = ada_value_ind (callee);
27710edb 11178 type = ada_check_typedef (type->target_type ());
efe3af2f
TT
11179 break;
11180 default:
11181 error (_("cannot subscript or call something of type `%s'"),
d0c97917 11182 ada_type_name (callee->type ()));
efe3af2f
TT
11183 break;
11184 }
11185 }
11186
11187 switch (type->code ())
11188 {
11189 case TYPE_CODE_FUNC:
11190 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11191 {
27710edb 11192 if (type->target_type () == NULL)
efe3af2f 11193 error_call_unknown_return_type (NULL);
317c3ed9 11194 return value::allocate (type->target_type ());
efe3af2f 11195 }
61f9fb1e 11196 return call_function_by_hand (callee, expect_type, argvec);
efe3af2f
TT
11197 case TYPE_CODE_INTERNAL_FUNCTION:
11198 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11199 /* We don't know anything about what the internal
11200 function might return, but we have to return
11201 something. */
ee7bb294 11202 return value::zero (builtin_type (exp->gdbarch)->builtin_int,
efe3af2f
TT
11203 not_lval);
11204 else
11205 return call_internal_function (exp->gdbarch, exp->language_defn,
11206 callee, nargs,
11207 argvec.data ());
11208
d3c54a1c
TT
11209 case TYPE_CODE_STRUCT:
11210 {
11211 int arity;
4c4b4cd2 11212
d3c54a1c
TT
11213 arity = ada_array_arity (type);
11214 type = ada_array_element_type (type, nargs);
11215 if (type == NULL)
11216 error (_("cannot subscript or call a record"));
11217 if (arity != nargs)
11218 error (_("wrong number of subscripts; expecting %d"), arity);
11219 if (noside == EVAL_AVOID_SIDE_EFFECTS)
ee7bb294 11220 return value::zero (ada_aligned_type (type), lval_memory);
d3c54a1c
TT
11221 return
11222 unwrap_value (ada_value_subscript
11223 (callee, nargs, argvec.data ()));
11224 }
11225 case TYPE_CODE_ARRAY:
14f9c5c9 11226 if (noside == EVAL_AVOID_SIDE_EFFECTS)
dda83cd7 11227 {
d3c54a1c
TT
11228 type = ada_array_element_type (type, nargs);
11229 if (type == NULL)
11230 error (_("element type of array unknown"));
dda83cd7 11231 else
ee7bb294 11232 return value::zero (ada_aligned_type (type), lval_memory);
dda83cd7 11233 }
d3c54a1c
TT
11234 return
11235 unwrap_value (ada_value_subscript
11236 (ada_coerce_to_simple_array (callee),
11237 nargs, argvec.data ()));
11238 case TYPE_CODE_PTR: /* Pointer to array */
11239 if (noside == EVAL_AVOID_SIDE_EFFECTS)
dda83cd7 11240 {
27710edb 11241 type = to_fixed_array_type (type->target_type (), NULL, 1);
d3c54a1c
TT
11242 type = ada_array_element_type (type, nargs);
11243 if (type == NULL)
11244 error (_("element type of array unknown"));
96967637 11245 else
ee7bb294 11246 return value::zero (ada_aligned_type (type), lval_memory);
dda83cd7 11247 }
d3c54a1c
TT
11248 return
11249 unwrap_value (ada_value_ptr_subscript (callee, nargs,
11250 argvec.data ()));
6b0d7253 11251
d3c54a1c
TT
11252 default:
11253 error (_("Attempt to index or call something other than an "
11254 "array or function"));
11255 }
11256}
5b4ee69b 11257
d3c54a1c
TT
11258bool
11259ada_funcall_operation::resolve (struct expression *exp,
11260 bool deprocedure_p,
11261 bool parse_completion,
11262 innermost_block_tracker *tracker,
11263 struct type *context_type)
11264{
11265 operation_up &callee_op = std::get<0> (m_storage);
5ec18f2b 11266
d3c54a1c
TT
11267 ada_var_value_operation *avv
11268 = dynamic_cast<ada_var_value_operation *> (callee_op.get ());
11269 if (avv == nullptr)
11270 return false;
5ec18f2b 11271
d3c54a1c 11272 symbol *sym = avv->get_symbol ();
6c9c307c 11273 if (sym->domain () != UNDEF_DOMAIN)
d3c54a1c 11274 return false;
dda83cd7 11275
d3c54a1c
TT
11276 const std::vector<operation_up> &args_up = std::get<1> (m_storage);
11277 int nargs = args_up.size ();
11278 std::vector<value *> argvec (nargs);
284614f0 11279
d3c54a1c
TT
11280 for (int i = 0; i < args_up.size (); ++i)
11281 argvec[i] = args_up[i]->evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
52ce6436 11282
d3c54a1c
TT
11283 const block *block = avv->get_block ();
11284 block_symbol resolved
11285 = ada_resolve_funcall (sym, block,
11286 context_type, parse_completion,
11287 nargs, argvec.data (),
11288 tracker);
11289
11290 std::get<0> (m_storage)
9e5e03df 11291 = make_operation<ada_var_value_operation> (resolved);
d3c54a1c
TT
11292 return false;
11293}
11294
11295bool
11296ada_ternop_slice_operation::resolve (struct expression *exp,
11297 bool deprocedure_p,
11298 bool parse_completion,
11299 innermost_block_tracker *tracker,
11300 struct type *context_type)
11301{
11302 /* Historically this check was done during resolution, so we
11303 continue that here. */
11304 value *v = std::get<0> (m_storage)->evaluate (context_type, exp,
11305 EVAL_AVOID_SIDE_EFFECTS);
d0c97917 11306 if (ada_is_any_packed_array_type (v->type ()))
d3c54a1c
TT
11307 error (_("cannot slice a packed array"));
11308 return false;
11309}
14f9c5c9 11310
14f9c5c9 11311}
d3c54a1c 11312
14f9c5c9 11313\f
d2e4a39e 11314
4c4b4cd2
PH
11315/* Return non-zero iff TYPE represents a System.Address type. */
11316
11317int
11318ada_is_system_address_type (struct type *type)
11319{
7d93a1e0 11320 return (type->name () && strcmp (type->name (), "system__address") == 0);
4c4b4cd2
PH
11321}
11322
14f9c5c9 11323\f
d2e4a39e 11324
dda83cd7 11325 /* Range types */
14f9c5c9
AS
11326
11327/* Scan STR beginning at position K for a discriminant name, and
11328 return the value of that discriminant field of DVAL in *PX. If
11329 PNEW_K is not null, put the position of the character beyond the
11330 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
4c4b4cd2 11331 not alter *PX and *PNEW_K if unsuccessful. */
14f9c5c9
AS
11332
11333static int
108d56a4 11334scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
dda83cd7 11335 int *pnew_k)
14f9c5c9 11336{
5f9febe0 11337 static std::string storage;
5da1a4d3 11338 const char *pstart, *pend, *bound;
d2e4a39e 11339 struct value *bound_val;
14f9c5c9
AS
11340
11341 if (dval == NULL || str == NULL || str[k] == '\0')
11342 return 0;
11343
5da1a4d3
SM
11344 pstart = str + k;
11345 pend = strstr (pstart, "__");
14f9c5c9
AS
11346 if (pend == NULL)
11347 {
5da1a4d3 11348 bound = pstart;
14f9c5c9
AS
11349 k += strlen (bound);
11350 }
d2e4a39e 11351 else
14f9c5c9 11352 {
5da1a4d3
SM
11353 int len = pend - pstart;
11354
11355 /* Strip __ and beyond. */
5f9febe0
TT
11356 storage = std::string (pstart, len);
11357 bound = storage.c_str ();
d2e4a39e 11358 k = pend - str;
14f9c5c9 11359 }
d2e4a39e 11360
d0c97917 11361 bound_val = ada_search_struct_field (bound, dval, 0, dval->type ());
14f9c5c9
AS
11362 if (bound_val == NULL)
11363 return 0;
11364
11365 *px = value_as_long (bound_val);
11366 if (pnew_k != NULL)
11367 *pnew_k = k;
11368 return 1;
11369}
11370
25a1127b
TT
11371/* Value of variable named NAME. Only exact matches are considered.
11372 If no such variable found, then if ERR_MSG is null, returns 0, and
4c4b4cd2
PH
11373 otherwise causes an error with message ERR_MSG. */
11374
d2e4a39e 11375static struct value *
edb0c9cb 11376get_var_value (const char *name, const char *err_msg)
14f9c5c9 11377{
25a1127b
TT
11378 std::string quoted_name = add_angle_brackets (name);
11379
11380 lookup_name_info lookup_name (quoted_name, symbol_name_match_type::FULL);
14f9c5c9 11381
d1183b06
TT
11382 std::vector<struct block_symbol> syms
11383 = ada_lookup_symbol_list_worker (lookup_name,
11384 get_selected_block (0),
11385 VAR_DOMAIN, 1);
14f9c5c9 11386
d1183b06 11387 if (syms.size () != 1)
14f9c5c9
AS
11388 {
11389 if (err_msg == NULL)
dda83cd7 11390 return 0;
14f9c5c9 11391 else
dda83cd7 11392 error (("%s"), err_msg);
14f9c5c9
AS
11393 }
11394
54d343a2 11395 return value_of_variable (syms[0].symbol, syms[0].block);
14f9c5c9 11396}
d2e4a39e 11397
edb0c9cb
PA
11398/* Value of integer variable named NAME in the current environment.
11399 If no such variable is found, returns false. Otherwise, sets VALUE
11400 to the variable's value and returns true. */
4c4b4cd2 11401
edb0c9cb
PA
11402bool
11403get_int_var_value (const char *name, LONGEST &value)
14f9c5c9 11404{
4c4b4cd2 11405 struct value *var_val = get_var_value (name, 0);
d2e4a39e 11406
14f9c5c9 11407 if (var_val == 0)
edb0c9cb
PA
11408 return false;
11409
11410 value = value_as_long (var_val);
11411 return true;
14f9c5c9 11412}
d2e4a39e 11413
14f9c5c9
AS
11414
11415/* Return a range type whose base type is that of the range type named
11416 NAME in the current environment, and whose bounds are calculated
4c4b4cd2 11417 from NAME according to the GNAT range encoding conventions.
1ce677a4
UW
11418 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11419 corresponding range type from debug information; fall back to using it
11420 if symbol lookup fails. If a new type must be created, allocate it
11421 like ORIG_TYPE was. The bounds information, in general, is encoded
11422 in NAME, the base type given in the named range type. */
14f9c5c9 11423
d2e4a39e 11424static struct type *
28c85d6c 11425to_fixed_range_type (struct type *raw_type, struct value *dval)
14f9c5c9 11426{
0d5cff50 11427 const char *name;
14f9c5c9 11428 struct type *base_type;
108d56a4 11429 const char *subtype_info;
14f9c5c9 11430
28c85d6c 11431 gdb_assert (raw_type != NULL);
7d93a1e0 11432 gdb_assert (raw_type->name () != NULL);
dddfab26 11433
78134374 11434 if (raw_type->code () == TYPE_CODE_RANGE)
27710edb 11435 base_type = raw_type->target_type ();
14f9c5c9
AS
11436 else
11437 base_type = raw_type;
11438
7d93a1e0 11439 name = raw_type->name ();
14f9c5c9
AS
11440 subtype_info = strstr (name, "___XD");
11441 if (subtype_info == NULL)
690cc4eb 11442 {
43bbcdc2
PH
11443 LONGEST L = ada_discrete_type_low_bound (raw_type);
11444 LONGEST U = ada_discrete_type_high_bound (raw_type);
5b4ee69b 11445
690cc4eb
PH
11446 if (L < INT_MIN || U > INT_MAX)
11447 return raw_type;
11448 else
e727c536
TT
11449 {
11450 type_allocator alloc (raw_type);
11451 return create_static_range_type (alloc, raw_type, L, U);
11452 }
690cc4eb 11453 }
14f9c5c9
AS
11454 else
11455 {
14f9c5c9
AS
11456 int prefix_len = subtype_info - name;
11457 LONGEST L, U;
11458 struct type *type;
108d56a4 11459 const char *bounds_str;
14f9c5c9
AS
11460 int n;
11461
14f9c5c9
AS
11462 subtype_info += 5;
11463 bounds_str = strchr (subtype_info, '_');
11464 n = 1;
11465
d2e4a39e 11466 if (*subtype_info == 'L')
dda83cd7
SM
11467 {
11468 if (!ada_scan_number (bounds_str, n, &L, &n)
11469 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11470 return raw_type;
11471 if (bounds_str[n] == '_')
11472 n += 2;
11473 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11474 n += 1;
11475 subtype_info += 1;
11476 }
d2e4a39e 11477 else
dda83cd7 11478 {
5f9febe0
TT
11479 std::string name_buf = std::string (name, prefix_len) + "___L";
11480 if (!get_int_var_value (name_buf.c_str (), L))
dda83cd7
SM
11481 {
11482 lim_warning (_("Unknown lower bound, using 1."));
11483 L = 1;
11484 }
11485 }
14f9c5c9 11486
d2e4a39e 11487 if (*subtype_info == 'U')
dda83cd7
SM
11488 {
11489 if (!ada_scan_number (bounds_str, n, &U, &n)
11490 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11491 return raw_type;
11492 }
d2e4a39e 11493 else
dda83cd7 11494 {
5f9febe0
TT
11495 std::string name_buf = std::string (name, prefix_len) + "___U";
11496 if (!get_int_var_value (name_buf.c_str (), U))
dda83cd7
SM
11497 {
11498 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11499 U = L;
11500 }
11501 }
14f9c5c9 11502
e727c536
TT
11503 type_allocator alloc (raw_type);
11504 type = create_static_range_type (alloc, base_type, L, U);
f5a91472 11505 /* create_static_range_type alters the resulting type's length
dda83cd7
SM
11506 to match the size of the base_type, which is not what we want.
11507 Set it back to the original range type's length. */
df86565b 11508 type->set_length (raw_type->length ());
d0e39ea2 11509 type->set_name (name);
14f9c5c9
AS
11510 return type;
11511 }
11512}
11513
4c4b4cd2
PH
11514/* True iff NAME is the name of a range type. */
11515
14f9c5c9 11516int
d2e4a39e 11517ada_is_range_type_name (const char *name)
14f9c5c9
AS
11518{
11519 return (name != NULL && strstr (name, "___XD"));
d2e4a39e 11520}
14f9c5c9 11521\f
d2e4a39e 11522
dda83cd7 11523 /* Modular types */
4c4b4cd2
PH
11524
11525/* True iff TYPE is an Ada modular type. */
14f9c5c9 11526
14f9c5c9 11527int
d2e4a39e 11528ada_is_modular_type (struct type *type)
14f9c5c9 11529{
18af8284 11530 struct type *subranged_type = get_base_type (type);
14f9c5c9 11531
78134374 11532 return (subranged_type != NULL && type->code () == TYPE_CODE_RANGE
dda83cd7
SM
11533 && subranged_type->code () == TYPE_CODE_INT
11534 && subranged_type->is_unsigned ());
14f9c5c9
AS
11535}
11536
4c4b4cd2
PH
11537/* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11538
61ee279c 11539ULONGEST
0056e4d5 11540ada_modulus (struct type *type)
14f9c5c9 11541{
5e500d33
SM
11542 const dynamic_prop &high = type->bounds ()->high;
11543
9c0fb734 11544 if (high.is_constant ())
5e500d33
SM
11545 return (ULONGEST) high.const_val () + 1;
11546
11547 /* If TYPE is unresolved, the high bound might be a location list. Return
11548 0, for lack of a better value to return. */
11549 return 0;
14f9c5c9 11550}
d2e4a39e 11551\f
f7f9143b
JB
11552
11553/* Ada exception catchpoint support:
11554 ---------------------------------
11555
11556 We support 3 kinds of exception catchpoints:
11557 . catchpoints on Ada exceptions
11558 . catchpoints on unhandled Ada exceptions
11559 . catchpoints on failed assertions
11560
11561 Exceptions raised during failed assertions, or unhandled exceptions
11562 could perfectly be caught with the general catchpoint on Ada exceptions.
11563 However, we can easily differentiate these two special cases, and having
11564 the option to distinguish these two cases from the rest can be useful
11565 to zero-in on certain situations.
11566
11567 Exception catchpoints are a specialized form of breakpoint,
11568 since they rely on inserting breakpoints inside known routines
11569 of the GNAT runtime. The implementation therefore uses a standard
11570 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11571 of breakpoint_ops.
11572
0259addd
JB
11573 Support in the runtime for exception catchpoints have been changed
11574 a few times already, and these changes affect the implementation
11575 of these catchpoints. In order to be able to support several
11576 variants of the runtime, we use a sniffer that will determine
28010a5d 11577 the runtime variant used by the program being debugged. */
f7f9143b 11578
82eacd52
JB
11579/* Ada's standard exceptions.
11580
11581 The Ada 83 standard also defined Numeric_Error. But there so many
11582 situations where it was unclear from the Ada 83 Reference Manual
11583 (RM) whether Constraint_Error or Numeric_Error should be raised,
11584 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11585 Interpretation saying that anytime the RM says that Numeric_Error
11586 should be raised, the implementation may raise Constraint_Error.
11587 Ada 95 went one step further and pretty much removed Numeric_Error
11588 from the list of standard exceptions (it made it a renaming of
11589 Constraint_Error, to help preserve compatibility when compiling
11590 an Ada83 compiler). As such, we do not include Numeric_Error from
11591 this list of standard exceptions. */
3d0b0fa3 11592
27087b7f 11593static const char * const standard_exc[] = {
3d0b0fa3
JB
11594 "constraint_error",
11595 "program_error",
11596 "storage_error",
11597 "tasking_error"
11598};
11599
0259addd
JB
11600typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11601
11602/* A structure that describes how to support exception catchpoints
11603 for a given executable. */
11604
11605struct exception_support_info
11606{
11607 /* The name of the symbol to break on in order to insert
11608 a catchpoint on exceptions. */
11609 const char *catch_exception_sym;
11610
11611 /* The name of the symbol to break on in order to insert
11612 a catchpoint on unhandled exceptions. */
11613 const char *catch_exception_unhandled_sym;
11614
11615 /* The name of the symbol to break on in order to insert
11616 a catchpoint on failed assertions. */
11617 const char *catch_assert_sym;
11618
9f757bf7
XR
11619 /* The name of the symbol to break on in order to insert
11620 a catchpoint on exception handling. */
11621 const char *catch_handlers_sym;
11622
0259addd
JB
11623 /* Assuming that the inferior just triggered an unhandled exception
11624 catchpoint, this function is responsible for returning the address
11625 in inferior memory where the name of that exception is stored.
11626 Return zero if the address could not be computed. */
11627 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11628};
11629
11630static CORE_ADDR ada_unhandled_exception_name_addr (void);
11631static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11632
11633/* The following exception support info structure describes how to
11634 implement exception catchpoints with the latest version of the
ca683e3a 11635 Ada runtime (as of 2019-08-??). */
0259addd
JB
11636
11637static const struct exception_support_info default_exception_support_info =
ca683e3a
AO
11638{
11639 "__gnat_debug_raise_exception", /* catch_exception_sym */
11640 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11641 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11642 "__gnat_begin_handler_v1", /* catch_handlers_sym */
11643 ada_unhandled_exception_name_addr
11644};
11645
11646/* The following exception support info structure describes how to
11647 implement exception catchpoints with an earlier version of the
11648 Ada runtime (as of 2007-03-06) using v0 of the EH ABI. */
11649
11650static const struct exception_support_info exception_support_info_v0 =
0259addd
JB
11651{
11652 "__gnat_debug_raise_exception", /* catch_exception_sym */
11653 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11654 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
9f757bf7 11655 "__gnat_begin_handler", /* catch_handlers_sym */
0259addd
JB
11656 ada_unhandled_exception_name_addr
11657};
11658
11659/* The following exception support info structure describes how to
11660 implement exception catchpoints with a slightly older version
11661 of the Ada runtime. */
11662
11663static const struct exception_support_info exception_support_info_fallback =
11664{
11665 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11666 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11667 "system__assertions__raise_assert_failure", /* catch_assert_sym */
9f757bf7 11668 "__gnat_begin_handler", /* catch_handlers_sym */
0259addd
JB
11669 ada_unhandled_exception_name_addr_from_raise
11670};
11671
f17011e0
JB
11672/* Return nonzero if we can detect the exception support routines
11673 described in EINFO.
11674
11675 This function errors out if an abnormal situation is detected
11676 (for instance, if we find the exception support routines, but
11677 that support is found to be incomplete). */
11678
11679static int
11680ada_has_this_exception_support (const struct exception_support_info *einfo)
11681{
11682 struct symbol *sym;
11683
11684 /* The symbol we're looking up is provided by a unit in the GNAT runtime
11685 that should be compiled with debugging information. As a result, we
11686 expect to find that symbol in the symtabs. */
11687
11688 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11689 if (sym == NULL)
a6af7abe
JB
11690 {
11691 /* Perhaps we did not find our symbol because the Ada runtime was
11692 compiled without debugging info, or simply stripped of it.
11693 It happens on some GNU/Linux distributions for instance, where
11694 users have to install a separate debug package in order to get
11695 the runtime's debugging info. In that situation, let the user
11696 know why we cannot insert an Ada exception catchpoint.
11697
11698 Note: Just for the purpose of inserting our Ada exception
11699 catchpoint, we could rely purely on the associated minimal symbol.
11700 But we would be operating in degraded mode anyway, since we are
11701 still lacking the debugging info needed later on to extract
11702 the name of the exception being raised (this name is printed in
11703 the catchpoint message, and is also used when trying to catch
11704 a specific exception). We do not handle this case for now. */
3b7344d5 11705 struct bound_minimal_symbol msym
1c8e84b0
JB
11706 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11707
60f62e2b 11708 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
a6af7abe
JB
11709 error (_("Your Ada runtime appears to be missing some debugging "
11710 "information.\nCannot insert Ada exception catchpoint "
11711 "in this configuration."));
11712
11713 return 0;
11714 }
f17011e0
JB
11715
11716 /* Make sure that the symbol we found corresponds to a function. */
11717
66d7f48f 11718 if (sym->aclass () != LOC_BLOCK)
fe043185
TT
11719 error (_("Symbol \"%s\" is not a function (class = %d)"),
11720 sym->linkage_name (), sym->aclass ());
ca683e3a
AO
11721
11722 sym = standard_lookup (einfo->catch_handlers_sym, NULL, VAR_DOMAIN);
11723 if (sym == NULL)
11724 {
11725 struct bound_minimal_symbol msym
11726 = lookup_minimal_symbol (einfo->catch_handlers_sym, NULL, NULL);
11727
60f62e2b 11728 if (msym.minsym && msym.minsym->type () != mst_solib_trampoline)
ca683e3a
AO
11729 error (_("Your Ada runtime appears to be missing some debugging "
11730 "information.\nCannot insert Ada exception catchpoint "
11731 "in this configuration."));
11732
11733 return 0;
11734 }
11735
11736 /* Make sure that the symbol we found corresponds to a function. */
11737
66d7f48f 11738 if (sym->aclass () != LOC_BLOCK)
fe043185
TT
11739 error (_("Symbol \"%s\" is not a function (class = %d)"),
11740 sym->linkage_name (), sym->aclass ());
f17011e0
JB
11741
11742 return 1;
11743}
11744
0259addd
JB
11745/* Inspect the Ada runtime and determine which exception info structure
11746 should be used to provide support for exception catchpoints.
11747
3eecfa55
JB
11748 This function will always set the per-inferior exception_info,
11749 or raise an error. */
0259addd
JB
11750
11751static void
11752ada_exception_support_info_sniffer (void)
11753{
3eecfa55 11754 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
0259addd
JB
11755
11756 /* If the exception info is already known, then no need to recompute it. */
3eecfa55 11757 if (data->exception_info != NULL)
0259addd
JB
11758 return;
11759
11760 /* Check the latest (default) exception support info. */
f17011e0 11761 if (ada_has_this_exception_support (&default_exception_support_info))
0259addd 11762 {
3eecfa55 11763 data->exception_info = &default_exception_support_info;
0259addd
JB
11764 return;
11765 }
11766
ca683e3a
AO
11767 /* Try the v0 exception suport info. */
11768 if (ada_has_this_exception_support (&exception_support_info_v0))
11769 {
11770 data->exception_info = &exception_support_info_v0;
11771 return;
11772 }
11773
0259addd 11774 /* Try our fallback exception suport info. */
f17011e0 11775 if (ada_has_this_exception_support (&exception_support_info_fallback))
0259addd 11776 {
3eecfa55 11777 data->exception_info = &exception_support_info_fallback;
0259addd
JB
11778 return;
11779 }
11780
2c4c710f
TT
11781 throw_error (NOT_FOUND_ERROR,
11782 _("Could not find Ada runtime exception support"));
0259addd
JB
11783}
11784
f7f9143b
JB
11785/* True iff FRAME is very likely to be that of a function that is
11786 part of the runtime system. This is all very heuristic, but is
11787 intended to be used as advice as to what frames are uninteresting
11788 to most users. */
11789
11790static int
bd2b40ac 11791is_known_support_routine (frame_info_ptr frame)
f7f9143b 11792{
692465f1 11793 enum language func_lang;
f7f9143b 11794 int i;
f35a17b5 11795 const char *fullname;
f7f9143b 11796
4ed6b5be
JB
11797 /* If this code does not have any debugging information (no symtab),
11798 This cannot be any user code. */
f7f9143b 11799
51abb421 11800 symtab_and_line sal = find_frame_sal (frame);
f7f9143b
JB
11801 if (sal.symtab == NULL)
11802 return 1;
11803
4ed6b5be
JB
11804 /* If there is a symtab, but the associated source file cannot be
11805 located, then assume this is not user code: Selecting a frame
11806 for which we cannot display the code would not be very helpful
11807 for the user. This should also take care of case such as VxWorks
11808 where the kernel has some debugging info provided for a few units. */
f7f9143b 11809
f35a17b5
JK
11810 fullname = symtab_to_fullname (sal.symtab);
11811 if (access (fullname, R_OK) != 0)
f7f9143b
JB
11812 return 1;
11813
85102364 11814 /* Check the unit filename against the Ada runtime file naming.
4ed6b5be
JB
11815 We also check the name of the objfile against the name of some
11816 known system libraries that sometimes come with debugging info
11817 too. */
11818
f7f9143b
JB
11819 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11820 {
11821 re_comp (known_runtime_file_name_patterns[i]);
f69c91ad 11822 if (re_exec (lbasename (sal.symtab->filename)))
dda83cd7 11823 return 1;
3c86fae3
SM
11824 if (sal.symtab->compunit ()->objfile () != NULL
11825 && re_exec (objfile_name (sal.symtab->compunit ()->objfile ())))
dda83cd7 11826 return 1;
f7f9143b
JB
11827 }
11828
4ed6b5be 11829 /* Check whether the function is a GNAT-generated entity. */
f7f9143b 11830
c6dc63a1
TT
11831 gdb::unique_xmalloc_ptr<char> func_name
11832 = find_frame_funname (frame, &func_lang, NULL);
f7f9143b
JB
11833 if (func_name == NULL)
11834 return 1;
11835
11836 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11837 {
11838 re_comp (known_auxiliary_function_name_patterns[i]);
c6dc63a1
TT
11839 if (re_exec (func_name.get ()))
11840 return 1;
f7f9143b
JB
11841 }
11842
11843 return 0;
11844}
11845
11846/* Find the first frame that contains debugging information and that is not
11847 part of the Ada run-time, starting from FI and moving upward. */
11848
0ef643c8 11849void
bd2b40ac 11850ada_find_printable_frame (frame_info_ptr fi)
f7f9143b
JB
11851{
11852 for (; fi != NULL; fi = get_prev_frame (fi))
11853 {
11854 if (!is_known_support_routine (fi))
dda83cd7
SM
11855 {
11856 select_frame (fi);
11857 break;
11858 }
f7f9143b
JB
11859 }
11860
11861}
11862
11863/* Assuming that the inferior just triggered an unhandled exception
11864 catchpoint, return the address in inferior memory where the name
11865 of the exception is stored.
11866
11867 Return zero if the address could not be computed. */
11868
11869static CORE_ADDR
11870ada_unhandled_exception_name_addr (void)
0259addd
JB
11871{
11872 return parse_and_eval_address ("e.full_name");
11873}
11874
11875/* Same as ada_unhandled_exception_name_addr, except that this function
11876 should be used when the inferior uses an older version of the runtime,
11877 where the exception name needs to be extracted from a specific frame
11878 several frames up in the callstack. */
11879
11880static CORE_ADDR
11881ada_unhandled_exception_name_addr_from_raise (void)
f7f9143b
JB
11882{
11883 int frame_level;
bd2b40ac 11884 frame_info_ptr fi;
3eecfa55 11885 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
f7f9143b
JB
11886
11887 /* To determine the name of this exception, we need to select
11888 the frame corresponding to RAISE_SYM_NAME. This frame is
11889 at least 3 levels up, so we simply skip the first 3 frames
11890 without checking the name of their associated function. */
11891 fi = get_current_frame ();
11892 for (frame_level = 0; frame_level < 3; frame_level += 1)
11893 if (fi != NULL)
11894 fi = get_prev_frame (fi);
11895
11896 while (fi != NULL)
11897 {
692465f1
JB
11898 enum language func_lang;
11899
c6dc63a1
TT
11900 gdb::unique_xmalloc_ptr<char> func_name
11901 = find_frame_funname (fi, &func_lang, NULL);
55b87a52
KS
11902 if (func_name != NULL)
11903 {
dda83cd7 11904 if (strcmp (func_name.get (),
55b87a52
KS
11905 data->exception_info->catch_exception_sym) == 0)
11906 break; /* We found the frame we were looking for... */
55b87a52 11907 }
fb44b1a7 11908 fi = get_prev_frame (fi);
f7f9143b
JB
11909 }
11910
11911 if (fi == NULL)
11912 return 0;
11913
11914 select_frame (fi);
11915 return parse_and_eval_address ("id.full_name");
11916}
11917
11918/* Assuming the inferior just triggered an Ada exception catchpoint
11919 (of any type), return the address in inferior memory where the name
11920 of the exception is stored, if applicable.
11921
45db7c09
PA
11922 Assumes the selected frame is the current frame.
11923
f7f9143b
JB
11924 Return zero if the address could not be computed, or if not relevant. */
11925
11926static CORE_ADDR
7bd86313 11927ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex)
f7f9143b 11928{
3eecfa55
JB
11929 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11930
f7f9143b
JB
11931 switch (ex)
11932 {
761269c8 11933 case ada_catch_exception:
dda83cd7
SM
11934 return (parse_and_eval_address ("e.full_name"));
11935 break;
f7f9143b 11936
761269c8 11937 case ada_catch_exception_unhandled:
dda83cd7
SM
11938 return data->exception_info->unhandled_exception_name_addr ();
11939 break;
9f757bf7
XR
11940
11941 case ada_catch_handlers:
dda83cd7 11942 return 0; /* The runtimes does not provide access to the exception
9f757bf7 11943 name. */
dda83cd7 11944 break;
9f757bf7 11945
761269c8 11946 case ada_catch_assert:
dda83cd7
SM
11947 return 0; /* Exception name is not relevant in this case. */
11948 break;
f7f9143b
JB
11949
11950 default:
f34652de 11951 internal_error (_("unexpected catchpoint type"));
dda83cd7 11952 break;
f7f9143b
JB
11953 }
11954
11955 return 0; /* Should never be reached. */
11956}
11957
e547c119
JB
11958/* Assuming the inferior is stopped at an exception catchpoint,
11959 return the message which was associated to the exception, if
11960 available. Return NULL if the message could not be retrieved.
11961
e547c119
JB
11962 Note: The exception message can be associated to an exception
11963 either through the use of the Raise_Exception function, or
11964 more simply (Ada 2005 and later), via:
11965
11966 raise Exception_Name with "exception message";
11967
11968 */
11969
6f46ac85 11970static gdb::unique_xmalloc_ptr<char>
e547c119
JB
11971ada_exception_message_1 (void)
11972{
11973 struct value *e_msg_val;
e547c119 11974 int e_msg_len;
e547c119
JB
11975
11976 /* For runtimes that support this feature, the exception message
11977 is passed as an unbounded string argument called "message". */
11978 e_msg_val = parse_and_eval ("message");
11979 if (e_msg_val == NULL)
11980 return NULL; /* Exception message not supported. */
11981
11982 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
11983 gdb_assert (e_msg_val != NULL);
d0c97917 11984 e_msg_len = e_msg_val->type ()->length ();
e547c119
JB
11985
11986 /* If the message string is empty, then treat it as if there was
11987 no exception message. */
11988 if (e_msg_len <= 0)
11989 return NULL;
11990
15f3b077 11991 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
9feb2d07 11992 read_memory (e_msg_val->address (), (gdb_byte *) e_msg.get (),
15f3b077
TT
11993 e_msg_len);
11994 e_msg.get ()[e_msg_len] = '\0';
11995
11996 return e_msg;
e547c119
JB
11997}
11998
11999/* Same as ada_exception_message_1, except that all exceptions are
12000 contained here (returning NULL instead). */
12001
6f46ac85 12002static gdb::unique_xmalloc_ptr<char>
e547c119
JB
12003ada_exception_message (void)
12004{
6f46ac85 12005 gdb::unique_xmalloc_ptr<char> e_msg;
e547c119 12006
a70b8144 12007 try
e547c119
JB
12008 {
12009 e_msg = ada_exception_message_1 ();
12010 }
230d2906 12011 catch (const gdb_exception_error &e)
e547c119 12012 {
6f46ac85 12013 e_msg.reset (nullptr);
e547c119 12014 }
e547c119
JB
12015
12016 return e_msg;
12017}
12018
f7f9143b
JB
12019/* Same as ada_exception_name_addr_1, except that it intercepts and contains
12020 any error that ada_exception_name_addr_1 might cause to be thrown.
12021 When an error is intercepted, a warning with the error message is printed,
12022 and zero is returned. */
12023
12024static CORE_ADDR
7bd86313 12025ada_exception_name_addr (enum ada_exception_catchpoint_kind ex)
f7f9143b 12026{
f7f9143b
JB
12027 CORE_ADDR result = 0;
12028
a70b8144 12029 try
f7f9143b 12030 {
7bd86313 12031 result = ada_exception_name_addr_1 (ex);
f7f9143b
JB
12032 }
12033
230d2906 12034 catch (const gdb_exception_error &e)
f7f9143b 12035 {
3d6e9d23 12036 warning (_("failed to get exception name: %s"), e.what ());
f7f9143b
JB
12037 return 0;
12038 }
12039
12040 return result;
12041}
12042
cb7de75e 12043static std::string ada_exception_catchpoint_cond_string
9f757bf7
XR
12044 (const char *excep_string,
12045 enum ada_exception_catchpoint_kind ex);
28010a5d
PA
12046
12047/* Ada catchpoints.
12048
12049 In the case of catchpoints on Ada exceptions, the catchpoint will
12050 stop the target on every exception the program throws. When a user
12051 specifies the name of a specific exception, we translate this
12052 request into a condition expression (in text form), and then parse
12053 it into an expression stored in each of the catchpoint's locations.
12054 We then use this condition to check whether the exception that was
12055 raised is the one the user is interested in. If not, then the
12056 target is resumed again. We store the name of the requested
12057 exception, in order to be able to re-set the condition expression
12058 when symbols change. */
12059
c1fc2657 12060/* An instance of this type is used to represent an Ada catchpoint. */
28010a5d 12061
74421c0b 12062struct ada_catchpoint : public code_breakpoint
28010a5d 12063{
73063f51 12064 ada_catchpoint (struct gdbarch *gdbarch_,
bd21b6c9 12065 enum ada_exception_catchpoint_kind kind,
2c4c710f 12066 const char *cond_string,
bd21b6c9
PA
12067 bool tempflag,
12068 bool enabled,
898db0f7
TT
12069 bool from_tty,
12070 std::string &&excep_string_)
2c4c710f 12071 : code_breakpoint (gdbarch_, bp_catchpoint, tempflag, cond_string),
03f531ea 12072 m_excep_string (std::move (excep_string_)),
73063f51 12073 m_kind (kind)
37f6a7f4 12074 {
74421c0b 12075 /* Unlike most code_breakpoint types, Ada catchpoints are
bd21b6c9 12076 pspace-specific. */
2c4c710f 12077 pspace = current_program_space;
bd21b6c9 12078 enable_state = enabled ? bp_enabled : bp_disabled;
bd21b6c9 12079 language = language_ada;
95f2fe27
TT
12080
12081 re_set ();
37f6a7f4
TT
12082 }
12083
ae72050b
TT
12084 struct bp_location *allocate_location () override;
12085 void re_set () override;
12086 void check_status (struct bpstat *bs) override;
7bd86313 12087 enum print_stop_action print_it (const bpstat *bs) const override;
5e632eca 12088 bool print_one (const bp_location **) const override;
b713485d 12089 void print_mention () const override;
4d1ae558 12090 void print_recreate (struct ui_file *fp) const override;
ae72050b 12091
03f531ea
TT
12092private:
12093
971149cb
TT
12094 /* A helper function for check_status. Returns true if we should
12095 stop for this breakpoint hit. If the user specified a specific
12096 exception, we only want to cause a stop if the program thrown
12097 that exception. */
12098 bool should_stop_exception (const struct bp_location *bl) const;
12099
28010a5d 12100 /* The name of the specific exception the user specified. */
03f531ea 12101 std::string m_excep_string;
37f6a7f4
TT
12102
12103 /* What kind of catchpoint this is. */
12104 enum ada_exception_catchpoint_kind m_kind;
28010a5d
PA
12105};
12106
8cd0bf5e
PA
12107/* An instance of this type is used to represent an Ada catchpoint
12108 breakpoint location. */
12109
12110class ada_catchpoint_location : public bp_location
12111{
12112public:
12113 explicit ada_catchpoint_location (ada_catchpoint *owner)
12114 : bp_location (owner, bp_loc_software_breakpoint)
12115 {}
12116
12117 /* The condition that checks whether the exception that was raised
12118 is the specific exception the user specified on catchpoint
12119 creation. */
12120 expression_up excep_cond_expr;
12121};
12122
2c4c710f
TT
12123static struct symtab_and_line ada_exception_sal
12124 (enum ada_exception_catchpoint_kind ex);
12125
95f2fe27
TT
12126/* Implement the RE_SET method in the structure for all exception
12127 catchpoint kinds. */
28010a5d 12128
95f2fe27
TT
12129void
12130ada_catchpoint::re_set ()
28010a5d 12131{
2c4c710f
TT
12132 std::vector<symtab_and_line> sals;
12133 try
12134 {
12135 struct symtab_and_line sal = ada_exception_sal (m_kind);
12136 sals.push_back (sal);
12137 }
12138 catch (const gdb_exception_error &ex)
12139 {
12140 /* For NOT_FOUND_ERROR, the breakpoint will be pending. */
12141 if (ex.error != NOT_FOUND_ERROR)
12142 throw;
12143 }
12144
12145 update_breakpoint_locations (this, pspace, sals, {});
95f2fe27
TT
12146
12147 /* Reparse the exception conditional expressions. One for each
12148 location. */
12149
28010a5d 12150 /* Nothing to do if there's no specific exception to catch. */
03f531ea 12151 if (m_excep_string.empty ())
28010a5d
PA
12152 return;
12153
12154 /* Same if there are no locations... */
95f2fe27 12155 if (!has_locations ())
28010a5d
PA
12156 return;
12157
fccf9de1 12158 /* Compute the condition expression in text form, from the specific
33b5899f 12159 exception we want to catch. */
fccf9de1 12160 std::string cond_string
03f531ea 12161 = ada_exception_catchpoint_cond_string (m_excep_string.c_str (), m_kind);
28010a5d 12162
fccf9de1
TT
12163 /* Iterate over all the catchpoint's locations, and parse an
12164 expression for each. */
95f2fe27 12165 for (bp_location &bl : locations ())
28010a5d 12166 {
b00b30b2
SM
12167 ada_catchpoint_location &ada_loc
12168 = static_cast<ada_catchpoint_location &> (bl);
4d01a485 12169 expression_up exp;
28010a5d 12170
b00b30b2 12171 if (!bl.shlib_disabled)
28010a5d 12172 {
bbc13ae3 12173 const char *s;
28010a5d 12174
cb7de75e 12175 s = cond_string.c_str ();
a70b8144 12176 try
28010a5d 12177 {
b00b30b2 12178 exp = parse_exp_1 (&s, bl.address, block_for_pc (bl.address), 0);
28010a5d 12179 }
230d2906 12180 catch (const gdb_exception_error &e)
849f2b52
JB
12181 {
12182 warning (_("failed to reevaluate internal exception condition "
12183 "for catchpoint %d: %s"),
95f2fe27 12184 number, e.what ());
849f2b52 12185 }
28010a5d
PA
12186 }
12187
b00b30b2 12188 ada_loc.excep_cond_expr = std::move (exp);
28010a5d 12189 }
28010a5d
PA
12190}
12191
ae72050b
TT
12192/* Implement the ALLOCATE_LOCATION method in the structure for all
12193 exception catchpoint kinds. */
28010a5d 12194
ae72050b
TT
12195struct bp_location *
12196ada_catchpoint::allocate_location ()
28010a5d 12197{
ae72050b 12198 return new ada_catchpoint_location (this);
28010a5d
PA
12199}
12200
971149cb 12201/* See declaration. */
28010a5d 12202
971149cb
TT
12203bool
12204ada_catchpoint::should_stop_exception (const struct bp_location *bl) const
28010a5d 12205{
8e032233 12206 ada_catchpoint *c = gdb::checked_static_cast<ada_catchpoint *> (bl->owner);
28010a5d
PA
12207 const struct ada_catchpoint_location *ada_loc
12208 = (const struct ada_catchpoint_location *) bl;
7ebaa5f7 12209 bool stop;
28010a5d 12210
37f6a7f4
TT
12211 struct internalvar *var = lookup_internalvar ("_ada_exception");
12212 if (c->m_kind == ada_catch_assert)
12213 clear_internalvar (var);
12214 else
12215 {
12216 try
12217 {
12218 const char *expr;
12219
12220 if (c->m_kind == ada_catch_handlers)
12221 expr = ("GNAT_GCC_exception_Access(gcc_exception)"
12222 ".all.occurrence.id");
12223 else
12224 expr = "e";
12225
12226 struct value *exc = parse_and_eval (expr);
12227 set_internalvar (var, exc);
12228 }
12229 catch (const gdb_exception_error &ex)
12230 {
12231 clear_internalvar (var);
12232 }
12233 }
12234
28010a5d 12235 /* With no specific exception, should always stop. */
03f531ea 12236 if (c->m_excep_string.empty ())
7ebaa5f7 12237 return true;
28010a5d
PA
12238
12239 if (ada_loc->excep_cond_expr == NULL)
12240 {
12241 /* We will have a NULL expression if back when we were creating
12242 the expressions, this location's had failed to parse. */
7ebaa5f7 12243 return true;
28010a5d
PA
12244 }
12245
7ebaa5f7 12246 stop = true;
a70b8144 12247 try
28010a5d 12248 {
65558ca5 12249 scoped_value_mark mark;
43048e46 12250 stop = value_true (ada_loc->excep_cond_expr->evaluate ());
28010a5d 12251 }
b1ffd112 12252 catch (const gdb_exception_error &ex)
492d29ea
PA
12253 {
12254 exception_fprintf (gdb_stderr, ex,
12255 _("Error in testing exception condition:\n"));
12256 }
492d29ea 12257
28010a5d
PA
12258 return stop;
12259}
12260
ae72050b
TT
12261/* Implement the CHECK_STATUS method in the structure for all
12262 exception catchpoint kinds. */
28010a5d 12263
ae72050b
TT
12264void
12265ada_catchpoint::check_status (bpstat *bs)
28010a5d 12266{
b6433ede 12267 bs->stop = should_stop_exception (bs->bp_location_at.get ());
28010a5d
PA
12268}
12269
ae72050b
TT
12270/* Implement the PRINT_IT method in the structure for all exception
12271 catchpoint kinds. */
f7f9143b 12272
ae72050b 12273enum print_stop_action
7bd86313 12274ada_catchpoint::print_it (const bpstat *bs) const
f7f9143b 12275{
79a45e25 12276 struct ui_out *uiout = current_uiout;
348d480f 12277
ae72050b 12278 annotate_catchpoint (number);
f7f9143b 12279
112e8700 12280 if (uiout->is_mi_like_p ())
f7f9143b 12281 {
112e8700 12282 uiout->field_string ("reason",
956a9fb9 12283 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
ae72050b 12284 uiout->field_string ("disp", bpdisp_text (disposition));
f7f9143b
JB
12285 }
12286
ae72050b 12287 uiout->text (disposition == disp_del
112e8700 12288 ? "\nTemporary catchpoint " : "\nCatchpoint ");
78805ff8 12289 print_num_locno (bs, uiout);
112e8700 12290 uiout->text (", ");
f7f9143b 12291
45db7c09
PA
12292 /* ada_exception_name_addr relies on the selected frame being the
12293 current frame. Need to do this here because this function may be
12294 called more than once when printing a stop, and below, we'll
12295 select the first frame past the Ada run-time (see
12296 ada_find_printable_frame). */
12297 select_frame (get_current_frame ());
12298
ae72050b 12299 switch (m_kind)
f7f9143b 12300 {
761269c8
JB
12301 case ada_catch_exception:
12302 case ada_catch_exception_unhandled:
9f757bf7 12303 case ada_catch_handlers:
956a9fb9 12304 {
7bd86313 12305 const CORE_ADDR addr = ada_exception_name_addr (m_kind);
956a9fb9
JB
12306 char exception_name[256];
12307
12308 if (addr != 0)
12309 {
c714b426
PA
12310 read_memory (addr, (gdb_byte *) exception_name,
12311 sizeof (exception_name) - 1);
956a9fb9
JB
12312 exception_name [sizeof (exception_name) - 1] = '\0';
12313 }
12314 else
12315 {
12316 /* For some reason, we were unable to read the exception
12317 name. This could happen if the Runtime was compiled
12318 without debugging info, for instance. In that case,
12319 just replace the exception name by the generic string
12320 "exception" - it will read as "an exception" in the
12321 notification we are about to print. */
967cff16 12322 memcpy (exception_name, "exception", sizeof ("exception"));
956a9fb9
JB
12323 }
12324 /* In the case of unhandled exception breakpoints, we print
12325 the exception name as "unhandled EXCEPTION_NAME", to make
12326 it clearer to the user which kind of catchpoint just got
12327 hit. We used ui_out_text to make sure that this extra
12328 info does not pollute the exception name in the MI case. */
ae72050b 12329 if (m_kind == ada_catch_exception_unhandled)
112e8700
SM
12330 uiout->text ("unhandled ");
12331 uiout->field_string ("exception-name", exception_name);
956a9fb9
JB
12332 }
12333 break;
761269c8 12334 case ada_catch_assert:
956a9fb9
JB
12335 /* In this case, the name of the exception is not really
12336 important. Just print "failed assertion" to make it clearer
12337 that his program just hit an assertion-failure catchpoint.
12338 We used ui_out_text because this info does not belong in
12339 the MI output. */
112e8700 12340 uiout->text ("failed assertion");
956a9fb9 12341 break;
f7f9143b 12342 }
e547c119 12343
6f46ac85 12344 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
e547c119
JB
12345 if (exception_message != NULL)
12346 {
e547c119 12347 uiout->text (" (");
6f46ac85 12348 uiout->field_string ("exception-message", exception_message.get ());
e547c119 12349 uiout->text (")");
e547c119
JB
12350 }
12351
112e8700 12352 uiout->text (" at ");
956a9fb9 12353 ada_find_printable_frame (get_current_frame ());
f7f9143b
JB
12354
12355 return PRINT_SRC_AND_LOC;
12356}
12357
ae72050b
TT
12358/* Implement the PRINT_ONE method in the structure for all exception
12359 catchpoint kinds. */
f7f9143b 12360
ae72050b 12361bool
5e632eca 12362ada_catchpoint::print_one (const bp_location **last_loc) const
f7f9143b 12363{
79a45e25 12364 struct ui_out *uiout = current_uiout;
79a45b7d
TT
12365 struct value_print_options opts;
12366
12367 get_user_print_options (&opts);
f06f1252 12368
79a45b7d 12369 if (opts.addressprint)
f06f1252 12370 uiout->field_skip ("addr");
f7f9143b
JB
12371
12372 annotate_field (5);
ae72050b 12373 switch (m_kind)
f7f9143b 12374 {
761269c8 12375 case ada_catch_exception:
03f531ea 12376 if (!m_excep_string.empty ())
dda83cd7 12377 {
bc18fbb5 12378 std::string msg = string_printf (_("`%s' Ada exception"),
03f531ea 12379 m_excep_string.c_str ());
28010a5d 12380
dda83cd7
SM
12381 uiout->field_string ("what", msg);
12382 }
12383 else
12384 uiout->field_string ("what", "all Ada exceptions");
12385
12386 break;
f7f9143b 12387
761269c8 12388 case ada_catch_exception_unhandled:
dda83cd7
SM
12389 uiout->field_string ("what", "unhandled Ada exceptions");
12390 break;
f7f9143b 12391
9f757bf7 12392 case ada_catch_handlers:
03f531ea 12393 if (!m_excep_string.empty ())
dda83cd7 12394 {
9f757bf7
XR
12395 uiout->field_fmt ("what",
12396 _("`%s' Ada exception handlers"),
03f531ea 12397 m_excep_string.c_str ());
dda83cd7
SM
12398 }
12399 else
9f757bf7 12400 uiout->field_string ("what", "all Ada exceptions handlers");
dda83cd7 12401 break;
9f757bf7 12402
761269c8 12403 case ada_catch_assert:
dda83cd7
SM
12404 uiout->field_string ("what", "failed Ada assertions");
12405 break;
f7f9143b
JB
12406
12407 default:
f34652de 12408 internal_error (_("unexpected catchpoint type"));
dda83cd7 12409 break;
f7f9143b 12410 }
c01e038b
TT
12411
12412 return true;
f7f9143b
JB
12413}
12414
12415/* Implement the PRINT_MENTION method in the breakpoint_ops structure
12416 for all exception catchpoint kinds. */
12417
ae72050b 12418void
b713485d 12419ada_catchpoint::print_mention () const
f7f9143b 12420{
79a45e25 12421 struct ui_out *uiout = current_uiout;
28010a5d 12422
ae72050b 12423 uiout->text (disposition == disp_del ? _("Temporary catchpoint ")
dda83cd7 12424 : _("Catchpoint "));
ae72050b 12425 uiout->field_signed ("bkptno", number);
112e8700 12426 uiout->text (": ");
00eb2c4a 12427
ae72050b 12428 switch (m_kind)
f7f9143b 12429 {
761269c8 12430 case ada_catch_exception:
03f531ea 12431 if (!m_excep_string.empty ())
00eb2c4a 12432 {
862d101a 12433 std::string info = string_printf (_("`%s' Ada exception"),
03f531ea 12434 m_excep_string.c_str ());
4915bfdc 12435 uiout->text (info);
00eb2c4a 12436 }
dda83cd7
SM
12437 else
12438 uiout->text (_("all Ada exceptions"));
12439 break;
f7f9143b 12440
761269c8 12441 case ada_catch_exception_unhandled:
dda83cd7
SM
12442 uiout->text (_("unhandled Ada exceptions"));
12443 break;
9f757bf7
XR
12444
12445 case ada_catch_handlers:
03f531ea 12446 if (!m_excep_string.empty ())
9f757bf7
XR
12447 {
12448 std::string info
12449 = string_printf (_("`%s' Ada exception handlers"),
03f531ea 12450 m_excep_string.c_str ());
4915bfdc 12451 uiout->text (info);
9f757bf7 12452 }
dda83cd7
SM
12453 else
12454 uiout->text (_("all Ada exceptions handlers"));
12455 break;
9f757bf7 12456
761269c8 12457 case ada_catch_assert:
dda83cd7
SM
12458 uiout->text (_("failed Ada assertions"));
12459 break;
f7f9143b
JB
12460
12461 default:
f34652de 12462 internal_error (_("unexpected catchpoint type"));
dda83cd7 12463 break;
f7f9143b
JB
12464 }
12465}
12466
ae72050b
TT
12467/* Implement the PRINT_RECREATE method in the structure for all
12468 exception catchpoint kinds. */
6149aea9 12469
ae72050b 12470void
4d1ae558 12471ada_catchpoint::print_recreate (struct ui_file *fp) const
6149aea9 12472{
ae72050b 12473 switch (m_kind)
6149aea9 12474 {
761269c8 12475 case ada_catch_exception:
6cb06a8c 12476 gdb_printf (fp, "catch exception");
03f531ea
TT
12477 if (!m_excep_string.empty ())
12478 gdb_printf (fp, " %s", m_excep_string.c_str ());
6149aea9
PA
12479 break;
12480
761269c8 12481 case ada_catch_exception_unhandled:
6cb06a8c 12482 gdb_printf (fp, "catch exception unhandled");
6149aea9
PA
12483 break;
12484
9f757bf7 12485 case ada_catch_handlers:
6cb06a8c 12486 gdb_printf (fp, "catch handlers");
9f757bf7
XR
12487 break;
12488
761269c8 12489 case ada_catch_assert:
6cb06a8c 12490 gdb_printf (fp, "catch assert");
6149aea9
PA
12491 break;
12492
12493 default:
f34652de 12494 internal_error (_("unexpected catchpoint type"));
6149aea9 12495 }
04d0163c 12496 print_recreate_thread (fp);
6149aea9
PA
12497}
12498
f06f1252
TT
12499/* See ada-lang.h. */
12500
12501bool
12502is_ada_exception_catchpoint (breakpoint *bp)
12503{
ae72050b 12504 return dynamic_cast<ada_catchpoint *> (bp) != nullptr;
f06f1252
TT
12505}
12506
f7f9143b
JB
12507/* Split the arguments specified in a "catch exception" command.
12508 Set EX to the appropriate catchpoint type.
28010a5d 12509 Set EXCEP_STRING to the name of the specific exception if
5845583d 12510 specified by the user.
9f757bf7
XR
12511 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12512 "catch handlers" command. False otherwise.
5845583d
JB
12513 If a condition is found at the end of the arguments, the condition
12514 expression is stored in COND_STRING (memory must be deallocated
12515 after use). Otherwise COND_STRING is set to NULL. */
f7f9143b
JB
12516
12517static void
a121b7c1 12518catch_ada_exception_command_split (const char *args,
9f757bf7 12519 bool is_catch_handlers_cmd,
dda83cd7 12520 enum ada_exception_catchpoint_kind *ex,
bc18fbb5
TT
12521 std::string *excep_string,
12522 std::string *cond_string)
f7f9143b 12523{
bc18fbb5 12524 std::string exception_name;
f7f9143b 12525
bc18fbb5
TT
12526 exception_name = extract_arg (&args);
12527 if (exception_name == "if")
5845583d
JB
12528 {
12529 /* This is not an exception name; this is the start of a condition
12530 expression for a catchpoint on all exceptions. So, "un-get"
12531 this token, and set exception_name to NULL. */
bc18fbb5 12532 exception_name.clear ();
5845583d
JB
12533 args -= 2;
12534 }
f7f9143b 12535
5845583d 12536 /* Check to see if we have a condition. */
f7f9143b 12537
f1735a53 12538 args = skip_spaces (args);
61012eef 12539 if (startswith (args, "if")
5845583d
JB
12540 && (isspace (args[2]) || args[2] == '\0'))
12541 {
12542 args += 2;
f1735a53 12543 args = skip_spaces (args);
5845583d
JB
12544
12545 if (args[0] == '\0')
dda83cd7 12546 error (_("Condition missing after `if' keyword"));
bc18fbb5 12547 *cond_string = args;
5845583d
JB
12548
12549 args += strlen (args);
12550 }
12551
12552 /* Check that we do not have any more arguments. Anything else
12553 is unexpected. */
f7f9143b
JB
12554
12555 if (args[0] != '\0')
12556 error (_("Junk at end of expression"));
12557
9f757bf7
XR
12558 if (is_catch_handlers_cmd)
12559 {
12560 /* Catch handling of exceptions. */
12561 *ex = ada_catch_handlers;
12562 *excep_string = exception_name;
12563 }
bc18fbb5 12564 else if (exception_name.empty ())
f7f9143b
JB
12565 {
12566 /* Catch all exceptions. */
761269c8 12567 *ex = ada_catch_exception;
bc18fbb5 12568 excep_string->clear ();
f7f9143b 12569 }
bc18fbb5 12570 else if (exception_name == "unhandled")
f7f9143b
JB
12571 {
12572 /* Catch unhandled exceptions. */
761269c8 12573 *ex = ada_catch_exception_unhandled;
bc18fbb5 12574 excep_string->clear ();
f7f9143b
JB
12575 }
12576 else
12577 {
12578 /* Catch a specific exception. */
761269c8 12579 *ex = ada_catch_exception;
28010a5d 12580 *excep_string = exception_name;
f7f9143b
JB
12581 }
12582}
12583
12584/* Return the name of the symbol on which we should break in order to
12585 implement a catchpoint of the EX kind. */
12586
12587static const char *
761269c8 12588ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
f7f9143b 12589{
3eecfa55
JB
12590 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12591
12592 gdb_assert (data->exception_info != NULL);
0259addd 12593
f7f9143b
JB
12594 switch (ex)
12595 {
761269c8 12596 case ada_catch_exception:
dda83cd7
SM
12597 return (data->exception_info->catch_exception_sym);
12598 break;
761269c8 12599 case ada_catch_exception_unhandled:
dda83cd7
SM
12600 return (data->exception_info->catch_exception_unhandled_sym);
12601 break;
761269c8 12602 case ada_catch_assert:
dda83cd7
SM
12603 return (data->exception_info->catch_assert_sym);
12604 break;
9f757bf7 12605 case ada_catch_handlers:
dda83cd7
SM
12606 return (data->exception_info->catch_handlers_sym);
12607 break;
f7f9143b 12608 default:
f34652de 12609 internal_error (_("unexpected catchpoint kind (%d)"), ex);
f7f9143b
JB
12610 }
12611}
12612
f7f9143b
JB
12613/* Return the condition that will be used to match the current exception
12614 being raised with the exception that the user wants to catch. This
12615 assumes that this condition is used when the inferior just triggered
12616 an exception catchpoint.
cb7de75e 12617 EX: the type of catchpoints used for catching Ada exceptions. */
f7f9143b 12618
cb7de75e 12619static std::string
9f757bf7 12620ada_exception_catchpoint_cond_string (const char *excep_string,
dda83cd7 12621 enum ada_exception_catchpoint_kind ex)
f7f9143b 12622{
fccf9de1 12623 bool is_standard_exc = false;
cb7de75e 12624 std::string result;
9f757bf7
XR
12625
12626 if (ex == ada_catch_handlers)
12627 {
12628 /* For exception handlers catchpoints, the condition string does
dda83cd7 12629 not use the same parameter as for the other exceptions. */
fccf9de1
TT
12630 result = ("long_integer (GNAT_GCC_exception_Access"
12631 "(gcc_exception).all.occurrence.id)");
9f757bf7
XR
12632 }
12633 else
fccf9de1 12634 result = "long_integer (e)";
3d0b0fa3 12635
0963b4bd 12636 /* The standard exceptions are a special case. They are defined in
3d0b0fa3 12637 runtime units that have been compiled without debugging info; if
28010a5d 12638 EXCEP_STRING is the not-fully-qualified name of a standard
3d0b0fa3
JB
12639 exception (e.g. "constraint_error") then, during the evaluation
12640 of the condition expression, the symbol lookup on this name would
0963b4bd 12641 *not* return this standard exception. The catchpoint condition
3d0b0fa3
JB
12642 may then be set only on user-defined exceptions which have the
12643 same not-fully-qualified name (e.g. my_package.constraint_error).
12644
12645 To avoid this unexcepted behavior, these standard exceptions are
0963b4bd 12646 systematically prefixed by "standard". This means that "catch
3d0b0fa3
JB
12647 exception constraint_error" is rewritten into "catch exception
12648 standard.constraint_error".
12649
85102364 12650 If an exception named constraint_error is defined in another package of
3d0b0fa3
JB
12651 the inferior program, then the only way to specify this exception as a
12652 breakpoint condition is to use its fully-qualified named:
fccf9de1 12653 e.g. my_package.constraint_error. */
3d0b0fa3 12654
696d6f4d 12655 for (const char *name : standard_exc)
3d0b0fa3 12656 {
696d6f4d 12657 if (strcmp (name, excep_string) == 0)
3d0b0fa3 12658 {
fccf9de1 12659 is_standard_exc = true;
9f757bf7 12660 break;
3d0b0fa3
JB
12661 }
12662 }
9f757bf7 12663
fccf9de1
TT
12664 result += " = ";
12665
12666 if (is_standard_exc)
12667 string_appendf (result, "long_integer (&standard.%s)", excep_string);
12668 else
12669 string_appendf (result, "long_integer (&%s)", excep_string);
9f757bf7 12670
9f757bf7 12671 return result;
f7f9143b
JB
12672}
12673
2c4c710f
TT
12674/* Return the symtab_and_line that should be used to insert an
12675 exception catchpoint of the TYPE kind. */
f7f9143b
JB
12676
12677static struct symtab_and_line
2c4c710f 12678ada_exception_sal (enum ada_exception_catchpoint_kind ex)
f7f9143b
JB
12679{
12680 const char *sym_name;
12681 struct symbol *sym;
f7f9143b 12682
0259addd
JB
12683 /* First, find out which exception support info to use. */
12684 ada_exception_support_info_sniffer ();
12685
12686 /* Then lookup the function on which we will break in order to catch
f7f9143b 12687 the Ada exceptions requested by the user. */
f7f9143b
JB
12688 sym_name = ada_exception_sym_name (ex);
12689 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12690
57aff202 12691 if (sym == NULL)
2c4c710f
TT
12692 throw_error (NOT_FOUND_ERROR, _("Catchpoint symbol not found: %s"),
12693 sym_name);
57aff202 12694
66d7f48f 12695 if (sym->aclass () != LOC_BLOCK)
57aff202 12696 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
f7f9143b 12697
f17011e0 12698 return find_function_start_sal (sym, 1);
f7f9143b
JB
12699}
12700
b4a5b78b 12701/* Create an Ada exception catchpoint.
f7f9143b 12702
b4a5b78b 12703 EX_KIND is the kind of exception catchpoint to be created.
5845583d 12704
bc18fbb5 12705 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
2df4d1d5 12706 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
bc18fbb5 12707 of the exception to which this catchpoint applies.
2df4d1d5 12708
bc18fbb5 12709 COND_STRING, if not empty, is the catchpoint condition.
f7f9143b 12710
b4a5b78b
JB
12711 TEMPFLAG, if nonzero, means that the underlying breakpoint
12712 should be temporary.
28010a5d 12713
b4a5b78b 12714 FROM_TTY is the usual argument passed to all commands implementations. */
28010a5d 12715
349774ef 12716void
28010a5d 12717create_ada_exception_catchpoint (struct gdbarch *gdbarch,
761269c8 12718 enum ada_exception_catchpoint_kind ex_kind,
898db0f7 12719 std::string &&excep_string,
56ecd069 12720 const std::string &cond_string,
28010a5d 12721 int tempflag,
12d67b37 12722 int enabled,
28010a5d
PA
12723 int from_tty)
12724{
bd21b6c9 12725 std::unique_ptr<ada_catchpoint> c
2c4c710f
TT
12726 (new ada_catchpoint (gdbarch, ex_kind,
12727 cond_string.empty () ? nullptr : cond_string.c_str (),
898db0f7
TT
12728 tempflag, enabled, from_tty,
12729 std::move (excep_string)));
b270e6f9 12730 install_breakpoint (0, std::move (c), 1);
f7f9143b
JB
12731}
12732
9ac4176b
PA
12733/* Implement the "catch exception" command. */
12734
12735static void
eb4c3f4a 12736catch_ada_exception_command (const char *arg_entry, int from_tty,
9ac4176b
PA
12737 struct cmd_list_element *command)
12738{
a121b7c1 12739 const char *arg = arg_entry;
9ac4176b
PA
12740 struct gdbarch *gdbarch = get_current_arch ();
12741 int tempflag;
761269c8 12742 enum ada_exception_catchpoint_kind ex_kind;
bc18fbb5 12743 std::string excep_string;
56ecd069 12744 std::string cond_string;
9ac4176b 12745
0f8e2034 12746 tempflag = command->context () == CATCH_TEMPORARY;
9ac4176b
PA
12747
12748 if (!arg)
12749 arg = "";
9f757bf7 12750 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
bc18fbb5 12751 &cond_string);
9f757bf7 12752 create_ada_exception_catchpoint (gdbarch, ex_kind,
898db0f7 12753 std::move (excep_string), cond_string,
9f757bf7
XR
12754 tempflag, 1 /* enabled */,
12755 from_tty);
12756}
12757
12758/* Implement the "catch handlers" command. */
12759
12760static void
12761catch_ada_handlers_command (const char *arg_entry, int from_tty,
12762 struct cmd_list_element *command)
12763{
12764 const char *arg = arg_entry;
12765 struct gdbarch *gdbarch = get_current_arch ();
12766 int tempflag;
12767 enum ada_exception_catchpoint_kind ex_kind;
bc18fbb5 12768 std::string excep_string;
56ecd069 12769 std::string cond_string;
9f757bf7 12770
0f8e2034 12771 tempflag = command->context () == CATCH_TEMPORARY;
9f757bf7
XR
12772
12773 if (!arg)
12774 arg = "";
12775 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
bc18fbb5 12776 &cond_string);
b4a5b78b 12777 create_ada_exception_catchpoint (gdbarch, ex_kind,
898db0f7 12778 std::move (excep_string), cond_string,
349774ef
JB
12779 tempflag, 1 /* enabled */,
12780 from_tty);
9ac4176b
PA
12781}
12782
71bed2db
TT
12783/* Completion function for the Ada "catch" commands. */
12784
12785static void
12786catch_ada_completer (struct cmd_list_element *cmd, completion_tracker &tracker,
12787 const char *text, const char *word)
12788{
12789 std::vector<ada_exc_info> exceptions = ada_exceptions_list (NULL);
12790
12791 for (const ada_exc_info &info : exceptions)
12792 {
12793 if (startswith (info.name, word))
b02f78f9 12794 tracker.add_completion (make_unique_xstrdup (info.name));
71bed2db
TT
12795 }
12796}
12797
b4a5b78b 12798/* Split the arguments specified in a "catch assert" command.
5845583d 12799
b4a5b78b
JB
12800 ARGS contains the command's arguments (or the empty string if
12801 no arguments were passed).
5845583d
JB
12802
12803 If ARGS contains a condition, set COND_STRING to that condition
b4a5b78b 12804 (the memory needs to be deallocated after use). */
5845583d 12805
b4a5b78b 12806static void
56ecd069 12807catch_ada_assert_command_split (const char *args, std::string &cond_string)
f7f9143b 12808{
f1735a53 12809 args = skip_spaces (args);
f7f9143b 12810
5845583d 12811 /* Check whether a condition was provided. */
61012eef 12812 if (startswith (args, "if")
5845583d 12813 && (isspace (args[2]) || args[2] == '\0'))
f7f9143b 12814 {
5845583d 12815 args += 2;
f1735a53 12816 args = skip_spaces (args);
5845583d 12817 if (args[0] == '\0')
dda83cd7 12818 error (_("condition missing after `if' keyword"));
56ecd069 12819 cond_string.assign (args);
f7f9143b
JB
12820 }
12821
5845583d
JB
12822 /* Otherwise, there should be no other argument at the end of
12823 the command. */
12824 else if (args[0] != '\0')
12825 error (_("Junk at end of arguments."));
f7f9143b
JB
12826}
12827
9ac4176b
PA
12828/* Implement the "catch assert" command. */
12829
12830static void
eb4c3f4a 12831catch_assert_command (const char *arg_entry, int from_tty,
9ac4176b
PA
12832 struct cmd_list_element *command)
12833{
a121b7c1 12834 const char *arg = arg_entry;
9ac4176b
PA
12835 struct gdbarch *gdbarch = get_current_arch ();
12836 int tempflag;
56ecd069 12837 std::string cond_string;
9ac4176b 12838
0f8e2034 12839 tempflag = command->context () == CATCH_TEMPORARY;
9ac4176b
PA
12840
12841 if (!arg)
12842 arg = "";
56ecd069 12843 catch_ada_assert_command_split (arg, cond_string);
761269c8 12844 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
898db0f7 12845 {}, cond_string,
349774ef
JB
12846 tempflag, 1 /* enabled */,
12847 from_tty);
9ac4176b 12848}
778865d3
JB
12849
12850/* Return non-zero if the symbol SYM is an Ada exception object. */
12851
12852static int
12853ada_is_exception_sym (struct symbol *sym)
12854{
5f9c5a63 12855 const char *type_name = sym->type ()->name ();
778865d3 12856
66d7f48f
SM
12857 return (sym->aclass () != LOC_TYPEDEF
12858 && sym->aclass () != LOC_BLOCK
12859 && sym->aclass () != LOC_CONST
12860 && sym->aclass () != LOC_UNRESOLVED
dda83cd7 12861 && type_name != NULL && strcmp (type_name, "exception") == 0);
778865d3
JB
12862}
12863
12864/* Given a global symbol SYM, return non-zero iff SYM is a non-standard
12865 Ada exception object. This matches all exceptions except the ones
12866 defined by the Ada language. */
12867
12868static int
12869ada_is_non_standard_exception_sym (struct symbol *sym)
12870{
778865d3
JB
12871 if (!ada_is_exception_sym (sym))
12872 return 0;
12873
696d6f4d
TT
12874 for (const char *name : standard_exc)
12875 if (strcmp (sym->linkage_name (), name) == 0)
778865d3
JB
12876 return 0; /* A standard exception. */
12877
12878 /* Numeric_Error is also a standard exception, so exclude it.
12879 See the STANDARD_EXC description for more details as to why
12880 this exception is not listed in that array. */
987012b8 12881 if (strcmp (sym->linkage_name (), "numeric_error") == 0)
778865d3
JB
12882 return 0;
12883
12884 return 1;
12885}
12886
ab816a27 12887/* A helper function for std::sort, comparing two struct ada_exc_info
778865d3
JB
12888 objects.
12889
12890 The comparison is determined first by exception name, and then
12891 by exception address. */
12892
ab816a27 12893bool
cc536b21 12894ada_exc_info::operator< (const ada_exc_info &other) const
778865d3 12895{
778865d3
JB
12896 int result;
12897
ab816a27
TT
12898 result = strcmp (name, other.name);
12899 if (result < 0)
12900 return true;
12901 if (result == 0 && addr < other.addr)
12902 return true;
12903 return false;
12904}
778865d3 12905
ab816a27 12906bool
cc536b21 12907ada_exc_info::operator== (const ada_exc_info &other) const
ab816a27
TT
12908{
12909 return addr == other.addr && strcmp (name, other.name) == 0;
778865d3
JB
12910}
12911
12912/* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
12913 routine, but keeping the first SKIP elements untouched.
12914
12915 All duplicates are also removed. */
12916
12917static void
ab816a27 12918sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
778865d3
JB
12919 int skip)
12920{
ab816a27
TT
12921 std::sort (exceptions->begin () + skip, exceptions->end ());
12922 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
12923 exceptions->end ());
778865d3
JB
12924}
12925
778865d3
JB
12926/* Add all exceptions defined by the Ada standard whose name match
12927 a regular expression.
12928
12929 If PREG is not NULL, then this regexp_t object is used to
12930 perform the symbol name matching. Otherwise, no name-based
12931 filtering is performed.
12932
12933 EXCEPTIONS is a vector of exceptions to which matching exceptions
12934 gets pushed. */
12935
12936static void
2d7cc5c7 12937ada_add_standard_exceptions (compiled_regex *preg,
ab816a27 12938 std::vector<ada_exc_info> *exceptions)
778865d3 12939{
696d6f4d 12940 for (const char *name : standard_exc)
778865d3 12941 {
696d6f4d 12942 if (preg == NULL || preg->exec (name, 0, NULL, 0) == 0)
778865d3 12943 {
4326580d
MM
12944 symbol_name_match_type match_type = name_match_type_from_name (name);
12945 lookup_name_info lookup_name (name, match_type);
778865d3 12946
4326580d
MM
12947 symbol_name_matcher_ftype *match_name
12948 = ada_get_symbol_name_matcher (lookup_name);
778865d3 12949
4326580d
MM
12950 /* Iterate over all objfiles irrespective of scope or linker
12951 namespaces so we get all exceptions anywhere in the
12952 progspace. */
12953 for (objfile *objfile : current_program_space->objfiles ())
12954 {
12955 for (minimal_symbol *msymbol : objfile->msymbols ())
12956 {
12957 if (match_name (msymbol->linkage_name (), lookup_name,
12958 nullptr)
12959 && msymbol->type () != mst_solib_trampoline)
12960 {
12961 ada_exc_info info
12962 = {name, msymbol->value_address (objfile)};
12963
12964 exceptions->push_back (info);
12965 }
12966 }
778865d3
JB
12967 }
12968 }
12969 }
12970}
12971
12972/* Add all Ada exceptions defined locally and accessible from the given
12973 FRAME.
12974
12975 If PREG is not NULL, then this regexp_t object is used to
12976 perform the symbol name matching. Otherwise, no name-based
12977 filtering is performed.
12978
12979 EXCEPTIONS is a vector of exceptions to which matching exceptions
12980 gets pushed. */
12981
12982static void
2d7cc5c7 12983ada_add_exceptions_from_frame (compiled_regex *preg,
bd2b40ac 12984 frame_info_ptr frame,
ab816a27 12985 std::vector<ada_exc_info> *exceptions)
778865d3 12986{
3977b71f 12987 const struct block *block = get_frame_block (frame, 0);
778865d3
JB
12988
12989 while (block != 0)
12990 {
548a89df 12991 for (struct symbol *sym : block_iterator_range (block))
778865d3 12992 {
66d7f48f 12993 switch (sym->aclass ())
778865d3
JB
12994 {
12995 case LOC_TYPEDEF:
12996 case LOC_BLOCK:
12997 case LOC_CONST:
12998 break;
12999 default:
13000 if (ada_is_exception_sym (sym))
13001 {
987012b8 13002 struct ada_exc_info info = {sym->print_name (),
4aeddc50 13003 sym->value_address ()};
778865d3 13004
ab816a27 13005 exceptions->push_back (info);
778865d3
JB
13006 }
13007 }
13008 }
6c00f721 13009 if (block->function () != NULL)
778865d3 13010 break;
f135fe72 13011 block = block->superblock ();
778865d3
JB
13012 }
13013}
13014
14bc53a8
PA
13015/* Return true if NAME matches PREG or if PREG is NULL. */
13016
13017static bool
2d7cc5c7 13018name_matches_regex (const char *name, compiled_regex *preg)
14bc53a8
PA
13019{
13020 return (preg == NULL
f945dedf 13021 || preg->exec (ada_decode (name).c_str (), 0, NULL, 0) == 0);
14bc53a8
PA
13022}
13023
778865d3
JB
13024/* Add all exceptions defined globally whose name name match
13025 a regular expression, excluding standard exceptions.
13026
13027 The reason we exclude standard exceptions is that they need
13028 to be handled separately: Standard exceptions are defined inside
13029 a runtime unit which is normally not compiled with debugging info,
13030 and thus usually do not show up in our symbol search. However,
13031 if the unit was in fact built with debugging info, we need to
13032 exclude them because they would duplicate the entry we found
13033 during the special loop that specifically searches for those
13034 standard exceptions.
13035
13036 If PREG is not NULL, then this regexp_t object is used to
13037 perform the symbol name matching. Otherwise, no name-based
13038 filtering is performed.
13039
13040 EXCEPTIONS is a vector of exceptions to which matching exceptions
13041 gets pushed. */
13042
13043static void
2d7cc5c7 13044ada_add_global_exceptions (compiled_regex *preg,
ab816a27 13045 std::vector<ada_exc_info> *exceptions)
778865d3 13046{
14bc53a8
PA
13047 /* In Ada, the symbol "search name" is a linkage name, whereas the
13048 regular expression used to do the matching refers to the natural
13049 name. So match against the decoded name. */
13050 expand_symtabs_matching (NULL,
b5ec771e 13051 lookup_name_info::match_any (),
14bc53a8
PA
13052 [&] (const char *search_name)
13053 {
f945dedf
CB
13054 std::string decoded = ada_decode (search_name);
13055 return name_matches_regex (decoded.c_str (), preg);
14bc53a8
PA
13056 },
13057 NULL,
03a8ea51 13058 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
14bc53a8 13059 VARIABLES_DOMAIN);
778865d3 13060
4326580d
MM
13061 /* Iterate over all objfiles irrespective of scope or linker namespaces
13062 so we get all exceptions anywhere in the progspace. */
2030c079 13063 for (objfile *objfile : current_program_space->objfiles ())
778865d3 13064 {
b669c953 13065 for (compunit_symtab *s : objfile->compunits ())
778865d3 13066 {
af39c5c8 13067 const struct blockvector *bv = s->blockvector ();
d8aeb77f 13068 int i;
778865d3 13069
d8aeb77f
TT
13070 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13071 {
63d609de 13072 const struct block *b = bv->block (i);
778865d3 13073
548a89df 13074 for (struct symbol *sym : block_iterator_range (b))
d8aeb77f 13075 if (ada_is_non_standard_exception_sym (sym)
987012b8 13076 && name_matches_regex (sym->natural_name (), preg))
d8aeb77f
TT
13077 {
13078 struct ada_exc_info info
4aeddc50 13079 = {sym->print_name (), sym->value_address ()};
d8aeb77f
TT
13080
13081 exceptions->push_back (info);
13082 }
13083 }
778865d3
JB
13084 }
13085 }
13086}
13087
13088/* Implements ada_exceptions_list with the regular expression passed
13089 as a regex_t, rather than a string.
13090
13091 If not NULL, PREG is used to filter out exceptions whose names
13092 do not match. Otherwise, all exceptions are listed. */
13093
ab816a27 13094static std::vector<ada_exc_info>
2d7cc5c7 13095ada_exceptions_list_1 (compiled_regex *preg)
778865d3 13096{
ab816a27 13097 std::vector<ada_exc_info> result;
778865d3
JB
13098 int prev_len;
13099
13100 /* First, list the known standard exceptions. These exceptions
13101 need to be handled separately, as they are usually defined in
13102 runtime units that have been compiled without debugging info. */
13103
13104 ada_add_standard_exceptions (preg, &result);
13105
13106 /* Next, find all exceptions whose scope is local and accessible
13107 from the currently selected frame. */
13108
13109 if (has_stack_frames ())
13110 {
ab816a27 13111 prev_len = result.size ();
778865d3
JB
13112 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13113 &result);
ab816a27 13114 if (result.size () > prev_len)
778865d3
JB
13115 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13116 }
13117
13118 /* Add all exceptions whose scope is global. */
13119
ab816a27 13120 prev_len = result.size ();
778865d3 13121 ada_add_global_exceptions (preg, &result);
ab816a27 13122 if (result.size () > prev_len)
778865d3
JB
13123 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13124
778865d3
JB
13125 return result;
13126}
13127
13128/* Return a vector of ada_exc_info.
13129
13130 If REGEXP is NULL, all exceptions are included in the result.
13131 Otherwise, it should contain a valid regular expression,
13132 and only the exceptions whose names match that regular expression
13133 are included in the result.
13134
13135 The exceptions are sorted in the following order:
13136 - Standard exceptions (defined by the Ada language), in
13137 alphabetical order;
13138 - Exceptions only visible from the current frame, in
13139 alphabetical order;
13140 - Exceptions whose scope is global, in alphabetical order. */
13141
ab816a27 13142std::vector<ada_exc_info>
778865d3
JB
13143ada_exceptions_list (const char *regexp)
13144{
2d7cc5c7
PA
13145 if (regexp == NULL)
13146 return ada_exceptions_list_1 (NULL);
778865d3 13147
2d7cc5c7
PA
13148 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13149 return ada_exceptions_list_1 (&reg);
778865d3
JB
13150}
13151
13152/* Implement the "info exceptions" command. */
13153
13154static void
1d12d88f 13155info_exceptions_command (const char *regexp, int from_tty)
778865d3 13156{
778865d3 13157 struct gdbarch *gdbarch = get_current_arch ();
778865d3 13158
ab816a27 13159 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
778865d3
JB
13160
13161 if (regexp != NULL)
6cb06a8c 13162 gdb_printf
778865d3
JB
13163 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13164 else
6cb06a8c 13165 gdb_printf (_("All defined Ada exceptions:\n"));
778865d3 13166
ab816a27 13167 for (const ada_exc_info &info : exceptions)
6cb06a8c 13168 gdb_printf ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
778865d3
JB
13169}
13170
6c038f32
PH
13171\f
13172 /* Language vector */
13173
b5ec771e
PA
13174/* symbol_name_matcher_ftype adapter for wild_match. */
13175
13176static bool
13177do_wild_match (const char *symbol_search_name,
13178 const lookup_name_info &lookup_name,
a207cff2 13179 completion_match_result *comp_match_res)
b5ec771e
PA
13180{
13181 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
13182}
13183
13184/* symbol_name_matcher_ftype adapter for full_match. */
13185
13186static bool
13187do_full_match (const char *symbol_search_name,
13188 const lookup_name_info &lookup_name,
a207cff2 13189 completion_match_result *comp_match_res)
b5ec771e 13190{
959d6a67
TT
13191 const char *lname = lookup_name.ada ().lookup_name ().c_str ();
13192
13193 /* If both symbols start with "_ada_", just let the loop below
13194 handle the comparison. However, if only the symbol name starts
13195 with "_ada_", skip the prefix and let the match proceed as
13196 usual. */
13197 if (startswith (symbol_search_name, "_ada_")
13198 && !startswith (lname, "_ada"))
86b44259 13199 symbol_search_name += 5;
81eaa506
TT
13200 /* Likewise for ghost entities. */
13201 if (startswith (symbol_search_name, "___ghost_")
13202 && !startswith (lname, "___ghost_"))
13203 symbol_search_name += 9;
86b44259 13204
86b44259
TT
13205 int uscore_count = 0;
13206 while (*lname != '\0')
13207 {
13208 if (*symbol_search_name != *lname)
13209 {
13210 if (*symbol_search_name == 'B' && uscore_count == 2
13211 && symbol_search_name[1] == '_')
13212 {
13213 symbol_search_name += 2;
13214 while (isdigit (*symbol_search_name))
13215 ++symbol_search_name;
13216 if (symbol_search_name[0] == '_'
13217 && symbol_search_name[1] == '_')
13218 {
13219 symbol_search_name += 2;
13220 continue;
13221 }
13222 }
13223 return false;
13224 }
13225
13226 if (*symbol_search_name == '_')
13227 ++uscore_count;
13228 else
13229 uscore_count = 0;
13230
13231 ++symbol_search_name;
13232 ++lname;
13233 }
13234
13235 return is_name_suffix (symbol_search_name);
b5ec771e
PA
13236}
13237
a2cd4f14
JB
13238/* symbol_name_matcher_ftype for exact (verbatim) matches. */
13239
13240static bool
13241do_exact_match (const char *symbol_search_name,
13242 const lookup_name_info &lookup_name,
13243 completion_match_result *comp_match_res)
13244{
13245 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
13246}
13247
b5ec771e
PA
13248/* Build the Ada lookup name for LOOKUP_NAME. */
13249
13250ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
13251{
e0802d59 13252 gdb::string_view user_name = lookup_name.name ();
b5ec771e 13253
6a780b67 13254 if (!user_name.empty () && user_name[0] == '<')
b5ec771e
PA
13255 {
13256 if (user_name.back () == '>')
e0802d59 13257 m_encoded_name
5ac58899 13258 = gdb::to_string (user_name.substr (1, user_name.size () - 2));
b5ec771e 13259 else
e0802d59 13260 m_encoded_name
5ac58899 13261 = gdb::to_string (user_name.substr (1, user_name.size () - 1));
b5ec771e
PA
13262 m_encoded_p = true;
13263 m_verbatim_p = true;
13264 m_wild_match_p = false;
13265 m_standard_p = false;
13266 }
13267 else
13268 {
13269 m_verbatim_p = false;
13270
e0802d59 13271 m_encoded_p = user_name.find ("__") != gdb::string_view::npos;
b5ec771e
PA
13272
13273 if (!m_encoded_p)
13274 {
e0802d59 13275 const char *folded = ada_fold_name (user_name);
5c4258f4
TT
13276 m_encoded_name = ada_encode_1 (folded, false);
13277 if (m_encoded_name.empty ())
5ac58899 13278 m_encoded_name = gdb::to_string (user_name);
b5ec771e
PA
13279 }
13280 else
5ac58899 13281 m_encoded_name = gdb::to_string (user_name);
b5ec771e
PA
13282
13283 /* Handle the 'package Standard' special case. See description
13284 of m_standard_p. */
13285 if (startswith (m_encoded_name.c_str (), "standard__"))
13286 {
13287 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
13288 m_standard_p = true;
13289 }
13290 else
13291 m_standard_p = false;
74ccd7f5 13292
b5ec771e
PA
13293 /* If the name contains a ".", then the user is entering a fully
13294 qualified entity name, and the match must not be done in wild
13295 mode. Similarly, if the user wants to complete what looks
13296 like an encoded name, the match must not be done in wild
13297 mode. Also, in the standard__ special case always do
13298 non-wild matching. */
13299 m_wild_match_p
13300 = (lookup_name.match_type () != symbol_name_match_type::FULL
13301 && !m_encoded_p
13302 && !m_standard_p
13303 && user_name.find ('.') == std::string::npos);
13304 }
13305}
13306
13307/* symbol_name_matcher_ftype method for Ada. This only handles
13308 completion mode. */
13309
13310static bool
13311ada_symbol_name_matches (const char *symbol_search_name,
13312 const lookup_name_info &lookup_name,
a207cff2 13313 completion_match_result *comp_match_res)
74ccd7f5 13314{
b5ec771e
PA
13315 return lookup_name.ada ().matches (symbol_search_name,
13316 lookup_name.match_type (),
a207cff2 13317 comp_match_res);
b5ec771e
PA
13318}
13319
de63c46b
PA
13320/* A name matcher that matches the symbol name exactly, with
13321 strcmp. */
13322
13323static bool
13324literal_symbol_name_matcher (const char *symbol_search_name,
13325 const lookup_name_info &lookup_name,
13326 completion_match_result *comp_match_res)
13327{
e0802d59 13328 gdb::string_view name_view = lookup_name.name ();
de63c46b 13329
e0802d59
TT
13330 if (lookup_name.completion_mode ()
13331 ? (strncmp (symbol_search_name, name_view.data (),
13332 name_view.size ()) == 0)
13333 : symbol_search_name == name_view)
de63c46b
PA
13334 {
13335 if (comp_match_res != NULL)
13336 comp_match_res->set_match (symbol_search_name);
13337 return true;
13338 }
13339 else
13340 return false;
13341}
13342
c9debfb9 13343/* Implement the "get_symbol_name_matcher" language_defn method for
b5ec771e
PA
13344 Ada. */
13345
13346static symbol_name_matcher_ftype *
13347ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
13348{
de63c46b
PA
13349 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
13350 return literal_symbol_name_matcher;
13351
b5ec771e
PA
13352 if (lookup_name.completion_mode ())
13353 return ada_symbol_name_matches;
74ccd7f5 13354 else
b5ec771e
PA
13355 {
13356 if (lookup_name.ada ().wild_match_p ())
13357 return do_wild_match;
a2cd4f14
JB
13358 else if (lookup_name.ada ().verbatim_p ())
13359 return do_exact_match;
b5ec771e
PA
13360 else
13361 return do_full_match;
13362 }
74ccd7f5
JB
13363}
13364
0874fd07
AB
13365/* Class representing the Ada language. */
13366
13367class ada_language : public language_defn
13368{
13369public:
13370 ada_language ()
0e25e767 13371 : language_defn (language_ada)
0874fd07 13372 { /* Nothing. */ }
5bd40f2a 13373
6f7664a9
AB
13374 /* See language.h. */
13375
13376 const char *name () const override
13377 { return "ada"; }
13378
13379 /* See language.h. */
13380
13381 const char *natural_name () const override
13382 { return "Ada"; }
13383
e171d6f1
AB
13384 /* See language.h. */
13385
13386 const std::vector<const char *> &filename_extensions () const override
13387 {
13388 static const std::vector<const char *> extensions
13389 = { ".adb", ".ads", ".a", ".ada", ".dg" };
13390 return extensions;
13391 }
13392
5bd40f2a
AB
13393 /* Print an array element index using the Ada syntax. */
13394
13395 void print_array_index (struct type *index_type,
13396 LONGEST index,
13397 struct ui_file *stream,
13398 const value_print_options *options) const override
13399 {
13400 struct value *index_value = val_atr (index_type, index);
13401
00c696a6 13402 value_print (index_value, stream, options);
6cb06a8c 13403 gdb_printf (stream, " => ");
5bd40f2a 13404 }
15e5fd35
AB
13405
13406 /* Implement the "read_var_value" language_defn method for Ada. */
13407
13408 struct value *read_var_value (struct symbol *var,
13409 const struct block *var_block,
bd2b40ac 13410 frame_info_ptr frame) const override
15e5fd35
AB
13411 {
13412 /* The only case where default_read_var_value is not sufficient
13413 is when VAR is a renaming... */
13414 if (frame != nullptr)
13415 {
13416 const struct block *frame_block = get_frame_block (frame, NULL);
13417 if (frame_block != nullptr && ada_is_renaming_symbol (var))
13418 return ada_read_renaming_var_value (var, frame_block);
13419 }
13420
13421 /* This is a typical case where we expect the default_read_var_value
13422 function to work. */
13423 return language_defn::read_var_value (var, var_block, frame);
13424 }
1fb314aa 13425
2c71f639 13426 /* See language.h. */
496feb16 13427 bool symbol_printing_suppressed (struct symbol *symbol) const override
2c71f639 13428 {
496feb16 13429 return symbol->is_artificial ();
2c71f639
TV
13430 }
13431
baab3753
AB
13432 /* See language.h. */
13433 struct value *value_string (struct gdbarch *gdbarch,
13434 const char *ptr, ssize_t len) const override
13435 {
13436 struct type *type = language_string_char_type (this, gdbarch);
13437 value *val = ::value_string (ptr, len, type);
13438 /* VAL will be a TYPE_CODE_STRING, but Ada only knows how to print
13439 strings that are arrays of characters, so fix the type now. */
13440 gdb_assert (val->type ()->code () == TYPE_CODE_STRING);
13441 val->type ()->set_code (TYPE_CODE_ARRAY);
13442 return val;
13443 }
13444
1fb314aa
AB
13445 /* See language.h. */
13446 void language_arch_info (struct gdbarch *gdbarch,
13447 struct language_arch_info *lai) const override
13448 {
13449 const struct builtin_type *builtin = builtin_type (gdbarch);
13450
7bea47f0
AB
13451 /* Helper function to allow shorter lines below. */
13452 auto add = [&] (struct type *t)
13453 {
13454 lai->add_primitive_type (t);
13455 };
13456
cc495054 13457 type_allocator alloc (gdbarch);
2d39ccd3 13458 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0 13459 0, "integer"));
2d39ccd3 13460 add (init_integer_type (alloc, gdbarch_long_bit (gdbarch),
7bea47f0 13461 0, "long_integer"));
2d39ccd3 13462 add (init_integer_type (alloc, gdbarch_short_bit (gdbarch),
7bea47f0 13463 0, "short_integer"));
f50b437c 13464 struct type *char_type = init_character_type (alloc, TARGET_CHAR_BIT,
c9f66f00 13465 1, "character");
7bea47f0
AB
13466 lai->set_string_char_type (char_type);
13467 add (char_type);
f50b437c
TT
13468 add (init_character_type (alloc, 16, 1, "wide_character"));
13469 add (init_character_type (alloc, 32, 1, "wide_wide_character"));
77c5f496 13470 add (init_float_type (alloc, gdbarch_float_bit (gdbarch),
7bea47f0 13471 "float", gdbarch_float_format (gdbarch)));
77c5f496 13472 add (init_float_type (alloc, gdbarch_double_bit (gdbarch),
7bea47f0 13473 "long_float", gdbarch_double_format (gdbarch)));
2d39ccd3 13474 add (init_integer_type (alloc, gdbarch_long_long_bit (gdbarch),
7bea47f0 13475 0, "long_long_integer"));
e49831ba
TT
13476 add (init_integer_type (alloc, 128, 0, "long_long_long_integer"));
13477 add (init_integer_type (alloc, 128, 1, "unsigned_long_long_long_integer"));
77c5f496 13478 add (init_float_type (alloc, gdbarch_long_double_bit (gdbarch),
7bea47f0
AB
13479 "long_long_float",
13480 gdbarch_long_double_format (gdbarch)));
2d39ccd3 13481 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0 13482 0, "natural"));
2d39ccd3 13483 add (init_integer_type (alloc, gdbarch_int_bit (gdbarch),
7bea47f0
AB
13484 0, "positive"));
13485 add (builtin->builtin_void);
13486
13487 struct type *system_addr_ptr
cc495054
TT
13488 = lookup_pointer_type (alloc.new_type (TYPE_CODE_VOID, TARGET_CHAR_BIT,
13489 "void"));
7bea47f0
AB
13490 system_addr_ptr->set_name ("system__address");
13491 add (system_addr_ptr);
1fb314aa
AB
13492
13493 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
13494 type. This is a signed integral type whose size is the same as
13495 the size of addresses. */
df86565b 13496 unsigned int addr_length = system_addr_ptr->length ();
2d39ccd3 13497 add (init_integer_type (alloc, addr_length * HOST_CHAR_BIT, 0,
7bea47f0 13498 "storage_offset"));
1fb314aa 13499
7bea47f0 13500 lai->set_bool_type (builtin->builtin_bool);
1fb314aa 13501 }
4009ee92
AB
13502
13503 /* See language.h. */
13504
13505 bool iterate_over_symbols
13506 (const struct block *block, const lookup_name_info &name,
13507 domain_enum domain,
13508 gdb::function_view<symbol_found_callback_ftype> callback) const override
13509 {
d1183b06
TT
13510 std::vector<struct block_symbol> results
13511 = ada_lookup_symbol_list_worker (name, block, domain, 0);
4009ee92
AB
13512 for (block_symbol &sym : results)
13513 {
13514 if (!callback (&sym))
13515 return false;
13516 }
13517
13518 return true;
13519 }
6f827019
AB
13520
13521 /* See language.h. */
3456e70c
TT
13522 bool sniff_from_mangled_name
13523 (const char *mangled,
13524 gdb::unique_xmalloc_ptr<char> *out) const override
6f827019
AB
13525 {
13526 std::string demangled = ada_decode (mangled);
13527
13528 *out = NULL;
13529
13530 if (demangled != mangled && demangled[0] != '<')
13531 {
13532 /* Set the gsymbol language to Ada, but still return 0.
13533 Two reasons for that:
13534
13535 1. For Ada, we prefer computing the symbol's decoded name
13536 on the fly rather than pre-compute it, in order to save
13537 memory (Ada projects are typically very large).
13538
13539 2. There are some areas in the definition of the GNAT
13540 encoding where, with a bit of bad luck, we might be able
13541 to decode a non-Ada symbol, generating an incorrect
13542 demangled name (Eg: names ending with "TB" for instance
13543 are identified as task bodies and so stripped from
13544 the decoded name returned).
13545
13546 Returning true, here, but not setting *DEMANGLED, helps us get
13547 a little bit of the best of both worlds. Because we're last,
13548 we should not affect any of the other languages that were
13549 able to demangle the symbol before us; we get to correctly
13550 tag Ada symbols as such; and even if we incorrectly tagged a
13551 non-Ada symbol, which should be rare, any routing through the
13552 Ada language should be transparent (Ada tries to behave much
13553 like C/C++ with non-Ada symbols). */
13554 return true;
13555 }
13556
13557 return false;
13558 }
fbfb0a46
AB
13559
13560 /* See language.h. */
13561
3456e70c
TT
13562 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
13563 int options) const override
0a50df5d 13564 {
3456e70c 13565 return make_unique_xstrdup (ada_decode (mangled).c_str ());
0a50df5d
AB
13566 }
13567
13568 /* See language.h. */
13569
fbfb0a46
AB
13570 void print_type (struct type *type, const char *varstring,
13571 struct ui_file *stream, int show, int level,
13572 const struct type_print_options *flags) const override
13573 {
13574 ada_print_type (type, varstring, stream, show, level, flags);
13575 }
c9debfb9 13576
53fc67f8
AB
13577 /* See language.h. */
13578
13579 const char *word_break_characters (void) const override
13580 {
13581 return ada_completer_word_break_characters;
13582 }
13583
7e56227d
AB
13584 /* See language.h. */
13585
13586 void collect_symbol_completion_matches (completion_tracker &tracker,
13587 complete_symbol_mode mode,
13588 symbol_name_match_type name_match_type,
13589 const char *text, const char *word,
13590 enum type_code code) const override
13591 {
7e56227d 13592 const struct block *b, *surrounding_static_block = 0;
7e56227d
AB
13593
13594 gdb_assert (code == TYPE_CODE_UNDEF);
13595
13596 lookup_name_info lookup_name (text, name_match_type, true);
13597
13598 /* First, look at the partial symtab symbols. */
13599 expand_symtabs_matching (NULL,
13600 lookup_name,
13601 NULL,
13602 NULL,
03a8ea51 13603 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
7e56227d
AB
13604 ALL_DOMAIN);
13605
13606 /* At this point scan through the misc symbol vectors and add each
13607 symbol you find to the list. Eventually we want to ignore
13608 anything that isn't a text symbol (everything else will be
13609 handled by the psymtab code above). */
13610
13611 for (objfile *objfile : current_program_space->objfiles ())
13612 {
13613 for (minimal_symbol *msymbol : objfile->msymbols ())
13614 {
13615 QUIT;
13616
13617 if (completion_skip_symbol (mode, msymbol))
13618 continue;
13619
13620 language symbol_language = msymbol->language ();
13621
13622 /* Ada minimal symbols won't have their language set to Ada. If
13623 we let completion_list_add_name compare using the
13624 default/C-like matcher, then when completing e.g., symbols in a
13625 package named "pck", we'd match internal Ada symbols like
13626 "pckS", which are invalid in an Ada expression, unless you wrap
13627 them in '<' '>' to request a verbatim match.
13628
13629 Unfortunately, some Ada encoded names successfully demangle as
13630 C++ symbols (using an old mangling scheme), such as "name__2Xn"
13631 -> "Xn::name(void)" and thus some Ada minimal symbols end up
13632 with the wrong language set. Paper over that issue here. */
129bce36 13633 if (symbol_language == language_unknown
7e56227d
AB
13634 || symbol_language == language_cplus)
13635 symbol_language = language_ada;
13636
13637 completion_list_add_name (tracker,
13638 symbol_language,
13639 msymbol->linkage_name (),
13640 lookup_name, text, word);
13641 }
13642 }
13643
13644 /* Search upwards from currently selected frame (so that we can
13645 complete on local vars. */
13646
f135fe72 13647 for (b = get_selected_block (0); b != NULL; b = b->superblock ())
7e56227d 13648 {
f135fe72 13649 if (!b->superblock ())
7e56227d
AB
13650 surrounding_static_block = b; /* For elmin of dups */
13651
548a89df 13652 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13653 {
13654 if (completion_skip_symbol (mode, sym))
13655 continue;
13656
13657 completion_list_add_name (tracker,
13658 sym->language (),
13659 sym->linkage_name (),
13660 lookup_name, text, word);
13661 }
13662 }
13663
13664 /* Go through the symtabs and check the externs and statics for
13665 symbols which match. */
13666
13667 for (objfile *objfile : current_program_space->objfiles ())
13668 {
13669 for (compunit_symtab *s : objfile->compunits ())
13670 {
13671 QUIT;
63d609de 13672 b = s->blockvector ()->global_block ();
548a89df 13673 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13674 {
13675 if (completion_skip_symbol (mode, sym))
13676 continue;
13677
13678 completion_list_add_name (tracker,
13679 sym->language (),
13680 sym->linkage_name (),
13681 lookup_name, text, word);
13682 }
13683 }
13684 }
13685
13686 for (objfile *objfile : current_program_space->objfiles ())
13687 {
13688 for (compunit_symtab *s : objfile->compunits ())
13689 {
13690 QUIT;
63d609de 13691 b = s->blockvector ()->static_block ();
7e56227d
AB
13692 /* Don't do this block twice. */
13693 if (b == surrounding_static_block)
13694 continue;
548a89df 13695 for (struct symbol *sym : block_iterator_range (b))
7e56227d
AB
13696 {
13697 if (completion_skip_symbol (mode, sym))
13698 continue;
13699
13700 completion_list_add_name (tracker,
13701 sym->language (),
13702 sym->linkage_name (),
13703 lookup_name, text, word);
13704 }
13705 }
13706 }
13707 }
13708
f16a9f57
AB
13709 /* See language.h. */
13710
13711 gdb::unique_xmalloc_ptr<char> watch_location_expression
13712 (struct type *type, CORE_ADDR addr) const override
13713 {
27710edb 13714 type = check_typedef (check_typedef (type)->target_type ());
f16a9f57 13715 std::string name = type_to_string (type);
8579fd13 13716 return xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr));
f16a9f57
AB
13717 }
13718
a1d1fa3e
AB
13719 /* See language.h. */
13720
13721 void value_print (struct value *val, struct ui_file *stream,
13722 const struct value_print_options *options) const override
13723 {
13724 return ada_value_print (val, stream, options);
13725 }
13726
ebe2334e
AB
13727 /* See language.h. */
13728
13729 void value_print_inner
13730 (struct value *val, struct ui_file *stream, int recurse,
13731 const struct value_print_options *options) const override
13732 {
13733 return ada_value_print_inner (val, stream, recurse, options);
13734 }
13735
a78a19b1
AB
13736 /* See language.h. */
13737
13738 struct block_symbol lookup_symbol_nonlocal
13739 (const char *name, const struct block *block,
13740 const domain_enum domain) const override
13741 {
13742 struct block_symbol sym;
13743
78004096
TT
13744 sym = ada_lookup_symbol (name,
13745 (block == nullptr
13746 ? nullptr
d24e14a0 13747 : block->static_block ()),
78004096 13748 domain);
a78a19b1
AB
13749 if (sym.symbol != NULL)
13750 return sym;
13751
13752 /* If we haven't found a match at this point, try the primitive
13753 types. In other languages, this search is performed before
13754 searching for global symbols in order to short-circuit that
13755 global-symbol search if it happens that the name corresponds
13756 to a primitive type. But we cannot do the same in Ada, because
13757 it is perfectly legitimate for a program to declare a type which
13758 has the same name as a standard type. If looking up a type in
13759 that situation, we have traditionally ignored the primitive type
13760 in favor of user-defined types. This is why, unlike most other
13761 languages, we search the primitive types this late and only after
13762 having searched the global symbols without success. */
13763
13764 if (domain == VAR_DOMAIN)
13765 {
13766 struct gdbarch *gdbarch;
13767
13768 if (block == NULL)
13769 gdbarch = target_gdbarch ();
13770 else
7f5937df 13771 gdbarch = block->gdbarch ();
a78a19b1
AB
13772 sym.symbol
13773 = language_lookup_primitive_type_as_symbol (this, gdbarch, name);
13774 if (sym.symbol != NULL)
13775 return sym;
13776 }
13777
13778 return {};
13779 }
13780
87afa652
AB
13781 /* See language.h. */
13782
13783 int parser (struct parser_state *ps) const override
13784 {
13785 warnings_issued = 0;
13786 return ada_parse (ps);
13787 }
13788
ec8cec5b
AB
13789 /* See language.h. */
13790
13791 void emitchar (int ch, struct type *chtype,
13792 struct ui_file *stream, int quoter) const override
13793 {
13794 ada_emit_char (ch, chtype, stream, quoter, 1);
13795 }
13796
52b50f2c
AB
13797 /* See language.h. */
13798
13799 void printchar (int ch, struct type *chtype,
13800 struct ui_file *stream) const override
13801 {
13802 ada_printchar (ch, chtype, stream);
13803 }
13804
d711ee67
AB
13805 /* See language.h. */
13806
13807 void printstr (struct ui_file *stream, struct type *elttype,
13808 const gdb_byte *string, unsigned int length,
13809 const char *encoding, int force_ellipses,
13810 const struct value_print_options *options) const override
13811 {
13812 ada_printstr (stream, elttype, string, length, encoding,
13813 force_ellipses, options);
13814 }
13815
4ffc13fb
AB
13816 /* See language.h. */
13817
13818 void print_typedef (struct type *type, struct symbol *new_symbol,
13819 struct ui_file *stream) const override
13820 {
13821 ada_print_typedef (type, new_symbol, stream);
13822 }
13823
39e7ecca
AB
13824 /* See language.h. */
13825
13826 bool is_string_type_p (struct type *type) const override
13827 {
13828 return ada_is_string_type (type);
13829 }
13830
22e3f3ed
AB
13831 /* See language.h. */
13832
26733fc7
TT
13833 bool is_array_like (struct type *type) const override
13834 {
13835 return (ada_is_constrained_packed_array_type (type)
13836 || ada_is_array_descriptor_type (type));
13837 }
13838
13839 /* See language.h. */
13840
13841 struct value *to_array (struct value *val) const override
13842 { return ada_coerce_to_simple_array (val); }
13843
13844 /* See language.h. */
13845
22e3f3ed
AB
13846 const char *struct_too_deep_ellipsis () const override
13847 { return "(...)"; }
39e7ecca 13848
67bd3fd5
AB
13849 /* See language.h. */
13850
13851 bool c_style_arrays_p () const override
13852 { return false; }
13853
d3355e4d
AB
13854 /* See language.h. */
13855
13856 bool store_sym_names_in_linkage_form_p () const override
13857 { return true; }
13858
b63a3f3f
AB
13859 /* See language.h. */
13860
13861 const struct lang_varobj_ops *varobj_ops () const override
13862 { return &ada_varobj_ops; }
13863
c9debfb9
AB
13864protected:
13865 /* See language.h. */
13866
13867 symbol_name_matcher_ftype *get_symbol_name_matcher_inner
13868 (const lookup_name_info &lookup_name) const override
13869 {
13870 return ada_get_symbol_name_matcher (lookup_name);
13871 }
0874fd07
AB
13872};
13873
13874/* Single instance of the Ada language class. */
13875
13876static ada_language ada_language_defn;
13877
5bf03f13
JB
13878/* Command-list for the "set/show ada" prefix command. */
13879static struct cmd_list_element *set_ada_list;
13880static struct cmd_list_element *show_ada_list;
13881
3d9434b5
JB
13882/* This module's 'new_objfile' observer. */
13883
13884static void
13885ada_new_objfile_observer (struct objfile *objfile)
13886{
74daa597 13887 ada_clear_symbol_cache (objfile->pspace);
3d9434b5
JB
13888}
13889
13890/* This module's 'free_objfile' observer. */
13891
13892static void
13893ada_free_objfile_observer (struct objfile *objfile)
13894{
74daa597 13895 ada_clear_symbol_cache (objfile->pspace);
3d9434b5
JB
13896}
13897
315e4ebb
TT
13898/* Charsets known to GNAT. */
13899static const char * const gnat_source_charsets[] =
13900{
13901 /* Note that code below assumes that the default comes first.
13902 Latin-1 is the default here, because that is also GNAT's
13903 default. */
13904 "ISO-8859-1",
13905 "ISO-8859-2",
13906 "ISO-8859-3",
13907 "ISO-8859-4",
13908 "ISO-8859-5",
13909 "ISO-8859-15",
13910 "CP437",
13911 "CP850",
13912 /* Note that this value is special-cased in the encoder and
13913 decoder. */
13914 ada_utf8,
13915 nullptr
13916};
13917
6c265988 13918void _initialize_ada_language ();
d2e4a39e 13919void
6c265988 13920_initialize_ada_language ()
14f9c5c9 13921{
f54bdb6d
SM
13922 add_setshow_prefix_cmd
13923 ("ada", no_class,
13924 _("Prefix command for changing Ada-specific settings."),
13925 _("Generic command for showing Ada-specific settings."),
13926 &set_ada_list, &show_ada_list,
13927 &setlist, &showlist);
5bf03f13
JB
13928
13929 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
dda83cd7 13930 &trust_pad_over_xvs, _("\
590042fc
PW
13931Enable or disable an optimization trusting PAD types over XVS types."), _("\
13932Show whether an optimization trusting PAD types over XVS types is activated."),
dda83cd7 13933 _("\
5bf03f13
JB
13934This is related to the encoding used by the GNAT compiler. The debugger\n\
13935should normally trust the contents of PAD types, but certain older versions\n\
13936of GNAT have a bug that sometimes causes the information in the PAD type\n\
13937to be incorrect. Turning this setting \"off\" allows the debugger to\n\
13938work around this bug. It is always safe to turn this option \"off\", but\n\
13939this incurs a slight performance penalty, so it is recommended to NOT change\n\
13940this option to \"off\" unless necessary."),
dda83cd7 13941 NULL, NULL, &set_ada_list, &show_ada_list);
5bf03f13 13942
d72413e6
PMR
13943 add_setshow_boolean_cmd ("print-signatures", class_vars,
13944 &print_signatures, _("\
13945Enable or disable the output of formal and return types for functions in the \
590042fc 13946overloads selection menu."), _("\
d72413e6 13947Show whether the output of formal and return types for functions in the \
590042fc 13948overloads selection menu is activated."),
d72413e6
PMR
13949 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
13950
315e4ebb
TT
13951 ada_source_charset = gnat_source_charsets[0];
13952 add_setshow_enum_cmd ("source-charset", class_files,
13953 gnat_source_charsets,
13954 &ada_source_charset, _("\
13955Set the Ada source character set."), _("\
13956Show the Ada source character set."), _("\
13957The character set used for Ada source files.\n\
13958This must correspond to the '-gnati' or '-gnatW' option passed to GNAT."),
13959 nullptr, nullptr,
13960 &set_ada_list, &show_ada_list);
13961
9ac4176b
PA
13962 add_catch_command ("exception", _("\
13963Catch Ada exceptions, when raised.\n\
9bf7038b 13964Usage: catch exception [ARG] [if CONDITION]\n\
60a90376
JB
13965Without any argument, stop when any Ada exception is raised.\n\
13966If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
13967being raised does not have a handler (and will therefore lead to the task's\n\
13968termination).\n\
13969Otherwise, the catchpoint only stops when the name of the exception being\n\
9bf7038b
TT
13970raised is the same as ARG.\n\
13971CONDITION is a boolean expression that is evaluated to see whether the\n\
13972exception should cause a stop."),
9ac4176b 13973 catch_ada_exception_command,
71bed2db 13974 catch_ada_completer,
9ac4176b
PA
13975 CATCH_PERMANENT,
13976 CATCH_TEMPORARY);
9f757bf7
XR
13977
13978 add_catch_command ("handlers", _("\
13979Catch Ada exceptions, when handled.\n\
9bf7038b
TT
13980Usage: catch handlers [ARG] [if CONDITION]\n\
13981Without any argument, stop when any Ada exception is handled.\n\
13982With an argument, catch only exceptions with the given name.\n\
13983CONDITION is a boolean expression that is evaluated to see whether the\n\
13984exception should cause a stop."),
9f757bf7 13985 catch_ada_handlers_command,
dda83cd7 13986 catch_ada_completer,
9f757bf7
XR
13987 CATCH_PERMANENT,
13988 CATCH_TEMPORARY);
9ac4176b
PA
13989 add_catch_command ("assert", _("\
13990Catch failed Ada assertions, when raised.\n\
9bf7038b
TT
13991Usage: catch assert [if CONDITION]\n\
13992CONDITION is a boolean expression that is evaluated to see whether the\n\
13993exception should cause a stop."),
9ac4176b 13994 catch_assert_command,
dda83cd7 13995 NULL,
9ac4176b
PA
13996 CATCH_PERMANENT,
13997 CATCH_TEMPORARY);
13998
778865d3
JB
13999 add_info ("exceptions", info_exceptions_command,
14000 _("\
14001List all Ada exception names.\n\
9bf7038b 14002Usage: info exceptions [REGEXP]\n\
778865d3
JB
14003If a regular expression is passed as an argument, only those matching\n\
14004the regular expression are listed."));
14005
f54bdb6d
SM
14006 add_setshow_prefix_cmd ("ada", class_maintenance,
14007 _("Set Ada maintenance-related variables."),
14008 _("Show Ada maintenance-related variables."),
14009 &maint_set_ada_cmdlist, &maint_show_ada_cmdlist,
14010 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
c6044dd1
JB
14011
14012 add_setshow_boolean_cmd
14013 ("ignore-descriptive-types", class_maintenance,
14014 &ada_ignore_descriptive_types_p,
14015 _("Set whether descriptive types generated by GNAT should be ignored."),
14016 _("Show whether descriptive types generated by GNAT should be ignored."),
14017 _("\
14018When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14019DWARF attribute."),
14020 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14021
2698f5ea
TT
14022 decoded_names_store = htab_create_alloc (256, htab_hash_string,
14023 htab_eq_string,
459a2e4c 14024 NULL, xcalloc, xfree);
6b69afc4 14025
3d9434b5 14026 /* The ada-lang observers. */
c90e7d63 14027 gdb::observers::new_objfile.attach (ada_new_objfile_observer, "ada-lang");
74daa597
SM
14028 gdb::observers::all_objfiles_removed.attach (ada_clear_symbol_cache,
14029 "ada-lang");
c90e7d63
SM
14030 gdb::observers::free_objfile.attach (ada_free_objfile_observer, "ada-lang");
14031 gdb::observers::inferior_exit.attach (ada_inferior_exit, "ada-lang");
033bc52b
TT
14032
14033#ifdef GDB_SELF_TEST
14034 selftests::register_test ("ada-decode", ada_decode_tests);
14035#endif
14f9c5c9 14036}