Sort includes for files gdb/[a-f]*.[chyl].
[deliverable/binutils-gdb.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.
2
3 Copyright (C) 1992-2019 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20
21 #include "defs.h"
22
23 /* Standard C includes. */
24 #include <ctype.h>
25 #include <sys/stat.h>
26
27 /* Standard C++ includes. */
28 #include <algorithm>
29
30 /* Local non-gdb includes. */
31 #include "ada-lang.h"
32 #include "annotate.h"
33 #include "arch-utils.h"
34 #include "block.h"
35 #include "breakpoint.h"
36 #include "c-lang.h"
37 #include "cli/cli-utils.h"
38 #include "common/byte-vector.h"
39 #include "common/function-view.h"
40 #include "common/gdb_vecs.h"
41 #include "common/vec.h"
42 #include "completer.h"
43 #include "demangle.h"
44 #include "dictionary.h"
45 #include "expression.h"
46 #include "frame.h"
47 #include "gdb_obstack.h"
48 #include "gdb_regex.h"
49 #include "gdbcmd.h"
50 #include "gdbcore.h"
51 #include "gdbtypes.h"
52 #include "hashtab.h"
53 #include "infcall.h"
54 #include "inferior.h"
55 #include "language.h"
56 #include "mi/mi-common.h"
57 #include "namespace.h"
58 #include "objfiles.h"
59 #include "observable.h"
60 #include "parser-defs.h"
61 #include "psymtab.h"
62 #include "source.h"
63 #include "stack.h"
64 #include "symfile.h"
65 #include "symtab.h"
66 #include "typeprint.h"
67 #include "ui-out.h"
68 #include "valprint.h"
69 #include "value.h"
70 #include "varobj.h"
71
72 /* Define whether or not the C operator '/' truncates towards zero for
73 differently signed operands (truncation direction is undefined in C).
74 Copied from valarith.c. */
75
76 #ifndef TRUNCATION_TOWARDS_ZERO
77 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
78 #endif
79
80 static struct type *desc_base_type (struct type *);
81
82 static struct type *desc_bounds_type (struct type *);
83
84 static struct value *desc_bounds (struct value *);
85
86 static int fat_pntr_bounds_bitpos (struct type *);
87
88 static int fat_pntr_bounds_bitsize (struct type *);
89
90 static struct type *desc_data_target_type (struct type *);
91
92 static struct value *desc_data (struct value *);
93
94 static int fat_pntr_data_bitpos (struct type *);
95
96 static int fat_pntr_data_bitsize (struct type *);
97
98 static struct value *desc_one_bound (struct value *, int, int);
99
100 static int desc_bound_bitpos (struct type *, int, int);
101
102 static int desc_bound_bitsize (struct type *, int, int);
103
104 static struct type *desc_index_type (struct type *, int);
105
106 static int desc_arity (struct type *);
107
108 static int ada_type_match (struct type *, struct type *, int);
109
110 static int ada_args_match (struct symbol *, struct value **, int);
111
112 static struct value *make_array_descriptor (struct type *, struct value *);
113
114 static void ada_add_block_symbols (struct obstack *,
115 const struct block *,
116 const lookup_name_info &lookup_name,
117 domain_enum, struct objfile *);
118
119 static void ada_add_all_symbols (struct obstack *, const struct block *,
120 const lookup_name_info &lookup_name,
121 domain_enum, int, int *);
122
123 static int is_nonfunction (struct block_symbol *, int);
124
125 static void add_defn_to_vec (struct obstack *, struct symbol *,
126 const struct block *);
127
128 static int num_defns_collected (struct obstack *);
129
130 static struct block_symbol *defns_collected (struct obstack *, int);
131
132 static struct value *resolve_subexp (expression_up *, int *, int,
133 struct type *, int,
134 innermost_block_tracker *);
135
136 static void replace_operator_with_call (expression_up *, int, int, int,
137 struct symbol *, const struct block *);
138
139 static int possible_user_operator_p (enum exp_opcode, struct value **);
140
141 static const char *ada_op_name (enum exp_opcode);
142
143 static const char *ada_decoded_op_name (enum exp_opcode);
144
145 static int numeric_type_p (struct type *);
146
147 static int integer_type_p (struct type *);
148
149 static int scalar_type_p (struct type *);
150
151 static int discrete_type_p (struct type *);
152
153 static enum ada_renaming_category parse_old_style_renaming (struct type *,
154 const char **,
155 int *,
156 const char **);
157
158 static struct symbol *find_old_style_renaming_symbol (const char *,
159 const struct block *);
160
161 static struct type *ada_lookup_struct_elt_type (struct type *, const char *,
162 int, int);
163
164 static struct value *evaluate_subexp_type (struct expression *, int *);
165
166 static struct type *ada_find_parallel_type_with_name (struct type *,
167 const char *);
168
169 static int is_dynamic_field (struct type *, int);
170
171 static struct type *to_fixed_variant_branch_type (struct type *,
172 const gdb_byte *,
173 CORE_ADDR, struct value *);
174
175 static struct type *to_fixed_array_type (struct type *, struct value *, int);
176
177 static struct type *to_fixed_range_type (struct type *, struct value *);
178
179 static struct type *to_static_fixed_type (struct type *);
180 static struct type *static_unwrap_type (struct type *type);
181
182 static struct value *unwrap_value (struct value *);
183
184 static struct type *constrained_packed_array_type (struct type *, long *);
185
186 static struct type *decode_constrained_packed_array_type (struct type *);
187
188 static long decode_packed_array_bitsize (struct type *);
189
190 static struct value *decode_constrained_packed_array (struct value *);
191
192 static int ada_is_packed_array_type (struct type *);
193
194 static int ada_is_unconstrained_packed_array_type (struct type *);
195
196 static struct value *value_subscript_packed (struct value *, int,
197 struct value **);
198
199 static struct value *coerce_unspec_val_to_type (struct value *,
200 struct type *);
201
202 static int lesseq_defined_than (struct symbol *, struct symbol *);
203
204 static int equiv_types (struct type *, struct type *);
205
206 static int is_name_suffix (const char *);
207
208 static int advance_wild_match (const char **, const char *, int);
209
210 static bool wild_match (const char *name, const char *patn);
211
212 static struct value *ada_coerce_ref (struct value *);
213
214 static LONGEST pos_atr (struct value *);
215
216 static struct value *value_pos_atr (struct type *, struct value *);
217
218 static struct value *value_val_atr (struct type *, struct value *);
219
220 static struct symbol *standard_lookup (const char *, const struct block *,
221 domain_enum);
222
223 static struct value *ada_search_struct_field (const char *, struct value *, int,
224 struct type *);
225
226 static struct value *ada_value_primitive_field (struct value *, int, int,
227 struct type *);
228
229 static int find_struct_field (const char *, struct type *, int,
230 struct type **, int *, int *, int *, int *);
231
232 static int ada_resolve_function (struct block_symbol *, int,
233 struct value **, int, const char *,
234 struct type *, int);
235
236 static int ada_is_direct_array_type (struct type *);
237
238 static void ada_language_arch_info (struct gdbarch *,
239 struct language_arch_info *);
240
241 static struct value *ada_index_struct_field (int, struct value *, int,
242 struct type *);
243
244 static struct value *assign_aggregate (struct value *, struct value *,
245 struct expression *,
246 int *, enum noside);
247
248 static void aggregate_assign_from_choices (struct value *, struct value *,
249 struct expression *,
250 int *, LONGEST *, int *,
251 int, LONGEST, LONGEST);
252
253 static void aggregate_assign_positional (struct value *, struct value *,
254 struct expression *,
255 int *, LONGEST *, int *, int,
256 LONGEST, LONGEST);
257
258
259 static void aggregate_assign_others (struct value *, struct value *,
260 struct expression *,
261 int *, LONGEST *, int, LONGEST, LONGEST);
262
263
264 static void add_component_interval (LONGEST, LONGEST, LONGEST *, int *, int);
265
266
267 static struct value *ada_evaluate_subexp (struct type *, struct expression *,
268 int *, enum noside);
269
270 static void ada_forward_operator_length (struct expression *, int, int *,
271 int *);
272
273 static struct type *ada_find_any_type (const char *name);
274
275 static symbol_name_matcher_ftype *ada_get_symbol_name_matcher
276 (const lookup_name_info &lookup_name);
277
278 \f
279
280 /* The result of a symbol lookup to be stored in our symbol cache. */
281
282 struct cache_entry
283 {
284 /* The name used to perform the lookup. */
285 const char *name;
286 /* The namespace used during the lookup. */
287 domain_enum domain;
288 /* The symbol returned by the lookup, or NULL if no matching symbol
289 was found. */
290 struct symbol *sym;
291 /* The block where the symbol was found, or NULL if no matching
292 symbol was found. */
293 const struct block *block;
294 /* A pointer to the next entry with the same hash. */
295 struct cache_entry *next;
296 };
297
298 /* The Ada symbol cache, used to store the result of Ada-mode symbol
299 lookups in the course of executing the user's commands.
300
301 The cache is implemented using a simple, fixed-sized hash.
302 The size is fixed on the grounds that there are not likely to be
303 all that many symbols looked up during any given session, regardless
304 of the size of the symbol table. If we decide to go to a resizable
305 table, let's just use the stuff from libiberty instead. */
306
307 #define HASH_SIZE 1009
308
309 struct ada_symbol_cache
310 {
311 /* An obstack used to store the entries in our cache. */
312 struct obstack cache_space;
313
314 /* The root of the hash table used to implement our symbol cache. */
315 struct cache_entry *root[HASH_SIZE];
316 };
317
318 static void ada_free_symbol_cache (struct ada_symbol_cache *sym_cache);
319
320 /* Maximum-sized dynamic type. */
321 static unsigned int varsize_limit;
322
323 static const char ada_completer_word_break_characters[] =
324 #ifdef VMS
325 " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
326 #else
327 " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
328 #endif
329
330 /* The name of the symbol to use to get the name of the main subprogram. */
331 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
332 = "__gnat_ada_main_program_name";
333
334 /* Limit on the number of warnings to raise per expression evaluation. */
335 static int warning_limit = 2;
336
337 /* Number of warning messages issued; reset to 0 by cleanups after
338 expression evaluation. */
339 static int warnings_issued = 0;
340
341 static const char *known_runtime_file_name_patterns[] = {
342 ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
343 };
344
345 static const char *known_auxiliary_function_name_patterns[] = {
346 ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
347 };
348
349 /* Maintenance-related settings for this module. */
350
351 static struct cmd_list_element *maint_set_ada_cmdlist;
352 static struct cmd_list_element *maint_show_ada_cmdlist;
353
354 /* Implement the "maintenance set ada" (prefix) command. */
355
356 static void
357 maint_set_ada_cmd (const char *args, int from_tty)
358 {
359 help_list (maint_set_ada_cmdlist, "maintenance set ada ", all_commands,
360 gdb_stdout);
361 }
362
363 /* Implement the "maintenance show ada" (prefix) command. */
364
365 static void
366 maint_show_ada_cmd (const char *args, int from_tty)
367 {
368 cmd_show_list (maint_show_ada_cmdlist, from_tty, "");
369 }
370
371 /* The "maintenance ada set/show ignore-descriptive-type" value. */
372
373 static int ada_ignore_descriptive_types_p = 0;
374
375 /* Inferior-specific data. */
376
377 /* Per-inferior data for this module. */
378
379 struct ada_inferior_data
380 {
381 /* The ada__tags__type_specific_data type, which is used when decoding
382 tagged types. With older versions of GNAT, this type was directly
383 accessible through a component ("tsd") in the object tag. But this
384 is no longer the case, so we cache it for each inferior. */
385 struct type *tsd_type;
386
387 /* The exception_support_info data. This data is used to determine
388 how to implement support for Ada exception catchpoints in a given
389 inferior. */
390 const struct exception_support_info *exception_info;
391 };
392
393 /* Our key to this module's inferior data. */
394 static const struct inferior_data *ada_inferior_data;
395
396 /* A cleanup routine for our inferior data. */
397 static void
398 ada_inferior_data_cleanup (struct inferior *inf, void *arg)
399 {
400 struct ada_inferior_data *data;
401
402 data = (struct ada_inferior_data *) inferior_data (inf, ada_inferior_data);
403 if (data != NULL)
404 xfree (data);
405 }
406
407 /* Return our inferior data for the given inferior (INF).
408
409 This function always returns a valid pointer to an allocated
410 ada_inferior_data structure. If INF's inferior data has not
411 been previously set, this functions creates a new one with all
412 fields set to zero, sets INF's inferior to it, and then returns
413 a pointer to that newly allocated ada_inferior_data. */
414
415 static struct ada_inferior_data *
416 get_ada_inferior_data (struct inferior *inf)
417 {
418 struct ada_inferior_data *data;
419
420 data = (struct ada_inferior_data *) inferior_data (inf, ada_inferior_data);
421 if (data == NULL)
422 {
423 data = XCNEW (struct ada_inferior_data);
424 set_inferior_data (inf, ada_inferior_data, data);
425 }
426
427 return data;
428 }
429
430 /* Perform all necessary cleanups regarding our module's inferior data
431 that is required after the inferior INF just exited. */
432
433 static void
434 ada_inferior_exit (struct inferior *inf)
435 {
436 ada_inferior_data_cleanup (inf, NULL);
437 set_inferior_data (inf, ada_inferior_data, NULL);
438 }
439
440
441 /* program-space-specific data. */
442
443 /* This module's per-program-space data. */
444 struct ada_pspace_data
445 {
446 /* The Ada symbol cache. */
447 struct ada_symbol_cache *sym_cache;
448 };
449
450 /* Key to our per-program-space data. */
451 static const struct program_space_data *ada_pspace_data_handle;
452
453 /* Return this module's data for the given program space (PSPACE).
454 If not is found, add a zero'ed one now.
455
456 This function always returns a valid object. */
457
458 static struct ada_pspace_data *
459 get_ada_pspace_data (struct program_space *pspace)
460 {
461 struct ada_pspace_data *data;
462
463 data = ((struct ada_pspace_data *)
464 program_space_data (pspace, ada_pspace_data_handle));
465 if (data == NULL)
466 {
467 data = XCNEW (struct ada_pspace_data);
468 set_program_space_data (pspace, ada_pspace_data_handle, data);
469 }
470
471 return data;
472 }
473
474 /* The cleanup callback for this module's per-program-space data. */
475
476 static void
477 ada_pspace_data_cleanup (struct program_space *pspace, void *data)
478 {
479 struct ada_pspace_data *pspace_data = (struct ada_pspace_data *) data;
480
481 if (pspace_data->sym_cache != NULL)
482 ada_free_symbol_cache (pspace_data->sym_cache);
483 xfree (pspace_data);
484 }
485
486 /* Utilities */
487
488 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
489 all typedef layers have been peeled. Otherwise, return TYPE.
490
491 Normally, we really expect a typedef type to only have 1 typedef layer.
492 In other words, we really expect the target type of a typedef type to be
493 a non-typedef type. This is particularly true for Ada units, because
494 the language does not have a typedef vs not-typedef distinction.
495 In that respect, the Ada compiler has been trying to eliminate as many
496 typedef definitions in the debugging information, since they generally
497 do not bring any extra information (we still use typedef under certain
498 circumstances related mostly to the GNAT encoding).
499
500 Unfortunately, we have seen situations where the debugging information
501 generated by the compiler leads to such multiple typedef layers. For
502 instance, consider the following example with stabs:
503
504 .stabs "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
505 .stabs "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
506
507 This is an error in the debugging information which causes type
508 pck__float_array___XUP to be defined twice, and the second time,
509 it is defined as a typedef of a typedef.
510
511 This is on the fringe of legality as far as debugging information is
512 concerned, and certainly unexpected. But it is easy to handle these
513 situations correctly, so we can afford to be lenient in this case. */
514
515 static struct type *
516 ada_typedef_target_type (struct type *type)
517 {
518 while (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
519 type = TYPE_TARGET_TYPE (type);
520 return type;
521 }
522
523 /* Given DECODED_NAME a string holding a symbol name in its
524 decoded form (ie using the Ada dotted notation), returns
525 its unqualified name. */
526
527 static const char *
528 ada_unqualified_name (const char *decoded_name)
529 {
530 const char *result;
531
532 /* If the decoded name starts with '<', it means that the encoded
533 name does not follow standard naming conventions, and thus that
534 it is not your typical Ada symbol name. Trying to unqualify it
535 is therefore pointless and possibly erroneous. */
536 if (decoded_name[0] == '<')
537 return decoded_name;
538
539 result = strrchr (decoded_name, '.');
540 if (result != NULL)
541 result++; /* Skip the dot... */
542 else
543 result = decoded_name;
544
545 return result;
546 }
547
548 /* Return a string starting with '<', followed by STR, and '>'. */
549
550 static std::string
551 add_angle_brackets (const char *str)
552 {
553 return string_printf ("<%s>", str);
554 }
555
556 static const char *
557 ada_get_gdb_completer_word_break_characters (void)
558 {
559 return ada_completer_word_break_characters;
560 }
561
562 /* Print an array element index using the Ada syntax. */
563
564 static void
565 ada_print_array_index (struct value *index_value, struct ui_file *stream,
566 const struct value_print_options *options)
567 {
568 LA_VALUE_PRINT (index_value, stream, options);
569 fprintf_filtered (stream, " => ");
570 }
571
572 /* la_watch_location_expression for Ada. */
573
574 gdb::unique_xmalloc_ptr<char>
575 ada_watch_location_expression (struct type *type, CORE_ADDR addr)
576 {
577 type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
578 std::string name = type_to_string (type);
579 return gdb::unique_xmalloc_ptr<char>
580 (xstrprintf ("{%s} %s", name.c_str (), core_addr_to_string (addr)));
581 }
582
583 /* Assuming VECT points to an array of *SIZE objects of size
584 ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
585 updating *SIZE as necessary and returning the (new) array. */
586
587 void *
588 grow_vect (void *vect, size_t *size, size_t min_size, int element_size)
589 {
590 if (*size < min_size)
591 {
592 *size *= 2;
593 if (*size < min_size)
594 *size = min_size;
595 vect = xrealloc (vect, *size * element_size);
596 }
597 return vect;
598 }
599
600 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
601 suffix of FIELD_NAME beginning "___". */
602
603 static int
604 field_name_match (const char *field_name, const char *target)
605 {
606 int len = strlen (target);
607
608 return
609 (strncmp (field_name, target, len) == 0
610 && (field_name[len] == '\0'
611 || (startswith (field_name + len, "___")
612 && strcmp (field_name + strlen (field_name) - 6,
613 "___XVN") != 0)));
614 }
615
616
617 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
618 a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
619 and return its index. This function also handles fields whose name
620 have ___ suffixes because the compiler sometimes alters their name
621 by adding such a suffix to represent fields with certain constraints.
622 If the field could not be found, return a negative number if
623 MAYBE_MISSING is set. Otherwise raise an error. */
624
625 int
626 ada_get_field_index (const struct type *type, const char *field_name,
627 int maybe_missing)
628 {
629 int fieldno;
630 struct type *struct_type = check_typedef ((struct type *) type);
631
632 for (fieldno = 0; fieldno < TYPE_NFIELDS (struct_type); fieldno++)
633 if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
634 return fieldno;
635
636 if (!maybe_missing)
637 error (_("Unable to find field %s in struct %s. Aborting"),
638 field_name, TYPE_NAME (struct_type));
639
640 return -1;
641 }
642
643 /* The length of the prefix of NAME prior to any "___" suffix. */
644
645 int
646 ada_name_prefix_len (const char *name)
647 {
648 if (name == NULL)
649 return 0;
650 else
651 {
652 const char *p = strstr (name, "___");
653
654 if (p == NULL)
655 return strlen (name);
656 else
657 return p - name;
658 }
659 }
660
661 /* Return non-zero if SUFFIX is a suffix of STR.
662 Return zero if STR is null. */
663
664 static int
665 is_suffix (const char *str, const char *suffix)
666 {
667 int len1, len2;
668
669 if (str == NULL)
670 return 0;
671 len1 = strlen (str);
672 len2 = strlen (suffix);
673 return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
674 }
675
676 /* The contents of value VAL, treated as a value of type TYPE. The
677 result is an lval in memory if VAL is. */
678
679 static struct value *
680 coerce_unspec_val_to_type (struct value *val, struct type *type)
681 {
682 type = ada_check_typedef (type);
683 if (value_type (val) == type)
684 return val;
685 else
686 {
687 struct value *result;
688
689 /* Make sure that the object size is not unreasonable before
690 trying to allocate some memory for it. */
691 ada_ensure_varsize_limit (type);
692
693 if (value_lazy (val)
694 || TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val)))
695 result = allocate_value_lazy (type);
696 else
697 {
698 result = allocate_value (type);
699 value_contents_copy_raw (result, 0, val, 0, TYPE_LENGTH (type));
700 }
701 set_value_component_location (result, val);
702 set_value_bitsize (result, value_bitsize (val));
703 set_value_bitpos (result, value_bitpos (val));
704 set_value_address (result, value_address (val));
705 return result;
706 }
707 }
708
709 static const gdb_byte *
710 cond_offset_host (const gdb_byte *valaddr, long offset)
711 {
712 if (valaddr == NULL)
713 return NULL;
714 else
715 return valaddr + offset;
716 }
717
718 static CORE_ADDR
719 cond_offset_target (CORE_ADDR address, long offset)
720 {
721 if (address == 0)
722 return 0;
723 else
724 return address + offset;
725 }
726
727 /* Issue a warning (as for the definition of warning in utils.c, but
728 with exactly one argument rather than ...), unless the limit on the
729 number of warnings has passed during the evaluation of the current
730 expression. */
731
732 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
733 provided by "complaint". */
734 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
735
736 static void
737 lim_warning (const char *format, ...)
738 {
739 va_list args;
740
741 va_start (args, format);
742 warnings_issued += 1;
743 if (warnings_issued <= warning_limit)
744 vwarning (format, args);
745
746 va_end (args);
747 }
748
749 /* Issue an error if the size of an object of type T is unreasonable,
750 i.e. if it would be a bad idea to allocate a value of this type in
751 GDB. */
752
753 void
754 ada_ensure_varsize_limit (const struct type *type)
755 {
756 if (TYPE_LENGTH (type) > varsize_limit)
757 error (_("object size is larger than varsize-limit"));
758 }
759
760 /* Maximum value of a SIZE-byte signed integer type. */
761 static LONGEST
762 max_of_size (int size)
763 {
764 LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
765
766 return top_bit | (top_bit - 1);
767 }
768
769 /* Minimum value of a SIZE-byte signed integer type. */
770 static LONGEST
771 min_of_size (int size)
772 {
773 return -max_of_size (size) - 1;
774 }
775
776 /* Maximum value of a SIZE-byte unsigned integer type. */
777 static ULONGEST
778 umax_of_size (int size)
779 {
780 ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
781
782 return top_bit | (top_bit - 1);
783 }
784
785 /* Maximum value of integral type T, as a signed quantity. */
786 static LONGEST
787 max_of_type (struct type *t)
788 {
789 if (TYPE_UNSIGNED (t))
790 return (LONGEST) umax_of_size (TYPE_LENGTH (t));
791 else
792 return max_of_size (TYPE_LENGTH (t));
793 }
794
795 /* Minimum value of integral type T, as a signed quantity. */
796 static LONGEST
797 min_of_type (struct type *t)
798 {
799 if (TYPE_UNSIGNED (t))
800 return 0;
801 else
802 return min_of_size (TYPE_LENGTH (t));
803 }
804
805 /* The largest value in the domain of TYPE, a discrete type, as an integer. */
806 LONGEST
807 ada_discrete_type_high_bound (struct type *type)
808 {
809 type = resolve_dynamic_type (type, NULL, 0);
810 switch (TYPE_CODE (type))
811 {
812 case TYPE_CODE_RANGE:
813 return TYPE_HIGH_BOUND (type);
814 case TYPE_CODE_ENUM:
815 return TYPE_FIELD_ENUMVAL (type, TYPE_NFIELDS (type) - 1);
816 case TYPE_CODE_BOOL:
817 return 1;
818 case TYPE_CODE_CHAR:
819 case TYPE_CODE_INT:
820 return max_of_type (type);
821 default:
822 error (_("Unexpected type in ada_discrete_type_high_bound."));
823 }
824 }
825
826 /* The smallest value in the domain of TYPE, a discrete type, as an integer. */
827 LONGEST
828 ada_discrete_type_low_bound (struct type *type)
829 {
830 type = resolve_dynamic_type (type, NULL, 0);
831 switch (TYPE_CODE (type))
832 {
833 case TYPE_CODE_RANGE:
834 return TYPE_LOW_BOUND (type);
835 case TYPE_CODE_ENUM:
836 return TYPE_FIELD_ENUMVAL (type, 0);
837 case TYPE_CODE_BOOL:
838 return 0;
839 case TYPE_CODE_CHAR:
840 case TYPE_CODE_INT:
841 return min_of_type (type);
842 default:
843 error (_("Unexpected type in ada_discrete_type_low_bound."));
844 }
845 }
846
847 /* The identity on non-range types. For range types, the underlying
848 non-range scalar type. */
849
850 static struct type *
851 get_base_type (struct type *type)
852 {
853 while (type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE)
854 {
855 if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
856 return type;
857 type = TYPE_TARGET_TYPE (type);
858 }
859 return type;
860 }
861
862 /* Return a decoded version of the given VALUE. This means returning
863 a value whose type is obtained by applying all the GNAT-specific
864 encondings, making the resulting type a static but standard description
865 of the initial type. */
866
867 struct value *
868 ada_get_decoded_value (struct value *value)
869 {
870 struct type *type = ada_check_typedef (value_type (value));
871
872 if (ada_is_array_descriptor_type (type)
873 || (ada_is_constrained_packed_array_type (type)
874 && TYPE_CODE (type) != TYPE_CODE_PTR))
875 {
876 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF) /* array access type. */
877 value = ada_coerce_to_simple_array_ptr (value);
878 else
879 value = ada_coerce_to_simple_array (value);
880 }
881 else
882 value = ada_to_fixed_value (value);
883
884 return value;
885 }
886
887 /* Same as ada_get_decoded_value, but with the given TYPE.
888 Because there is no associated actual value for this type,
889 the resulting type might be a best-effort approximation in
890 the case of dynamic types. */
891
892 struct type *
893 ada_get_decoded_type (struct type *type)
894 {
895 type = to_static_fixed_type (type);
896 if (ada_is_constrained_packed_array_type (type))
897 type = ada_coerce_to_simple_array_type (type);
898 return type;
899 }
900
901 \f
902
903 /* Language Selection */
904
905 /* If the main program is in Ada, return language_ada, otherwise return LANG
906 (the main program is in Ada iif the adainit symbol is found). */
907
908 enum language
909 ada_update_initial_language (enum language lang)
910 {
911 if (lookup_minimal_symbol ("adainit", (const char *) NULL,
912 (struct objfile *) NULL).minsym != NULL)
913 return language_ada;
914
915 return lang;
916 }
917
918 /* If the main procedure is written in Ada, then return its name.
919 The result is good until the next call. Return NULL if the main
920 procedure doesn't appear to be in Ada. */
921
922 char *
923 ada_main_name (void)
924 {
925 struct bound_minimal_symbol msym;
926 static gdb::unique_xmalloc_ptr<char> main_program_name;
927
928 /* For Ada, the name of the main procedure is stored in a specific
929 string constant, generated by the binder. Look for that symbol,
930 extract its address, and then read that string. If we didn't find
931 that string, then most probably the main procedure is not written
932 in Ada. */
933 msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
934
935 if (msym.minsym != NULL)
936 {
937 CORE_ADDR main_program_name_addr;
938 int err_code;
939
940 main_program_name_addr = BMSYMBOL_VALUE_ADDRESS (msym);
941 if (main_program_name_addr == 0)
942 error (_("Invalid address for Ada main program name."));
943
944 target_read_string (main_program_name_addr, &main_program_name,
945 1024, &err_code);
946
947 if (err_code != 0)
948 return NULL;
949 return main_program_name.get ();
950 }
951
952 /* The main procedure doesn't seem to be in Ada. */
953 return NULL;
954 }
955 \f
956 /* Symbols */
957
958 /* Table of Ada operators and their GNAT-encoded names. Last entry is pair
959 of NULLs. */
960
961 const struct ada_opname_map ada_opname_table[] = {
962 {"Oadd", "\"+\"", BINOP_ADD},
963 {"Osubtract", "\"-\"", BINOP_SUB},
964 {"Omultiply", "\"*\"", BINOP_MUL},
965 {"Odivide", "\"/\"", BINOP_DIV},
966 {"Omod", "\"mod\"", BINOP_MOD},
967 {"Orem", "\"rem\"", BINOP_REM},
968 {"Oexpon", "\"**\"", BINOP_EXP},
969 {"Olt", "\"<\"", BINOP_LESS},
970 {"Ole", "\"<=\"", BINOP_LEQ},
971 {"Ogt", "\">\"", BINOP_GTR},
972 {"Oge", "\">=\"", BINOP_GEQ},
973 {"Oeq", "\"=\"", BINOP_EQUAL},
974 {"One", "\"/=\"", BINOP_NOTEQUAL},
975 {"Oand", "\"and\"", BINOP_BITWISE_AND},
976 {"Oor", "\"or\"", BINOP_BITWISE_IOR},
977 {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
978 {"Oconcat", "\"&\"", BINOP_CONCAT},
979 {"Oabs", "\"abs\"", UNOP_ABS},
980 {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
981 {"Oadd", "\"+\"", UNOP_PLUS},
982 {"Osubtract", "\"-\"", UNOP_NEG},
983 {NULL, NULL}
984 };
985
986 /* The "encoded" form of DECODED, according to GNAT conventions. The
987 result is valid until the next call to ada_encode. If
988 THROW_ERRORS, throw an error if invalid operator name is found.
989 Otherwise, return NULL in that case. */
990
991 static char *
992 ada_encode_1 (const char *decoded, bool throw_errors)
993 {
994 static char *encoding_buffer = NULL;
995 static size_t encoding_buffer_size = 0;
996 const char *p;
997 int k;
998
999 if (decoded == NULL)
1000 return NULL;
1001
1002 GROW_VECT (encoding_buffer, encoding_buffer_size,
1003 2 * strlen (decoded) + 10);
1004
1005 k = 0;
1006 for (p = decoded; *p != '\0'; p += 1)
1007 {
1008 if (*p == '.')
1009 {
1010 encoding_buffer[k] = encoding_buffer[k + 1] = '_';
1011 k += 2;
1012 }
1013 else if (*p == '"')
1014 {
1015 const struct ada_opname_map *mapping;
1016
1017 for (mapping = ada_opname_table;
1018 mapping->encoded != NULL
1019 && !startswith (p, mapping->decoded); mapping += 1)
1020 ;
1021 if (mapping->encoded == NULL)
1022 {
1023 if (throw_errors)
1024 error (_("invalid Ada operator name: %s"), p);
1025 else
1026 return NULL;
1027 }
1028 strcpy (encoding_buffer + k, mapping->encoded);
1029 k += strlen (mapping->encoded);
1030 break;
1031 }
1032 else
1033 {
1034 encoding_buffer[k] = *p;
1035 k += 1;
1036 }
1037 }
1038
1039 encoding_buffer[k] = '\0';
1040 return encoding_buffer;
1041 }
1042
1043 /* The "encoded" form of DECODED, according to GNAT conventions.
1044 The result is valid until the next call to ada_encode. */
1045
1046 char *
1047 ada_encode (const char *decoded)
1048 {
1049 return ada_encode_1 (decoded, true);
1050 }
1051
1052 /* Return NAME folded to lower case, or, if surrounded by single
1053 quotes, unfolded, but with the quotes stripped away. Result good
1054 to next call. */
1055
1056 char *
1057 ada_fold_name (const char *name)
1058 {
1059 static char *fold_buffer = NULL;
1060 static size_t fold_buffer_size = 0;
1061
1062 int len = strlen (name);
1063 GROW_VECT (fold_buffer, fold_buffer_size, len + 1);
1064
1065 if (name[0] == '\'')
1066 {
1067 strncpy (fold_buffer, name + 1, len - 2);
1068 fold_buffer[len - 2] = '\000';
1069 }
1070 else
1071 {
1072 int i;
1073
1074 for (i = 0; i <= len; i += 1)
1075 fold_buffer[i] = tolower (name[i]);
1076 }
1077
1078 return fold_buffer;
1079 }
1080
1081 /* Return nonzero if C is either a digit or a lowercase alphabet character. */
1082
1083 static int
1084 is_lower_alphanum (const char c)
1085 {
1086 return (isdigit (c) || (isalpha (c) && islower (c)));
1087 }
1088
1089 /* ENCODED is the linkage name of a symbol and LEN contains its length.
1090 This function saves in LEN the length of that same symbol name but
1091 without either of these suffixes:
1092 . .{DIGIT}+
1093 . ${DIGIT}+
1094 . ___{DIGIT}+
1095 . __{DIGIT}+.
1096
1097 These are suffixes introduced by the compiler for entities such as
1098 nested subprogram for instance, in order to avoid name clashes.
1099 They do not serve any purpose for the debugger. */
1100
1101 static void
1102 ada_remove_trailing_digits (const char *encoded, int *len)
1103 {
1104 if (*len > 1 && isdigit (encoded[*len - 1]))
1105 {
1106 int i = *len - 2;
1107
1108 while (i > 0 && isdigit (encoded[i]))
1109 i--;
1110 if (i >= 0 && encoded[i] == '.')
1111 *len = i;
1112 else if (i >= 0 && encoded[i] == '$')
1113 *len = i;
1114 else if (i >= 2 && startswith (encoded + i - 2, "___"))
1115 *len = i - 2;
1116 else if (i >= 1 && startswith (encoded + i - 1, "__"))
1117 *len = i - 1;
1118 }
1119 }
1120
1121 /* Remove the suffix introduced by the compiler for protected object
1122 subprograms. */
1123
1124 static void
1125 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
1126 {
1127 /* Remove trailing N. */
1128
1129 /* Protected entry subprograms are broken into two
1130 separate subprograms: The first one is unprotected, and has
1131 a 'N' suffix; the second is the protected version, and has
1132 the 'P' suffix. The second calls the first one after handling
1133 the protection. Since the P subprograms are internally generated,
1134 we leave these names undecoded, giving the user a clue that this
1135 entity is internal. */
1136
1137 if (*len > 1
1138 && encoded[*len - 1] == 'N'
1139 && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
1140 *len = *len - 1;
1141 }
1142
1143 /* Remove trailing X[bn]* suffixes (indicating names in package bodies). */
1144
1145 static void
1146 ada_remove_Xbn_suffix (const char *encoded, int *len)
1147 {
1148 int i = *len - 1;
1149
1150 while (i > 0 && (encoded[i] == 'b' || encoded[i] == 'n'))
1151 i--;
1152
1153 if (encoded[i] != 'X')
1154 return;
1155
1156 if (i == 0)
1157 return;
1158
1159 if (isalnum (encoded[i-1]))
1160 *len = i;
1161 }
1162
1163 /* If ENCODED follows the GNAT entity encoding conventions, then return
1164 the decoded form of ENCODED. Otherwise, return "<%s>" where "%s" is
1165 replaced by ENCODED.
1166
1167 The resulting string is valid until the next call of ada_decode.
1168 If the string is unchanged by decoding, the original string pointer
1169 is returned. */
1170
1171 const char *
1172 ada_decode (const char *encoded)
1173 {
1174 int i, j;
1175 int len0;
1176 const char *p;
1177 char *decoded;
1178 int at_start_name;
1179 static char *decoding_buffer = NULL;
1180 static size_t decoding_buffer_size = 0;
1181
1182 /* With function descriptors on PPC64, the value of a symbol named
1183 ".FN", if it exists, is the entry point of the function "FN". */
1184 if (encoded[0] == '.')
1185 encoded += 1;
1186
1187 /* The name of the Ada main procedure starts with "_ada_".
1188 This prefix is not part of the decoded name, so skip this part
1189 if we see this prefix. */
1190 if (startswith (encoded, "_ada_"))
1191 encoded += 5;
1192
1193 /* If the name starts with '_', then it is not a properly encoded
1194 name, so do not attempt to decode it. Similarly, if the name
1195 starts with '<', the name should not be decoded. */
1196 if (encoded[0] == '_' || encoded[0] == '<')
1197 goto Suppress;
1198
1199 len0 = strlen (encoded);
1200
1201 ada_remove_trailing_digits (encoded, &len0);
1202 ada_remove_po_subprogram_suffix (encoded, &len0);
1203
1204 /* Remove the ___X.* suffix if present. Do not forget to verify that
1205 the suffix is located before the current "end" of ENCODED. We want
1206 to avoid re-matching parts of ENCODED that have previously been
1207 marked as discarded (by decrementing LEN0). */
1208 p = strstr (encoded, "___");
1209 if (p != NULL && p - encoded < len0 - 3)
1210 {
1211 if (p[3] == 'X')
1212 len0 = p - encoded;
1213 else
1214 goto Suppress;
1215 }
1216
1217 /* Remove any trailing TKB suffix. It tells us that this symbol
1218 is for the body of a task, but that information does not actually
1219 appear in the decoded name. */
1220
1221 if (len0 > 3 && startswith (encoded + len0 - 3, "TKB"))
1222 len0 -= 3;
1223
1224 /* Remove any trailing TB suffix. The TB suffix is slightly different
1225 from the TKB suffix because it is used for non-anonymous task
1226 bodies. */
1227
1228 if (len0 > 2 && startswith (encoded + len0 - 2, "TB"))
1229 len0 -= 2;
1230
1231 /* Remove trailing "B" suffixes. */
1232 /* FIXME: brobecker/2006-04-19: Not sure what this are used for... */
1233
1234 if (len0 > 1 && startswith (encoded + len0 - 1, "B"))
1235 len0 -= 1;
1236
1237 /* Make decoded big enough for possible expansion by operator name. */
1238
1239 GROW_VECT (decoding_buffer, decoding_buffer_size, 2 * len0 + 1);
1240 decoded = decoding_buffer;
1241
1242 /* Remove trailing __{digit}+ or trailing ${digit}+. */
1243
1244 if (len0 > 1 && isdigit (encoded[len0 - 1]))
1245 {
1246 i = len0 - 2;
1247 while ((i >= 0 && isdigit (encoded[i]))
1248 || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
1249 i -= 1;
1250 if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
1251 len0 = i - 1;
1252 else if (encoded[i] == '$')
1253 len0 = i;
1254 }
1255
1256 /* The first few characters that are not alphabetic are not part
1257 of any encoding we use, so we can copy them over verbatim. */
1258
1259 for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
1260 decoded[j] = encoded[i];
1261
1262 at_start_name = 1;
1263 while (i < len0)
1264 {
1265 /* Is this a symbol function? */
1266 if (at_start_name && encoded[i] == 'O')
1267 {
1268 int k;
1269
1270 for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
1271 {
1272 int op_len = strlen (ada_opname_table[k].encoded);
1273 if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
1274 op_len - 1) == 0)
1275 && !isalnum (encoded[i + op_len]))
1276 {
1277 strcpy (decoded + j, ada_opname_table[k].decoded);
1278 at_start_name = 0;
1279 i += op_len;
1280 j += strlen (ada_opname_table[k].decoded);
1281 break;
1282 }
1283 }
1284 if (ada_opname_table[k].encoded != NULL)
1285 continue;
1286 }
1287 at_start_name = 0;
1288
1289 /* Replace "TK__" with "__", which will eventually be translated
1290 into "." (just below). */
1291
1292 if (i < len0 - 4 && startswith (encoded + i, "TK__"))
1293 i += 2;
1294
1295 /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
1296 be translated into "." (just below). These are internal names
1297 generated for anonymous blocks inside which our symbol is nested. */
1298
1299 if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
1300 && encoded [i+2] == 'B' && encoded [i+3] == '_'
1301 && isdigit (encoded [i+4]))
1302 {
1303 int k = i + 5;
1304
1305 while (k < len0 && isdigit (encoded[k]))
1306 k++; /* Skip any extra digit. */
1307
1308 /* Double-check that the "__B_{DIGITS}+" sequence we found
1309 is indeed followed by "__". */
1310 if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1311 i = k;
1312 }
1313
1314 /* Remove _E{DIGITS}+[sb] */
1315
1316 /* Just as for protected object subprograms, there are 2 categories
1317 of subprograms created by the compiler for each entry. The first
1318 one implements the actual entry code, and has a suffix following
1319 the convention above; the second one implements the barrier and
1320 uses the same convention as above, except that the 'E' is replaced
1321 by a 'B'.
1322
1323 Just as above, we do not decode the name of barrier functions
1324 to give the user a clue that the code he is debugging has been
1325 internally generated. */
1326
1327 if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1328 && isdigit (encoded[i+2]))
1329 {
1330 int k = i + 3;
1331
1332 while (k < len0 && isdigit (encoded[k]))
1333 k++;
1334
1335 if (k < len0
1336 && (encoded[k] == 'b' || encoded[k] == 's'))
1337 {
1338 k++;
1339 /* Just as an extra precaution, make sure that if this
1340 suffix is followed by anything else, it is a '_'.
1341 Otherwise, we matched this sequence by accident. */
1342 if (k == len0
1343 || (k < len0 && encoded[k] == '_'))
1344 i = k;
1345 }
1346 }
1347
1348 /* Remove trailing "N" in [a-z0-9]+N__. The N is added by
1349 the GNAT front-end in protected object subprograms. */
1350
1351 if (i < len0 + 3
1352 && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1353 {
1354 /* Backtrack a bit up until we reach either the begining of
1355 the encoded name, or "__". Make sure that we only find
1356 digits or lowercase characters. */
1357 const char *ptr = encoded + i - 1;
1358
1359 while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1360 ptr--;
1361 if (ptr < encoded
1362 || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1363 i++;
1364 }
1365
1366 if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1367 {
1368 /* This is a X[bn]* sequence not separated from the previous
1369 part of the name with a non-alpha-numeric character (in other
1370 words, immediately following an alpha-numeric character), then
1371 verify that it is placed at the end of the encoded name. If
1372 not, then the encoding is not valid and we should abort the
1373 decoding. Otherwise, just skip it, it is used in body-nested
1374 package names. */
1375 do
1376 i += 1;
1377 while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1378 if (i < len0)
1379 goto Suppress;
1380 }
1381 else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1382 {
1383 /* Replace '__' by '.'. */
1384 decoded[j] = '.';
1385 at_start_name = 1;
1386 i += 2;
1387 j += 1;
1388 }
1389 else
1390 {
1391 /* It's a character part of the decoded name, so just copy it
1392 over. */
1393 decoded[j] = encoded[i];
1394 i += 1;
1395 j += 1;
1396 }
1397 }
1398 decoded[j] = '\000';
1399
1400 /* Decoded names should never contain any uppercase character.
1401 Double-check this, and abort the decoding if we find one. */
1402
1403 for (i = 0; decoded[i] != '\0'; i += 1)
1404 if (isupper (decoded[i]) || decoded[i] == ' ')
1405 goto Suppress;
1406
1407 if (strcmp (decoded, encoded) == 0)
1408 return encoded;
1409 else
1410 return decoded;
1411
1412 Suppress:
1413 GROW_VECT (decoding_buffer, decoding_buffer_size, strlen (encoded) + 3);
1414 decoded = decoding_buffer;
1415 if (encoded[0] == '<')
1416 strcpy (decoded, encoded);
1417 else
1418 xsnprintf (decoded, decoding_buffer_size, "<%s>", encoded);
1419 return decoded;
1420
1421 }
1422
1423 /* Table for keeping permanent unique copies of decoded names. Once
1424 allocated, names in this table are never released. While this is a
1425 storage leak, it should not be significant unless there are massive
1426 changes in the set of decoded names in successive versions of a
1427 symbol table loaded during a single session. */
1428 static struct htab *decoded_names_store;
1429
1430 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1431 in the language-specific part of GSYMBOL, if it has not been
1432 previously computed. Tries to save the decoded name in the same
1433 obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1434 in any case, the decoded symbol has a lifetime at least that of
1435 GSYMBOL).
1436 The GSYMBOL parameter is "mutable" in the C++ sense: logically
1437 const, but nevertheless modified to a semantically equivalent form
1438 when a decoded name is cached in it. */
1439
1440 const char *
1441 ada_decode_symbol (const struct general_symbol_info *arg)
1442 {
1443 struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
1444 const char **resultp =
1445 &gsymbol->language_specific.demangled_name;
1446
1447 if (!gsymbol->ada_mangled)
1448 {
1449 const char *decoded = ada_decode (gsymbol->name);
1450 struct obstack *obstack = gsymbol->language_specific.obstack;
1451
1452 gsymbol->ada_mangled = 1;
1453
1454 if (obstack != NULL)
1455 *resultp
1456 = (const char *) obstack_copy0 (obstack, decoded, strlen (decoded));
1457 else
1458 {
1459 /* Sometimes, we can't find a corresponding objfile, in
1460 which case, we put the result on the heap. Since we only
1461 decode when needed, we hope this usually does not cause a
1462 significant memory leak (FIXME). */
1463
1464 char **slot = (char **) htab_find_slot (decoded_names_store,
1465 decoded, INSERT);
1466
1467 if (*slot == NULL)
1468 *slot = xstrdup (decoded);
1469 *resultp = *slot;
1470 }
1471 }
1472
1473 return *resultp;
1474 }
1475
1476 static char *
1477 ada_la_decode (const char *encoded, int options)
1478 {
1479 return xstrdup (ada_decode (encoded));
1480 }
1481
1482 /* Implement la_sniff_from_mangled_name for Ada. */
1483
1484 static int
1485 ada_sniff_from_mangled_name (const char *mangled, char **out)
1486 {
1487 const char *demangled = ada_decode (mangled);
1488
1489 *out = NULL;
1490
1491 if (demangled != mangled && demangled != NULL && demangled[0] != '<')
1492 {
1493 /* Set the gsymbol language to Ada, but still return 0.
1494 Two reasons for that:
1495
1496 1. For Ada, we prefer computing the symbol's decoded name
1497 on the fly rather than pre-compute it, in order to save
1498 memory (Ada projects are typically very large).
1499
1500 2. There are some areas in the definition of the GNAT
1501 encoding where, with a bit of bad luck, we might be able
1502 to decode a non-Ada symbol, generating an incorrect
1503 demangled name (Eg: names ending with "TB" for instance
1504 are identified as task bodies and so stripped from
1505 the decoded name returned).
1506
1507 Returning 1, here, but not setting *DEMANGLED, helps us get a
1508 little bit of the best of both worlds. Because we're last,
1509 we should not affect any of the other languages that were
1510 able to demangle the symbol before us; we get to correctly
1511 tag Ada symbols as such; and even if we incorrectly tagged a
1512 non-Ada symbol, which should be rare, any routing through the
1513 Ada language should be transparent (Ada tries to behave much
1514 like C/C++ with non-Ada symbols). */
1515 return 1;
1516 }
1517
1518 return 0;
1519 }
1520
1521 \f
1522
1523 /* Arrays */
1524
1525 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
1526 generated by the GNAT compiler to describe the index type used
1527 for each dimension of an array, check whether it follows the latest
1528 known encoding. If not, fix it up to conform to the latest encoding.
1529 Otherwise, do nothing. This function also does nothing if
1530 INDEX_DESC_TYPE is NULL.
1531
1532 The GNAT encoding used to describle the array index type evolved a bit.
1533 Initially, the information would be provided through the name of each
1534 field of the structure type only, while the type of these fields was
1535 described as unspecified and irrelevant. The debugger was then expected
1536 to perform a global type lookup using the name of that field in order
1537 to get access to the full index type description. Because these global
1538 lookups can be very expensive, the encoding was later enhanced to make
1539 the global lookup unnecessary by defining the field type as being
1540 the full index type description.
1541
1542 The purpose of this routine is to allow us to support older versions
1543 of the compiler by detecting the use of the older encoding, and by
1544 fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
1545 we essentially replace each field's meaningless type by the associated
1546 index subtype). */
1547
1548 void
1549 ada_fixup_array_indexes_type (struct type *index_desc_type)
1550 {
1551 int i;
1552
1553 if (index_desc_type == NULL)
1554 return;
1555 gdb_assert (TYPE_NFIELDS (index_desc_type) > 0);
1556
1557 /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
1558 to check one field only, no need to check them all). If not, return
1559 now.
1560
1561 If our INDEX_DESC_TYPE was generated using the older encoding,
1562 the field type should be a meaningless integer type whose name
1563 is not equal to the field name. */
1564 if (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)) != NULL
1565 && strcmp (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)),
1566 TYPE_FIELD_NAME (index_desc_type, 0)) == 0)
1567 return;
1568
1569 /* Fixup each field of INDEX_DESC_TYPE. */
1570 for (i = 0; i < TYPE_NFIELDS (index_desc_type); i++)
1571 {
1572 const char *name = TYPE_FIELD_NAME (index_desc_type, i);
1573 struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
1574
1575 if (raw_type)
1576 TYPE_FIELD_TYPE (index_desc_type, i) = raw_type;
1577 }
1578 }
1579
1580 /* Names of MAX_ADA_DIMENS bounds in P_BOUNDS fields of array descriptors. */
1581
1582 static const char *bound_name[] = {
1583 "LB0", "UB0", "LB1", "UB1", "LB2", "UB2", "LB3", "UB3",
1584 "LB4", "UB4", "LB5", "UB5", "LB6", "UB6", "LB7", "UB7"
1585 };
1586
1587 /* Maximum number of array dimensions we are prepared to handle. */
1588
1589 #define MAX_ADA_DIMENS (sizeof(bound_name) / (2*sizeof(char *)))
1590
1591
1592 /* The desc_* routines return primitive portions of array descriptors
1593 (fat pointers). */
1594
1595 /* The descriptor or array type, if any, indicated by TYPE; removes
1596 level of indirection, if needed. */
1597
1598 static struct type *
1599 desc_base_type (struct type *type)
1600 {
1601 if (type == NULL)
1602 return NULL;
1603 type = ada_check_typedef (type);
1604 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
1605 type = ada_typedef_target_type (type);
1606
1607 if (type != NULL
1608 && (TYPE_CODE (type) == TYPE_CODE_PTR
1609 || TYPE_CODE (type) == TYPE_CODE_REF))
1610 return ada_check_typedef (TYPE_TARGET_TYPE (type));
1611 else
1612 return type;
1613 }
1614
1615 /* True iff TYPE indicates a "thin" array pointer type. */
1616
1617 static int
1618 is_thin_pntr (struct type *type)
1619 {
1620 return
1621 is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1622 || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1623 }
1624
1625 /* The descriptor type for thin pointer type TYPE. */
1626
1627 static struct type *
1628 thin_descriptor_type (struct type *type)
1629 {
1630 struct type *base_type = desc_base_type (type);
1631
1632 if (base_type == NULL)
1633 return NULL;
1634 if (is_suffix (ada_type_name (base_type), "___XVE"))
1635 return base_type;
1636 else
1637 {
1638 struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1639
1640 if (alt_type == NULL)
1641 return base_type;
1642 else
1643 return alt_type;
1644 }
1645 }
1646
1647 /* A pointer to the array data for thin-pointer value VAL. */
1648
1649 static struct value *
1650 thin_data_pntr (struct value *val)
1651 {
1652 struct type *type = ada_check_typedef (value_type (val));
1653 struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
1654
1655 data_type = lookup_pointer_type (data_type);
1656
1657 if (TYPE_CODE (type) == TYPE_CODE_PTR)
1658 return value_cast (data_type, value_copy (val));
1659 else
1660 return value_from_longest (data_type, value_address (val));
1661 }
1662
1663 /* True iff TYPE indicates a "thick" array pointer type. */
1664
1665 static int
1666 is_thick_pntr (struct type *type)
1667 {
1668 type = desc_base_type (type);
1669 return (type != NULL && TYPE_CODE (type) == TYPE_CODE_STRUCT
1670 && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1671 }
1672
1673 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1674 pointer to one, the type of its bounds data; otherwise, NULL. */
1675
1676 static struct type *
1677 desc_bounds_type (struct type *type)
1678 {
1679 struct type *r;
1680
1681 type = desc_base_type (type);
1682
1683 if (type == NULL)
1684 return NULL;
1685 else if (is_thin_pntr (type))
1686 {
1687 type = thin_descriptor_type (type);
1688 if (type == NULL)
1689 return NULL;
1690 r = lookup_struct_elt_type (type, "BOUNDS", 1);
1691 if (r != NULL)
1692 return ada_check_typedef (r);
1693 }
1694 else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1695 {
1696 r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1697 if (r != NULL)
1698 return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1699 }
1700 return NULL;
1701 }
1702
1703 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1704 one, a pointer to its bounds data. Otherwise NULL. */
1705
1706 static struct value *
1707 desc_bounds (struct value *arr)
1708 {
1709 struct type *type = ada_check_typedef (value_type (arr));
1710
1711 if (is_thin_pntr (type))
1712 {
1713 struct type *bounds_type =
1714 desc_bounds_type (thin_descriptor_type (type));
1715 LONGEST addr;
1716
1717 if (bounds_type == NULL)
1718 error (_("Bad GNAT array descriptor"));
1719
1720 /* NOTE: The following calculation is not really kosher, but
1721 since desc_type is an XVE-encoded type (and shouldn't be),
1722 the correct calculation is a real pain. FIXME (and fix GCC). */
1723 if (TYPE_CODE (type) == TYPE_CODE_PTR)
1724 addr = value_as_long (arr);
1725 else
1726 addr = value_address (arr);
1727
1728 return
1729 value_from_longest (lookup_pointer_type (bounds_type),
1730 addr - TYPE_LENGTH (bounds_type));
1731 }
1732
1733 else if (is_thick_pntr (type))
1734 {
1735 struct value *p_bounds = value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
1736 _("Bad GNAT array descriptor"));
1737 struct type *p_bounds_type = value_type (p_bounds);
1738
1739 if (p_bounds_type
1740 && TYPE_CODE (p_bounds_type) == TYPE_CODE_PTR)
1741 {
1742 struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
1743
1744 if (TYPE_STUB (target_type))
1745 p_bounds = value_cast (lookup_pointer_type
1746 (ada_check_typedef (target_type)),
1747 p_bounds);
1748 }
1749 else
1750 error (_("Bad GNAT array descriptor"));
1751
1752 return p_bounds;
1753 }
1754 else
1755 return NULL;
1756 }
1757
1758 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1759 position of the field containing the address of the bounds data. */
1760
1761 static int
1762 fat_pntr_bounds_bitpos (struct type *type)
1763 {
1764 return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
1765 }
1766
1767 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1768 size of the field containing the address of the bounds data. */
1769
1770 static int
1771 fat_pntr_bounds_bitsize (struct type *type)
1772 {
1773 type = desc_base_type (type);
1774
1775 if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1776 return TYPE_FIELD_BITSIZE (type, 1);
1777 else
1778 return 8 * TYPE_LENGTH (ada_check_typedef (TYPE_FIELD_TYPE (type, 1)));
1779 }
1780
1781 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1782 pointer to one, the type of its array data (a array-with-no-bounds type);
1783 otherwise, NULL. Use ada_type_of_array to get an array type with bounds
1784 data. */
1785
1786 static struct type *
1787 desc_data_target_type (struct type *type)
1788 {
1789 type = desc_base_type (type);
1790
1791 /* NOTE: The following is bogus; see comment in desc_bounds. */
1792 if (is_thin_pntr (type))
1793 return desc_base_type (TYPE_FIELD_TYPE (thin_descriptor_type (type), 1));
1794 else if (is_thick_pntr (type))
1795 {
1796 struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
1797
1798 if (data_type
1799 && TYPE_CODE (ada_check_typedef (data_type)) == TYPE_CODE_PTR)
1800 return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
1801 }
1802
1803 return NULL;
1804 }
1805
1806 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1807 its array data. */
1808
1809 static struct value *
1810 desc_data (struct value *arr)
1811 {
1812 struct type *type = value_type (arr);
1813
1814 if (is_thin_pntr (type))
1815 return thin_data_pntr (arr);
1816 else if (is_thick_pntr (type))
1817 return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
1818 _("Bad GNAT array descriptor"));
1819 else
1820 return NULL;
1821 }
1822
1823
1824 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1825 position of the field containing the address of the data. */
1826
1827 static int
1828 fat_pntr_data_bitpos (struct type *type)
1829 {
1830 return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
1831 }
1832
1833 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1834 size of the field containing the address of the data. */
1835
1836 static int
1837 fat_pntr_data_bitsize (struct type *type)
1838 {
1839 type = desc_base_type (type);
1840
1841 if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1842 return TYPE_FIELD_BITSIZE (type, 0);
1843 else
1844 return TARGET_CHAR_BIT * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0));
1845 }
1846
1847 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1848 the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1849 bound, if WHICH is 1. The first bound is I=1. */
1850
1851 static struct value *
1852 desc_one_bound (struct value *bounds, int i, int which)
1853 {
1854 return value_struct_elt (&bounds, NULL, bound_name[2 * i + which - 2], NULL,
1855 _("Bad GNAT array descriptor bounds"));
1856 }
1857
1858 /* If BOUNDS is an array-bounds structure type, return the bit position
1859 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1860 bound, if WHICH is 1. The first bound is I=1. */
1861
1862 static int
1863 desc_bound_bitpos (struct type *type, int i, int which)
1864 {
1865 return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
1866 }
1867
1868 /* If BOUNDS is an array-bounds structure type, return the bit field size
1869 of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1870 bound, if WHICH is 1. The first bound is I=1. */
1871
1872 static int
1873 desc_bound_bitsize (struct type *type, int i, int which)
1874 {
1875 type = desc_base_type (type);
1876
1877 if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1878 return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1879 else
1880 return 8 * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 2 * i + which - 2));
1881 }
1882
1883 /* If TYPE is the type of an array-bounds structure, the type of its
1884 Ith bound (numbering from 1). Otherwise, NULL. */
1885
1886 static struct type *
1887 desc_index_type (struct type *type, int i)
1888 {
1889 type = desc_base_type (type);
1890
1891 if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1892 return lookup_struct_elt_type (type, bound_name[2 * i - 2], 1);
1893 else
1894 return NULL;
1895 }
1896
1897 /* The number of index positions in the array-bounds type TYPE.
1898 Return 0 if TYPE is NULL. */
1899
1900 static int
1901 desc_arity (struct type *type)
1902 {
1903 type = desc_base_type (type);
1904
1905 if (type != NULL)
1906 return TYPE_NFIELDS (type) / 2;
1907 return 0;
1908 }
1909
1910 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or
1911 an array descriptor type (representing an unconstrained array
1912 type). */
1913
1914 static int
1915 ada_is_direct_array_type (struct type *type)
1916 {
1917 if (type == NULL)
1918 return 0;
1919 type = ada_check_typedef (type);
1920 return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1921 || ada_is_array_descriptor_type (type));
1922 }
1923
1924 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
1925 * to one. */
1926
1927 static int
1928 ada_is_array_type (struct type *type)
1929 {
1930 while (type != NULL
1931 && (TYPE_CODE (type) == TYPE_CODE_PTR
1932 || TYPE_CODE (type) == TYPE_CODE_REF))
1933 type = TYPE_TARGET_TYPE (type);
1934 return ada_is_direct_array_type (type);
1935 }
1936
1937 /* Non-zero iff TYPE is a simple array type or pointer to one. */
1938
1939 int
1940 ada_is_simple_array_type (struct type *type)
1941 {
1942 if (type == NULL)
1943 return 0;
1944 type = ada_check_typedef (type);
1945 return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1946 || (TYPE_CODE (type) == TYPE_CODE_PTR
1947 && TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type)))
1948 == TYPE_CODE_ARRAY));
1949 }
1950
1951 /* Non-zero iff TYPE belongs to a GNAT array descriptor. */
1952
1953 int
1954 ada_is_array_descriptor_type (struct type *type)
1955 {
1956 struct type *data_type = desc_data_target_type (type);
1957
1958 if (type == NULL)
1959 return 0;
1960 type = ada_check_typedef (type);
1961 return (data_type != NULL
1962 && TYPE_CODE (data_type) == TYPE_CODE_ARRAY
1963 && desc_arity (desc_bounds_type (type)) > 0);
1964 }
1965
1966 /* Non-zero iff type is a partially mal-formed GNAT array
1967 descriptor. FIXME: This is to compensate for some problems with
1968 debugging output from GNAT. Re-examine periodically to see if it
1969 is still needed. */
1970
1971 int
1972 ada_is_bogus_array_descriptor (struct type *type)
1973 {
1974 return
1975 type != NULL
1976 && TYPE_CODE (type) == TYPE_CODE_STRUCT
1977 && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1978 || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1979 && !ada_is_array_descriptor_type (type);
1980 }
1981
1982
1983 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1984 (fat pointer) returns the type of the array data described---specifically,
1985 a pointer-to-array type. If BOUNDS is non-zero, the bounds data are filled
1986 in from the descriptor; otherwise, they are left unspecified. If
1987 the ARR denotes a null array descriptor and BOUNDS is non-zero,
1988 returns NULL. The result is simply the type of ARR if ARR is not
1989 a descriptor. */
1990 struct type *
1991 ada_type_of_array (struct value *arr, int bounds)
1992 {
1993 if (ada_is_constrained_packed_array_type (value_type (arr)))
1994 return decode_constrained_packed_array_type (value_type (arr));
1995
1996 if (!ada_is_array_descriptor_type (value_type (arr)))
1997 return value_type (arr);
1998
1999 if (!bounds)
2000 {
2001 struct type *array_type =
2002 ada_check_typedef (desc_data_target_type (value_type (arr)));
2003
2004 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
2005 TYPE_FIELD_BITSIZE (array_type, 0) =
2006 decode_packed_array_bitsize (value_type (arr));
2007
2008 return array_type;
2009 }
2010 else
2011 {
2012 struct type *elt_type;
2013 int arity;
2014 struct value *descriptor;
2015
2016 elt_type = ada_array_element_type (value_type (arr), -1);
2017 arity = ada_array_arity (value_type (arr));
2018
2019 if (elt_type == NULL || arity == 0)
2020 return ada_check_typedef (value_type (arr));
2021
2022 descriptor = desc_bounds (arr);
2023 if (value_as_long (descriptor) == 0)
2024 return NULL;
2025 while (arity > 0)
2026 {
2027 struct type *range_type = alloc_type_copy (value_type (arr));
2028 struct type *array_type = alloc_type_copy (value_type (arr));
2029 struct value *low = desc_one_bound (descriptor, arity, 0);
2030 struct value *high = desc_one_bound (descriptor, arity, 1);
2031
2032 arity -= 1;
2033 create_static_range_type (range_type, value_type (low),
2034 longest_to_int (value_as_long (low)),
2035 longest_to_int (value_as_long (high)));
2036 elt_type = create_array_type (array_type, elt_type, range_type);
2037
2038 if (ada_is_unconstrained_packed_array_type (value_type (arr)))
2039 {
2040 /* We need to store the element packed bitsize, as well as
2041 recompute the array size, because it was previously
2042 computed based on the unpacked element size. */
2043 LONGEST lo = value_as_long (low);
2044 LONGEST hi = value_as_long (high);
2045
2046 TYPE_FIELD_BITSIZE (elt_type, 0) =
2047 decode_packed_array_bitsize (value_type (arr));
2048 /* If the array has no element, then the size is already
2049 zero, and does not need to be recomputed. */
2050 if (lo < hi)
2051 {
2052 int array_bitsize =
2053 (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
2054
2055 TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
2056 }
2057 }
2058 }
2059
2060 return lookup_pointer_type (elt_type);
2061 }
2062 }
2063
2064 /* If ARR does not represent an array, returns ARR unchanged.
2065 Otherwise, returns either a standard GDB array with bounds set
2066 appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
2067 GDB array. Returns NULL if ARR is a null fat pointer. */
2068
2069 struct value *
2070 ada_coerce_to_simple_array_ptr (struct value *arr)
2071 {
2072 if (ada_is_array_descriptor_type (value_type (arr)))
2073 {
2074 struct type *arrType = ada_type_of_array (arr, 1);
2075
2076 if (arrType == NULL)
2077 return NULL;
2078 return value_cast (arrType, value_copy (desc_data (arr)));
2079 }
2080 else if (ada_is_constrained_packed_array_type (value_type (arr)))
2081 return decode_constrained_packed_array (arr);
2082 else
2083 return arr;
2084 }
2085
2086 /* If ARR does not represent an array, returns ARR unchanged.
2087 Otherwise, returns a standard GDB array describing ARR (which may
2088 be ARR itself if it already is in the proper form). */
2089
2090 struct value *
2091 ada_coerce_to_simple_array (struct value *arr)
2092 {
2093 if (ada_is_array_descriptor_type (value_type (arr)))
2094 {
2095 struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
2096
2097 if (arrVal == NULL)
2098 error (_("Bounds unavailable for null array pointer."));
2099 ada_ensure_varsize_limit (TYPE_TARGET_TYPE (value_type (arrVal)));
2100 return value_ind (arrVal);
2101 }
2102 else if (ada_is_constrained_packed_array_type (value_type (arr)))
2103 return decode_constrained_packed_array (arr);
2104 else
2105 return arr;
2106 }
2107
2108 /* If TYPE represents a GNAT array type, return it translated to an
2109 ordinary GDB array type (possibly with BITSIZE fields indicating
2110 packing). For other types, is the identity. */
2111
2112 struct type *
2113 ada_coerce_to_simple_array_type (struct type *type)
2114 {
2115 if (ada_is_constrained_packed_array_type (type))
2116 return decode_constrained_packed_array_type (type);
2117
2118 if (ada_is_array_descriptor_type (type))
2119 return ada_check_typedef (desc_data_target_type (type));
2120
2121 return type;
2122 }
2123
2124 /* Non-zero iff TYPE represents a standard GNAT packed-array type. */
2125
2126 static int
2127 ada_is_packed_array_type (struct type *type)
2128 {
2129 if (type == NULL)
2130 return 0;
2131 type = desc_base_type (type);
2132 type = ada_check_typedef (type);
2133 return
2134 ada_type_name (type) != NULL
2135 && strstr (ada_type_name (type), "___XP") != NULL;
2136 }
2137
2138 /* Non-zero iff TYPE represents a standard GNAT constrained
2139 packed-array type. */
2140
2141 int
2142 ada_is_constrained_packed_array_type (struct type *type)
2143 {
2144 return ada_is_packed_array_type (type)
2145 && !ada_is_array_descriptor_type (type);
2146 }
2147
2148 /* Non-zero iff TYPE represents an array descriptor for a
2149 unconstrained packed-array type. */
2150
2151 static int
2152 ada_is_unconstrained_packed_array_type (struct type *type)
2153 {
2154 return ada_is_packed_array_type (type)
2155 && ada_is_array_descriptor_type (type);
2156 }
2157
2158 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
2159 return the size of its elements in bits. */
2160
2161 static long
2162 decode_packed_array_bitsize (struct type *type)
2163 {
2164 const char *raw_name;
2165 const char *tail;
2166 long bits;
2167
2168 /* Access to arrays implemented as fat pointers are encoded as a typedef
2169 of the fat pointer type. We need the name of the fat pointer type
2170 to do the decoding, so strip the typedef layer. */
2171 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
2172 type = ada_typedef_target_type (type);
2173
2174 raw_name = ada_type_name (ada_check_typedef (type));
2175 if (!raw_name)
2176 raw_name = ada_type_name (desc_base_type (type));
2177
2178 if (!raw_name)
2179 return 0;
2180
2181 tail = strstr (raw_name, "___XP");
2182 gdb_assert (tail != NULL);
2183
2184 if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
2185 {
2186 lim_warning
2187 (_("could not understand bit size information on packed array"));
2188 return 0;
2189 }
2190
2191 return bits;
2192 }
2193
2194 /* Given that TYPE is a standard GDB array type with all bounds filled
2195 in, and that the element size of its ultimate scalar constituents
2196 (that is, either its elements, or, if it is an array of arrays, its
2197 elements' elements, etc.) is *ELT_BITS, return an identical type,
2198 but with the bit sizes of its elements (and those of any
2199 constituent arrays) recorded in the BITSIZE components of its
2200 TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
2201 in bits.
2202
2203 Note that, for arrays whose index type has an XA encoding where
2204 a bound references a record discriminant, getting that discriminant,
2205 and therefore the actual value of that bound, is not possible
2206 because none of the given parameters gives us access to the record.
2207 This function assumes that it is OK in the context where it is being
2208 used to return an array whose bounds are still dynamic and where
2209 the length is arbitrary. */
2210
2211 static struct type *
2212 constrained_packed_array_type (struct type *type, long *elt_bits)
2213 {
2214 struct type *new_elt_type;
2215 struct type *new_type;
2216 struct type *index_type_desc;
2217 struct type *index_type;
2218 LONGEST low_bound, high_bound;
2219
2220 type = ada_check_typedef (type);
2221 if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
2222 return type;
2223
2224 index_type_desc = ada_find_parallel_type (type, "___XA");
2225 if (index_type_desc)
2226 index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, 0),
2227 NULL);
2228 else
2229 index_type = TYPE_INDEX_TYPE (type);
2230
2231 new_type = alloc_type_copy (type);
2232 new_elt_type =
2233 constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
2234 elt_bits);
2235 create_array_type (new_type, new_elt_type, index_type);
2236 TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
2237 TYPE_NAME (new_type) = ada_type_name (type);
2238
2239 if ((TYPE_CODE (check_typedef (index_type)) == TYPE_CODE_RANGE
2240 && is_dynamic_type (check_typedef (index_type)))
2241 || get_discrete_bounds (index_type, &low_bound, &high_bound) < 0)
2242 low_bound = high_bound = 0;
2243 if (high_bound < low_bound)
2244 *elt_bits = TYPE_LENGTH (new_type) = 0;
2245 else
2246 {
2247 *elt_bits *= (high_bound - low_bound + 1);
2248 TYPE_LENGTH (new_type) =
2249 (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2250 }
2251
2252 TYPE_FIXED_INSTANCE (new_type) = 1;
2253 return new_type;
2254 }
2255
2256 /* The array type encoded by TYPE, where
2257 ada_is_constrained_packed_array_type (TYPE). */
2258
2259 static struct type *
2260 decode_constrained_packed_array_type (struct type *type)
2261 {
2262 const char *raw_name = ada_type_name (ada_check_typedef (type));
2263 char *name;
2264 const char *tail;
2265 struct type *shadow_type;
2266 long bits;
2267
2268 if (!raw_name)
2269 raw_name = ada_type_name (desc_base_type (type));
2270
2271 if (!raw_name)
2272 return NULL;
2273
2274 name = (char *) alloca (strlen (raw_name) + 1);
2275 tail = strstr (raw_name, "___XP");
2276 type = desc_base_type (type);
2277
2278 memcpy (name, raw_name, tail - raw_name);
2279 name[tail - raw_name] = '\000';
2280
2281 shadow_type = ada_find_parallel_type_with_name (type, name);
2282
2283 if (shadow_type == NULL)
2284 {
2285 lim_warning (_("could not find bounds information on packed array"));
2286 return NULL;
2287 }
2288 shadow_type = check_typedef (shadow_type);
2289
2290 if (TYPE_CODE (shadow_type) != TYPE_CODE_ARRAY)
2291 {
2292 lim_warning (_("could not understand bounds "
2293 "information on packed array"));
2294 return NULL;
2295 }
2296
2297 bits = decode_packed_array_bitsize (type);
2298 return constrained_packed_array_type (shadow_type, &bits);
2299 }
2300
2301 /* Given that ARR is a struct value *indicating a GNAT constrained packed
2302 array, returns a simple array that denotes that array. Its type is a
2303 standard GDB array type except that the BITSIZEs of the array
2304 target types are set to the number of bits in each element, and the
2305 type length is set appropriately. */
2306
2307 static struct value *
2308 decode_constrained_packed_array (struct value *arr)
2309 {
2310 struct type *type;
2311
2312 /* If our value is a pointer, then dereference it. Likewise if
2313 the value is a reference. Make sure that this operation does not
2314 cause the target type to be fixed, as this would indirectly cause
2315 this array to be decoded. The rest of the routine assumes that
2316 the array hasn't been decoded yet, so we use the basic "coerce_ref"
2317 and "value_ind" routines to perform the dereferencing, as opposed
2318 to using "ada_coerce_ref" or "ada_value_ind". */
2319 arr = coerce_ref (arr);
2320 if (TYPE_CODE (ada_check_typedef (value_type (arr))) == TYPE_CODE_PTR)
2321 arr = value_ind (arr);
2322
2323 type = decode_constrained_packed_array_type (value_type (arr));
2324 if (type == NULL)
2325 {
2326 error (_("can't unpack array"));
2327 return NULL;
2328 }
2329
2330 if (gdbarch_bits_big_endian (get_type_arch (value_type (arr)))
2331 && ada_is_modular_type (value_type (arr)))
2332 {
2333 /* This is a (right-justified) modular type representing a packed
2334 array with no wrapper. In order to interpret the value through
2335 the (left-justified) packed array type we just built, we must
2336 first left-justify it. */
2337 int bit_size, bit_pos;
2338 ULONGEST mod;
2339
2340 mod = ada_modulus (value_type (arr)) - 1;
2341 bit_size = 0;
2342 while (mod > 0)
2343 {
2344 bit_size += 1;
2345 mod >>= 1;
2346 }
2347 bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
2348 arr = ada_value_primitive_packed_val (arr, NULL,
2349 bit_pos / HOST_CHAR_BIT,
2350 bit_pos % HOST_CHAR_BIT,
2351 bit_size,
2352 type);
2353 }
2354
2355 return coerce_unspec_val_to_type (arr, type);
2356 }
2357
2358
2359 /* The value of the element of packed array ARR at the ARITY indices
2360 given in IND. ARR must be a simple array. */
2361
2362 static struct value *
2363 value_subscript_packed (struct value *arr, int arity, struct value **ind)
2364 {
2365 int i;
2366 int bits, elt_off, bit_off;
2367 long elt_total_bit_offset;
2368 struct type *elt_type;
2369 struct value *v;
2370
2371 bits = 0;
2372 elt_total_bit_offset = 0;
2373 elt_type = ada_check_typedef (value_type (arr));
2374 for (i = 0; i < arity; i += 1)
2375 {
2376 if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY
2377 || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
2378 error
2379 (_("attempt to do packed indexing of "
2380 "something other than a packed array"));
2381 else
2382 {
2383 struct type *range_type = TYPE_INDEX_TYPE (elt_type);
2384 LONGEST lowerbound, upperbound;
2385 LONGEST idx;
2386
2387 if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
2388 {
2389 lim_warning (_("don't know bounds of array"));
2390 lowerbound = upperbound = 0;
2391 }
2392
2393 idx = pos_atr (ind[i]);
2394 if (idx < lowerbound || idx > upperbound)
2395 lim_warning (_("packed array index %ld out of bounds"),
2396 (long) idx);
2397 bits = TYPE_FIELD_BITSIZE (elt_type, 0);
2398 elt_total_bit_offset += (idx - lowerbound) * bits;
2399 elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
2400 }
2401 }
2402 elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
2403 bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
2404
2405 v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
2406 bits, elt_type);
2407 return v;
2408 }
2409
2410 /* Non-zero iff TYPE includes negative integer values. */
2411
2412 static int
2413 has_negatives (struct type *type)
2414 {
2415 switch (TYPE_CODE (type))
2416 {
2417 default:
2418 return 0;
2419 case TYPE_CODE_INT:
2420 return !TYPE_UNSIGNED (type);
2421 case TYPE_CODE_RANGE:
2422 return TYPE_LOW_BOUND (type) < 0;
2423 }
2424 }
2425
2426 /* With SRC being a buffer containing BIT_SIZE bits of data at BIT_OFFSET,
2427 unpack that data into UNPACKED. UNPACKED_LEN is the size in bytes of
2428 the unpacked buffer.
2429
2430 The size of the unpacked buffer (UNPACKED_LEN) is expected to be large
2431 enough to contain at least BIT_OFFSET bits. If not, an error is raised.
2432
2433 IS_BIG_ENDIAN is nonzero if the data is stored in big endian mode,
2434 zero otherwise.
2435
2436 IS_SIGNED_TYPE is nonzero if the data corresponds to a signed type.
2437
2438 IS_SCALAR is nonzero if the data corresponds to a signed type. */
2439
2440 static void
2441 ada_unpack_from_contents (const gdb_byte *src, int bit_offset, int bit_size,
2442 gdb_byte *unpacked, int unpacked_len,
2443 int is_big_endian, int is_signed_type,
2444 int is_scalar)
2445 {
2446 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2447 int src_idx; /* Index into the source area */
2448 int src_bytes_left; /* Number of source bytes left to process. */
2449 int srcBitsLeft; /* Number of source bits left to move */
2450 int unusedLS; /* Number of bits in next significant
2451 byte of source that are unused */
2452
2453 int unpacked_idx; /* Index into the unpacked buffer */
2454 int unpacked_bytes_left; /* Number of bytes left to set in unpacked. */
2455
2456 unsigned long accum; /* Staging area for bits being transferred */
2457 int accumSize; /* Number of meaningful bits in accum */
2458 unsigned char sign;
2459
2460 /* Transmit bytes from least to most significant; delta is the direction
2461 the indices move. */
2462 int delta = is_big_endian ? -1 : 1;
2463
2464 /* Make sure that unpacked is large enough to receive the BIT_SIZE
2465 bits from SRC. .*/
2466 if ((bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT > unpacked_len)
2467 error (_("Cannot unpack %d bits into buffer of %d bytes"),
2468 bit_size, unpacked_len);
2469
2470 srcBitsLeft = bit_size;
2471 src_bytes_left = src_len;
2472 unpacked_bytes_left = unpacked_len;
2473 sign = 0;
2474
2475 if (is_big_endian)
2476 {
2477 src_idx = src_len - 1;
2478 if (is_signed_type
2479 && ((src[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2480 sign = ~0;
2481
2482 unusedLS =
2483 (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2484 % HOST_CHAR_BIT;
2485
2486 if (is_scalar)
2487 {
2488 accumSize = 0;
2489 unpacked_idx = unpacked_len - 1;
2490 }
2491 else
2492 {
2493 /* Non-scalar values must be aligned at a byte boundary... */
2494 accumSize =
2495 (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2496 /* ... And are placed at the beginning (most-significant) bytes
2497 of the target. */
2498 unpacked_idx = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2499 unpacked_bytes_left = unpacked_idx + 1;
2500 }
2501 }
2502 else
2503 {
2504 int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2505
2506 src_idx = unpacked_idx = 0;
2507 unusedLS = bit_offset;
2508 accumSize = 0;
2509
2510 if (is_signed_type && (src[src_len - 1] & (1 << sign_bit_offset)))
2511 sign = ~0;
2512 }
2513
2514 accum = 0;
2515 while (src_bytes_left > 0)
2516 {
2517 /* Mask for removing bits of the next source byte that are not
2518 part of the value. */
2519 unsigned int unusedMSMask =
2520 (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2521 1;
2522 /* Sign-extend bits for this byte. */
2523 unsigned int signMask = sign & ~unusedMSMask;
2524
2525 accum |=
2526 (((src[src_idx] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2527 accumSize += HOST_CHAR_BIT - unusedLS;
2528 if (accumSize >= HOST_CHAR_BIT)
2529 {
2530 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2531 accumSize -= HOST_CHAR_BIT;
2532 accum >>= HOST_CHAR_BIT;
2533 unpacked_bytes_left -= 1;
2534 unpacked_idx += delta;
2535 }
2536 srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2537 unusedLS = 0;
2538 src_bytes_left -= 1;
2539 src_idx += delta;
2540 }
2541 while (unpacked_bytes_left > 0)
2542 {
2543 accum |= sign << accumSize;
2544 unpacked[unpacked_idx] = accum & ~(~0UL << HOST_CHAR_BIT);
2545 accumSize -= HOST_CHAR_BIT;
2546 if (accumSize < 0)
2547 accumSize = 0;
2548 accum >>= HOST_CHAR_BIT;
2549 unpacked_bytes_left -= 1;
2550 unpacked_idx += delta;
2551 }
2552 }
2553
2554 /* Create a new value of type TYPE from the contents of OBJ starting
2555 at byte OFFSET, and bit offset BIT_OFFSET within that byte,
2556 proceeding for BIT_SIZE bits. If OBJ is an lval in memory, then
2557 assigning through the result will set the field fetched from.
2558 VALADDR is ignored unless OBJ is NULL, in which case,
2559 VALADDR+OFFSET must address the start of storage containing the
2560 packed value. The value returned in this case is never an lval.
2561 Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT. */
2562
2563 struct value *
2564 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
2565 long offset, int bit_offset, int bit_size,
2566 struct type *type)
2567 {
2568 struct value *v;
2569 const gdb_byte *src; /* First byte containing data to unpack */
2570 gdb_byte *unpacked;
2571 const int is_scalar = is_scalar_type (type);
2572 const int is_big_endian = gdbarch_bits_big_endian (get_type_arch (type));
2573 gdb::byte_vector staging;
2574
2575 type = ada_check_typedef (type);
2576
2577 if (obj == NULL)
2578 src = valaddr + offset;
2579 else
2580 src = value_contents (obj) + offset;
2581
2582 if (is_dynamic_type (type))
2583 {
2584 /* The length of TYPE might by dynamic, so we need to resolve
2585 TYPE in order to know its actual size, which we then use
2586 to create the contents buffer of the value we return.
2587 The difficulty is that the data containing our object is
2588 packed, and therefore maybe not at a byte boundary. So, what
2589 we do, is unpack the data into a byte-aligned buffer, and then
2590 use that buffer as our object's value for resolving the type. */
2591 int staging_len = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2592 staging.resize (staging_len);
2593
2594 ada_unpack_from_contents (src, bit_offset, bit_size,
2595 staging.data (), staging.size (),
2596 is_big_endian, has_negatives (type),
2597 is_scalar);
2598 type = resolve_dynamic_type (type, staging.data (), 0);
2599 if (TYPE_LENGTH (type) < (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT)
2600 {
2601 /* This happens when the length of the object is dynamic,
2602 and is actually smaller than the space reserved for it.
2603 For instance, in an array of variant records, the bit_size
2604 we're given is the array stride, which is constant and
2605 normally equal to the maximum size of its element.
2606 But, in reality, each element only actually spans a portion
2607 of that stride. */
2608 bit_size = TYPE_LENGTH (type) * HOST_CHAR_BIT;
2609 }
2610 }
2611
2612 if (obj == NULL)
2613 {
2614 v = allocate_value (type);
2615 src = valaddr + offset;
2616 }
2617 else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
2618 {
2619 int src_len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
2620 gdb_byte *buf;
2621
2622 v = value_at (type, value_address (obj) + offset);
2623 buf = (gdb_byte *) alloca (src_len);
2624 read_memory (value_address (v), buf, src_len);
2625 src = buf;
2626 }
2627 else
2628 {
2629 v = allocate_value (type);
2630 src = value_contents (obj) + offset;
2631 }
2632
2633 if (obj != NULL)
2634 {
2635 long new_offset = offset;
2636
2637 set_value_component_location (v, obj);
2638 set_value_bitpos (v, bit_offset + value_bitpos (obj));
2639 set_value_bitsize (v, bit_size);
2640 if (value_bitpos (v) >= HOST_CHAR_BIT)
2641 {
2642 ++new_offset;
2643 set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
2644 }
2645 set_value_offset (v, new_offset);
2646
2647 /* Also set the parent value. This is needed when trying to
2648 assign a new value (in inferior memory). */
2649 set_value_parent (v, obj);
2650 }
2651 else
2652 set_value_bitsize (v, bit_size);
2653 unpacked = value_contents_writeable (v);
2654
2655 if (bit_size == 0)
2656 {
2657 memset (unpacked, 0, TYPE_LENGTH (type));
2658 return v;
2659 }
2660
2661 if (staging.size () == TYPE_LENGTH (type))
2662 {
2663 /* Small short-cut: If we've unpacked the data into a buffer
2664 of the same size as TYPE's length, then we can reuse that,
2665 instead of doing the unpacking again. */
2666 memcpy (unpacked, staging.data (), staging.size ());
2667 }
2668 else
2669 ada_unpack_from_contents (src, bit_offset, bit_size,
2670 unpacked, TYPE_LENGTH (type),
2671 is_big_endian, has_negatives (type), is_scalar);
2672
2673 return v;
2674 }
2675
2676 /* Store the contents of FROMVAL into the location of TOVAL.
2677 Return a new value with the location of TOVAL and contents of
2678 FROMVAL. Handles assignment into packed fields that have
2679 floating-point or non-scalar types. */
2680
2681 static struct value *
2682 ada_value_assign (struct value *toval, struct value *fromval)
2683 {
2684 struct type *type = value_type (toval);
2685 int bits = value_bitsize (toval);
2686
2687 toval = ada_coerce_ref (toval);
2688 fromval = ada_coerce_ref (fromval);
2689
2690 if (ada_is_direct_array_type (value_type (toval)))
2691 toval = ada_coerce_to_simple_array (toval);
2692 if (ada_is_direct_array_type (value_type (fromval)))
2693 fromval = ada_coerce_to_simple_array (fromval);
2694
2695 if (!deprecated_value_modifiable (toval))
2696 error (_("Left operand of assignment is not a modifiable lvalue."));
2697
2698 if (VALUE_LVAL (toval) == lval_memory
2699 && bits > 0
2700 && (TYPE_CODE (type) == TYPE_CODE_FLT
2701 || TYPE_CODE (type) == TYPE_CODE_STRUCT))
2702 {
2703 int len = (value_bitpos (toval)
2704 + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2705 int from_size;
2706 gdb_byte *buffer = (gdb_byte *) alloca (len);
2707 struct value *val;
2708 CORE_ADDR to_addr = value_address (toval);
2709
2710 if (TYPE_CODE (type) == TYPE_CODE_FLT)
2711 fromval = value_cast (type, fromval);
2712
2713 read_memory (to_addr, buffer, len);
2714 from_size = value_bitsize (fromval);
2715 if (from_size == 0)
2716 from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2717 if (gdbarch_bits_big_endian (get_type_arch (type)))
2718 copy_bitwise (buffer, value_bitpos (toval),
2719 value_contents (fromval), from_size - bits, bits, 1);
2720 else
2721 copy_bitwise (buffer, value_bitpos (toval),
2722 value_contents (fromval), 0, bits, 0);
2723 write_memory_with_notification (to_addr, buffer, len);
2724
2725 val = value_copy (toval);
2726 memcpy (value_contents_raw (val), value_contents (fromval),
2727 TYPE_LENGTH (type));
2728 deprecated_set_value_type (val, type);
2729
2730 return val;
2731 }
2732
2733 return value_assign (toval, fromval);
2734 }
2735
2736
2737 /* Given that COMPONENT is a memory lvalue that is part of the lvalue
2738 CONTAINER, assign the contents of VAL to COMPONENTS's place in
2739 CONTAINER. Modifies the VALUE_CONTENTS of CONTAINER only, not
2740 COMPONENT, and not the inferior's memory. The current contents
2741 of COMPONENT are ignored.
2742
2743 Although not part of the initial design, this function also works
2744 when CONTAINER and COMPONENT are not_lval's: it works as if CONTAINER
2745 had a null address, and COMPONENT had an address which is equal to
2746 its offset inside CONTAINER. */
2747
2748 static void
2749 value_assign_to_component (struct value *container, struct value *component,
2750 struct value *val)
2751 {
2752 LONGEST offset_in_container =
2753 (LONGEST) (value_address (component) - value_address (container));
2754 int bit_offset_in_container =
2755 value_bitpos (component) - value_bitpos (container);
2756 int bits;
2757
2758 val = value_cast (value_type (component), val);
2759
2760 if (value_bitsize (component) == 0)
2761 bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2762 else
2763 bits = value_bitsize (component);
2764
2765 if (gdbarch_bits_big_endian (get_type_arch (value_type (container))))
2766 {
2767 int src_offset;
2768
2769 if (is_scalar_type (check_typedef (value_type (component))))
2770 src_offset
2771 = TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits;
2772 else
2773 src_offset = 0;
2774 copy_bitwise (value_contents_writeable (container) + offset_in_container,
2775 value_bitpos (container) + bit_offset_in_container,
2776 value_contents (val), src_offset, bits, 1);
2777 }
2778 else
2779 copy_bitwise (value_contents_writeable (container) + offset_in_container,
2780 value_bitpos (container) + bit_offset_in_container,
2781 value_contents (val), 0, bits, 0);
2782 }
2783
2784 /* Determine if TYPE is an access to an unconstrained array. */
2785
2786 bool
2787 ada_is_access_to_unconstrained_array (struct type *type)
2788 {
2789 return (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
2790 && is_thick_pntr (ada_typedef_target_type (type)));
2791 }
2792
2793 /* The value of the element of array ARR at the ARITY indices given in IND.
2794 ARR may be either a simple array, GNAT array descriptor, or pointer
2795 thereto. */
2796
2797 struct value *
2798 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2799 {
2800 int k;
2801 struct value *elt;
2802 struct type *elt_type;
2803
2804 elt = ada_coerce_to_simple_array (arr);
2805
2806 elt_type = ada_check_typedef (value_type (elt));
2807 if (TYPE_CODE (elt_type) == TYPE_CODE_ARRAY
2808 && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2809 return value_subscript_packed (elt, arity, ind);
2810
2811 for (k = 0; k < arity; k += 1)
2812 {
2813 struct type *saved_elt_type = TYPE_TARGET_TYPE (elt_type);
2814
2815 if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY)
2816 error (_("too many subscripts (%d expected)"), k);
2817
2818 elt = value_subscript (elt, pos_atr (ind[k]));
2819
2820 if (ada_is_access_to_unconstrained_array (saved_elt_type)
2821 && TYPE_CODE (value_type (elt)) != TYPE_CODE_TYPEDEF)
2822 {
2823 /* The element is a typedef to an unconstrained array,
2824 except that the value_subscript call stripped the
2825 typedef layer. The typedef layer is GNAT's way to
2826 specify that the element is, at the source level, an
2827 access to the unconstrained array, rather than the
2828 unconstrained array. So, we need to restore that
2829 typedef layer, which we can do by forcing the element's
2830 type back to its original type. Otherwise, the returned
2831 value is going to be printed as the array, rather
2832 than as an access. Another symptom of the same issue
2833 would be that an expression trying to dereference the
2834 element would also be improperly rejected. */
2835 deprecated_set_value_type (elt, saved_elt_type);
2836 }
2837
2838 elt_type = ada_check_typedef (value_type (elt));
2839 }
2840
2841 return elt;
2842 }
2843
2844 /* Assuming ARR is a pointer to a GDB array, the value of the element
2845 of *ARR at the ARITY indices given in IND.
2846 Does not read the entire array into memory.
2847
2848 Note: Unlike what one would expect, this function is used instead of
2849 ada_value_subscript for basically all non-packed array types. The reason
2850 for this is that a side effect of doing our own pointer arithmetics instead
2851 of relying on value_subscript is that there is no implicit typedef peeling.
2852 This is important for arrays of array accesses, where it allows us to
2853 preserve the fact that the array's element is an array access, where the
2854 access part os encoded in a typedef layer. */
2855
2856 static struct value *
2857 ada_value_ptr_subscript (struct value *arr, int arity, struct value **ind)
2858 {
2859 int k;
2860 struct value *array_ind = ada_value_ind (arr);
2861 struct type *type
2862 = check_typedef (value_enclosing_type (array_ind));
2863
2864 if (TYPE_CODE (type) == TYPE_CODE_ARRAY
2865 && TYPE_FIELD_BITSIZE (type, 0) > 0)
2866 return value_subscript_packed (array_ind, arity, ind);
2867
2868 for (k = 0; k < arity; k += 1)
2869 {
2870 LONGEST lwb, upb;
2871 struct value *lwb_value;
2872
2873 if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
2874 error (_("too many subscripts (%d expected)"), k);
2875 arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2876 value_copy (arr));
2877 get_discrete_bounds (TYPE_INDEX_TYPE (type), &lwb, &upb);
2878 lwb_value = value_from_longest (value_type(ind[k]), lwb);
2879 arr = value_ptradd (arr, pos_atr (ind[k]) - pos_atr (lwb_value));
2880 type = TYPE_TARGET_TYPE (type);
2881 }
2882
2883 return value_ind (arr);
2884 }
2885
2886 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2887 actual type of ARRAY_PTR is ignored), returns the Ada slice of
2888 HIGH'Pos-LOW'Pos+1 elements starting at index LOW. The lower bound of
2889 this array is LOW, as per Ada rules. */
2890 static struct value *
2891 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
2892 int low, int high)
2893 {
2894 struct type *type0 = ada_check_typedef (type);
2895 struct type *base_index_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type0));
2896 struct type *index_type
2897 = create_static_range_type (NULL, base_index_type, low, high);
2898 struct type *slice_type = create_array_type_with_stride
2899 (NULL, TYPE_TARGET_TYPE (type0), index_type,
2900 get_dyn_prop (DYN_PROP_BYTE_STRIDE, type0),
2901 TYPE_FIELD_BITSIZE (type0, 0));
2902 int base_low = ada_discrete_type_low_bound (TYPE_INDEX_TYPE (type0));
2903 LONGEST base_low_pos, low_pos;
2904 CORE_ADDR base;
2905
2906 if (!discrete_position (base_index_type, low, &low_pos)
2907 || !discrete_position (base_index_type, base_low, &base_low_pos))
2908 {
2909 warning (_("unable to get positions in slice, use bounds instead"));
2910 low_pos = low;
2911 base_low_pos = base_low;
2912 }
2913
2914 base = value_as_address (array_ptr)
2915 + ((low_pos - base_low_pos)
2916 * TYPE_LENGTH (TYPE_TARGET_TYPE (type0)));
2917 return value_at_lazy (slice_type, base);
2918 }
2919
2920
2921 static struct value *
2922 ada_value_slice (struct value *array, int low, int high)
2923 {
2924 struct type *type = ada_check_typedef (value_type (array));
2925 struct type *base_index_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type));
2926 struct type *index_type
2927 = create_static_range_type (NULL, TYPE_INDEX_TYPE (type), low, high);
2928 struct type *slice_type = create_array_type_with_stride
2929 (NULL, TYPE_TARGET_TYPE (type), index_type,
2930 get_dyn_prop (DYN_PROP_BYTE_STRIDE, type),
2931 TYPE_FIELD_BITSIZE (type, 0));
2932 LONGEST low_pos, high_pos;
2933
2934 if (!discrete_position (base_index_type, low, &low_pos)
2935 || !discrete_position (base_index_type, high, &high_pos))
2936 {
2937 warning (_("unable to get positions in slice, use bounds instead"));
2938 low_pos = low;
2939 high_pos = high;
2940 }
2941
2942 return value_cast (slice_type,
2943 value_slice (array, low, high_pos - low_pos + 1));
2944 }
2945
2946 /* If type is a record type in the form of a standard GNAT array
2947 descriptor, returns the number of dimensions for type. If arr is a
2948 simple array, returns the number of "array of"s that prefix its
2949 type designation. Otherwise, returns 0. */
2950
2951 int
2952 ada_array_arity (struct type *type)
2953 {
2954 int arity;
2955
2956 if (type == NULL)
2957 return 0;
2958
2959 type = desc_base_type (type);
2960
2961 arity = 0;
2962 if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2963 return desc_arity (desc_bounds_type (type));
2964 else
2965 while (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2966 {
2967 arity += 1;
2968 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
2969 }
2970
2971 return arity;
2972 }
2973
2974 /* If TYPE is a record type in the form of a standard GNAT array
2975 descriptor or a simple array type, returns the element type for
2976 TYPE after indexing by NINDICES indices, or by all indices if
2977 NINDICES is -1. Otherwise, returns NULL. */
2978
2979 struct type *
2980 ada_array_element_type (struct type *type, int nindices)
2981 {
2982 type = desc_base_type (type);
2983
2984 if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2985 {
2986 int k;
2987 struct type *p_array_type;
2988
2989 p_array_type = desc_data_target_type (type);
2990
2991 k = ada_array_arity (type);
2992 if (k == 0)
2993 return NULL;
2994
2995 /* Initially p_array_type = elt_type(*)[]...(k times)...[]. */
2996 if (nindices >= 0 && k > nindices)
2997 k = nindices;
2998 while (k > 0 && p_array_type != NULL)
2999 {
3000 p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
3001 k -= 1;
3002 }
3003 return p_array_type;
3004 }
3005 else if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
3006 {
3007 while (nindices != 0 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
3008 {
3009 type = TYPE_TARGET_TYPE (type);
3010 nindices -= 1;
3011 }
3012 return type;
3013 }
3014
3015 return NULL;
3016 }
3017
3018 /* The type of nth index in arrays of given type (n numbering from 1).
3019 Does not examine memory. Throws an error if N is invalid or TYPE
3020 is not an array type. NAME is the name of the Ada attribute being
3021 evaluated ('range, 'first, 'last, or 'length); it is used in building
3022 the error message. */
3023
3024 static struct type *
3025 ada_index_type (struct type *type, int n, const char *name)
3026 {
3027 struct type *result_type;
3028
3029 type = desc_base_type (type);
3030
3031 if (n < 0 || n > ada_array_arity (type))
3032 error (_("invalid dimension number to '%s"), name);
3033
3034 if (ada_is_simple_array_type (type))
3035 {
3036 int i;
3037
3038 for (i = 1; i < n; i += 1)
3039 type = TYPE_TARGET_TYPE (type);
3040 result_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type));
3041 /* FIXME: The stabs type r(0,0);bound;bound in an array type
3042 has a target type of TYPE_CODE_UNDEF. We compensate here, but
3043 perhaps stabsread.c would make more sense. */
3044 if (result_type && TYPE_CODE (result_type) == TYPE_CODE_UNDEF)
3045 result_type = NULL;
3046 }
3047 else
3048 {
3049 result_type = desc_index_type (desc_bounds_type (type), n);
3050 if (result_type == NULL)
3051 error (_("attempt to take bound of something that is not an array"));
3052 }
3053
3054 return result_type;
3055 }
3056
3057 /* Given that arr is an array type, returns the lower bound of the
3058 Nth index (numbering from 1) if WHICH is 0, and the upper bound if
3059 WHICH is 1. This returns bounds 0 .. -1 if ARR_TYPE is an
3060 array-descriptor type. It works for other arrays with bounds supplied
3061 by run-time quantities other than discriminants. */
3062
3063 static LONGEST
3064 ada_array_bound_from_type (struct type *arr_type, int n, int which)
3065 {
3066 struct type *type, *index_type_desc, *index_type;
3067 int i;
3068
3069 gdb_assert (which == 0 || which == 1);
3070
3071 if (ada_is_constrained_packed_array_type (arr_type))
3072 arr_type = decode_constrained_packed_array_type (arr_type);
3073
3074 if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
3075 return (LONGEST) - which;
3076
3077 if (TYPE_CODE (arr_type) == TYPE_CODE_PTR)
3078 type = TYPE_TARGET_TYPE (arr_type);
3079 else
3080 type = arr_type;
3081
3082 if (TYPE_FIXED_INSTANCE (type))
3083 {
3084 /* The array has already been fixed, so we do not need to
3085 check the parallel ___XA type again. That encoding has
3086 already been applied, so ignore it now. */
3087 index_type_desc = NULL;
3088 }
3089 else
3090 {
3091 index_type_desc = ada_find_parallel_type (type, "___XA");
3092 ada_fixup_array_indexes_type (index_type_desc);
3093 }
3094
3095 if (index_type_desc != NULL)
3096 index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, n - 1),
3097 NULL);
3098 else
3099 {
3100 struct type *elt_type = check_typedef (type);
3101
3102 for (i = 1; i < n; i++)
3103 elt_type = check_typedef (TYPE_TARGET_TYPE (elt_type));
3104
3105 index_type = TYPE_INDEX_TYPE (elt_type);
3106 }
3107
3108 return
3109 (LONGEST) (which == 0
3110 ? ada_discrete_type_low_bound (index_type)
3111 : ada_discrete_type_high_bound (index_type));
3112 }
3113
3114 /* Given that arr is an array value, returns the lower bound of the
3115 nth index (numbering from 1) if WHICH is 0, and the upper bound if
3116 WHICH is 1. This routine will also work for arrays with bounds
3117 supplied by run-time quantities other than discriminants. */
3118
3119 static LONGEST
3120 ada_array_bound (struct value *arr, int n, int which)
3121 {
3122 struct type *arr_type;
3123
3124 if (TYPE_CODE (check_typedef (value_type (arr))) == TYPE_CODE_PTR)
3125 arr = value_ind (arr);
3126 arr_type = value_enclosing_type (arr);
3127
3128 if (ada_is_constrained_packed_array_type (arr_type))
3129 return ada_array_bound (decode_constrained_packed_array (arr), n, which);
3130 else if (ada_is_simple_array_type (arr_type))
3131 return ada_array_bound_from_type (arr_type, n, which);
3132 else
3133 return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
3134 }
3135
3136 /* Given that arr is an array value, returns the length of the
3137 nth index. This routine will also work for arrays with bounds
3138 supplied by run-time quantities other than discriminants.
3139 Does not work for arrays indexed by enumeration types with representation
3140 clauses at the moment. */
3141
3142 static LONGEST
3143 ada_array_length (struct value *arr, int n)
3144 {
3145 struct type *arr_type, *index_type;
3146 int low, high;
3147
3148 if (TYPE_CODE (check_typedef (value_type (arr))) == TYPE_CODE_PTR)
3149 arr = value_ind (arr);
3150 arr_type = value_enclosing_type (arr);
3151
3152 if (ada_is_constrained_packed_array_type (arr_type))
3153 return ada_array_length (decode_constrained_packed_array (arr), n);
3154
3155 if (ada_is_simple_array_type (arr_type))
3156 {
3157 low = ada_array_bound_from_type (arr_type, n, 0);
3158 high = ada_array_bound_from_type (arr_type, n, 1);
3159 }
3160 else
3161 {
3162 low = value_as_long (desc_one_bound (desc_bounds (arr), n, 0));
3163 high = value_as_long (desc_one_bound (desc_bounds (arr), n, 1));
3164 }
3165
3166 arr_type = check_typedef (arr_type);
3167 index_type = ada_index_type (arr_type, n, "length");
3168 if (index_type != NULL)
3169 {
3170 struct type *base_type;
3171 if (TYPE_CODE (index_type) == TYPE_CODE_RANGE)
3172 base_type = TYPE_TARGET_TYPE (index_type);
3173 else
3174 base_type = index_type;
3175
3176 low = pos_atr (value_from_longest (base_type, low));
3177 high = pos_atr (value_from_longest (base_type, high));
3178 }
3179 return high - low + 1;
3180 }
3181
3182 /* An array whose type is that of ARR_TYPE (an array type), with
3183 bounds LOW to HIGH, but whose contents are unimportant. If HIGH is
3184 less than LOW, then LOW-1 is used. */
3185
3186 static struct value *
3187 empty_array (struct type *arr_type, int low, int high)
3188 {
3189 struct type *arr_type0 = ada_check_typedef (arr_type);
3190 struct type *index_type
3191 = create_static_range_type
3192 (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (arr_type0)), low,
3193 high < low ? low - 1 : high);
3194 struct type *elt_type = ada_array_element_type (arr_type0, 1);
3195
3196 return allocate_value (create_array_type (NULL, elt_type, index_type));
3197 }
3198 \f
3199
3200 /* Name resolution */
3201
3202 /* The "decoded" name for the user-definable Ada operator corresponding
3203 to OP. */
3204
3205 static const char *
3206 ada_decoded_op_name (enum exp_opcode op)
3207 {
3208 int i;
3209
3210 for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
3211 {
3212 if (ada_opname_table[i].op == op)
3213 return ada_opname_table[i].decoded;
3214 }
3215 error (_("Could not find operator name for opcode"));
3216 }
3217
3218
3219 /* Same as evaluate_type (*EXP), but resolves ambiguous symbol
3220 references (marked by OP_VAR_VALUE nodes in which the symbol has an
3221 undefined namespace) and converts operators that are
3222 user-defined into appropriate function calls. If CONTEXT_TYPE is
3223 non-null, it provides a preferred result type [at the moment, only
3224 type void has any effect---causing procedures to be preferred over
3225 functions in calls]. A null CONTEXT_TYPE indicates that a non-void
3226 return type is preferred. May change (expand) *EXP. */
3227
3228 static void
3229 resolve (expression_up *expp, int void_context_p, int parse_completion,
3230 innermost_block_tracker *tracker)
3231 {
3232 struct type *context_type = NULL;
3233 int pc = 0;
3234
3235 if (void_context_p)
3236 context_type = builtin_type ((*expp)->gdbarch)->builtin_void;
3237
3238 resolve_subexp (expp, &pc, 1, context_type, parse_completion, tracker);
3239 }
3240
3241 /* Resolve the operator of the subexpression beginning at
3242 position *POS of *EXPP. "Resolving" consists of replacing
3243 the symbols that have undefined namespaces in OP_VAR_VALUE nodes
3244 with their resolutions, replacing built-in operators with
3245 function calls to user-defined operators, where appropriate, and,
3246 when DEPROCEDURE_P is non-zero, converting function-valued variables
3247 into parameterless calls. May expand *EXPP. The CONTEXT_TYPE functions
3248 are as in ada_resolve, above. */
3249
3250 static struct value *
3251 resolve_subexp (expression_up *expp, int *pos, int deprocedure_p,
3252 struct type *context_type, int parse_completion,
3253 innermost_block_tracker *tracker)
3254 {
3255 int pc = *pos;
3256 int i;
3257 struct expression *exp; /* Convenience: == *expp. */
3258 enum exp_opcode op = (*expp)->elts[pc].opcode;
3259 struct value **argvec; /* Vector of operand types (alloca'ed). */
3260 int nargs; /* Number of operands. */
3261 int oplen;
3262
3263 argvec = NULL;
3264 nargs = 0;
3265 exp = expp->get ();
3266
3267 /* Pass one: resolve operands, saving their types and updating *pos,
3268 if needed. */
3269 switch (op)
3270 {
3271 case OP_FUNCALL:
3272 if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3273 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3274 *pos += 7;
3275 else
3276 {
3277 *pos += 3;
3278 resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3279 }
3280 nargs = longest_to_int (exp->elts[pc + 1].longconst);
3281 break;
3282
3283 case UNOP_ADDR:
3284 *pos += 1;
3285 resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3286 break;
3287
3288 case UNOP_QUAL:
3289 *pos += 3;
3290 resolve_subexp (expp, pos, 1, check_typedef (exp->elts[pc + 1].type),
3291 parse_completion, tracker);
3292 break;
3293
3294 case OP_ATR_MODULUS:
3295 case OP_ATR_SIZE:
3296 case OP_ATR_TAG:
3297 case OP_ATR_FIRST:
3298 case OP_ATR_LAST:
3299 case OP_ATR_LENGTH:
3300 case OP_ATR_POS:
3301 case OP_ATR_VAL:
3302 case OP_ATR_MIN:
3303 case OP_ATR_MAX:
3304 case TERNOP_IN_RANGE:
3305 case BINOP_IN_BOUNDS:
3306 case UNOP_IN_RANGE:
3307 case OP_AGGREGATE:
3308 case OP_OTHERS:
3309 case OP_CHOICES:
3310 case OP_POSITIONAL:
3311 case OP_DISCRETE_RANGE:
3312 case OP_NAME:
3313 ada_forward_operator_length (exp, pc, &oplen, &nargs);
3314 *pos += oplen;
3315 break;
3316
3317 case BINOP_ASSIGN:
3318 {
3319 struct value *arg1;
3320
3321 *pos += 1;
3322 arg1 = resolve_subexp (expp, pos, 0, NULL, parse_completion, tracker);
3323 if (arg1 == NULL)
3324 resolve_subexp (expp, pos, 1, NULL, parse_completion, tracker);
3325 else
3326 resolve_subexp (expp, pos, 1, value_type (arg1), parse_completion,
3327 tracker);
3328 break;
3329 }
3330
3331 case UNOP_CAST:
3332 *pos += 3;
3333 nargs = 1;
3334 break;
3335
3336 case BINOP_ADD:
3337 case BINOP_SUB:
3338 case BINOP_MUL:
3339 case BINOP_DIV:
3340 case BINOP_REM:
3341 case BINOP_MOD:
3342 case BINOP_EXP:
3343 case BINOP_CONCAT:
3344 case BINOP_LOGICAL_AND:
3345 case BINOP_LOGICAL_OR:
3346 case BINOP_BITWISE_AND:
3347 case BINOP_BITWISE_IOR:
3348 case BINOP_BITWISE_XOR:
3349
3350 case BINOP_EQUAL:
3351 case BINOP_NOTEQUAL:
3352 case BINOP_LESS:
3353 case BINOP_GTR:
3354 case BINOP_LEQ:
3355 case BINOP_GEQ:
3356
3357 case BINOP_REPEAT:
3358 case BINOP_SUBSCRIPT:
3359 case BINOP_COMMA:
3360 *pos += 1;
3361 nargs = 2;
3362 break;
3363
3364 case UNOP_NEG:
3365 case UNOP_PLUS:
3366 case UNOP_LOGICAL_NOT:
3367 case UNOP_ABS:
3368 case UNOP_IND:
3369 *pos += 1;
3370 nargs = 1;
3371 break;
3372
3373 case OP_LONG:
3374 case OP_FLOAT:
3375 case OP_VAR_VALUE:
3376 case OP_VAR_MSYM_VALUE:
3377 *pos += 4;
3378 break;
3379
3380 case OP_TYPE:
3381 case OP_BOOL:
3382 case OP_LAST:
3383 case OP_INTERNALVAR:
3384 *pos += 3;
3385 break;
3386
3387 case UNOP_MEMVAL:
3388 *pos += 3;
3389 nargs = 1;
3390 break;
3391
3392 case OP_REGISTER:
3393 *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3394 break;
3395
3396 case STRUCTOP_STRUCT:
3397 *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
3398 nargs = 1;
3399 break;
3400
3401 case TERNOP_SLICE:
3402 *pos += 1;
3403 nargs = 3;
3404 break;
3405
3406 case OP_STRING:
3407 break;
3408
3409 default:
3410 error (_("Unexpected operator during name resolution"));
3411 }
3412
3413 argvec = XALLOCAVEC (struct value *, nargs + 1);
3414 for (i = 0; i < nargs; i += 1)
3415 argvec[i] = resolve_subexp (expp, pos, 1, NULL, parse_completion,
3416 tracker);
3417 argvec[i] = NULL;
3418 exp = expp->get ();
3419
3420 /* Pass two: perform any resolution on principal operator. */
3421 switch (op)
3422 {
3423 default:
3424 break;
3425
3426 case OP_VAR_VALUE:
3427 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
3428 {
3429 std::vector<struct block_symbol> candidates;
3430 int n_candidates;
3431
3432 n_candidates =
3433 ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
3434 (exp->elts[pc + 2].symbol),
3435 exp->elts[pc + 1].block, VAR_DOMAIN,
3436 &candidates);
3437
3438 if (n_candidates > 1)
3439 {
3440 /* Types tend to get re-introduced locally, so if there
3441 are any local symbols that are not types, first filter
3442 out all types. */
3443 int j;
3444 for (j = 0; j < n_candidates; j += 1)
3445 switch (SYMBOL_CLASS (candidates[j].symbol))
3446 {
3447 case LOC_REGISTER:
3448 case LOC_ARG:
3449 case LOC_REF_ARG:
3450 case LOC_REGPARM_ADDR:
3451 case LOC_LOCAL:
3452 case LOC_COMPUTED:
3453 goto FoundNonType;
3454 default:
3455 break;
3456 }
3457 FoundNonType:
3458 if (j < n_candidates)
3459 {
3460 j = 0;
3461 while (j < n_candidates)
3462 {
3463 if (SYMBOL_CLASS (candidates[j].symbol) == LOC_TYPEDEF)
3464 {
3465 candidates[j] = candidates[n_candidates - 1];
3466 n_candidates -= 1;
3467 }
3468 else
3469 j += 1;
3470 }
3471 }
3472 }
3473
3474 if (n_candidates == 0)
3475 error (_("No definition found for %s"),
3476 SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
3477 else if (n_candidates == 1)
3478 i = 0;
3479 else if (deprocedure_p
3480 && !is_nonfunction (candidates.data (), n_candidates))
3481 {
3482 i = ada_resolve_function
3483 (candidates.data (), n_candidates, NULL, 0,
3484 SYMBOL_LINKAGE_NAME (exp->elts[pc + 2].symbol),
3485 context_type, parse_completion);
3486 if (i < 0)
3487 error (_("Could not find a match for %s"),
3488 SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
3489 }
3490 else
3491 {
3492 printf_filtered (_("Multiple matches for %s\n"),
3493 SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
3494 user_select_syms (candidates.data (), n_candidates, 1);
3495 i = 0;
3496 }
3497
3498 exp->elts[pc + 1].block = candidates[i].block;
3499 exp->elts[pc + 2].symbol = candidates[i].symbol;
3500 tracker->update (candidates[i]);
3501 }
3502
3503 if (deprocedure_p
3504 && (TYPE_CODE (SYMBOL_TYPE (exp->elts[pc + 2].symbol))
3505 == TYPE_CODE_FUNC))
3506 {
3507 replace_operator_with_call (expp, pc, 0, 4,
3508 exp->elts[pc + 2].symbol,
3509 exp->elts[pc + 1].block);
3510 exp = expp->get ();
3511 }
3512 break;
3513
3514 case OP_FUNCALL:
3515 {
3516 if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
3517 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
3518 {
3519 std::vector<struct block_symbol> candidates;
3520 int n_candidates;
3521
3522 n_candidates =
3523 ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
3524 (exp->elts[pc + 5].symbol),
3525 exp->elts[pc + 4].block, VAR_DOMAIN,
3526 &candidates);
3527
3528 if (n_candidates == 1)
3529 i = 0;
3530 else
3531 {
3532 i = ada_resolve_function
3533 (candidates.data (), n_candidates,
3534 argvec, nargs,
3535 SYMBOL_LINKAGE_NAME (exp->elts[pc + 5].symbol),
3536 context_type, parse_completion);
3537 if (i < 0)
3538 error (_("Could not find a match for %s"),
3539 SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
3540 }
3541
3542 exp->elts[pc + 4].block = candidates[i].block;
3543 exp->elts[pc + 5].symbol = candidates[i].symbol;
3544 tracker->update (candidates[i]);
3545 }
3546 }
3547 break;
3548 case BINOP_ADD:
3549 case BINOP_SUB:
3550 case BINOP_MUL:
3551 case BINOP_DIV:
3552 case BINOP_REM:
3553 case BINOP_MOD:
3554 case BINOP_CONCAT:
3555 case BINOP_BITWISE_AND:
3556 case BINOP_BITWISE_IOR:
3557 case BINOP_BITWISE_XOR:
3558 case BINOP_EQUAL:
3559 case BINOP_NOTEQUAL:
3560 case BINOP_LESS:
3561 case BINOP_GTR:
3562 case BINOP_LEQ:
3563 case BINOP_GEQ:
3564 case BINOP_EXP:
3565 case UNOP_NEG:
3566 case UNOP_PLUS:
3567 case UNOP_LOGICAL_NOT:
3568 case UNOP_ABS:
3569 if (possible_user_operator_p (op, argvec))
3570 {
3571 std::vector<struct block_symbol> candidates;
3572 int n_candidates;
3573
3574 n_candidates =
3575 ada_lookup_symbol_list (ada_decoded_op_name (op),
3576 NULL, VAR_DOMAIN,
3577 &candidates);
3578
3579 i = ada_resolve_function (candidates.data (), n_candidates, argvec,
3580 nargs, ada_decoded_op_name (op), NULL,
3581 parse_completion);
3582 if (i < 0)
3583 break;
3584
3585 replace_operator_with_call (expp, pc, nargs, 1,
3586 candidates[i].symbol,
3587 candidates[i].block);
3588 exp = expp->get ();
3589 }
3590 break;
3591
3592 case OP_TYPE:
3593 case OP_REGISTER:
3594 return NULL;
3595 }
3596
3597 *pos = pc;
3598 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
3599 return evaluate_var_msym_value (EVAL_AVOID_SIDE_EFFECTS,
3600 exp->elts[pc + 1].objfile,
3601 exp->elts[pc + 2].msymbol);
3602 else
3603 return evaluate_subexp_type (exp, pos);
3604 }
3605
3606 /* Return non-zero if formal type FTYPE matches actual type ATYPE. If
3607 MAY_DEREF is non-zero, the formal may be a pointer and the actual
3608 a non-pointer. */
3609 /* The term "match" here is rather loose. The match is heuristic and
3610 liberal. */
3611
3612 static int
3613 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
3614 {
3615 ftype = ada_check_typedef (ftype);
3616 atype = ada_check_typedef (atype);
3617
3618 if (TYPE_CODE (ftype) == TYPE_CODE_REF)
3619 ftype = TYPE_TARGET_TYPE (ftype);
3620 if (TYPE_CODE (atype) == TYPE_CODE_REF)
3621 atype = TYPE_TARGET_TYPE (atype);
3622
3623 switch (TYPE_CODE (ftype))
3624 {
3625 default:
3626 return TYPE_CODE (ftype) == TYPE_CODE (atype);
3627 case TYPE_CODE_PTR:
3628 if (TYPE_CODE (atype) == TYPE_CODE_PTR)
3629 return ada_type_match (TYPE_TARGET_TYPE (ftype),
3630 TYPE_TARGET_TYPE (atype), 0);
3631 else
3632 return (may_deref
3633 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
3634 case TYPE_CODE_INT:
3635 case TYPE_CODE_ENUM:
3636 case TYPE_CODE_RANGE:
3637 switch (TYPE_CODE (atype))
3638 {
3639 case TYPE_CODE_INT:
3640 case TYPE_CODE_ENUM:
3641 case TYPE_CODE_RANGE:
3642 return 1;
3643 default:
3644 return 0;
3645 }
3646
3647 case TYPE_CODE_ARRAY:
3648 return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
3649 || ada_is_array_descriptor_type (atype));
3650
3651 case TYPE_CODE_STRUCT:
3652 if (ada_is_array_descriptor_type (ftype))
3653 return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
3654 || ada_is_array_descriptor_type (atype));
3655 else
3656 return (TYPE_CODE (atype) == TYPE_CODE_STRUCT
3657 && !ada_is_array_descriptor_type (atype));
3658
3659 case TYPE_CODE_UNION:
3660 case TYPE_CODE_FLT:
3661 return (TYPE_CODE (atype) == TYPE_CODE (ftype));
3662 }
3663 }
3664
3665 /* Return non-zero if the formals of FUNC "sufficiently match" the
3666 vector of actual argument types ACTUALS of size N_ACTUALS. FUNC
3667 may also be an enumeral, in which case it is treated as a 0-
3668 argument function. */
3669
3670 static int
3671 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3672 {
3673 int i;
3674 struct type *func_type = SYMBOL_TYPE (func);
3675
3676 if (SYMBOL_CLASS (func) == LOC_CONST
3677 && TYPE_CODE (func_type) == TYPE_CODE_ENUM)
3678 return (n_actuals == 0);
3679 else if (func_type == NULL || TYPE_CODE (func_type) != TYPE_CODE_FUNC)
3680 return 0;
3681
3682 if (TYPE_NFIELDS (func_type) != n_actuals)
3683 return 0;
3684
3685 for (i = 0; i < n_actuals; i += 1)
3686 {
3687 if (actuals[i] == NULL)
3688 return 0;
3689 else
3690 {
3691 struct type *ftype = ada_check_typedef (TYPE_FIELD_TYPE (func_type,
3692 i));
3693 struct type *atype = ada_check_typedef (value_type (actuals[i]));
3694
3695 if (!ada_type_match (ftype, atype, 1))
3696 return 0;
3697 }
3698 }
3699 return 1;
3700 }
3701
3702 /* False iff function type FUNC_TYPE definitely does not produce a value
3703 compatible with type CONTEXT_TYPE. Conservatively returns 1 if
3704 FUNC_TYPE is not a valid function type with a non-null return type
3705 or an enumerated type. A null CONTEXT_TYPE indicates any non-void type. */
3706
3707 static int
3708 return_match (struct type *func_type, struct type *context_type)
3709 {
3710 struct type *return_type;
3711
3712 if (func_type == NULL)
3713 return 1;
3714
3715 if (TYPE_CODE (func_type) == TYPE_CODE_FUNC)
3716 return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
3717 else
3718 return_type = get_base_type (func_type);
3719 if (return_type == NULL)
3720 return 1;
3721
3722 context_type = get_base_type (context_type);
3723
3724 if (TYPE_CODE (return_type) == TYPE_CODE_ENUM)
3725 return context_type == NULL || return_type == context_type;
3726 else if (context_type == NULL)
3727 return TYPE_CODE (return_type) != TYPE_CODE_VOID;
3728 else
3729 return TYPE_CODE (return_type) == TYPE_CODE (context_type);
3730 }
3731
3732
3733 /* Returns the index in SYMS[0..NSYMS-1] that contains the symbol for the
3734 function (if any) that matches the types of the NARGS arguments in
3735 ARGS. If CONTEXT_TYPE is non-null and there is at least one match
3736 that returns that type, then eliminate matches that don't. If
3737 CONTEXT_TYPE is void and there is at least one match that does not
3738 return void, eliminate all matches that do.
3739
3740 Asks the user if there is more than one match remaining. Returns -1
3741 if there is no such symbol or none is selected. NAME is used
3742 solely for messages. May re-arrange and modify SYMS in
3743 the process; the index returned is for the modified vector. */
3744
3745 static int
3746 ada_resolve_function (struct block_symbol syms[],
3747 int nsyms, struct value **args, int nargs,
3748 const char *name, struct type *context_type,
3749 int parse_completion)
3750 {
3751 int fallback;
3752 int k;
3753 int m; /* Number of hits */
3754
3755 m = 0;
3756 /* In the first pass of the loop, we only accept functions matching
3757 context_type. If none are found, we add a second pass of the loop
3758 where every function is accepted. */
3759 for (fallback = 0; m == 0 && fallback < 2; fallback++)
3760 {
3761 for (k = 0; k < nsyms; k += 1)
3762 {
3763 struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].symbol));
3764
3765 if (ada_args_match (syms[k].symbol, args, nargs)
3766 && (fallback || return_match (type, context_type)))
3767 {
3768 syms[m] = syms[k];
3769 m += 1;
3770 }
3771 }
3772 }
3773
3774 /* If we got multiple matches, ask the user which one to use. Don't do this
3775 interactive thing during completion, though, as the purpose of the
3776 completion is providing a list of all possible matches. Prompting the
3777 user to filter it down would be completely unexpected in this case. */
3778 if (m == 0)
3779 return -1;
3780 else if (m > 1 && !parse_completion)
3781 {
3782 printf_filtered (_("Multiple matches for %s\n"), name);
3783 user_select_syms (syms, m, 1);
3784 return 0;
3785 }
3786 return 0;
3787 }
3788
3789 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3790 in a listing of choices during disambiguation (see sort_choices, below).
3791 The idea is that overloadings of a subprogram name from the
3792 same package should sort in their source order. We settle for ordering
3793 such symbols by their trailing number (__N or $N). */
3794
3795 static int
3796 encoded_ordered_before (const char *N0, const char *N1)
3797 {
3798 if (N1 == NULL)
3799 return 0;
3800 else if (N0 == NULL)
3801 return 1;
3802 else
3803 {
3804 int k0, k1;
3805
3806 for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3807 ;
3808 for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3809 ;
3810 if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3811 && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3812 {
3813 int n0, n1;
3814
3815 n0 = k0;
3816 while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3817 n0 -= 1;
3818 n1 = k1;
3819 while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3820 n1 -= 1;
3821 if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3822 return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3823 }
3824 return (strcmp (N0, N1) < 0);
3825 }
3826 }
3827
3828 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3829 encoded names. */
3830
3831 static void
3832 sort_choices (struct block_symbol syms[], int nsyms)
3833 {
3834 int i;
3835
3836 for (i = 1; i < nsyms; i += 1)
3837 {
3838 struct block_symbol sym = syms[i];
3839 int j;
3840
3841 for (j = i - 1; j >= 0; j -= 1)
3842 {
3843 if (encoded_ordered_before (SYMBOL_LINKAGE_NAME (syms[j].symbol),
3844 SYMBOL_LINKAGE_NAME (sym.symbol)))
3845 break;
3846 syms[j + 1] = syms[j];
3847 }
3848 syms[j + 1] = sym;
3849 }
3850 }
3851
3852 /* Whether GDB should display formals and return types for functions in the
3853 overloads selection menu. */
3854 static int print_signatures = 1;
3855
3856 /* Print the signature for SYM on STREAM according to the FLAGS options. For
3857 all but functions, the signature is just the name of the symbol. For
3858 functions, this is the name of the function, the list of types for formals
3859 and the return type (if any). */
3860
3861 static void
3862 ada_print_symbol_signature (struct ui_file *stream, struct symbol *sym,
3863 const struct type_print_options *flags)
3864 {
3865 struct type *type = SYMBOL_TYPE (sym);
3866
3867 fprintf_filtered (stream, "%s", SYMBOL_PRINT_NAME (sym));
3868 if (!print_signatures
3869 || type == NULL
3870 || TYPE_CODE (type) != TYPE_CODE_FUNC)
3871 return;
3872
3873 if (TYPE_NFIELDS (type) > 0)
3874 {
3875 int i;
3876
3877 fprintf_filtered (stream, " (");
3878 for (i = 0; i < TYPE_NFIELDS (type); ++i)
3879 {
3880 if (i > 0)
3881 fprintf_filtered (stream, "; ");
3882 ada_print_type (TYPE_FIELD_TYPE (type, i), NULL, stream, -1, 0,
3883 flags);
3884 }
3885 fprintf_filtered (stream, ")");
3886 }
3887 if (TYPE_TARGET_TYPE (type) != NULL
3888 && TYPE_CODE (TYPE_TARGET_TYPE (type)) != TYPE_CODE_VOID)
3889 {
3890 fprintf_filtered (stream, " return ");
3891 ada_print_type (TYPE_TARGET_TYPE (type), NULL, stream, -1, 0, flags);
3892 }
3893 }
3894
3895 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0
3896 by asking the user (if necessary), returning the number selected,
3897 and setting the first elements of SYMS items. Error if no symbols
3898 selected. */
3899
3900 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3901 to be re-integrated one of these days. */
3902
3903 int
3904 user_select_syms (struct block_symbol *syms, int nsyms, int max_results)
3905 {
3906 int i;
3907 int *chosen = XALLOCAVEC (int , nsyms);
3908 int n_chosen;
3909 int first_choice = (max_results == 1) ? 1 : 2;
3910 const char *select_mode = multiple_symbols_select_mode ();
3911
3912 if (max_results < 1)
3913 error (_("Request to select 0 symbols!"));
3914 if (nsyms <= 1)
3915 return nsyms;
3916
3917 if (select_mode == multiple_symbols_cancel)
3918 error (_("\
3919 canceled because the command is ambiguous\n\
3920 See set/show multiple-symbol."));
3921
3922 /* If select_mode is "all", then return all possible symbols.
3923 Only do that if more than one symbol can be selected, of course.
3924 Otherwise, display the menu as usual. */
3925 if (select_mode == multiple_symbols_all && max_results > 1)
3926 return nsyms;
3927
3928 printf_filtered (_("[0] cancel\n"));
3929 if (max_results > 1)
3930 printf_filtered (_("[1] all\n"));
3931
3932 sort_choices (syms, nsyms);
3933
3934 for (i = 0; i < nsyms; i += 1)
3935 {
3936 if (syms[i].symbol == NULL)
3937 continue;
3938
3939 if (SYMBOL_CLASS (syms[i].symbol) == LOC_BLOCK)
3940 {
3941 struct symtab_and_line sal =
3942 find_function_start_sal (syms[i].symbol, 1);
3943
3944 printf_filtered ("[%d] ", i + first_choice);
3945 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3946 &type_print_raw_options);
3947 if (sal.symtab == NULL)
3948 printf_filtered (_(" at <no source file available>:%d\n"),
3949 sal.line);
3950 else
3951 printf_filtered (_(" at %s:%d\n"),
3952 symtab_to_filename_for_display (sal.symtab),
3953 sal.line);
3954 continue;
3955 }
3956 else
3957 {
3958 int is_enumeral =
3959 (SYMBOL_CLASS (syms[i].symbol) == LOC_CONST
3960 && SYMBOL_TYPE (syms[i].symbol) != NULL
3961 && TYPE_CODE (SYMBOL_TYPE (syms[i].symbol)) == TYPE_CODE_ENUM);
3962 struct symtab *symtab = NULL;
3963
3964 if (SYMBOL_OBJFILE_OWNED (syms[i].symbol))
3965 symtab = symbol_symtab (syms[i].symbol);
3966
3967 if (SYMBOL_LINE (syms[i].symbol) != 0 && symtab != NULL)
3968 {
3969 printf_filtered ("[%d] ", i + first_choice);
3970 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3971 &type_print_raw_options);
3972 printf_filtered (_(" at %s:%d\n"),
3973 symtab_to_filename_for_display (symtab),
3974 SYMBOL_LINE (syms[i].symbol));
3975 }
3976 else if (is_enumeral
3977 && TYPE_NAME (SYMBOL_TYPE (syms[i].symbol)) != NULL)
3978 {
3979 printf_filtered (("[%d] "), i + first_choice);
3980 ada_print_type (SYMBOL_TYPE (syms[i].symbol), NULL,
3981 gdb_stdout, -1, 0, &type_print_raw_options);
3982 printf_filtered (_("'(%s) (enumeral)\n"),
3983 SYMBOL_PRINT_NAME (syms[i].symbol));
3984 }
3985 else
3986 {
3987 printf_filtered ("[%d] ", i + first_choice);
3988 ada_print_symbol_signature (gdb_stdout, syms[i].symbol,
3989 &type_print_raw_options);
3990
3991 if (symtab != NULL)
3992 printf_filtered (is_enumeral
3993 ? _(" in %s (enumeral)\n")
3994 : _(" at %s:?\n"),
3995 symtab_to_filename_for_display (symtab));
3996 else
3997 printf_filtered (is_enumeral
3998 ? _(" (enumeral)\n")
3999 : _(" at ?\n"));
4000 }
4001 }
4002 }
4003
4004 n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
4005 "overload-choice");
4006
4007 for (i = 0; i < n_chosen; i += 1)
4008 syms[i] = syms[chosen[i]];
4009
4010 return n_chosen;
4011 }
4012
4013 /* Read and validate a set of numeric choices from the user in the
4014 range 0 .. N_CHOICES-1. Place the results in increasing
4015 order in CHOICES[0 .. N-1], and return N.
4016
4017 The user types choices as a sequence of numbers on one line
4018 separated by blanks, encoding them as follows:
4019
4020 + A choice of 0 means to cancel the selection, throwing an error.
4021 + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
4022 + The user chooses k by typing k+IS_ALL_CHOICE+1.
4023
4024 The user is not allowed to choose more than MAX_RESULTS values.
4025
4026 ANNOTATION_SUFFIX, if present, is used to annotate the input
4027 prompts (for use with the -f switch). */
4028
4029 int
4030 get_selections (int *choices, int n_choices, int max_results,
4031 int is_all_choice, const char *annotation_suffix)
4032 {
4033 char *args;
4034 const char *prompt;
4035 int n_chosen;
4036 int first_choice = is_all_choice ? 2 : 1;
4037
4038 prompt = getenv ("PS2");
4039 if (prompt == NULL)
4040 prompt = "> ";
4041
4042 args = command_line_input (prompt, annotation_suffix);
4043
4044 if (args == NULL)
4045 error_no_arg (_("one or more choice numbers"));
4046
4047 n_chosen = 0;
4048
4049 /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
4050 order, as given in args. Choices are validated. */
4051 while (1)
4052 {
4053 char *args2;
4054 int choice, j;
4055
4056 args = skip_spaces (args);
4057 if (*args == '\0' && n_chosen == 0)
4058 error_no_arg (_("one or more choice numbers"));
4059 else if (*args == '\0')
4060 break;
4061
4062 choice = strtol (args, &args2, 10);
4063 if (args == args2 || choice < 0
4064 || choice > n_choices + first_choice - 1)
4065 error (_("Argument must be choice number"));
4066 args = args2;
4067
4068 if (choice == 0)
4069 error (_("cancelled"));
4070
4071 if (choice < first_choice)
4072 {
4073 n_chosen = n_choices;
4074 for (j = 0; j < n_choices; j += 1)
4075 choices[j] = j;
4076 break;
4077 }
4078 choice -= first_choice;
4079
4080 for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
4081 {
4082 }
4083
4084 if (j < 0 || choice != choices[j])
4085 {
4086 int k;
4087
4088 for (k = n_chosen - 1; k > j; k -= 1)
4089 choices[k + 1] = choices[k];
4090 choices[j + 1] = choice;
4091 n_chosen += 1;
4092 }
4093 }
4094
4095 if (n_chosen > max_results)
4096 error (_("Select no more than %d of the above"), max_results);
4097
4098 return n_chosen;
4099 }
4100
4101 /* Replace the operator of length OPLEN at position PC in *EXPP with a call
4102 on the function identified by SYM and BLOCK, and taking NARGS
4103 arguments. Update *EXPP as needed to hold more space. */
4104
4105 static void
4106 replace_operator_with_call (expression_up *expp, int pc, int nargs,
4107 int oplen, struct symbol *sym,
4108 const struct block *block)
4109 {
4110 /* A new expression, with 6 more elements (3 for funcall, 4 for function
4111 symbol, -oplen for operator being replaced). */
4112 struct expression *newexp = (struct expression *)
4113 xzalloc (sizeof (struct expression)
4114 + EXP_ELEM_TO_BYTES ((*expp)->nelts + 7 - oplen));
4115 struct expression *exp = expp->get ();
4116
4117 newexp->nelts = exp->nelts + 7 - oplen;
4118 newexp->language_defn = exp->language_defn;
4119 newexp->gdbarch = exp->gdbarch;
4120 memcpy (newexp->elts, exp->elts, EXP_ELEM_TO_BYTES (pc));
4121 memcpy (newexp->elts + pc + 7, exp->elts + pc + oplen,
4122 EXP_ELEM_TO_BYTES (exp->nelts - pc - oplen));
4123
4124 newexp->elts[pc].opcode = newexp->elts[pc + 2].opcode = OP_FUNCALL;
4125 newexp->elts[pc + 1].longconst = (LONGEST) nargs;
4126
4127 newexp->elts[pc + 3].opcode = newexp->elts[pc + 6].opcode = OP_VAR_VALUE;
4128 newexp->elts[pc + 4].block = block;
4129 newexp->elts[pc + 5].symbol = sym;
4130
4131 expp->reset (newexp);
4132 }
4133
4134 /* Type-class predicates */
4135
4136 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
4137 or FLOAT). */
4138
4139 static int
4140 numeric_type_p (struct type *type)
4141 {
4142 if (type == NULL)
4143 return 0;
4144 else
4145 {
4146 switch (TYPE_CODE (type))
4147 {
4148 case TYPE_CODE_INT:
4149 case TYPE_CODE_FLT:
4150 return 1;
4151 case TYPE_CODE_RANGE:
4152 return (type == TYPE_TARGET_TYPE (type)
4153 || numeric_type_p (TYPE_TARGET_TYPE (type)));
4154 default:
4155 return 0;
4156 }
4157 }
4158 }
4159
4160 /* True iff TYPE is integral (an INT or RANGE of INTs). */
4161
4162 static int
4163 integer_type_p (struct type *type)
4164 {
4165 if (type == NULL)
4166 return 0;
4167 else
4168 {
4169 switch (TYPE_CODE (type))
4170 {
4171 case TYPE_CODE_INT:
4172 return 1;
4173 case TYPE_CODE_RANGE:
4174 return (type == TYPE_TARGET_TYPE (type)
4175 || integer_type_p (TYPE_TARGET_TYPE (type)));
4176 default:
4177 return 0;
4178 }
4179 }
4180 }
4181
4182 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM). */
4183
4184 static int
4185 scalar_type_p (struct type *type)
4186 {
4187 if (type == NULL)
4188 return 0;
4189 else
4190 {
4191 switch (TYPE_CODE (type))
4192 {
4193 case TYPE_CODE_INT:
4194 case TYPE_CODE_RANGE:
4195 case TYPE_CODE_ENUM:
4196 case TYPE_CODE_FLT:
4197 return 1;
4198 default:
4199 return 0;
4200 }
4201 }
4202 }
4203
4204 /* True iff TYPE is discrete (INT, RANGE, ENUM). */
4205
4206 static int
4207 discrete_type_p (struct type *type)
4208 {
4209 if (type == NULL)
4210 return 0;
4211 else
4212 {
4213 switch (TYPE_CODE (type))
4214 {
4215 case TYPE_CODE_INT:
4216 case TYPE_CODE_RANGE:
4217 case TYPE_CODE_ENUM:
4218 case TYPE_CODE_BOOL:
4219 return 1;
4220 default:
4221 return 0;
4222 }
4223 }
4224 }
4225
4226 /* Returns non-zero if OP with operands in the vector ARGS could be
4227 a user-defined function. Errs on the side of pre-defined operators
4228 (i.e., result 0). */
4229
4230 static int
4231 possible_user_operator_p (enum exp_opcode op, struct value *args[])
4232 {
4233 struct type *type0 =
4234 (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
4235 struct type *type1 =
4236 (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
4237
4238 if (type0 == NULL)
4239 return 0;
4240
4241 switch (op)
4242 {
4243 default:
4244 return 0;
4245
4246 case BINOP_ADD:
4247 case BINOP_SUB:
4248 case BINOP_MUL:
4249 case BINOP_DIV:
4250 return (!(numeric_type_p (type0) && numeric_type_p (type1)));
4251
4252 case BINOP_REM:
4253 case BINOP_MOD:
4254 case BINOP_BITWISE_AND:
4255 case BINOP_BITWISE_IOR:
4256 case BINOP_BITWISE_XOR:
4257 return (!(integer_type_p (type0) && integer_type_p (type1)));
4258
4259 case BINOP_EQUAL:
4260 case BINOP_NOTEQUAL:
4261 case BINOP_LESS:
4262 case BINOP_GTR:
4263 case BINOP_LEQ:
4264 case BINOP_GEQ:
4265 return (!(scalar_type_p (type0) && scalar_type_p (type1)));
4266
4267 case BINOP_CONCAT:
4268 return !ada_is_array_type (type0) || !ada_is_array_type (type1);
4269
4270 case BINOP_EXP:
4271 return (!(numeric_type_p (type0) && integer_type_p (type1)));
4272
4273 case UNOP_NEG:
4274 case UNOP_PLUS:
4275 case UNOP_LOGICAL_NOT:
4276 case UNOP_ABS:
4277 return (!numeric_type_p (type0));
4278
4279 }
4280 }
4281 \f
4282 /* Renaming */
4283
4284 /* NOTES:
4285
4286 1. In the following, we assume that a renaming type's name may
4287 have an ___XD suffix. It would be nice if this went away at some
4288 point.
4289 2. We handle both the (old) purely type-based representation of
4290 renamings and the (new) variable-based encoding. At some point,
4291 it is devoutly to be hoped that the former goes away
4292 (FIXME: hilfinger-2007-07-09).
4293 3. Subprogram renamings are not implemented, although the XRS
4294 suffix is recognized (FIXME: hilfinger-2007-07-09). */
4295
4296 /* If SYM encodes a renaming,
4297
4298 <renaming> renames <renamed entity>,
4299
4300 sets *LEN to the length of the renamed entity's name,
4301 *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
4302 the string describing the subcomponent selected from the renamed
4303 entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
4304 (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
4305 are undefined). Otherwise, returns a value indicating the category
4306 of entity renamed: an object (ADA_OBJECT_RENAMING), exception
4307 (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
4308 subprogram (ADA_SUBPROGRAM_RENAMING). Does no allocation; the
4309 strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
4310 deallocated. The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
4311 may be NULL, in which case they are not assigned.
4312
4313 [Currently, however, GCC does not generate subprogram renamings.] */
4314
4315 enum ada_renaming_category
4316 ada_parse_renaming (struct symbol *sym,
4317 const char **renamed_entity, int *len,
4318 const char **renaming_expr)
4319 {
4320 enum ada_renaming_category kind;
4321 const char *info;
4322 const char *suffix;
4323
4324 if (sym == NULL)
4325 return ADA_NOT_RENAMING;
4326 switch (SYMBOL_CLASS (sym))
4327 {
4328 default:
4329 return ADA_NOT_RENAMING;
4330 case LOC_TYPEDEF:
4331 return parse_old_style_renaming (SYMBOL_TYPE (sym),
4332 renamed_entity, len, renaming_expr);
4333 case LOC_LOCAL:
4334 case LOC_STATIC:
4335 case LOC_COMPUTED:
4336 case LOC_OPTIMIZED_OUT:
4337 info = strstr (SYMBOL_LINKAGE_NAME (sym), "___XR");
4338 if (info == NULL)
4339 return ADA_NOT_RENAMING;
4340 switch (info[5])
4341 {
4342 case '_':
4343 kind = ADA_OBJECT_RENAMING;
4344 info += 6;
4345 break;
4346 case 'E':
4347 kind = ADA_EXCEPTION_RENAMING;
4348 info += 7;
4349 break;
4350 case 'P':
4351 kind = ADA_PACKAGE_RENAMING;
4352 info += 7;
4353 break;
4354 case 'S':
4355 kind = ADA_SUBPROGRAM_RENAMING;
4356 info += 7;
4357 break;
4358 default:
4359 return ADA_NOT_RENAMING;
4360 }
4361 }
4362
4363 if (renamed_entity != NULL)
4364 *renamed_entity = info;
4365 suffix = strstr (info, "___XE");
4366 if (suffix == NULL || suffix == info)
4367 return ADA_NOT_RENAMING;
4368 if (len != NULL)
4369 *len = strlen (info) - strlen (suffix);
4370 suffix += 5;
4371 if (renaming_expr != NULL)
4372 *renaming_expr = suffix;
4373 return kind;
4374 }
4375
4376 /* Assuming TYPE encodes a renaming according to the old encoding in
4377 exp_dbug.ads, returns details of that renaming in *RENAMED_ENTITY,
4378 *LEN, and *RENAMING_EXPR, as for ada_parse_renaming, above. Returns
4379 ADA_NOT_RENAMING otherwise. */
4380 static enum ada_renaming_category
4381 parse_old_style_renaming (struct type *type,
4382 const char **renamed_entity, int *len,
4383 const char **renaming_expr)
4384 {
4385 enum ada_renaming_category kind;
4386 const char *name;
4387 const char *info;
4388 const char *suffix;
4389
4390 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
4391 || TYPE_NFIELDS (type) != 1)
4392 return ADA_NOT_RENAMING;
4393
4394 name = TYPE_NAME (type);
4395 if (name == NULL)
4396 return ADA_NOT_RENAMING;
4397
4398 name = strstr (name, "___XR");
4399 if (name == NULL)
4400 return ADA_NOT_RENAMING;
4401 switch (name[5])
4402 {
4403 case '\0':
4404 case '_':
4405 kind = ADA_OBJECT_RENAMING;
4406 break;
4407 case 'E':
4408 kind = ADA_EXCEPTION_RENAMING;
4409 break;
4410 case 'P':
4411 kind = ADA_PACKAGE_RENAMING;
4412 break;
4413 case 'S':
4414 kind = ADA_SUBPROGRAM_RENAMING;
4415 break;
4416 default:
4417 return ADA_NOT_RENAMING;
4418 }
4419
4420 info = TYPE_FIELD_NAME (type, 0);
4421 if (info == NULL)
4422 return ADA_NOT_RENAMING;
4423 if (renamed_entity != NULL)
4424 *renamed_entity = info;
4425 suffix = strstr (info, "___XE");
4426 if (renaming_expr != NULL)
4427 *renaming_expr = suffix + 5;
4428 if (suffix == NULL || suffix == info)
4429 return ADA_NOT_RENAMING;
4430 if (len != NULL)
4431 *len = suffix - info;
4432 return kind;
4433 }
4434
4435 /* Compute the value of the given RENAMING_SYM, which is expected to
4436 be a symbol encoding a renaming expression. BLOCK is the block
4437 used to evaluate the renaming. */
4438
4439 static struct value *
4440 ada_read_renaming_var_value (struct symbol *renaming_sym,
4441 const struct block *block)
4442 {
4443 const char *sym_name;
4444
4445 sym_name = SYMBOL_LINKAGE_NAME (renaming_sym);
4446 expression_up expr = parse_exp_1 (&sym_name, 0, block, 0);
4447 return evaluate_expression (expr.get ());
4448 }
4449 \f
4450
4451 /* Evaluation: Function Calls */
4452
4453 /* Return an lvalue containing the value VAL. This is the identity on
4454 lvalues, and otherwise has the side-effect of allocating memory
4455 in the inferior where a copy of the value contents is copied. */
4456
4457 static struct value *
4458 ensure_lval (struct value *val)
4459 {
4460 if (VALUE_LVAL (val) == not_lval
4461 || VALUE_LVAL (val) == lval_internalvar)
4462 {
4463 int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
4464 const CORE_ADDR addr =
4465 value_as_long (value_allocate_space_in_inferior (len));
4466
4467 VALUE_LVAL (val) = lval_memory;
4468 set_value_address (val, addr);
4469 write_memory (addr, value_contents (val), len);
4470 }
4471
4472 return val;
4473 }
4474
4475 /* Return the value ACTUAL, converted to be an appropriate value for a
4476 formal of type FORMAL_TYPE. Use *SP as a stack pointer for
4477 allocating any necessary descriptors (fat pointers), or copies of
4478 values not residing in memory, updating it as needed. */
4479
4480 struct value *
4481 ada_convert_actual (struct value *actual, struct type *formal_type0)
4482 {
4483 struct type *actual_type = ada_check_typedef (value_type (actual));
4484 struct type *formal_type = ada_check_typedef (formal_type0);
4485 struct type *formal_target =
4486 TYPE_CODE (formal_type) == TYPE_CODE_PTR
4487 ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
4488 struct type *actual_target =
4489 TYPE_CODE (actual_type) == TYPE_CODE_PTR
4490 ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
4491
4492 if (ada_is_array_descriptor_type (formal_target)
4493 && TYPE_CODE (actual_target) == TYPE_CODE_ARRAY)
4494 return make_array_descriptor (formal_type, actual);
4495 else if (TYPE_CODE (formal_type) == TYPE_CODE_PTR
4496 || TYPE_CODE (formal_type) == TYPE_CODE_REF)
4497 {
4498 struct value *result;
4499
4500 if (TYPE_CODE (formal_target) == TYPE_CODE_ARRAY
4501 && ada_is_array_descriptor_type (actual_target))
4502 result = desc_data (actual);
4503 else if (TYPE_CODE (formal_type) != TYPE_CODE_PTR)
4504 {
4505 if (VALUE_LVAL (actual) != lval_memory)
4506 {
4507 struct value *val;
4508
4509 actual_type = ada_check_typedef (value_type (actual));
4510 val = allocate_value (actual_type);
4511 memcpy ((char *) value_contents_raw (val),
4512 (char *) value_contents (actual),
4513 TYPE_LENGTH (actual_type));
4514 actual = ensure_lval (val);
4515 }
4516 result = value_addr (actual);
4517 }
4518 else
4519 return actual;
4520 return value_cast_pointers (formal_type, result, 0);
4521 }
4522 else if (TYPE_CODE (actual_type) == TYPE_CODE_PTR)
4523 return ada_value_ind (actual);
4524 else if (ada_is_aligner_type (formal_type))
4525 {
4526 /* We need to turn this parameter into an aligner type
4527 as well. */
4528 struct value *aligner = allocate_value (formal_type);
4529 struct value *component = ada_value_struct_elt (aligner, "F", 0);
4530
4531 value_assign_to_component (aligner, component, actual);
4532 return aligner;
4533 }
4534
4535 return actual;
4536 }
4537
4538 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
4539 type TYPE. This is usually an inefficient no-op except on some targets
4540 (such as AVR) where the representation of a pointer and an address
4541 differs. */
4542
4543 static CORE_ADDR
4544 value_pointer (struct value *value, struct type *type)
4545 {
4546 struct gdbarch *gdbarch = get_type_arch (type);
4547 unsigned len = TYPE_LENGTH (type);
4548 gdb_byte *buf = (gdb_byte *) alloca (len);
4549 CORE_ADDR addr;
4550
4551 addr = value_address (value);
4552 gdbarch_address_to_pointer (gdbarch, type, buf, addr);
4553 addr = extract_unsigned_integer (buf, len, gdbarch_byte_order (gdbarch));
4554 return addr;
4555 }
4556
4557
4558 /* Push a descriptor of type TYPE for array value ARR on the stack at
4559 *SP, updating *SP to reflect the new descriptor. Return either
4560 an lvalue representing the new descriptor, or (if TYPE is a pointer-
4561 to-descriptor type rather than a descriptor type), a struct value *
4562 representing a pointer to this descriptor. */
4563
4564 static struct value *
4565 make_array_descriptor (struct type *type, struct value *arr)
4566 {
4567 struct type *bounds_type = desc_bounds_type (type);
4568 struct type *desc_type = desc_base_type (type);
4569 struct value *descriptor = allocate_value (desc_type);
4570 struct value *bounds = allocate_value (bounds_type);
4571 int i;
4572
4573 for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
4574 i > 0; i -= 1)
4575 {
4576 modify_field (value_type (bounds), value_contents_writeable (bounds),
4577 ada_array_bound (arr, i, 0),
4578 desc_bound_bitpos (bounds_type, i, 0),
4579 desc_bound_bitsize (bounds_type, i, 0));
4580 modify_field (value_type (bounds), value_contents_writeable (bounds),
4581 ada_array_bound (arr, i, 1),
4582 desc_bound_bitpos (bounds_type, i, 1),
4583 desc_bound_bitsize (bounds_type, i, 1));
4584 }
4585
4586 bounds = ensure_lval (bounds);
4587
4588 modify_field (value_type (descriptor),
4589 value_contents_writeable (descriptor),
4590 value_pointer (ensure_lval (arr),
4591 TYPE_FIELD_TYPE (desc_type, 0)),
4592 fat_pntr_data_bitpos (desc_type),
4593 fat_pntr_data_bitsize (desc_type));
4594
4595 modify_field (value_type (descriptor),
4596 value_contents_writeable (descriptor),
4597 value_pointer (bounds,
4598 TYPE_FIELD_TYPE (desc_type, 1)),
4599 fat_pntr_bounds_bitpos (desc_type),
4600 fat_pntr_bounds_bitsize (desc_type));
4601
4602 descriptor = ensure_lval (descriptor);
4603
4604 if (TYPE_CODE (type) == TYPE_CODE_PTR)
4605 return value_addr (descriptor);
4606 else
4607 return descriptor;
4608 }
4609 \f
4610 /* Symbol Cache Module */
4611
4612 /* Performance measurements made as of 2010-01-15 indicate that
4613 this cache does bring some noticeable improvements. Depending
4614 on the type of entity being printed, the cache can make it as much
4615 as an order of magnitude faster than without it.
4616
4617 The descriptive type DWARF extension has significantly reduced
4618 the need for this cache, at least when DWARF is being used. However,
4619 even in this case, some expensive name-based symbol searches are still
4620 sometimes necessary - to find an XVZ variable, mostly. */
4621
4622 /* Initialize the contents of SYM_CACHE. */
4623
4624 static void
4625 ada_init_symbol_cache (struct ada_symbol_cache *sym_cache)
4626 {
4627 obstack_init (&sym_cache->cache_space);
4628 memset (sym_cache->root, '\000', sizeof (sym_cache->root));
4629 }
4630
4631 /* Free the memory used by SYM_CACHE. */
4632
4633 static void
4634 ada_free_symbol_cache (struct ada_symbol_cache *sym_cache)
4635 {
4636 obstack_free (&sym_cache->cache_space, NULL);
4637 xfree (sym_cache);
4638 }
4639
4640 /* Return the symbol cache associated to the given program space PSPACE.
4641 If not allocated for this PSPACE yet, allocate and initialize one. */
4642
4643 static struct ada_symbol_cache *
4644 ada_get_symbol_cache (struct program_space *pspace)
4645 {
4646 struct ada_pspace_data *pspace_data = get_ada_pspace_data (pspace);
4647
4648 if (pspace_data->sym_cache == NULL)
4649 {
4650 pspace_data->sym_cache = XCNEW (struct ada_symbol_cache);
4651 ada_init_symbol_cache (pspace_data->sym_cache);
4652 }
4653
4654 return pspace_data->sym_cache;
4655 }
4656
4657 /* Clear all entries from the symbol cache. */
4658
4659 static void
4660 ada_clear_symbol_cache (void)
4661 {
4662 struct ada_symbol_cache *sym_cache
4663 = ada_get_symbol_cache (current_program_space);
4664
4665 obstack_free (&sym_cache->cache_space, NULL);
4666 ada_init_symbol_cache (sym_cache);
4667 }
4668
4669 /* Search our cache for an entry matching NAME and DOMAIN.
4670 Return it if found, or NULL otherwise. */
4671
4672 static struct cache_entry **
4673 find_entry (const char *name, domain_enum domain)
4674 {
4675 struct ada_symbol_cache *sym_cache
4676 = ada_get_symbol_cache (current_program_space);
4677 int h = msymbol_hash (name) % HASH_SIZE;
4678 struct cache_entry **e;
4679
4680 for (e = &sym_cache->root[h]; *e != NULL; e = &(*e)->next)
4681 {
4682 if (domain == (*e)->domain && strcmp (name, (*e)->name) == 0)
4683 return e;
4684 }
4685 return NULL;
4686 }
4687
4688 /* Search the symbol cache for an entry matching NAME and DOMAIN.
4689 Return 1 if found, 0 otherwise.
4690
4691 If an entry was found and SYM is not NULL, set *SYM to the entry's
4692 SYM. Same principle for BLOCK if not NULL. */
4693
4694 static int
4695 lookup_cached_symbol (const char *name, domain_enum domain,
4696 struct symbol **sym, const struct block **block)
4697 {
4698 struct cache_entry **e = find_entry (name, domain);
4699
4700 if (e == NULL)
4701 return 0;
4702 if (sym != NULL)
4703 *sym = (*e)->sym;
4704 if (block != NULL)
4705 *block = (*e)->block;
4706 return 1;
4707 }
4708
4709 /* Assuming that (SYM, BLOCK) is the result of the lookup of NAME
4710 in domain DOMAIN, save this result in our symbol cache. */
4711
4712 static void
4713 cache_symbol (const char *name, domain_enum domain, struct symbol *sym,
4714 const struct block *block)
4715 {
4716 struct ada_symbol_cache *sym_cache
4717 = ada_get_symbol_cache (current_program_space);
4718 int h;
4719 char *copy;
4720 struct cache_entry *e;
4721
4722 /* Symbols for builtin types don't have a block.
4723 For now don't cache such symbols. */
4724 if (sym != NULL && !SYMBOL_OBJFILE_OWNED (sym))
4725 return;
4726
4727 /* If the symbol is a local symbol, then do not cache it, as a search
4728 for that symbol depends on the context. To determine whether
4729 the symbol is local or not, we check the block where we found it
4730 against the global and static blocks of its associated symtab. */
4731 if (sym
4732 && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4733 GLOBAL_BLOCK) != block
4734 && BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symbol_symtab (sym)),
4735 STATIC_BLOCK) != block)
4736 return;
4737
4738 h = msymbol_hash (name) % HASH_SIZE;
4739 e = XOBNEW (&sym_cache->cache_space, cache_entry);
4740 e->next = sym_cache->root[h];
4741 sym_cache->root[h] = e;
4742 e->name = copy
4743 = (char *) obstack_alloc (&sym_cache->cache_space, strlen (name) + 1);
4744 strcpy (copy, name);
4745 e->sym = sym;
4746 e->domain = domain;
4747 e->block = block;
4748 }
4749 \f
4750 /* Symbol Lookup */
4751
4752 /* Return the symbol name match type that should be used used when
4753 searching for all symbols matching LOOKUP_NAME.
4754
4755 LOOKUP_NAME is expected to be a symbol name after transformation
4756 for Ada lookups. */
4757
4758 static symbol_name_match_type
4759 name_match_type_from_name (const char *lookup_name)
4760 {
4761 return (strstr (lookup_name, "__") == NULL
4762 ? symbol_name_match_type::WILD
4763 : symbol_name_match_type::FULL);
4764 }
4765
4766 /* Return the result of a standard (literal, C-like) lookup of NAME in
4767 given DOMAIN, visible from lexical block BLOCK. */
4768
4769 static struct symbol *
4770 standard_lookup (const char *name, const struct block *block,
4771 domain_enum domain)
4772 {
4773 /* Initialize it just to avoid a GCC false warning. */
4774 struct block_symbol sym = {};
4775
4776 if (lookup_cached_symbol (name, domain, &sym.symbol, NULL))
4777 return sym.symbol;
4778 ada_lookup_encoded_symbol (name, block, domain, &sym);
4779 cache_symbol (name, domain, sym.symbol, sym.block);
4780 return sym.symbol;
4781 }
4782
4783
4784 /* Non-zero iff there is at least one non-function/non-enumeral symbol
4785 in the symbol fields of SYMS[0..N-1]. We treat enumerals as functions,
4786 since they contend in overloading in the same way. */
4787 static int
4788 is_nonfunction (struct block_symbol syms[], int n)
4789 {
4790 int i;
4791
4792 for (i = 0; i < n; i += 1)
4793 if (TYPE_CODE (SYMBOL_TYPE (syms[i].symbol)) != TYPE_CODE_FUNC
4794 && (TYPE_CODE (SYMBOL_TYPE (syms[i].symbol)) != TYPE_CODE_ENUM
4795 || SYMBOL_CLASS (syms[i].symbol) != LOC_CONST))
4796 return 1;
4797
4798 return 0;
4799 }
4800
4801 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
4802 struct types. Otherwise, they may not. */
4803
4804 static int
4805 equiv_types (struct type *type0, struct type *type1)
4806 {
4807 if (type0 == type1)
4808 return 1;
4809 if (type0 == NULL || type1 == NULL
4810 || TYPE_CODE (type0) != TYPE_CODE (type1))
4811 return 0;
4812 if ((TYPE_CODE (type0) == TYPE_CODE_STRUCT
4813 || TYPE_CODE (type0) == TYPE_CODE_ENUM)
4814 && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
4815 && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
4816 return 1;
4817
4818 return 0;
4819 }
4820
4821 /* True iff SYM0 represents the same entity as SYM1, or one that is
4822 no more defined than that of SYM1. */
4823
4824 static int
4825 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
4826 {
4827 if (sym0 == sym1)
4828 return 1;
4829 if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
4830 || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
4831 return 0;
4832
4833 switch (SYMBOL_CLASS (sym0))
4834 {
4835 case LOC_UNDEF:
4836 return 1;
4837 case LOC_TYPEDEF:
4838 {
4839 struct type *type0 = SYMBOL_TYPE (sym0);
4840 struct type *type1 = SYMBOL_TYPE (sym1);
4841 const char *name0 = SYMBOL_LINKAGE_NAME (sym0);
4842 const char *name1 = SYMBOL_LINKAGE_NAME (sym1);
4843 int len0 = strlen (name0);
4844
4845 return
4846 TYPE_CODE (type0) == TYPE_CODE (type1)
4847 && (equiv_types (type0, type1)
4848 || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
4849 && startswith (name1 + len0, "___XV")));
4850 }
4851 case LOC_CONST:
4852 return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
4853 && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
4854 default:
4855 return 0;
4856 }
4857 }
4858
4859 /* Append (SYM,BLOCK,SYMTAB) to the end of the array of struct block_symbol
4860 records in OBSTACKP. Do nothing if SYM is a duplicate. */
4861
4862 static void
4863 add_defn_to_vec (struct obstack *obstackp,
4864 struct symbol *sym,
4865 const struct block *block)
4866 {
4867 int i;
4868 struct block_symbol *prevDefns = defns_collected (obstackp, 0);
4869
4870 /* Do not try to complete stub types, as the debugger is probably
4871 already scanning all symbols matching a certain name at the
4872 time when this function is called. Trying to replace the stub
4873 type by its associated full type will cause us to restart a scan
4874 which may lead to an infinite recursion. Instead, the client
4875 collecting the matching symbols will end up collecting several
4876 matches, with at least one of them complete. It can then filter
4877 out the stub ones if needed. */
4878
4879 for (i = num_defns_collected (obstackp) - 1; i >= 0; i -= 1)
4880 {
4881 if (lesseq_defined_than (sym, prevDefns[i].symbol))
4882 return;
4883 else if (lesseq_defined_than (prevDefns[i].symbol, sym))
4884 {
4885 prevDefns[i].symbol = sym;
4886 prevDefns[i].block = block;
4887 return;
4888 }
4889 }
4890
4891 {
4892 struct block_symbol info;
4893
4894 info.symbol = sym;
4895 info.block = block;
4896 obstack_grow (obstackp, &info, sizeof (struct block_symbol));
4897 }
4898 }
4899
4900 /* Number of block_symbol structures currently collected in current vector in
4901 OBSTACKP. */
4902
4903 static int
4904 num_defns_collected (struct obstack *obstackp)
4905 {
4906 return obstack_object_size (obstackp) / sizeof (struct block_symbol);
4907 }
4908
4909 /* Vector of block_symbol structures currently collected in current vector in
4910 OBSTACKP. If FINISH, close off the vector and return its final address. */
4911
4912 static struct block_symbol *
4913 defns_collected (struct obstack *obstackp, int finish)
4914 {
4915 if (finish)
4916 return (struct block_symbol *) obstack_finish (obstackp);
4917 else
4918 return (struct block_symbol *) obstack_base (obstackp);
4919 }
4920
4921 /* Return a bound minimal symbol matching NAME according to Ada
4922 decoding rules. Returns an invalid symbol if there is no such
4923 minimal symbol. Names prefixed with "standard__" are handled
4924 specially: "standard__" is first stripped off, and only static and
4925 global symbols are searched. */
4926
4927 struct bound_minimal_symbol
4928 ada_lookup_simple_minsym (const char *name)
4929 {
4930 struct bound_minimal_symbol result;
4931
4932 memset (&result, 0, sizeof (result));
4933
4934 symbol_name_match_type match_type = name_match_type_from_name (name);
4935 lookup_name_info lookup_name (name, match_type);
4936
4937 symbol_name_matcher_ftype *match_name
4938 = ada_get_symbol_name_matcher (lookup_name);
4939
4940 for (objfile *objfile : current_program_space->objfiles ())
4941 {
4942 for (minimal_symbol *msymbol : objfile->msymbols ())
4943 {
4944 if (match_name (MSYMBOL_LINKAGE_NAME (msymbol), lookup_name, NULL)
4945 && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4946 {
4947 result.minsym = msymbol;
4948 result.objfile = objfile;
4949 break;
4950 }
4951 }
4952 }
4953
4954 return result;
4955 }
4956
4957 /* For all subprograms that statically enclose the subprogram of the
4958 selected frame, add symbols matching identifier NAME in DOMAIN
4959 and their blocks to the list of data in OBSTACKP, as for
4960 ada_add_block_symbols (q.v.). If WILD_MATCH_P, treat as NAME
4961 with a wildcard prefix. */
4962
4963 static void
4964 add_symbols_from_enclosing_procs (struct obstack *obstackp,
4965 const lookup_name_info &lookup_name,
4966 domain_enum domain)
4967 {
4968 }
4969
4970 /* True if TYPE is definitely an artificial type supplied to a symbol
4971 for which no debugging information was given in the symbol file. */
4972
4973 static int
4974 is_nondebugging_type (struct type *type)
4975 {
4976 const char *name = ada_type_name (type);
4977
4978 return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4979 }
4980
4981 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
4982 that are deemed "identical" for practical purposes.
4983
4984 This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
4985 types and that their number of enumerals is identical (in other
4986 words, TYPE_NFIELDS (type1) == TYPE_NFIELDS (type2)). */
4987
4988 static int
4989 ada_identical_enum_types_p (struct type *type1, struct type *type2)
4990 {
4991 int i;
4992
4993 /* The heuristic we use here is fairly conservative. We consider
4994 that 2 enumerate types are identical if they have the same
4995 number of enumerals and that all enumerals have the same
4996 underlying value and name. */
4997
4998 /* All enums in the type should have an identical underlying value. */
4999 for (i = 0; i < TYPE_NFIELDS (type1); i++)
5000 if (TYPE_FIELD_ENUMVAL (type1, i) != TYPE_FIELD_ENUMVAL (type2, i))
5001 return 0;
5002
5003 /* All enumerals should also have the same name (modulo any numerical
5004 suffix). */
5005 for (i = 0; i < TYPE_NFIELDS (type1); i++)
5006 {
5007 const char *name_1 = TYPE_FIELD_NAME (type1, i);
5008 const char *name_2 = TYPE_FIELD_NAME (type2, i);
5009 int len_1 = strlen (name_1);
5010 int len_2 = strlen (name_2);
5011
5012 ada_remove_trailing_digits (TYPE_FIELD_NAME (type1, i), &len_1);
5013 ada_remove_trailing_digits (TYPE_FIELD_NAME (type2, i), &len_2);
5014 if (len_1 != len_2
5015 || strncmp (TYPE_FIELD_NAME (type1, i),
5016 TYPE_FIELD_NAME (type2, i),
5017 len_1) != 0)
5018 return 0;
5019 }
5020
5021 return 1;
5022 }
5023
5024 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
5025 that are deemed "identical" for practical purposes. Sometimes,
5026 enumerals are not strictly identical, but their types are so similar
5027 that they can be considered identical.
5028
5029 For instance, consider the following code:
5030
5031 type Color is (Black, Red, Green, Blue, White);
5032 type RGB_Color is new Color range Red .. Blue;
5033
5034 Type RGB_Color is a subrange of an implicit type which is a copy
5035 of type Color. If we call that implicit type RGB_ColorB ("B" is
5036 for "Base Type"), then type RGB_ColorB is a copy of type Color.
5037 As a result, when an expression references any of the enumeral
5038 by name (Eg. "print green"), the expression is technically
5039 ambiguous and the user should be asked to disambiguate. But
5040 doing so would only hinder the user, since it wouldn't matter
5041 what choice he makes, the outcome would always be the same.
5042 So, for practical purposes, we consider them as the same. */
5043
5044 static int
5045 symbols_are_identical_enums (const std::vector<struct block_symbol> &syms)
5046 {
5047 int i;
5048
5049 /* Before performing a thorough comparison check of each type,
5050 we perform a series of inexpensive checks. We expect that these
5051 checks will quickly fail in the vast majority of cases, and thus
5052 help prevent the unnecessary use of a more expensive comparison.
5053 Said comparison also expects us to make some of these checks
5054 (see ada_identical_enum_types_p). */
5055
5056 /* Quick check: All symbols should have an enum type. */
5057 for (i = 0; i < syms.size (); i++)
5058 if (TYPE_CODE (SYMBOL_TYPE (syms[i].symbol)) != TYPE_CODE_ENUM)
5059 return 0;
5060
5061 /* Quick check: They should all have the same value. */
5062 for (i = 1; i < syms.size (); i++)
5063 if (SYMBOL_VALUE (syms[i].symbol) != SYMBOL_VALUE (syms[0].symbol))
5064 return 0;
5065
5066 /* Quick check: They should all have the same number of enumerals. */
5067 for (i = 1; i < syms.size (); i++)
5068 if (TYPE_NFIELDS (SYMBOL_TYPE (syms[i].symbol))
5069 != TYPE_NFIELDS (SYMBOL_TYPE (syms[0].symbol)))
5070 return 0;
5071
5072 /* All the sanity checks passed, so we might have a set of
5073 identical enumeration types. Perform a more complete
5074 comparison of the type of each symbol. */
5075 for (i = 1; i < syms.size (); i++)
5076 if (!ada_identical_enum_types_p (SYMBOL_TYPE (syms[i].symbol),
5077 SYMBOL_TYPE (syms[0].symbol)))
5078 return 0;
5079
5080 return 1;
5081 }
5082
5083 /* Remove any non-debugging symbols in SYMS that definitely
5084 duplicate other symbols in the list (The only case I know of where
5085 this happens is when object files containing stabs-in-ecoff are
5086 linked with files containing ordinary ecoff debugging symbols (or no
5087 debugging symbols)). Modifies SYMS to squeeze out deleted entries.
5088 Returns the number of items in the modified list. */
5089
5090 static int
5091 remove_extra_symbols (std::vector<struct block_symbol> *syms)
5092 {
5093 int i, j;
5094
5095 /* We should never be called with less than 2 symbols, as there
5096 cannot be any extra symbol in that case. But it's easy to
5097 handle, since we have nothing to do in that case. */
5098 if (syms->size () < 2)
5099 return syms->size ();
5100
5101 i = 0;
5102 while (i < syms->size ())
5103 {
5104 int remove_p = 0;
5105
5106 /* If two symbols have the same name and one of them is a stub type,
5107 the get rid of the stub. */
5108
5109 if (TYPE_STUB (SYMBOL_TYPE ((*syms)[i].symbol))
5110 && SYMBOL_LINKAGE_NAME ((*syms)[i].symbol) != NULL)
5111 {
5112 for (j = 0; j < syms->size (); j++)
5113 {
5114 if (j != i
5115 && !TYPE_STUB (SYMBOL_TYPE ((*syms)[j].symbol))
5116 && SYMBOL_LINKAGE_NAME ((*syms)[j].symbol) != NULL
5117 && strcmp (SYMBOL_LINKAGE_NAME ((*syms)[i].symbol),
5118 SYMBOL_LINKAGE_NAME ((*syms)[j].symbol)) == 0)
5119 remove_p = 1;
5120 }
5121 }
5122
5123 /* Two symbols with the same name, same class and same address
5124 should be identical. */
5125
5126 else if (SYMBOL_LINKAGE_NAME ((*syms)[i].symbol) != NULL
5127 && SYMBOL_CLASS ((*syms)[i].symbol) == LOC_STATIC
5128 && is_nondebugging_type (SYMBOL_TYPE ((*syms)[i].symbol)))
5129 {
5130 for (j = 0; j < syms->size (); j += 1)
5131 {
5132 if (i != j
5133 && SYMBOL_LINKAGE_NAME ((*syms)[j].symbol) != NULL
5134 && strcmp (SYMBOL_LINKAGE_NAME ((*syms)[i].symbol),
5135 SYMBOL_LINKAGE_NAME ((*syms)[j].symbol)) == 0
5136 && SYMBOL_CLASS ((*syms)[i].symbol)
5137 == SYMBOL_CLASS ((*syms)[j].symbol)
5138 && SYMBOL_VALUE_ADDRESS ((*syms)[i].symbol)
5139 == SYMBOL_VALUE_ADDRESS ((*syms)[j].symbol))
5140 remove_p = 1;
5141 }
5142 }
5143
5144 if (remove_p)
5145 syms->erase (syms->begin () + i);
5146
5147 i += 1;
5148 }
5149
5150 /* If all the remaining symbols are identical enumerals, then
5151 just keep the first one and discard the rest.
5152
5153 Unlike what we did previously, we do not discard any entry
5154 unless they are ALL identical. This is because the symbol
5155 comparison is not a strict comparison, but rather a practical
5156 comparison. If all symbols are considered identical, then
5157 we can just go ahead and use the first one and discard the rest.
5158 But if we cannot reduce the list to a single element, we have
5159 to ask the user to disambiguate anyways. And if we have to
5160 present a multiple-choice menu, it's less confusing if the list
5161 isn't missing some choices that were identical and yet distinct. */
5162 if (symbols_are_identical_enums (*syms))
5163 syms->resize (1);
5164
5165 return syms->size ();
5166 }
5167
5168 /* Given a type that corresponds to a renaming entity, use the type name
5169 to extract the scope (package name or function name, fully qualified,
5170 and following the GNAT encoding convention) where this renaming has been
5171 defined. */
5172
5173 static std::string
5174 xget_renaming_scope (struct type *renaming_type)
5175 {
5176 /* The renaming types adhere to the following convention:
5177 <scope>__<rename>___<XR extension>.
5178 So, to extract the scope, we search for the "___XR" extension,
5179 and then backtrack until we find the first "__". */
5180
5181 const char *name = TYPE_NAME (renaming_type);
5182 const char *suffix = strstr (name, "___XR");
5183 const char *last;
5184
5185 /* Now, backtrack a bit until we find the first "__". Start looking
5186 at suffix - 3, as the <rename> part is at least one character long. */
5187
5188 for (last = suffix - 3; last > name; last--)
5189 if (last[0] == '_' && last[1] == '_')
5190 break;
5191
5192 /* Make a copy of scope and return it. */
5193 return std::string (name, last);
5194 }
5195
5196 /* Return nonzero if NAME corresponds to a package name. */
5197
5198 static int
5199 is_package_name (const char *name)
5200 {
5201 /* Here, We take advantage of the fact that no symbols are generated
5202 for packages, while symbols are generated for each function.
5203 So the condition for NAME represent a package becomes equivalent
5204 to NAME not existing in our list of symbols. There is only one
5205 small complication with library-level functions (see below). */
5206
5207 /* If it is a function that has not been defined at library level,
5208 then we should be able to look it up in the symbols. */
5209 if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
5210 return 0;
5211
5212 /* Library-level function names start with "_ada_". See if function
5213 "_ada_" followed by NAME can be found. */
5214
5215 /* Do a quick check that NAME does not contain "__", since library-level
5216 functions names cannot contain "__" in them. */
5217 if (strstr (name, "__") != NULL)
5218 return 0;
5219
5220 std::string fun_name = string_printf ("_ada_%s", name);
5221
5222 return (standard_lookup (fun_name.c_str (), NULL, VAR_DOMAIN) == NULL);
5223 }
5224
5225 /* Return nonzero if SYM corresponds to a renaming entity that is
5226 not visible from FUNCTION_NAME. */
5227
5228 static int
5229 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
5230 {
5231 if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
5232 return 0;
5233
5234 std::string scope = xget_renaming_scope (SYMBOL_TYPE (sym));
5235
5236 /* If the rename has been defined in a package, then it is visible. */
5237 if (is_package_name (scope.c_str ()))
5238 return 0;
5239
5240 /* Check that the rename is in the current function scope by checking
5241 that its name starts with SCOPE. */
5242
5243 /* If the function name starts with "_ada_", it means that it is
5244 a library-level function. Strip this prefix before doing the
5245 comparison, as the encoding for the renaming does not contain
5246 this prefix. */
5247 if (startswith (function_name, "_ada_"))
5248 function_name += 5;
5249
5250 return !startswith (function_name, scope.c_str ());
5251 }
5252
5253 /* Remove entries from SYMS that corresponds to a renaming entity that
5254 is not visible from the function associated with CURRENT_BLOCK or
5255 that is superfluous due to the presence of more specific renaming
5256 information. Places surviving symbols in the initial entries of
5257 SYMS and returns the number of surviving symbols.
5258
5259 Rationale:
5260 First, in cases where an object renaming is implemented as a
5261 reference variable, GNAT may produce both the actual reference
5262 variable and the renaming encoding. In this case, we discard the
5263 latter.
5264
5265 Second, GNAT emits a type following a specified encoding for each renaming
5266 entity. Unfortunately, STABS currently does not support the definition
5267 of types that are local to a given lexical block, so all renamings types
5268 are emitted at library level. As a consequence, if an application
5269 contains two renaming entities using the same name, and a user tries to
5270 print the value of one of these entities, the result of the ada symbol
5271 lookup will also contain the wrong renaming type.
5272
5273 This function partially covers for this limitation by attempting to
5274 remove from the SYMS list renaming symbols that should be visible
5275 from CURRENT_BLOCK. However, there does not seem be a 100% reliable
5276 method with the current information available. The implementation
5277 below has a couple of limitations (FIXME: brobecker-2003-05-12):
5278
5279 - When the user tries to print a rename in a function while there
5280 is another rename entity defined in a package: Normally, the
5281 rename in the function has precedence over the rename in the
5282 package, so the latter should be removed from the list. This is
5283 currently not the case.
5284
5285 - This function will incorrectly remove valid renames if
5286 the CURRENT_BLOCK corresponds to a function which symbol name
5287 has been changed by an "Export" pragma. As a consequence,
5288 the user will be unable to print such rename entities. */
5289
5290 static int
5291 remove_irrelevant_renamings (std::vector<struct block_symbol> *syms,
5292 const struct block *current_block)
5293 {
5294 struct symbol *current_function;
5295 const char *current_function_name;
5296 int i;
5297 int is_new_style_renaming;
5298
5299 /* If there is both a renaming foo___XR... encoded as a variable and
5300 a simple variable foo in the same block, discard the latter.
5301 First, zero out such symbols, then compress. */
5302 is_new_style_renaming = 0;
5303 for (i = 0; i < syms->size (); i += 1)
5304 {
5305 struct symbol *sym = (*syms)[i].symbol;
5306 const struct block *block = (*syms)[i].block;
5307 const char *name;
5308 const char *suffix;
5309
5310 if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
5311 continue;
5312 name = SYMBOL_LINKAGE_NAME (sym);
5313 suffix = strstr (name, "___XR");
5314
5315 if (suffix != NULL)
5316 {
5317 int name_len = suffix - name;
5318 int j;
5319
5320 is_new_style_renaming = 1;
5321 for (j = 0; j < syms->size (); j += 1)
5322 if (i != j && (*syms)[j].symbol != NULL
5323 && strncmp (name, SYMBOL_LINKAGE_NAME ((*syms)[j].symbol),
5324 name_len) == 0
5325 && block == (*syms)[j].block)
5326 (*syms)[j].symbol = NULL;
5327 }
5328 }
5329 if (is_new_style_renaming)
5330 {
5331 int j, k;
5332
5333 for (j = k = 0; j < syms->size (); j += 1)
5334 if ((*syms)[j].symbol != NULL)
5335 {
5336 (*syms)[k] = (*syms)[j];
5337 k += 1;
5338 }
5339 return k;
5340 }
5341
5342 /* Extract the function name associated to CURRENT_BLOCK.
5343 Abort if unable to do so. */
5344
5345 if (current_block == NULL)
5346 return syms->size ();
5347
5348 current_function = block_linkage_function (current_block);
5349 if (current_function == NULL)
5350 return syms->size ();
5351
5352 current_function_name = SYMBOL_LINKAGE_NAME (current_function);
5353 if (current_function_name == NULL)
5354 return syms->size ();
5355
5356 /* Check each of the symbols, and remove it from the list if it is
5357 a type corresponding to a renaming that is out of the scope of
5358 the current block. */
5359
5360 i = 0;
5361 while (i < syms->size ())
5362 {
5363 if (ada_parse_renaming ((*syms)[i].symbol, NULL, NULL, NULL)
5364 == ADA_OBJECT_RENAMING
5365 && old_renaming_is_invisible ((*syms)[i].symbol,
5366 current_function_name))
5367 syms->erase (syms->begin () + i);
5368 else
5369 i += 1;
5370 }
5371
5372 return syms->size ();
5373 }
5374
5375 /* Add to OBSTACKP all symbols from BLOCK (and its super-blocks)
5376 whose name and domain match NAME and DOMAIN respectively.
5377 If no match was found, then extend the search to "enclosing"
5378 routines (in other words, if we're inside a nested function,
5379 search the symbols defined inside the enclosing functions).
5380 If WILD_MATCH_P is nonzero, perform the naming matching in
5381 "wild" mode (see function "wild_match" for more info).
5382
5383 Note: This function assumes that OBSTACKP has 0 (zero) element in it. */
5384
5385 static void
5386 ada_add_local_symbols (struct obstack *obstackp,
5387 const lookup_name_info &lookup_name,
5388 const struct block *block, domain_enum domain)
5389 {
5390 int block_depth = 0;
5391
5392 while (block != NULL)
5393 {
5394 block_depth += 1;
5395 ada_add_block_symbols (obstackp, block, lookup_name, domain, NULL);
5396
5397 /* If we found a non-function match, assume that's the one. */
5398 if (is_nonfunction (defns_collected (obstackp, 0),
5399 num_defns_collected (obstackp)))
5400 return;
5401
5402 block = BLOCK_SUPERBLOCK (block);
5403 }
5404
5405 /* If no luck so far, try to find NAME as a local symbol in some lexically
5406 enclosing subprogram. */
5407 if (num_defns_collected (obstackp) == 0 && block_depth > 2)
5408 add_symbols_from_enclosing_procs (obstackp, lookup_name, domain);
5409 }
5410
5411 /* An object of this type is used as the user_data argument when
5412 calling the map_matching_symbols method. */
5413
5414 struct match_data
5415 {
5416 struct objfile *objfile;
5417 struct obstack *obstackp;
5418 struct symbol *arg_sym;
5419 int found_sym;
5420 };
5421
5422 /* A callback for add_nonlocal_symbols that adds SYM, found in BLOCK,
5423 to a list of symbols. DATA0 is a pointer to a struct match_data *
5424 containing the obstack that collects the symbol list, the file that SYM
5425 must come from, a flag indicating whether a non-argument symbol has
5426 been found in the current block, and the last argument symbol
5427 passed in SYM within the current block (if any). When SYM is null,
5428 marking the end of a block, the argument symbol is added if no
5429 other has been found. */
5430
5431 static int
5432 aux_add_nonlocal_symbols (const struct block *block, struct symbol *sym,
5433 void *data0)
5434 {
5435 struct match_data *data = (struct match_data *) data0;
5436
5437 if (sym == NULL)
5438 {
5439 if (!data->found_sym && data->arg_sym != NULL)
5440 add_defn_to_vec (data->obstackp,
5441 fixup_symbol_section (data->arg_sym, data->objfile),
5442 block);
5443 data->found_sym = 0;
5444 data->arg_sym = NULL;
5445 }
5446 else
5447 {
5448 if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
5449 return 0;
5450 else if (SYMBOL_IS_ARGUMENT (sym))
5451 data->arg_sym = sym;
5452 else
5453 {
5454 data->found_sym = 1;
5455 add_defn_to_vec (data->obstackp,
5456 fixup_symbol_section (sym, data->objfile),
5457 block);
5458 }
5459 }
5460 return 0;
5461 }
5462
5463 /* Helper for add_nonlocal_symbols. Find symbols in DOMAIN which are
5464 targeted by renamings matching LOOKUP_NAME in BLOCK. Add these
5465 symbols to OBSTACKP. Return whether we found such symbols. */
5466
5467 static int
5468 ada_add_block_renamings (struct obstack *obstackp,
5469 const struct block *block,
5470 const lookup_name_info &lookup_name,
5471 domain_enum domain)
5472 {
5473 struct using_direct *renaming;
5474 int defns_mark = num_defns_collected (obstackp);
5475
5476 symbol_name_matcher_ftype *name_match
5477 = ada_get_symbol_name_matcher (lookup_name);
5478
5479 for (renaming = block_using (block);
5480 renaming != NULL;
5481 renaming = renaming->next)
5482 {
5483 const char *r_name;
5484
5485 /* Avoid infinite recursions: skip this renaming if we are actually
5486 already traversing it.
5487
5488 Currently, symbol lookup in Ada don't use the namespace machinery from
5489 C++/Fortran support: skip namespace imports that use them. */
5490 if (renaming->searched
5491 || (renaming->import_src != NULL
5492 && renaming->import_src[0] != '\0')
5493 || (renaming->import_dest != NULL
5494 && renaming->import_dest[0] != '\0'))
5495 continue;
5496 renaming->searched = 1;
5497
5498 /* TODO: here, we perform another name-based symbol lookup, which can
5499 pull its own multiple overloads. In theory, we should be able to do
5500 better in this case since, in DWARF, DW_AT_import is a DIE reference,
5501 not a simple name. But in order to do this, we would need to enhance
5502 the DWARF reader to associate a symbol to this renaming, instead of a
5503 name. So, for now, we do something simpler: re-use the C++/Fortran
5504 namespace machinery. */
5505 r_name = (renaming->alias != NULL
5506 ? renaming->alias
5507 : renaming->declaration);
5508 if (name_match (r_name, lookup_name, NULL))
5509 {
5510 lookup_name_info decl_lookup_name (renaming->declaration,
5511 lookup_name.match_type ());
5512 ada_add_all_symbols (obstackp, block, decl_lookup_name, domain,
5513 1, NULL);
5514 }
5515 renaming->searched = 0;
5516 }
5517 return num_defns_collected (obstackp) != defns_mark;
5518 }
5519
5520 /* Implements compare_names, but only applying the comparision using
5521 the given CASING. */
5522
5523 static int
5524 compare_names_with_case (const char *string1, const char *string2,
5525 enum case_sensitivity casing)
5526 {
5527 while (*string1 != '\0' && *string2 != '\0')
5528 {
5529 char c1, c2;
5530
5531 if (isspace (*string1) || isspace (*string2))
5532 return strcmp_iw_ordered (string1, string2);
5533
5534 if (casing == case_sensitive_off)
5535 {
5536 c1 = tolower (*string1);
5537 c2 = tolower (*string2);
5538 }
5539 else
5540 {
5541 c1 = *string1;
5542 c2 = *string2;
5543 }
5544 if (c1 != c2)
5545 break;
5546
5547 string1 += 1;
5548 string2 += 1;
5549 }
5550
5551 switch (*string1)
5552 {
5553 case '(':
5554 return strcmp_iw_ordered (string1, string2);
5555 case '_':
5556 if (*string2 == '\0')
5557 {
5558 if (is_name_suffix (string1))
5559 return 0;
5560 else
5561 return 1;
5562 }
5563 /* FALLTHROUGH */
5564 default:
5565 if (*string2 == '(')
5566 return strcmp_iw_ordered (string1, string2);
5567 else
5568 {
5569 if (casing == case_sensitive_off)
5570 return tolower (*string1) - tolower (*string2);
5571 else
5572 return *string1 - *string2;
5573 }
5574 }
5575 }
5576
5577 /* Compare STRING1 to STRING2, with results as for strcmp.
5578 Compatible with strcmp_iw_ordered in that...
5579
5580 strcmp_iw_ordered (STRING1, STRING2) <= 0
5581
5582 ... implies...
5583
5584 compare_names (STRING1, STRING2) <= 0
5585
5586 (they may differ as to what symbols compare equal). */
5587
5588 static int
5589 compare_names (const char *string1, const char *string2)
5590 {
5591 int result;
5592
5593 /* Similar to what strcmp_iw_ordered does, we need to perform
5594 a case-insensitive comparison first, and only resort to
5595 a second, case-sensitive, comparison if the first one was
5596 not sufficient to differentiate the two strings. */
5597
5598 result = compare_names_with_case (string1, string2, case_sensitive_off);
5599 if (result == 0)
5600 result = compare_names_with_case (string1, string2, case_sensitive_on);
5601
5602 return result;
5603 }
5604
5605 /* Convenience function to get at the Ada encoded lookup name for
5606 LOOKUP_NAME, as a C string. */
5607
5608 static const char *
5609 ada_lookup_name (const lookup_name_info &lookup_name)
5610 {
5611 return lookup_name.ada ().lookup_name ().c_str ();
5612 }
5613
5614 /* Add to OBSTACKP all non-local symbols whose name and domain match
5615 LOOKUP_NAME and DOMAIN respectively. The search is performed on
5616 GLOBAL_BLOCK symbols if GLOBAL is non-zero, or on STATIC_BLOCK
5617 symbols otherwise. */
5618
5619 static void
5620 add_nonlocal_symbols (struct obstack *obstackp,
5621 const lookup_name_info &lookup_name,
5622 domain_enum domain, int global)
5623 {
5624 struct match_data data;
5625
5626 memset (&data, 0, sizeof data);
5627 data.obstackp = obstackp;
5628
5629 bool is_wild_match = lookup_name.ada ().wild_match_p ();
5630
5631 for (objfile *objfile : current_program_space->objfiles ())
5632 {
5633 data.objfile = objfile;
5634
5635 if (is_wild_match)
5636 objfile->sf->qf->map_matching_symbols (objfile, lookup_name.name ().c_str (),
5637 domain, global,
5638 aux_add_nonlocal_symbols, &data,
5639 symbol_name_match_type::WILD,
5640 NULL);
5641 else
5642 objfile->sf->qf->map_matching_symbols (objfile, lookup_name.name ().c_str (),
5643 domain, global,
5644 aux_add_nonlocal_symbols, &data,
5645 symbol_name_match_type::FULL,
5646 compare_names);
5647
5648 for (compunit_symtab *cu : objfile->compunits ())
5649 {
5650 const struct block *global_block
5651 = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cu), GLOBAL_BLOCK);
5652
5653 if (ada_add_block_renamings (obstackp, global_block, lookup_name,
5654 domain))
5655 data.found_sym = 1;
5656 }
5657 }
5658
5659 if (num_defns_collected (obstackp) == 0 && global && !is_wild_match)
5660 {
5661 const char *name = ada_lookup_name (lookup_name);
5662 std::string name1 = std::string ("<_ada_") + name + '>';
5663
5664 for (objfile *objfile : current_program_space->objfiles ())
5665 {
5666 data.objfile = objfile;
5667 objfile->sf->qf->map_matching_symbols (objfile, name1.c_str (),
5668 domain, global,
5669 aux_add_nonlocal_symbols,
5670 &data,
5671 symbol_name_match_type::FULL,
5672 compare_names);
5673 }
5674 }
5675 }
5676
5677 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if
5678 FULL_SEARCH is non-zero, enclosing scope and in global scopes,
5679 returning the number of matches. Add these to OBSTACKP.
5680
5681 When FULL_SEARCH is non-zero, any non-function/non-enumeral
5682 symbol match within the nest of blocks whose innermost member is BLOCK,
5683 is the one match returned (no other matches in that or
5684 enclosing blocks is returned). If there are any matches in or
5685 surrounding BLOCK, then these alone are returned.
5686
5687 Names prefixed with "standard__" are handled specially:
5688 "standard__" is first stripped off (by the lookup_name
5689 constructor), and only static and global symbols are searched.
5690
5691 If MADE_GLOBAL_LOOKUP_P is non-null, set it before return to whether we had
5692 to lookup global symbols. */
5693
5694 static void
5695 ada_add_all_symbols (struct obstack *obstackp,
5696 const struct block *block,
5697 const lookup_name_info &lookup_name,
5698 domain_enum domain,
5699 int full_search,
5700 int *made_global_lookup_p)
5701 {
5702 struct symbol *sym;
5703
5704 if (made_global_lookup_p)
5705 *made_global_lookup_p = 0;
5706
5707 /* Special case: If the user specifies a symbol name inside package
5708 Standard, do a non-wild matching of the symbol name without
5709 the "standard__" prefix. This was primarily introduced in order
5710 to allow the user to specifically access the standard exceptions
5711 using, for instance, Standard.Constraint_Error when Constraint_Error
5712 is ambiguous (due to the user defining its own Constraint_Error
5713 entity inside its program). */
5714 if (lookup_name.ada ().standard_p ())
5715 block = NULL;
5716
5717 /* Check the non-global symbols. If we have ANY match, then we're done. */
5718
5719 if (block != NULL)
5720 {
5721 if (full_search)
5722 ada_add_local_symbols (obstackp, lookup_name, block, domain);
5723 else
5724 {
5725 /* In the !full_search case we're are being called by
5726 ada_iterate_over_symbols, and we don't want to search
5727 superblocks. */
5728 ada_add_block_symbols (obstackp, block, lookup_name, domain, NULL);
5729 }
5730 if (num_defns_collected (obstackp) > 0 || !full_search)
5731 return;
5732 }
5733
5734 /* No non-global symbols found. Check our cache to see if we have
5735 already performed this search before. If we have, then return
5736 the same result. */
5737
5738 if (lookup_cached_symbol (ada_lookup_name (lookup_name),
5739 domain, &sym, &block))
5740 {
5741 if (sym != NULL)
5742 add_defn_to_vec (obstackp, sym, block);
5743 return;
5744 }
5745
5746 if (made_global_lookup_p)
5747 *made_global_lookup_p = 1;
5748
5749 /* Search symbols from all global blocks. */
5750
5751 add_nonlocal_symbols (obstackp, lookup_name, domain, 1);
5752
5753 /* Now add symbols from all per-file blocks if we've gotten no hits
5754 (not strictly correct, but perhaps better than an error). */
5755
5756 if (num_defns_collected (obstackp) == 0)
5757 add_nonlocal_symbols (obstackp, lookup_name, domain, 0);
5758 }
5759
5760 /* Find symbols in DOMAIN matching LOOKUP_NAME, in BLOCK and, if FULL_SEARCH
5761 is non-zero, enclosing scope and in global scopes, returning the number of
5762 matches.
5763 Fills *RESULTS with (SYM,BLOCK) tuples, indicating the symbols
5764 found and the blocks and symbol tables (if any) in which they were
5765 found.
5766
5767 When full_search is non-zero, any non-function/non-enumeral
5768 symbol match within the nest of blocks whose innermost member is BLOCK,
5769 is the one match returned (no other matches in that or
5770 enclosing blocks is returned). If there are any matches in or
5771 surrounding BLOCK, then these alone are returned.
5772
5773 Names prefixed with "standard__" are handled specially: "standard__"
5774 is first stripped off, and only static and global symbols are searched. */
5775
5776 static int
5777 ada_lookup_symbol_list_worker (const lookup_name_info &lookup_name,
5778 const struct block *block,
5779 domain_enum domain,
5780 std::vector<struct block_symbol> *results,
5781 int full_search)
5782 {
5783 int syms_from_global_search;
5784 int ndefns;
5785 auto_obstack obstack;
5786
5787 ada_add_all_symbols (&obstack, block, lookup_name,
5788 domain, full_search, &syms_from_global_search);
5789
5790 ndefns = num_defns_collected (&obstack);
5791
5792 struct block_symbol *base = defns_collected (&obstack, 1);
5793 for (int i = 0; i < ndefns; ++i)
5794 results->push_back (base[i]);
5795
5796 ndefns = remove_extra_symbols (results);
5797
5798 if (ndefns == 0 && full_search && syms_from_global_search)
5799 cache_symbol (ada_lookup_name (lookup_name), domain, NULL, NULL);
5800
5801 if (ndefns == 1 && full_search && syms_from_global_search)
5802 cache_symbol (ada_lookup_name (lookup_name), domain,
5803 (*results)[0].symbol, (*results)[0].block);
5804
5805 ndefns = remove_irrelevant_renamings (results, block);
5806
5807 return ndefns;
5808 }
5809
5810 /* Find symbols in DOMAIN matching NAME, in BLOCK and enclosing scope and
5811 in global scopes, returning the number of matches, and filling *RESULTS
5812 with (SYM,BLOCK) tuples.
5813
5814 See ada_lookup_symbol_list_worker for further details. */
5815
5816 int
5817 ada_lookup_symbol_list (const char *name, const struct block *block,
5818 domain_enum domain,
5819 std::vector<struct block_symbol> *results)
5820 {
5821 symbol_name_match_type name_match_type = name_match_type_from_name (name);
5822 lookup_name_info lookup_name (name, name_match_type);
5823
5824 return ada_lookup_symbol_list_worker (lookup_name, block, domain, results, 1);
5825 }
5826
5827 /* Implementation of the la_iterate_over_symbols method. */
5828
5829 static void
5830 ada_iterate_over_symbols
5831 (const struct block *block, const lookup_name_info &name,
5832 domain_enum domain,
5833 gdb::function_view<symbol_found_callback_ftype> callback)
5834 {
5835 int ndefs, i;
5836 std::vector<struct block_symbol> results;
5837
5838 ndefs = ada_lookup_symbol_list_worker (name, block, domain, &results, 0);
5839
5840 for (i = 0; i < ndefs; ++i)
5841 {
5842 if (!callback (&results[i]))
5843 break;
5844 }
5845 }
5846
5847 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
5848 to 1, but choosing the first symbol found if there are multiple
5849 choices.
5850
5851 The result is stored in *INFO, which must be non-NULL.
5852 If no match is found, INFO->SYM is set to NULL. */
5853
5854 void
5855 ada_lookup_encoded_symbol (const char *name, const struct block *block,
5856 domain_enum domain,
5857 struct block_symbol *info)
5858 {
5859 /* Since we already have an encoded name, wrap it in '<>' to force a
5860 verbatim match. Otherwise, if the name happens to not look like
5861 an encoded name (because it doesn't include a "__"),
5862 ada_lookup_name_info would re-encode/fold it again, and that
5863 would e.g., incorrectly lowercase object renaming names like
5864 "R28b" -> "r28b". */
5865 std::string verbatim = std::string ("<") + name + '>';
5866
5867 gdb_assert (info != NULL);
5868 *info = ada_lookup_symbol (verbatim.c_str (), block, domain, NULL);
5869 }
5870
5871 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
5872 scope and in global scopes, or NULL if none. NAME is folded and
5873 encoded first. Otherwise, the result is as for ada_lookup_symbol_list,
5874 choosing the first symbol if there are multiple choices.
5875 If IS_A_FIELD_OF_THIS is not NULL, it is set to zero. */
5876
5877 struct block_symbol
5878 ada_lookup_symbol (const char *name, const struct block *block0,
5879 domain_enum domain, int *is_a_field_of_this)
5880 {
5881 if (is_a_field_of_this != NULL)
5882 *is_a_field_of_this = 0;
5883
5884 std::vector<struct block_symbol> candidates;
5885 int n_candidates;
5886
5887 n_candidates = ada_lookup_symbol_list (name, block0, domain, &candidates);
5888
5889 if (n_candidates == 0)
5890 return {};
5891
5892 block_symbol info = candidates[0];
5893 info.symbol = fixup_symbol_section (info.symbol, NULL);
5894 return info;
5895 }
5896
5897 static struct block_symbol
5898 ada_lookup_symbol_nonlocal (const struct language_defn *langdef,
5899 const char *name,
5900 const struct block *block,
5901 const domain_enum domain)
5902 {
5903 struct block_symbol sym;
5904
5905 sym = ada_lookup_symbol (name, block_static_block (block), domain, NULL);
5906 if (sym.symbol != NULL)
5907 return sym;
5908
5909 /* If we haven't found a match at this point, try the primitive
5910 types. In other languages, this search is performed before
5911 searching for global symbols in order to short-circuit that
5912 global-symbol search if it happens that the name corresponds
5913 to a primitive type. But we cannot do the same in Ada, because
5914 it is perfectly legitimate for a program to declare a type which
5915 has the same name as a standard type. If looking up a type in
5916 that situation, we have traditionally ignored the primitive type
5917 in favor of user-defined types. This is why, unlike most other
5918 languages, we search the primitive types this late and only after
5919 having searched the global symbols without success. */
5920
5921 if (domain == VAR_DOMAIN)
5922 {
5923 struct gdbarch *gdbarch;
5924
5925 if (block == NULL)
5926 gdbarch = target_gdbarch ();
5927 else
5928 gdbarch = block_gdbarch (block);
5929 sym.symbol = language_lookup_primitive_type_as_symbol (langdef, gdbarch, name);
5930 if (sym.symbol != NULL)
5931 return sym;
5932 }
5933
5934 return {};
5935 }
5936
5937
5938 /* True iff STR is a possible encoded suffix of a normal Ada name
5939 that is to be ignored for matching purposes. Suffixes of parallel
5940 names (e.g., XVE) are not included here. Currently, the possible suffixes
5941 are given by any of the regular expressions:
5942
5943 [.$][0-9]+ [nested subprogram suffix, on platforms such as GNU/Linux]
5944 ___[0-9]+ [nested subprogram suffix, on platforms such as HP/UX]
5945 TKB [subprogram suffix for task bodies]
5946 _E[0-9]+[bs]$ [protected object entry suffixes]
5947 (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
5948
5949 Also, any leading "__[0-9]+" sequence is skipped before the suffix
5950 match is performed. This sequence is used to differentiate homonyms,
5951 is an optional part of a valid name suffix. */
5952
5953 static int
5954 is_name_suffix (const char *str)
5955 {
5956 int k;
5957 const char *matching;
5958 const int len = strlen (str);
5959
5960 /* Skip optional leading __[0-9]+. */
5961
5962 if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
5963 {
5964 str += 3;
5965 while (isdigit (str[0]))
5966 str += 1;
5967 }
5968
5969 /* [.$][0-9]+ */
5970
5971 if (str[0] == '.' || str[0] == '$')
5972 {
5973 matching = str + 1;
5974 while (isdigit (matching[0]))
5975 matching += 1;
5976 if (matching[0] == '\0')
5977 return 1;
5978 }
5979
5980 /* ___[0-9]+ */
5981
5982 if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
5983 {
5984 matching = str + 3;
5985 while (isdigit (matching[0]))
5986 matching += 1;
5987 if (matching[0] == '\0')
5988 return 1;
5989 }
5990
5991 /* "TKB" suffixes are used for subprograms implementing task bodies. */
5992
5993 if (strcmp (str, "TKB") == 0)
5994 return 1;
5995
5996 #if 0
5997 /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
5998 with a N at the end. Unfortunately, the compiler uses the same
5999 convention for other internal types it creates. So treating
6000 all entity names that end with an "N" as a name suffix causes
6001 some regressions. For instance, consider the case of an enumerated
6002 type. To support the 'Image attribute, it creates an array whose
6003 name ends with N.
6004 Having a single character like this as a suffix carrying some
6005 information is a bit risky. Perhaps we should change the encoding
6006 to be something like "_N" instead. In the meantime, do not do
6007 the following check. */
6008 /* Protected Object Subprograms */
6009 if (len == 1 && str [0] == 'N')
6010 return 1;
6011 #endif
6012
6013 /* _E[0-9]+[bs]$ */
6014 if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
6015 {
6016 matching = str + 3;
6017 while (isdigit (matching[0]))
6018 matching += 1;
6019 if ((matching[0] == 'b' || matching[0] == 's')
6020 && matching [1] == '\0')
6021 return 1;
6022 }
6023
6024 /* ??? We should not modify STR directly, as we are doing below. This
6025 is fine in this case, but may become problematic later if we find
6026 that this alternative did not work, and want to try matching
6027 another one from the begining of STR. Since we modified it, we
6028 won't be able to find the begining of the string anymore! */
6029 if (str[0] == 'X')
6030 {
6031 str += 1;
6032 while (str[0] != '_' && str[0] != '\0')
6033 {
6034 if (str[0] != 'n' && str[0] != 'b')
6035 return 0;
6036 str += 1;
6037 }
6038 }
6039
6040 if (str[0] == '\000')
6041 return 1;
6042
6043 if (str[0] == '_')
6044 {
6045 if (str[1] != '_' || str[2] == '\000')
6046 return 0;
6047 if (str[2] == '_')
6048 {
6049 if (strcmp (str + 3, "JM") == 0)
6050 return 1;
6051 /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
6052 the LJM suffix in favor of the JM one. But we will
6053 still accept LJM as a valid suffix for a reasonable
6054 amount of time, just to allow ourselves to debug programs
6055 compiled using an older version of GNAT. */
6056 if (strcmp (str + 3, "LJM") == 0)
6057 return 1;
6058 if (str[3] != 'X')
6059 return 0;
6060 if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
6061 || str[4] == 'U' || str[4] == 'P')
6062 return 1;
6063 if (str[4] == 'R' && str[5] != 'T')
6064 return 1;
6065 return 0;
6066 }
6067 if (!isdigit (str[2]))
6068 return 0;
6069 for (k = 3; str[k] != '\0'; k += 1)
6070 if (!isdigit (str[k]) && str[k] != '_')
6071 return 0;
6072 return 1;
6073 }
6074 if (str[0] == '$' && isdigit (str[1]))
6075 {
6076 for (k = 2; str[k] != '\0'; k += 1)
6077 if (!isdigit (str[k]) && str[k] != '_')
6078 return 0;
6079 return 1;
6080 }
6081 return 0;
6082 }
6083
6084 /* Return non-zero if the string starting at NAME and ending before
6085 NAME_END contains no capital letters. */
6086
6087 static int
6088 is_valid_name_for_wild_match (const char *name0)
6089 {
6090 const char *decoded_name = ada_decode (name0);
6091 int i;
6092
6093 /* If the decoded name starts with an angle bracket, it means that
6094 NAME0 does not follow the GNAT encoding format. It should then
6095 not be allowed as a possible wild match. */
6096 if (decoded_name[0] == '<')
6097 return 0;
6098
6099 for (i=0; decoded_name[i] != '\0'; i++)
6100 if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
6101 return 0;
6102
6103 return 1;
6104 }
6105
6106 /* Advance *NAMEP to next occurrence of TARGET0 in the string NAME0
6107 that could start a simple name. Assumes that *NAMEP points into
6108 the string beginning at NAME0. */
6109
6110 static int
6111 advance_wild_match (const char **namep, const char *name0, int target0)
6112 {
6113 const char *name = *namep;
6114
6115 while (1)
6116 {
6117 int t0, t1;
6118
6119 t0 = *name;
6120 if (t0 == '_')
6121 {
6122 t1 = name[1];
6123 if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
6124 {
6125 name += 1;
6126 if (name == name0 + 5 && startswith (name0, "_ada"))
6127 break;
6128 else
6129 name += 1;
6130 }
6131 else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
6132 || name[2] == target0))
6133 {
6134 name += 2;
6135 break;
6136 }
6137 else
6138 return 0;
6139 }
6140 else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
6141 name += 1;
6142 else
6143 return 0;
6144 }
6145
6146 *namep = name;
6147 return 1;
6148 }
6149
6150 /* Return true iff NAME encodes a name of the form prefix.PATN.
6151 Ignores any informational suffixes of NAME (i.e., for which
6152 is_name_suffix is true). Assumes that PATN is a lower-cased Ada
6153 simple name. */
6154
6155 static bool
6156 wild_match (const char *name, const char *patn)
6157 {
6158 const char *p;
6159 const char *name0 = name;
6160
6161 while (1)
6162 {
6163 const char *match = name;
6164
6165 if (*name == *patn)
6166 {
6167 for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
6168 if (*p != *name)
6169 break;
6170 if (*p == '\0' && is_name_suffix (name))
6171 return match == name0 || is_valid_name_for_wild_match (name0);
6172
6173 if (name[-1] == '_')
6174 name -= 1;
6175 }
6176 if (!advance_wild_match (&name, name0, *patn))
6177 return false;
6178 }
6179 }
6180
6181 /* Returns true iff symbol name SYM_NAME matches SEARCH_NAME, ignoring
6182 any trailing suffixes that encode debugging information or leading
6183 _ada_ on SYM_NAME (see is_name_suffix commentary for the debugging
6184 information that is ignored). */
6185
6186 static bool
6187 full_match (const char *sym_name, const char *search_name)
6188 {
6189 size_t search_name_len = strlen (search_name);
6190
6191 if (strncmp (sym_name, search_name, search_name_len) == 0
6192 && is_name_suffix (sym_name + search_name_len))
6193 return true;
6194
6195 if (startswith (sym_name, "_ada_")
6196 && strncmp (sym_name + 5, search_name, search_name_len) == 0
6197 && is_name_suffix (sym_name + search_name_len + 5))
6198 return true;
6199
6200 return false;
6201 }
6202
6203 /* Add symbols from BLOCK matching LOOKUP_NAME in DOMAIN to vector
6204 *defn_symbols, updating the list of symbols in OBSTACKP (if
6205 necessary). OBJFILE is the section containing BLOCK. */
6206
6207 static void
6208 ada_add_block_symbols (struct obstack *obstackp,
6209 const struct block *block,
6210 const lookup_name_info &lookup_name,
6211 domain_enum domain, struct objfile *objfile)
6212 {
6213 struct block_iterator iter;
6214 /* A matching argument symbol, if any. */
6215 struct symbol *arg_sym;
6216 /* Set true when we find a matching non-argument symbol. */
6217 int found_sym;
6218 struct symbol *sym;
6219
6220 arg_sym = NULL;
6221 found_sym = 0;
6222 for (sym = block_iter_match_first (block, lookup_name, &iter);
6223 sym != NULL;
6224 sym = block_iter_match_next (lookup_name, &iter))
6225 {
6226 if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
6227 SYMBOL_DOMAIN (sym), domain))
6228 {
6229 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
6230 {
6231 if (SYMBOL_IS_ARGUMENT (sym))
6232 arg_sym = sym;
6233 else
6234 {
6235 found_sym = 1;
6236 add_defn_to_vec (obstackp,
6237 fixup_symbol_section (sym, objfile),
6238 block);
6239 }
6240 }
6241 }
6242 }
6243
6244 /* Handle renamings. */
6245
6246 if (ada_add_block_renamings (obstackp, block, lookup_name, domain))
6247 found_sym = 1;
6248
6249 if (!found_sym && arg_sym != NULL)
6250 {
6251 add_defn_to_vec (obstackp,
6252 fixup_symbol_section (arg_sym, objfile),
6253 block);
6254 }
6255
6256 if (!lookup_name.ada ().wild_match_p ())
6257 {
6258 arg_sym = NULL;
6259 found_sym = 0;
6260 const std::string &ada_lookup_name = lookup_name.ada ().lookup_name ();
6261 const char *name = ada_lookup_name.c_str ();
6262 size_t name_len = ada_lookup_name.size ();
6263
6264 ALL_BLOCK_SYMBOLS (block, iter, sym)
6265 {
6266 if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
6267 SYMBOL_DOMAIN (sym), domain))
6268 {
6269 int cmp;
6270
6271 cmp = (int) '_' - (int) SYMBOL_LINKAGE_NAME (sym)[0];
6272 if (cmp == 0)
6273 {
6274 cmp = !startswith (SYMBOL_LINKAGE_NAME (sym), "_ada_");
6275 if (cmp == 0)
6276 cmp = strncmp (name, SYMBOL_LINKAGE_NAME (sym) + 5,
6277 name_len);
6278 }
6279
6280 if (cmp == 0
6281 && is_name_suffix (SYMBOL_LINKAGE_NAME (sym) + name_len + 5))
6282 {
6283 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
6284 {
6285 if (SYMBOL_IS_ARGUMENT (sym))
6286 arg_sym = sym;
6287 else
6288 {
6289 found_sym = 1;
6290 add_defn_to_vec (obstackp,
6291 fixup_symbol_section (sym, objfile),
6292 block);
6293 }
6294 }
6295 }
6296 }
6297 }
6298
6299 /* NOTE: This really shouldn't be needed for _ada_ symbols.
6300 They aren't parameters, right? */
6301 if (!found_sym && arg_sym != NULL)
6302 {
6303 add_defn_to_vec (obstackp,
6304 fixup_symbol_section (arg_sym, objfile),
6305 block);
6306 }
6307 }
6308 }
6309 \f
6310
6311 /* Symbol Completion */
6312
6313 /* See symtab.h. */
6314
6315 bool
6316 ada_lookup_name_info::matches
6317 (const char *sym_name,
6318 symbol_name_match_type match_type,
6319 completion_match_result *comp_match_res) const
6320 {
6321 bool match = false;
6322 const char *text = m_encoded_name.c_str ();
6323 size_t text_len = m_encoded_name.size ();
6324
6325 /* First, test against the fully qualified name of the symbol. */
6326
6327 if (strncmp (sym_name, text, text_len) == 0)
6328 match = true;
6329
6330 if (match && !m_encoded_p)
6331 {
6332 /* One needed check before declaring a positive match is to verify
6333 that iff we are doing a verbatim match, the decoded version
6334 of the symbol name starts with '<'. Otherwise, this symbol name
6335 is not a suitable completion. */
6336 const char *sym_name_copy = sym_name;
6337 bool has_angle_bracket;
6338
6339 sym_name = ada_decode (sym_name);
6340 has_angle_bracket = (sym_name[0] == '<');
6341 match = (has_angle_bracket == m_verbatim_p);
6342 sym_name = sym_name_copy;
6343 }
6344
6345 if (match && !m_verbatim_p)
6346 {
6347 /* When doing non-verbatim match, another check that needs to
6348 be done is to verify that the potentially matching symbol name
6349 does not include capital letters, because the ada-mode would
6350 not be able to understand these symbol names without the
6351 angle bracket notation. */
6352 const char *tmp;
6353
6354 for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
6355 if (*tmp != '\0')
6356 match = false;
6357 }
6358
6359 /* Second: Try wild matching... */
6360
6361 if (!match && m_wild_match_p)
6362 {
6363 /* Since we are doing wild matching, this means that TEXT
6364 may represent an unqualified symbol name. We therefore must
6365 also compare TEXT against the unqualified name of the symbol. */
6366 sym_name = ada_unqualified_name (ada_decode (sym_name));
6367
6368 if (strncmp (sym_name, text, text_len) == 0)
6369 match = true;
6370 }
6371
6372 /* Finally: If we found a match, prepare the result to return. */
6373
6374 if (!match)
6375 return false;
6376
6377 if (comp_match_res != NULL)
6378 {
6379 std::string &match_str = comp_match_res->match.storage ();
6380
6381 if (!m_encoded_p)
6382 match_str = ada_decode (sym_name);
6383 else
6384 {
6385 if (m_verbatim_p)
6386 match_str = add_angle_brackets (sym_name);
6387 else
6388 match_str = sym_name;
6389
6390 }
6391
6392 comp_match_res->set_match (match_str.c_str ());
6393 }
6394
6395 return true;
6396 }
6397
6398 /* Add the list of possible symbol names completing TEXT to TRACKER.
6399 WORD is the entire command on which completion is made. */
6400
6401 static void
6402 ada_collect_symbol_completion_matches (completion_tracker &tracker,
6403 complete_symbol_mode mode,
6404 symbol_name_match_type name_match_type,
6405 const char *text, const char *word,
6406 enum type_code code)
6407 {
6408 struct symbol *sym;
6409 const struct block *b, *surrounding_static_block = 0;
6410 struct block_iterator iter;
6411
6412 gdb_assert (code == TYPE_CODE_UNDEF);
6413
6414 lookup_name_info lookup_name (text, name_match_type, true);
6415
6416 /* First, look at the partial symtab symbols. */
6417 expand_symtabs_matching (NULL,
6418 lookup_name,
6419 NULL,
6420 NULL,
6421 ALL_DOMAIN);
6422
6423 /* At this point scan through the misc symbol vectors and add each
6424 symbol you find to the list. Eventually we want to ignore
6425 anything that isn't a text symbol (everything else will be
6426 handled by the psymtab code above). */
6427
6428 for (objfile *objfile : current_program_space->objfiles ())
6429 {
6430 for (minimal_symbol *msymbol : objfile->msymbols ())
6431 {
6432 QUIT;
6433
6434 if (completion_skip_symbol (mode, msymbol))
6435 continue;
6436
6437 language symbol_language = MSYMBOL_LANGUAGE (msymbol);
6438
6439 /* Ada minimal symbols won't have their language set to Ada. If
6440 we let completion_list_add_name compare using the
6441 default/C-like matcher, then when completing e.g., symbols in a
6442 package named "pck", we'd match internal Ada symbols like
6443 "pckS", which are invalid in an Ada expression, unless you wrap
6444 them in '<' '>' to request a verbatim match.
6445
6446 Unfortunately, some Ada encoded names successfully demangle as
6447 C++ symbols (using an old mangling scheme), such as "name__2Xn"
6448 -> "Xn::name(void)" and thus some Ada minimal symbols end up
6449 with the wrong language set. Paper over that issue here. */
6450 if (symbol_language == language_auto
6451 || symbol_language == language_cplus)
6452 symbol_language = language_ada;
6453
6454 completion_list_add_name (tracker,
6455 symbol_language,
6456 MSYMBOL_LINKAGE_NAME (msymbol),
6457 lookup_name, text, word);
6458 }
6459 }
6460
6461 /* Search upwards from currently selected frame (so that we can
6462 complete on local vars. */
6463
6464 for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
6465 {
6466 if (!BLOCK_SUPERBLOCK (b))
6467 surrounding_static_block = b; /* For elmin of dups */
6468
6469 ALL_BLOCK_SYMBOLS (b, iter, sym)
6470 {
6471 if (completion_skip_symbol (mode, sym))
6472 continue;
6473
6474 completion_list_add_name (tracker,
6475 SYMBOL_LANGUAGE (sym),
6476 SYMBOL_LINKAGE_NAME (sym),
6477 lookup_name, text, word);
6478 }
6479 }
6480
6481 /* Go through the symtabs and check the externs and statics for
6482 symbols which match. */
6483
6484 for (objfile *objfile : current_program_space->objfiles ())
6485 {
6486 for (compunit_symtab *s : objfile->compunits ())
6487 {
6488 QUIT;
6489 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), GLOBAL_BLOCK);
6490 ALL_BLOCK_SYMBOLS (b, iter, sym)
6491 {
6492 if (completion_skip_symbol (mode, sym))
6493 continue;
6494
6495 completion_list_add_name (tracker,
6496 SYMBOL_LANGUAGE (sym),
6497 SYMBOL_LINKAGE_NAME (sym),
6498 lookup_name, text, word);
6499 }
6500 }
6501 }
6502
6503 for (objfile *objfile : current_program_space->objfiles ())
6504 {
6505 for (compunit_symtab *s : objfile->compunits ())
6506 {
6507 QUIT;
6508 b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (s), STATIC_BLOCK);
6509 /* Don't do this block twice. */
6510 if (b == surrounding_static_block)
6511 continue;
6512 ALL_BLOCK_SYMBOLS (b, iter, sym)
6513 {
6514 if (completion_skip_symbol (mode, sym))
6515 continue;
6516
6517 completion_list_add_name (tracker,
6518 SYMBOL_LANGUAGE (sym),
6519 SYMBOL_LINKAGE_NAME (sym),
6520 lookup_name, text, word);
6521 }
6522 }
6523 }
6524 }
6525
6526 /* Field Access */
6527
6528 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
6529 for tagged types. */
6530
6531 static int
6532 ada_is_dispatch_table_ptr_type (struct type *type)
6533 {
6534 const char *name;
6535
6536 if (TYPE_CODE (type) != TYPE_CODE_PTR)
6537 return 0;
6538
6539 name = TYPE_NAME (TYPE_TARGET_TYPE (type));
6540 if (name == NULL)
6541 return 0;
6542
6543 return (strcmp (name, "ada__tags__dispatch_table") == 0);
6544 }
6545
6546 /* Return non-zero if TYPE is an interface tag. */
6547
6548 static int
6549 ada_is_interface_tag (struct type *type)
6550 {
6551 const char *name = TYPE_NAME (type);
6552
6553 if (name == NULL)
6554 return 0;
6555
6556 return (strcmp (name, "ada__tags__interface_tag") == 0);
6557 }
6558
6559 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
6560 to be invisible to users. */
6561
6562 int
6563 ada_is_ignored_field (struct type *type, int field_num)
6564 {
6565 if (field_num < 0 || field_num > TYPE_NFIELDS (type))
6566 return 1;
6567
6568 /* Check the name of that field. */
6569 {
6570 const char *name = TYPE_FIELD_NAME (type, field_num);
6571
6572 /* Anonymous field names should not be printed.
6573 brobecker/2007-02-20: I don't think this can actually happen
6574 but we don't want to print the value of annonymous fields anyway. */
6575 if (name == NULL)
6576 return 1;
6577
6578 /* Normally, fields whose name start with an underscore ("_")
6579 are fields that have been internally generated by the compiler,
6580 and thus should not be printed. The "_parent" field is special,
6581 however: This is a field internally generated by the compiler
6582 for tagged types, and it contains the components inherited from
6583 the parent type. This field should not be printed as is, but
6584 should not be ignored either. */
6585 if (name[0] == '_' && !startswith (name, "_parent"))
6586 return 1;
6587 }
6588
6589 /* If this is the dispatch table of a tagged type or an interface tag,
6590 then ignore. */
6591 if (ada_is_tagged_type (type, 1)
6592 && (ada_is_dispatch_table_ptr_type (TYPE_FIELD_TYPE (type, field_num))
6593 || ada_is_interface_tag (TYPE_FIELD_TYPE (type, field_num))))
6594 return 1;
6595
6596 /* Not a special field, so it should not be ignored. */
6597 return 0;
6598 }
6599
6600 /* True iff TYPE has a tag field. If REFOK, then TYPE may also be a
6601 pointer or reference type whose ultimate target has a tag field. */
6602
6603 int
6604 ada_is_tagged_type (struct type *type, int refok)
6605 {
6606 return (ada_lookup_struct_elt_type (type, "_tag", refok, 1) != NULL);
6607 }
6608
6609 /* True iff TYPE represents the type of X'Tag */
6610
6611 int
6612 ada_is_tag_type (struct type *type)
6613 {
6614 type = ada_check_typedef (type);
6615
6616 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_PTR)
6617 return 0;
6618 else
6619 {
6620 const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
6621
6622 return (name != NULL
6623 && strcmp (name, "ada__tags__dispatch_table") == 0);
6624 }
6625 }
6626
6627 /* The type of the tag on VAL. */
6628
6629 struct type *
6630 ada_tag_type (struct value *val)
6631 {
6632 return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0);
6633 }
6634
6635 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
6636 retired at Ada 05). */
6637
6638 static int
6639 is_ada95_tag (struct value *tag)
6640 {
6641 return ada_value_struct_elt (tag, "tsd", 1) != NULL;
6642 }
6643
6644 /* The value of the tag on VAL. */
6645
6646 struct value *
6647 ada_value_tag (struct value *val)
6648 {
6649 return ada_value_struct_elt (val, "_tag", 0);
6650 }
6651
6652 /* The value of the tag on the object of type TYPE whose contents are
6653 saved at VALADDR, if it is non-null, or is at memory address
6654 ADDRESS. */
6655
6656 static struct value *
6657 value_tag_from_contents_and_address (struct type *type,
6658 const gdb_byte *valaddr,
6659 CORE_ADDR address)
6660 {
6661 int tag_byte_offset;
6662 struct type *tag_type;
6663
6664 if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
6665 NULL, NULL, NULL))
6666 {
6667 const gdb_byte *valaddr1 = ((valaddr == NULL)
6668 ? NULL
6669 : valaddr + tag_byte_offset);
6670 CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
6671
6672 return value_from_contents_and_address (tag_type, valaddr1, address1);
6673 }
6674 return NULL;
6675 }
6676
6677 static struct type *
6678 type_from_tag (struct value *tag)
6679 {
6680 const char *type_name = ada_tag_name (tag);
6681
6682 if (type_name != NULL)
6683 return ada_find_any_type (ada_encode (type_name));
6684 return NULL;
6685 }
6686
6687 /* Given a value OBJ of a tagged type, return a value of this
6688 type at the base address of the object. The base address, as
6689 defined in Ada.Tags, it is the address of the primary tag of
6690 the object, and therefore where the field values of its full
6691 view can be fetched. */
6692
6693 struct value *
6694 ada_tag_value_at_base_address (struct value *obj)
6695 {
6696 struct value *val;
6697 LONGEST offset_to_top = 0;
6698 struct type *ptr_type, *obj_type;
6699 struct value *tag;
6700 CORE_ADDR base_address;
6701
6702 obj_type = value_type (obj);
6703
6704 /* It is the responsability of the caller to deref pointers. */
6705
6706 if (TYPE_CODE (obj_type) == TYPE_CODE_PTR
6707 || TYPE_CODE (obj_type) == TYPE_CODE_REF)
6708 return obj;
6709
6710 tag = ada_value_tag (obj);
6711 if (!tag)
6712 return obj;
6713
6714 /* Base addresses only appeared with Ada 05 and multiple inheritance. */
6715
6716 if (is_ada95_tag (tag))
6717 return obj;
6718
6719 ptr_type = language_lookup_primitive_type
6720 (language_def (language_ada), target_gdbarch(), "storage_offset");
6721 ptr_type = lookup_pointer_type (ptr_type);
6722 val = value_cast (ptr_type, tag);
6723 if (!val)
6724 return obj;
6725
6726 /* It is perfectly possible that an exception be raised while
6727 trying to determine the base address, just like for the tag;
6728 see ada_tag_name for more details. We do not print the error
6729 message for the same reason. */
6730
6731 TRY
6732 {
6733 offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
6734 }
6735
6736 CATCH (e, RETURN_MASK_ERROR)
6737 {
6738 return obj;
6739 }
6740 END_CATCH
6741
6742 /* If offset is null, nothing to do. */
6743
6744 if (offset_to_top == 0)
6745 return obj;
6746
6747 /* -1 is a special case in Ada.Tags; however, what should be done
6748 is not quite clear from the documentation. So do nothing for
6749 now. */
6750
6751 if (offset_to_top == -1)
6752 return obj;
6753
6754 /* OFFSET_TO_TOP used to be a positive value to be subtracted
6755 from the base address. This was however incompatible with
6756 C++ dispatch table: C++ uses a *negative* value to *add*
6757 to the base address. Ada's convention has therefore been
6758 changed in GNAT 19.0w 20171023: since then, C++ and Ada
6759 use the same convention. Here, we support both cases by
6760 checking the sign of OFFSET_TO_TOP. */
6761
6762 if (offset_to_top > 0)
6763 offset_to_top = -offset_to_top;
6764
6765 base_address = value_address (obj) + offset_to_top;
6766 tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
6767
6768 /* Make sure that we have a proper tag at the new address.
6769 Otherwise, offset_to_top is bogus (which can happen when
6770 the object is not initialized yet). */
6771
6772 if (!tag)
6773 return obj;
6774
6775 obj_type = type_from_tag (tag);
6776
6777 if (!obj_type)
6778 return obj;
6779
6780 return value_from_contents_and_address (obj_type, NULL, base_address);
6781 }
6782
6783 /* Return the "ada__tags__type_specific_data" type. */
6784
6785 static struct type *
6786 ada_get_tsd_type (struct inferior *inf)
6787 {
6788 struct ada_inferior_data *data = get_ada_inferior_data (inf);
6789
6790 if (data->tsd_type == 0)
6791 data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
6792 return data->tsd_type;
6793 }
6794
6795 /* Return the TSD (type-specific data) associated to the given TAG.
6796 TAG is assumed to be the tag of a tagged-type entity.
6797
6798 May return NULL if we are unable to get the TSD. */
6799
6800 static struct value *
6801 ada_get_tsd_from_tag (struct value *tag)
6802 {
6803 struct value *val;
6804 struct type *type;
6805
6806 /* First option: The TSD is simply stored as a field of our TAG.
6807 Only older versions of GNAT would use this format, but we have
6808 to test it first, because there are no visible markers for
6809 the current approach except the absence of that field. */
6810
6811 val = ada_value_struct_elt (tag, "tsd", 1);
6812 if (val)
6813 return val;
6814
6815 /* Try the second representation for the dispatch table (in which
6816 there is no explicit 'tsd' field in the referent of the tag pointer,
6817 and instead the tsd pointer is stored just before the dispatch
6818 table. */
6819
6820 type = ada_get_tsd_type (current_inferior());
6821 if (type == NULL)
6822 return NULL;
6823 type = lookup_pointer_type (lookup_pointer_type (type));
6824 val = value_cast (type, tag);
6825 if (val == NULL)
6826 return NULL;
6827 return value_ind (value_ptradd (val, -1));
6828 }
6829
6830 /* Given the TSD of a tag (type-specific data), return a string
6831 containing the name of the associated type.
6832
6833 The returned value is good until the next call. May return NULL
6834 if we are unable to determine the tag name. */
6835
6836 static char *
6837 ada_tag_name_from_tsd (struct value *tsd)
6838 {
6839 static char name[1024];
6840 char *p;
6841 struct value *val;
6842
6843 val = ada_value_struct_elt (tsd, "expanded_name", 1);
6844 if (val == NULL)
6845 return NULL;
6846 read_memory_string (value_as_address (val), name, sizeof (name) - 1);
6847 for (p = name; *p != '\0'; p += 1)
6848 if (isalpha (*p))
6849 *p = tolower (*p);
6850 return name;
6851 }
6852
6853 /* The type name of the dynamic type denoted by the 'tag value TAG, as
6854 a C string.
6855
6856 Return NULL if the TAG is not an Ada tag, or if we were unable to
6857 determine the name of that tag. The result is good until the next
6858 call. */
6859
6860 const char *
6861 ada_tag_name (struct value *tag)
6862 {
6863 char *name = NULL;
6864
6865 if (!ada_is_tag_type (value_type (tag)))
6866 return NULL;
6867
6868 /* It is perfectly possible that an exception be raised while trying
6869 to determine the TAG's name, even under normal circumstances:
6870 The associated variable may be uninitialized or corrupted, for
6871 instance. We do not let any exception propagate past this point.
6872 instead we return NULL.
6873
6874 We also do not print the error message either (which often is very
6875 low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
6876 the caller print a more meaningful message if necessary. */
6877 TRY
6878 {
6879 struct value *tsd = ada_get_tsd_from_tag (tag);
6880
6881 if (tsd != NULL)
6882 name = ada_tag_name_from_tsd (tsd);
6883 }
6884 CATCH (e, RETURN_MASK_ERROR)
6885 {
6886 }
6887 END_CATCH
6888
6889 return name;
6890 }
6891
6892 /* The parent type of TYPE, or NULL if none. */
6893
6894 struct type *
6895 ada_parent_type (struct type *type)
6896 {
6897 int i;
6898
6899 type = ada_check_typedef (type);
6900
6901 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
6902 return NULL;
6903
6904 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6905 if (ada_is_parent_field (type, i))
6906 {
6907 struct type *parent_type = TYPE_FIELD_TYPE (type, i);
6908
6909 /* If the _parent field is a pointer, then dereference it. */
6910 if (TYPE_CODE (parent_type) == TYPE_CODE_PTR)
6911 parent_type = TYPE_TARGET_TYPE (parent_type);
6912 /* If there is a parallel XVS type, get the actual base type. */
6913 parent_type = ada_get_base_type (parent_type);
6914
6915 return ada_check_typedef (parent_type);
6916 }
6917
6918 return NULL;
6919 }
6920
6921 /* True iff field number FIELD_NUM of structure type TYPE contains the
6922 parent-type (inherited) fields of a derived type. Assumes TYPE is
6923 a structure type with at least FIELD_NUM+1 fields. */
6924
6925 int
6926 ada_is_parent_field (struct type *type, int field_num)
6927 {
6928 const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);
6929
6930 return (name != NULL
6931 && (startswith (name, "PARENT")
6932 || startswith (name, "_parent")));
6933 }
6934
6935 /* True iff field number FIELD_NUM of structure type TYPE is a
6936 transparent wrapper field (which should be silently traversed when doing
6937 field selection and flattened when printing). Assumes TYPE is a
6938 structure type with at least FIELD_NUM+1 fields. Such fields are always
6939 structures. */
6940
6941 int
6942 ada_is_wrapper_field (struct type *type, int field_num)
6943 {
6944 const char *name = TYPE_FIELD_NAME (type, field_num);
6945
6946 if (name != NULL && strcmp (name, "RETVAL") == 0)
6947 {
6948 /* This happens in functions with "out" or "in out" parameters
6949 which are passed by copy. For such functions, GNAT describes
6950 the function's return type as being a struct where the return
6951 value is in a field called RETVAL, and where the other "out"
6952 or "in out" parameters are fields of that struct. This is not
6953 a wrapper. */
6954 return 0;
6955 }
6956
6957 return (name != NULL
6958 && (startswith (name, "PARENT")
6959 || strcmp (name, "REP") == 0
6960 || startswith (name, "_parent")
6961 || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
6962 }
6963
6964 /* True iff field number FIELD_NUM of structure or union type TYPE
6965 is a variant wrapper. Assumes TYPE is a structure type with at least
6966 FIELD_NUM+1 fields. */
6967
6968 int
6969 ada_is_variant_part (struct type *type, int field_num)
6970 {
6971 struct type *field_type = TYPE_FIELD_TYPE (type, field_num);
6972
6973 return (TYPE_CODE (field_type) == TYPE_CODE_UNION
6974 || (is_dynamic_field (type, field_num)
6975 && (TYPE_CODE (TYPE_TARGET_TYPE (field_type))
6976 == TYPE_CODE_UNION)));
6977 }
6978
6979 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
6980 whose discriminants are contained in the record type OUTER_TYPE,
6981 returns the type of the controlling discriminant for the variant.
6982 May return NULL if the type could not be found. */
6983
6984 struct type *
6985 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
6986 {
6987 const char *name = ada_variant_discrim_name (var_type);
6988
6989 return ada_lookup_struct_elt_type (outer_type, name, 1, 1);
6990 }
6991
6992 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
6993 valid field number within it, returns 1 iff field FIELD_NUM of TYPE
6994 represents a 'when others' clause; otherwise 0. */
6995
6996 int
6997 ada_is_others_clause (struct type *type, int field_num)
6998 {
6999 const char *name = TYPE_FIELD_NAME (type, field_num);
7000
7001 return (name != NULL && name[0] == 'O');
7002 }
7003
7004 /* Assuming that TYPE0 is the type of the variant part of a record,
7005 returns the name of the discriminant controlling the variant.
7006 The value is valid until the next call to ada_variant_discrim_name. */
7007
7008 const char *
7009 ada_variant_discrim_name (struct type *type0)
7010 {
7011 static char *result = NULL;
7012 static size_t result_len = 0;
7013 struct type *type;
7014 const char *name;
7015 const char *discrim_end;
7016 const char *discrim_start;
7017
7018 if (TYPE_CODE (type0) == TYPE_CODE_PTR)
7019 type = TYPE_TARGET_TYPE (type0);
7020 else
7021 type = type0;
7022
7023 name = ada_type_name (type);
7024
7025 if (name == NULL || name[0] == '\000')
7026 return "";
7027
7028 for (discrim_end = name + strlen (name) - 6; discrim_end != name;
7029 discrim_end -= 1)
7030 {
7031 if (startswith (discrim_end, "___XVN"))
7032 break;
7033 }
7034 if (discrim_end == name)
7035 return "";
7036
7037 for (discrim_start = discrim_end; discrim_start != name + 3;
7038 discrim_start -= 1)
7039 {
7040 if (discrim_start == name + 1)
7041 return "";
7042 if ((discrim_start > name + 3
7043 && startswith (discrim_start - 3, "___"))
7044 || discrim_start[-1] == '.')
7045 break;
7046 }
7047
7048 GROW_VECT (result, result_len, discrim_end - discrim_start + 1);
7049 strncpy (result, discrim_start, discrim_end - discrim_start);
7050 result[discrim_end - discrim_start] = '\0';
7051 return result;
7052 }
7053
7054 /* Scan STR for a subtype-encoded number, beginning at position K.
7055 Put the position of the character just past the number scanned in
7056 *NEW_K, if NEW_K!=NULL. Put the scanned number in *R, if R!=NULL.
7057 Return 1 if there was a valid number at the given position, and 0
7058 otherwise. A "subtype-encoded" number consists of the absolute value
7059 in decimal, followed by the letter 'm' to indicate a negative number.
7060 Assumes 0m does not occur. */
7061
7062 int
7063 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
7064 {
7065 ULONGEST RU;
7066
7067 if (!isdigit (str[k]))
7068 return 0;
7069
7070 /* Do it the hard way so as not to make any assumption about
7071 the relationship of unsigned long (%lu scan format code) and
7072 LONGEST. */
7073 RU = 0;
7074 while (isdigit (str[k]))
7075 {
7076 RU = RU * 10 + (str[k] - '0');
7077 k += 1;
7078 }
7079
7080 if (str[k] == 'm')
7081 {
7082 if (R != NULL)
7083 *R = (-(LONGEST) (RU - 1)) - 1;
7084 k += 1;
7085 }
7086 else if (R != NULL)
7087 *R = (LONGEST) RU;
7088
7089 /* NOTE on the above: Technically, C does not say what the results of
7090 - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
7091 number representable as a LONGEST (although either would probably work
7092 in most implementations). When RU>0, the locution in the then branch
7093 above is always equivalent to the negative of RU. */
7094
7095 if (new_k != NULL)
7096 *new_k = k;
7097 return 1;
7098 }
7099
7100 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
7101 and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
7102 in the range encoded by field FIELD_NUM of TYPE; otherwise 0. */
7103
7104 int
7105 ada_in_variant (LONGEST val, struct type *type, int field_num)
7106 {
7107 const char *name = TYPE_FIELD_NAME (type, field_num);
7108 int p;
7109
7110 p = 0;
7111 while (1)
7112 {
7113 switch (name[p])
7114 {
7115 case '\0':
7116 return 0;
7117 case 'S':
7118 {
7119 LONGEST W;
7120
7121 if (!ada_scan_number (name, p + 1, &W, &p))
7122 return 0;
7123 if (val == W)
7124 return 1;
7125 break;
7126 }
7127 case 'R':
7128 {
7129 LONGEST L, U;
7130
7131 if (!ada_scan_number (name, p + 1, &L, &p)
7132 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
7133 return 0;
7134 if (val >= L && val <= U)
7135 return 1;
7136 break;
7137 }
7138 case 'O':
7139 return 1;
7140 default:
7141 return 0;
7142 }
7143 }
7144 }
7145
7146 /* FIXME: Lots of redundancy below. Try to consolidate. */
7147
7148 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
7149 ARG_TYPE, extract and return the value of one of its (non-static)
7150 fields. FIELDNO says which field. Differs from value_primitive_field
7151 only in that it can handle packed values of arbitrary type. */
7152
7153 static struct value *
7154 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
7155 struct type *arg_type)
7156 {
7157 struct type *type;
7158
7159 arg_type = ada_check_typedef (arg_type);
7160 type = TYPE_FIELD_TYPE (arg_type, fieldno);
7161
7162 /* Handle packed fields. */
7163
7164 if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0)
7165 {
7166 int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
7167 int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
7168
7169 return ada_value_primitive_packed_val (arg1, value_contents (arg1),
7170 offset + bit_pos / 8,
7171 bit_pos % 8, bit_size, type);
7172 }
7173 else
7174 return value_primitive_field (arg1, offset, fieldno, arg_type);
7175 }
7176
7177 /* Find field with name NAME in object of type TYPE. If found,
7178 set the following for each argument that is non-null:
7179 - *FIELD_TYPE_P to the field's type;
7180 - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within
7181 an object of that type;
7182 - *BIT_OFFSET_P to the bit offset modulo byte size of the field;
7183 - *BIT_SIZE_P to its size in bits if the field is packed, and
7184 0 otherwise;
7185 If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
7186 fields up to but not including the desired field, or by the total
7187 number of fields if not found. A NULL value of NAME never
7188 matches; the function just counts visible fields in this case.
7189
7190 Notice that we need to handle when a tagged record hierarchy
7191 has some components with the same name, like in this scenario:
7192
7193 type Top_T is tagged record
7194 N : Integer := 1;
7195 U : Integer := 974;
7196 A : Integer := 48;
7197 end record;
7198
7199 type Middle_T is new Top.Top_T with record
7200 N : Character := 'a';
7201 C : Integer := 3;
7202 end record;
7203
7204 type Bottom_T is new Middle.Middle_T with record
7205 N : Float := 4.0;
7206 C : Character := '5';
7207 X : Integer := 6;
7208 A : Character := 'J';
7209 end record;
7210
7211 Let's say we now have a variable declared and initialized as follow:
7212
7213 TC : Top_A := new Bottom_T;
7214
7215 And then we use this variable to call this function
7216
7217 procedure Assign (Obj: in out Top_T; TV : Integer);
7218
7219 as follow:
7220
7221 Assign (Top_T (B), 12);
7222
7223 Now, we're in the debugger, and we're inside that procedure
7224 then and we want to print the value of obj.c:
7225
7226 Usually, the tagged record or one of the parent type owns the
7227 component to print and there's no issue but in this particular
7228 case, what does it mean to ask for Obj.C? Since the actual
7229 type for object is type Bottom_T, it could mean two things: type
7230 component C from the Middle_T view, but also component C from
7231 Bottom_T. So in that "undefined" case, when the component is
7232 not found in the non-resolved type (which includes all the
7233 components of the parent type), then resolve it and see if we
7234 get better luck once expanded.
7235
7236 In the case of homonyms in the derived tagged type, we don't
7237 guaranty anything, and pick the one that's easiest for us
7238 to program.
7239
7240 Returns 1 if found, 0 otherwise. */
7241
7242 static int
7243 find_struct_field (const char *name, struct type *type, int offset,
7244 struct type **field_type_p,
7245 int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
7246 int *index_p)
7247 {
7248 int i;
7249 int parent_offset = -1;
7250
7251 type = ada_check_typedef (type);
7252
7253 if (field_type_p != NULL)
7254 *field_type_p = NULL;
7255 if (byte_offset_p != NULL)
7256 *byte_offset_p = 0;
7257 if (bit_offset_p != NULL)
7258 *bit_offset_p = 0;
7259 if (bit_size_p != NULL)
7260 *bit_size_p = 0;
7261
7262 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7263 {
7264 int bit_pos = TYPE_FIELD_BITPOS (type, i);
7265 int fld_offset = offset + bit_pos / 8;
7266 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7267
7268 if (t_field_name == NULL)
7269 continue;
7270
7271 else if (ada_is_parent_field (type, i))
7272 {
7273 /* This is a field pointing us to the parent type of a tagged
7274 type. As hinted in this function's documentation, we give
7275 preference to fields in the current record first, so what
7276 we do here is just record the index of this field before
7277 we skip it. If it turns out we couldn't find our field
7278 in the current record, then we'll get back to it and search
7279 inside it whether the field might exist in the parent. */
7280
7281 parent_offset = i;
7282 continue;
7283 }
7284
7285 else if (name != NULL && field_name_match (t_field_name, name))
7286 {
7287 int bit_size = TYPE_FIELD_BITSIZE (type, i);
7288
7289 if (field_type_p != NULL)
7290 *field_type_p = TYPE_FIELD_TYPE (type, i);
7291 if (byte_offset_p != NULL)
7292 *byte_offset_p = fld_offset;
7293 if (bit_offset_p != NULL)
7294 *bit_offset_p = bit_pos % 8;
7295 if (bit_size_p != NULL)
7296 *bit_size_p = bit_size;
7297 return 1;
7298 }
7299 else if (ada_is_wrapper_field (type, i))
7300 {
7301 if (find_struct_field (name, TYPE_FIELD_TYPE (type, i), fld_offset,
7302 field_type_p, byte_offset_p, bit_offset_p,
7303 bit_size_p, index_p))
7304 return 1;
7305 }
7306 else if (ada_is_variant_part (type, i))
7307 {
7308 /* PNH: Wait. Do we ever execute this section, or is ARG always of
7309 fixed type?? */
7310 int j;
7311 struct type *field_type
7312 = ada_check_typedef (TYPE_FIELD_TYPE (type, i));
7313
7314 for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
7315 {
7316 if (find_struct_field (name, TYPE_FIELD_TYPE (field_type, j),
7317 fld_offset
7318 + TYPE_FIELD_BITPOS (field_type, j) / 8,
7319 field_type_p, byte_offset_p,
7320 bit_offset_p, bit_size_p, index_p))
7321 return 1;
7322 }
7323 }
7324 else if (index_p != NULL)
7325 *index_p += 1;
7326 }
7327
7328 /* Field not found so far. If this is a tagged type which
7329 has a parent, try finding that field in the parent now. */
7330
7331 if (parent_offset != -1)
7332 {
7333 int bit_pos = TYPE_FIELD_BITPOS (type, parent_offset);
7334 int fld_offset = offset + bit_pos / 8;
7335
7336 if (find_struct_field (name, TYPE_FIELD_TYPE (type, parent_offset),
7337 fld_offset, field_type_p, byte_offset_p,
7338 bit_offset_p, bit_size_p, index_p))
7339 return 1;
7340 }
7341
7342 return 0;
7343 }
7344
7345 /* Number of user-visible fields in record type TYPE. */
7346
7347 static int
7348 num_visible_fields (struct type *type)
7349 {
7350 int n;
7351
7352 n = 0;
7353 find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
7354 return n;
7355 }
7356
7357 /* Look for a field NAME in ARG. Adjust the address of ARG by OFFSET bytes,
7358 and search in it assuming it has (class) type TYPE.
7359 If found, return value, else return NULL.
7360
7361 Searches recursively through wrapper fields (e.g., '_parent').
7362
7363 In the case of homonyms in the tagged types, please refer to the
7364 long explanation in find_struct_field's function documentation. */
7365
7366 static struct value *
7367 ada_search_struct_field (const char *name, struct value *arg, int offset,
7368 struct type *type)
7369 {
7370 int i;
7371 int parent_offset = -1;
7372
7373 type = ada_check_typedef (type);
7374 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7375 {
7376 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7377
7378 if (t_field_name == NULL)
7379 continue;
7380
7381 else if (ada_is_parent_field (type, i))
7382 {
7383 /* This is a field pointing us to the parent type of a tagged
7384 type. As hinted in this function's documentation, we give
7385 preference to fields in the current record first, so what
7386 we do here is just record the index of this field before
7387 we skip it. If it turns out we couldn't find our field
7388 in the current record, then we'll get back to it and search
7389 inside it whether the field might exist in the parent. */
7390
7391 parent_offset = i;
7392 continue;
7393 }
7394
7395 else if (field_name_match (t_field_name, name))
7396 return ada_value_primitive_field (arg, offset, i, type);
7397
7398 else if (ada_is_wrapper_field (type, i))
7399 {
7400 struct value *v = /* Do not let indent join lines here. */
7401 ada_search_struct_field (name, arg,
7402 offset + TYPE_FIELD_BITPOS (type, i) / 8,
7403 TYPE_FIELD_TYPE (type, i));
7404
7405 if (v != NULL)
7406 return v;
7407 }
7408
7409 else if (ada_is_variant_part (type, i))
7410 {
7411 /* PNH: Do we ever get here? See find_struct_field. */
7412 int j;
7413 struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
7414 i));
7415 int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
7416
7417 for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
7418 {
7419 struct value *v = ada_search_struct_field /* Force line
7420 break. */
7421 (name, arg,
7422 var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
7423 TYPE_FIELD_TYPE (field_type, j));
7424
7425 if (v != NULL)
7426 return v;
7427 }
7428 }
7429 }
7430
7431 /* Field not found so far. If this is a tagged type which
7432 has a parent, try finding that field in the parent now. */
7433
7434 if (parent_offset != -1)
7435 {
7436 struct value *v = ada_search_struct_field (
7437 name, arg, offset + TYPE_FIELD_BITPOS (type, parent_offset) / 8,
7438 TYPE_FIELD_TYPE (type, parent_offset));
7439
7440 if (v != NULL)
7441 return v;
7442 }
7443
7444 return NULL;
7445 }
7446
7447 static struct value *ada_index_struct_field_1 (int *, struct value *,
7448 int, struct type *);
7449
7450
7451 /* Return field #INDEX in ARG, where the index is that returned by
7452 * find_struct_field through its INDEX_P argument. Adjust the address
7453 * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
7454 * If found, return value, else return NULL. */
7455
7456 static struct value *
7457 ada_index_struct_field (int index, struct value *arg, int offset,
7458 struct type *type)
7459 {
7460 return ada_index_struct_field_1 (&index, arg, offset, type);
7461 }
7462
7463
7464 /* Auxiliary function for ada_index_struct_field. Like
7465 * ada_index_struct_field, but takes index from *INDEX_P and modifies
7466 * *INDEX_P. */
7467
7468 static struct value *
7469 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
7470 struct type *type)
7471 {
7472 int i;
7473 type = ada_check_typedef (type);
7474
7475 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7476 {
7477 if (TYPE_FIELD_NAME (type, i) == NULL)
7478 continue;
7479 else if (ada_is_wrapper_field (type, i))
7480 {
7481 struct value *v = /* Do not let indent join lines here. */
7482 ada_index_struct_field_1 (index_p, arg,
7483 offset + TYPE_FIELD_BITPOS (type, i) / 8,
7484 TYPE_FIELD_TYPE (type, i));
7485
7486 if (v != NULL)
7487 return v;
7488 }
7489
7490 else if (ada_is_variant_part (type, i))
7491 {
7492 /* PNH: Do we ever get here? See ada_search_struct_field,
7493 find_struct_field. */
7494 error (_("Cannot assign this kind of variant record"));
7495 }
7496 else if (*index_p == 0)
7497 return ada_value_primitive_field (arg, offset, i, type);
7498 else
7499 *index_p -= 1;
7500 }
7501 return NULL;
7502 }
7503
7504 /* Given ARG, a value of type (pointer or reference to a)*
7505 structure/union, extract the component named NAME from the ultimate
7506 target structure/union and return it as a value with its
7507 appropriate type.
7508
7509 The routine searches for NAME among all members of the structure itself
7510 and (recursively) among all members of any wrapper members
7511 (e.g., '_parent').
7512
7513 If NO_ERR, then simply return NULL in case of error, rather than
7514 calling error. */
7515
7516 struct value *
7517 ada_value_struct_elt (struct value *arg, const char *name, int no_err)
7518 {
7519 struct type *t, *t1;
7520 struct value *v;
7521 int check_tag;
7522
7523 v = NULL;
7524 t1 = t = ada_check_typedef (value_type (arg));
7525 if (TYPE_CODE (t) == TYPE_CODE_REF)
7526 {
7527 t1 = TYPE_TARGET_TYPE (t);
7528 if (t1 == NULL)
7529 goto BadValue;
7530 t1 = ada_check_typedef (t1);
7531 if (TYPE_CODE (t1) == TYPE_CODE_PTR)
7532 {
7533 arg = coerce_ref (arg);
7534 t = t1;
7535 }
7536 }
7537
7538 while (TYPE_CODE (t) == TYPE_CODE_PTR)
7539 {
7540 t1 = TYPE_TARGET_TYPE (t);
7541 if (t1 == NULL)
7542 goto BadValue;
7543 t1 = ada_check_typedef (t1);
7544 if (TYPE_CODE (t1) == TYPE_CODE_PTR)
7545 {
7546 arg = value_ind (arg);
7547 t = t1;
7548 }
7549 else
7550 break;
7551 }
7552
7553 if (TYPE_CODE (t1) != TYPE_CODE_STRUCT && TYPE_CODE (t1) != TYPE_CODE_UNION)
7554 goto BadValue;
7555
7556 if (t1 == t)
7557 v = ada_search_struct_field (name, arg, 0, t);
7558 else
7559 {
7560 int bit_offset, bit_size, byte_offset;
7561 struct type *field_type;
7562 CORE_ADDR address;
7563
7564 if (TYPE_CODE (t) == TYPE_CODE_PTR)
7565 address = value_address (ada_value_ind (arg));
7566 else
7567 address = value_address (ada_coerce_ref (arg));
7568
7569 /* Check to see if this is a tagged type. We also need to handle
7570 the case where the type is a reference to a tagged type, but
7571 we have to be careful to exclude pointers to tagged types.
7572 The latter should be shown as usual (as a pointer), whereas
7573 a reference should mostly be transparent to the user. */
7574
7575 if (ada_is_tagged_type (t1, 0)
7576 || (TYPE_CODE (t1) == TYPE_CODE_REF
7577 && ada_is_tagged_type (TYPE_TARGET_TYPE (t1), 0)))
7578 {
7579 /* We first try to find the searched field in the current type.
7580 If not found then let's look in the fixed type. */
7581
7582 if (!find_struct_field (name, t1, 0,
7583 &field_type, &byte_offset, &bit_offset,
7584 &bit_size, NULL))
7585 check_tag = 1;
7586 else
7587 check_tag = 0;
7588 }
7589 else
7590 check_tag = 0;
7591
7592 /* Convert to fixed type in all cases, so that we have proper
7593 offsets to each field in unconstrained record types. */
7594 t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL,
7595 address, NULL, check_tag);
7596
7597 if (find_struct_field (name, t1, 0,
7598 &field_type, &byte_offset, &bit_offset,
7599 &bit_size, NULL))
7600 {
7601 if (bit_size != 0)
7602 {
7603 if (TYPE_CODE (t) == TYPE_CODE_REF)
7604 arg = ada_coerce_ref (arg);
7605 else
7606 arg = ada_value_ind (arg);
7607 v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
7608 bit_offset, bit_size,
7609 field_type);
7610 }
7611 else
7612 v = value_at_lazy (field_type, address + byte_offset);
7613 }
7614 }
7615
7616 if (v != NULL || no_err)
7617 return v;
7618 else
7619 error (_("There is no member named %s."), name);
7620
7621 BadValue:
7622 if (no_err)
7623 return NULL;
7624 else
7625 error (_("Attempt to extract a component of "
7626 "a value that is not a record."));
7627 }
7628
7629 /* Return a string representation of type TYPE. */
7630
7631 static std::string
7632 type_as_string (struct type *type)
7633 {
7634 string_file tmp_stream;
7635
7636 type_print (type, "", &tmp_stream, -1);
7637
7638 return std::move (tmp_stream.string ());
7639 }
7640
7641 /* Given a type TYPE, look up the type of the component of type named NAME.
7642 If DISPP is non-null, add its byte displacement from the beginning of a
7643 structure (pointed to by a value) of type TYPE to *DISPP (does not
7644 work for packed fields).
7645
7646 Matches any field whose name has NAME as a prefix, possibly
7647 followed by "___".
7648
7649 TYPE can be either a struct or union. If REFOK, TYPE may also
7650 be a (pointer or reference)+ to a struct or union, and the
7651 ultimate target type will be searched.
7652
7653 Looks recursively into variant clauses and parent types.
7654
7655 In the case of homonyms in the tagged types, please refer to the
7656 long explanation in find_struct_field's function documentation.
7657
7658 If NOERR is nonzero, return NULL if NAME is not suitably defined or
7659 TYPE is not a type of the right kind. */
7660
7661 static struct type *
7662 ada_lookup_struct_elt_type (struct type *type, const char *name, int refok,
7663 int noerr)
7664 {
7665 int i;
7666 int parent_offset = -1;
7667
7668 if (name == NULL)
7669 goto BadName;
7670
7671 if (refok && type != NULL)
7672 while (1)
7673 {
7674 type = ada_check_typedef (type);
7675 if (TYPE_CODE (type) != TYPE_CODE_PTR
7676 && TYPE_CODE (type) != TYPE_CODE_REF)
7677 break;
7678 type = TYPE_TARGET_TYPE (type);
7679 }
7680
7681 if (type == NULL
7682 || (TYPE_CODE (type) != TYPE_CODE_STRUCT
7683 && TYPE_CODE (type) != TYPE_CODE_UNION))
7684 {
7685 if (noerr)
7686 return NULL;
7687
7688 error (_("Type %s is not a structure or union type"),
7689 type != NULL ? type_as_string (type).c_str () : _("(null)"));
7690 }
7691
7692 type = to_static_fixed_type (type);
7693
7694 for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7695 {
7696 const char *t_field_name = TYPE_FIELD_NAME (type, i);
7697 struct type *t;
7698
7699 if (t_field_name == NULL)
7700 continue;
7701
7702 else if (ada_is_parent_field (type, i))
7703 {
7704 /* This is a field pointing us to the parent type of a tagged
7705 type. As hinted in this function's documentation, we give
7706 preference to fields in the current record first, so what
7707 we do here is just record the index of this field before
7708 we skip it. If it turns out we couldn't find our field
7709 in the current record, then we'll get back to it and search
7710 inside it whether the field might exist in the parent. */
7711
7712 parent_offset = i;
7713 continue;
7714 }
7715
7716 else if (field_name_match (t_field_name, name))
7717 return TYPE_FIELD_TYPE (type, i);
7718
7719 else if (ada_is_wrapper_field (type, i))
7720 {
7721 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, i), name,
7722 0, 1);
7723 if (t != NULL)
7724 return t;
7725 }
7726
7727 else if (ada_is_variant_part (type, i))
7728 {
7729 int j;
7730 struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
7731 i));
7732
7733 for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
7734 {
7735 /* FIXME pnh 2008/01/26: We check for a field that is
7736 NOT wrapped in a struct, since the compiler sometimes
7737 generates these for unchecked variant types. Revisit
7738 if the compiler changes this practice. */
7739 const char *v_field_name = TYPE_FIELD_NAME (field_type, j);
7740
7741 if (v_field_name != NULL
7742 && field_name_match (v_field_name, name))
7743 t = TYPE_FIELD_TYPE (field_type, j);
7744 else
7745 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (field_type,
7746 j),
7747 name, 0, 1);
7748
7749 if (t != NULL)
7750 return t;
7751 }
7752 }
7753
7754 }
7755
7756 /* Field not found so far. If this is a tagged type which
7757 has a parent, try finding that field in the parent now. */
7758
7759 if (parent_offset != -1)
7760 {
7761 struct type *t;
7762
7763 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, parent_offset),
7764 name, 0, 1);
7765 if (t != NULL)
7766 return t;
7767 }
7768
7769 BadName:
7770 if (!noerr)
7771 {
7772 const char *name_str = name != NULL ? name : _("<null>");
7773
7774 error (_("Type %s has no component named %s"),
7775 type_as_string (type).c_str (), name_str);
7776 }
7777
7778 return NULL;
7779 }
7780
7781 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7782 within a value of type OUTER_TYPE, return true iff VAR_TYPE
7783 represents an unchecked union (that is, the variant part of a
7784 record that is named in an Unchecked_Union pragma). */
7785
7786 static int
7787 is_unchecked_variant (struct type *var_type, struct type *outer_type)
7788 {
7789 const char *discrim_name = ada_variant_discrim_name (var_type);
7790
7791 return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1) == NULL);
7792 }
7793
7794
7795 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
7796 within a value of type OUTER_TYPE that is stored in GDB at
7797 OUTER_VALADDR, determine which variant clause (field number in VAR_TYPE,
7798 numbering from 0) is applicable. Returns -1 if none are. */
7799
7800 int
7801 ada_which_variant_applies (struct type *var_type, struct type *outer_type,
7802 const gdb_byte *outer_valaddr)
7803 {
7804 int others_clause;
7805 int i;
7806 const char *discrim_name = ada_variant_discrim_name (var_type);
7807 struct value *outer;
7808 struct value *discrim;
7809 LONGEST discrim_val;
7810
7811 /* Using plain value_from_contents_and_address here causes problems
7812 because we will end up trying to resolve a type that is currently
7813 being constructed. */
7814 outer = value_from_contents_and_address_unresolved (outer_type,
7815 outer_valaddr, 0);
7816 discrim = ada_value_struct_elt (outer, discrim_name, 1);
7817 if (discrim == NULL)
7818 return -1;
7819 discrim_val = value_as_long (discrim);
7820
7821 others_clause = -1;
7822 for (i = 0; i < TYPE_NFIELDS (var_type); i += 1)
7823 {
7824 if (ada_is_others_clause (var_type, i))
7825 others_clause = i;
7826 else if (ada_in_variant (discrim_val, var_type, i))
7827 return i;
7828 }
7829
7830 return others_clause;
7831 }
7832 \f
7833
7834
7835 /* Dynamic-Sized Records */
7836
7837 /* Strategy: The type ostensibly attached to a value with dynamic size
7838 (i.e., a size that is not statically recorded in the debugging
7839 data) does not accurately reflect the size or layout of the value.
7840 Our strategy is to convert these values to values with accurate,
7841 conventional types that are constructed on the fly. */
7842
7843 /* There is a subtle and tricky problem here. In general, we cannot
7844 determine the size of dynamic records without its data. However,
7845 the 'struct value' data structure, which GDB uses to represent
7846 quantities in the inferior process (the target), requires the size
7847 of the type at the time of its allocation in order to reserve space
7848 for GDB's internal copy of the data. That's why the
7849 'to_fixed_xxx_type' routines take (target) addresses as parameters,
7850 rather than struct value*s.
7851
7852 However, GDB's internal history variables ($1, $2, etc.) are
7853 struct value*s containing internal copies of the data that are not, in
7854 general, the same as the data at their corresponding addresses in
7855 the target. Fortunately, the types we give to these values are all
7856 conventional, fixed-size types (as per the strategy described
7857 above), so that we don't usually have to perform the
7858 'to_fixed_xxx_type' conversions to look at their values.
7859 Unfortunately, there is one exception: if one of the internal
7860 history variables is an array whose elements are unconstrained
7861 records, then we will need to create distinct fixed types for each
7862 element selected. */
7863
7864 /* The upshot of all of this is that many routines take a (type, host
7865 address, target address) triple as arguments to represent a value.
7866 The host address, if non-null, is supposed to contain an internal
7867 copy of the relevant data; otherwise, the program is to consult the
7868 target at the target address. */
7869
7870 /* Assuming that VAL0 represents a pointer value, the result of
7871 dereferencing it. Differs from value_ind in its treatment of
7872 dynamic-sized types. */
7873
7874 struct value *
7875 ada_value_ind (struct value *val0)
7876 {
7877 struct value *val = value_ind (val0);
7878
7879 if (ada_is_tagged_type (value_type (val), 0))
7880 val = ada_tag_value_at_base_address (val);
7881
7882 return ada_to_fixed_value (val);
7883 }
7884
7885 /* The value resulting from dereferencing any "reference to"
7886 qualifiers on VAL0. */
7887
7888 static struct value *
7889 ada_coerce_ref (struct value *val0)
7890 {
7891 if (TYPE_CODE (value_type (val0)) == TYPE_CODE_REF)
7892 {
7893 struct value *val = val0;
7894
7895 val = coerce_ref (val);
7896
7897 if (ada_is_tagged_type (value_type (val), 0))
7898 val = ada_tag_value_at_base_address (val);
7899
7900 return ada_to_fixed_value (val);
7901 }
7902 else
7903 return val0;
7904 }
7905
7906 /* Return OFF rounded upward if necessary to a multiple of
7907 ALIGNMENT (a power of 2). */
7908
7909 static unsigned int
7910 align_value (unsigned int off, unsigned int alignment)
7911 {
7912 return (off + alignment - 1) & ~(alignment - 1);
7913 }
7914
7915 /* Return the bit alignment required for field #F of template type TYPE. */
7916
7917 static unsigned int
7918 field_alignment (struct type *type, int f)
7919 {
7920 const char *name = TYPE_FIELD_NAME (type, f);
7921 int len;
7922 int align_offset;
7923
7924 /* The field name should never be null, unless the debugging information
7925 is somehow malformed. In this case, we assume the field does not
7926 require any alignment. */
7927 if (name == NULL)
7928 return 1;
7929
7930 len = strlen (name);
7931
7932 if (!isdigit (name[len - 1]))
7933 return 1;
7934
7935 if (isdigit (name[len - 2]))
7936 align_offset = len - 2;
7937 else
7938 align_offset = len - 1;
7939
7940 if (align_offset < 7 || !startswith (name + align_offset - 6, "___XV"))
7941 return TARGET_CHAR_BIT;
7942
7943 return atoi (name + align_offset) * TARGET_CHAR_BIT;
7944 }
7945
7946 /* Find a typedef or tag symbol named NAME. Ignores ambiguity. */
7947
7948 static struct symbol *
7949 ada_find_any_type_symbol (const char *name)
7950 {
7951 struct symbol *sym;
7952
7953 sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
7954 if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
7955 return sym;
7956
7957 sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
7958 return sym;
7959 }
7960
7961 /* Find a type named NAME. Ignores ambiguity. This routine will look
7962 solely for types defined by debug info, it will not search the GDB
7963 primitive types. */
7964
7965 static struct type *
7966 ada_find_any_type (const char *name)
7967 {
7968 struct symbol *sym = ada_find_any_type_symbol (name);
7969
7970 if (sym != NULL)
7971 return SYMBOL_TYPE (sym);
7972
7973 return NULL;
7974 }
7975
7976 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
7977 associated with NAME_SYM's name. NAME_SYM may itself be a renaming
7978 symbol, in which case it is returned. Otherwise, this looks for
7979 symbols whose name is that of NAME_SYM suffixed with "___XR".
7980 Return symbol if found, and NULL otherwise. */
7981
7982 struct symbol *
7983 ada_find_renaming_symbol (struct symbol *name_sym, const struct block *block)
7984 {
7985 const char *name = SYMBOL_LINKAGE_NAME (name_sym);
7986 struct symbol *sym;
7987
7988 if (strstr (name, "___XR") != NULL)
7989 return name_sym;
7990
7991 sym = find_old_style_renaming_symbol (name, block);
7992
7993 if (sym != NULL)
7994 return sym;
7995
7996 /* Not right yet. FIXME pnh 7/20/2007. */
7997 sym = ada_find_any_type_symbol (name);
7998 if (sym != NULL && strstr (SYMBOL_LINKAGE_NAME (sym), "___XR") != NULL)
7999 return sym;
8000 else
8001 return NULL;
8002 }
8003
8004 static struct symbol *
8005 find_old_style_renaming_symbol (const char *name, const struct block *block)
8006 {
8007 const struct symbol *function_sym = block_linkage_function (block);
8008 char *rename;
8009
8010 if (function_sym != NULL)
8011 {
8012 /* If the symbol is defined inside a function, NAME is not fully
8013 qualified. This means we need to prepend the function name
8014 as well as adding the ``___XR'' suffix to build the name of
8015 the associated renaming symbol. */
8016 const char *function_name = SYMBOL_LINKAGE_NAME (function_sym);
8017 /* Function names sometimes contain suffixes used
8018 for instance to qualify nested subprograms. When building
8019 the XR type name, we need to make sure that this suffix is
8020 not included. So do not include any suffix in the function
8021 name length below. */
8022 int function_name_len = ada_name_prefix_len (function_name);
8023 const int rename_len = function_name_len + 2 /* "__" */
8024 + strlen (name) + 6 /* "___XR\0" */ ;
8025
8026 /* Strip the suffix if necessary. */
8027 ada_remove_trailing_digits (function_name, &function_name_len);
8028 ada_remove_po_subprogram_suffix (function_name, &function_name_len);
8029 ada_remove_Xbn_suffix (function_name, &function_name_len);
8030
8031 /* Library-level functions are a special case, as GNAT adds
8032 a ``_ada_'' prefix to the function name to avoid namespace
8033 pollution. However, the renaming symbols themselves do not
8034 have this prefix, so we need to skip this prefix if present. */
8035 if (function_name_len > 5 /* "_ada_" */
8036 && strstr (function_name, "_ada_") == function_name)
8037 {
8038 function_name += 5;
8039 function_name_len -= 5;
8040 }
8041
8042 rename = (char *) alloca (rename_len * sizeof (char));
8043 strncpy (rename, function_name, function_name_len);
8044 xsnprintf (rename + function_name_len, rename_len - function_name_len,
8045 "__%s___XR", name);
8046 }
8047 else
8048 {
8049 const int rename_len = strlen (name) + 6;
8050
8051 rename = (char *) alloca (rename_len * sizeof (char));
8052 xsnprintf (rename, rename_len * sizeof (char), "%s___XR", name);
8053 }
8054
8055 return ada_find_any_type_symbol (rename);
8056 }
8057
8058 /* Because of GNAT encoding conventions, several GDB symbols may match a
8059 given type name. If the type denoted by TYPE0 is to be preferred to
8060 that of TYPE1 for purposes of type printing, return non-zero;
8061 otherwise return 0. */
8062
8063 int
8064 ada_prefer_type (struct type *type0, struct type *type1)
8065 {
8066 if (type1 == NULL)
8067 return 1;
8068 else if (type0 == NULL)
8069 return 0;
8070 else if (TYPE_CODE (type1) == TYPE_CODE_VOID)
8071 return 1;
8072 else if (TYPE_CODE (type0) == TYPE_CODE_VOID)
8073 return 0;
8074 else if (TYPE_NAME (type1) == NULL && TYPE_NAME (type0) != NULL)
8075 return 1;
8076 else if (ada_is_constrained_packed_array_type (type0))
8077 return 1;
8078 else if (ada_is_array_descriptor_type (type0)
8079 && !ada_is_array_descriptor_type (type1))
8080 return 1;
8081 else
8082 {
8083 const char *type0_name = TYPE_NAME (type0);
8084 const char *type1_name = TYPE_NAME (type1);
8085
8086 if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
8087 && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
8088 return 1;
8089 }
8090 return 0;
8091 }
8092
8093 /* The name of TYPE, which is its TYPE_NAME. Null if TYPE is
8094 null. */
8095
8096 const char *
8097 ada_type_name (struct type *type)
8098 {
8099 if (type == NULL)
8100 return NULL;
8101 return TYPE_NAME (type);
8102 }
8103
8104 /* Search the list of "descriptive" types associated to TYPE for a type
8105 whose name is NAME. */
8106
8107 static struct type *
8108 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
8109 {
8110 struct type *result, *tmp;
8111
8112 if (ada_ignore_descriptive_types_p)
8113 return NULL;
8114
8115 /* If there no descriptive-type info, then there is no parallel type
8116 to be found. */
8117 if (!HAVE_GNAT_AUX_INFO (type))
8118 return NULL;
8119
8120 result = TYPE_DESCRIPTIVE_TYPE (type);
8121 while (result != NULL)
8122 {
8123 const char *result_name = ada_type_name (result);
8124
8125 if (result_name == NULL)
8126 {
8127 warning (_("unexpected null name on descriptive type"));
8128 return NULL;
8129 }
8130
8131 /* If the names match, stop. */
8132 if (strcmp (result_name, name) == 0)
8133 break;
8134
8135 /* Otherwise, look at the next item on the list, if any. */
8136 if (HAVE_GNAT_AUX_INFO (result))
8137 tmp = TYPE_DESCRIPTIVE_TYPE (result);
8138 else
8139 tmp = NULL;
8140
8141 /* If not found either, try after having resolved the typedef. */
8142 if (tmp != NULL)
8143 result = tmp;
8144 else
8145 {
8146 result = check_typedef (result);
8147 if (HAVE_GNAT_AUX_INFO (result))
8148 result = TYPE_DESCRIPTIVE_TYPE (result);
8149 else
8150 result = NULL;
8151 }
8152 }
8153
8154 /* If we didn't find a match, see whether this is a packed array. With
8155 older compilers, the descriptive type information is either absent or
8156 irrelevant when it comes to packed arrays so the above lookup fails.
8157 Fall back to using a parallel lookup by name in this case. */
8158 if (result == NULL && ada_is_constrained_packed_array_type (type))
8159 return ada_find_any_type (name);
8160
8161 return result;
8162 }
8163
8164 /* Find a parallel type to TYPE with the specified NAME, using the
8165 descriptive type taken from the debugging information, if available,
8166 and otherwise using the (slower) name-based method. */
8167
8168 static struct type *
8169 ada_find_parallel_type_with_name (struct type *type, const char *name)
8170 {
8171 struct type *result = NULL;
8172
8173 if (HAVE_GNAT_AUX_INFO (type))
8174 result = find_parallel_type_by_descriptive_type (type, name);
8175 else
8176 result = ada_find_any_type (name);
8177
8178 return result;
8179 }
8180
8181 /* Same as above, but specify the name of the parallel type by appending
8182 SUFFIX to the name of TYPE. */
8183
8184 struct type *
8185 ada_find_parallel_type (struct type *type, const char *suffix)
8186 {
8187 char *name;
8188 const char *type_name = ada_type_name (type);
8189 int len;
8190
8191 if (type_name == NULL)
8192 return NULL;
8193
8194 len = strlen (type_name);
8195
8196 name = (char *) alloca (len + strlen (suffix) + 1);
8197
8198 strcpy (name, type_name);
8199 strcpy (name + len, suffix);
8200
8201 return ada_find_parallel_type_with_name (type, name);
8202 }
8203
8204 /* If TYPE is a variable-size record type, return the corresponding template
8205 type describing its fields. Otherwise, return NULL. */
8206
8207 static struct type *
8208 dynamic_template_type (struct type *type)
8209 {
8210 type = ada_check_typedef (type);
8211
8212 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
8213 || ada_type_name (type) == NULL)
8214 return NULL;
8215 else
8216 {
8217 int len = strlen (ada_type_name (type));
8218
8219 if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
8220 return type;
8221 else
8222 return ada_find_parallel_type (type, "___XVE");
8223 }
8224 }
8225
8226 /* Assuming that TEMPL_TYPE is a union or struct type, returns
8227 non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size. */
8228
8229 static int
8230 is_dynamic_field (struct type *templ_type, int field_num)
8231 {
8232 const char *name = TYPE_FIELD_NAME (templ_type, field_num);
8233
8234 return name != NULL
8235 && TYPE_CODE (TYPE_FIELD_TYPE (templ_type, field_num)) == TYPE_CODE_PTR
8236 && strstr (name, "___XVL") != NULL;
8237 }
8238
8239 /* The index of the variant field of TYPE, or -1 if TYPE does not
8240 represent a variant record type. */
8241
8242 static int
8243 variant_field_index (struct type *type)
8244 {
8245 int f;
8246
8247 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
8248 return -1;
8249
8250 for (f = 0; f < TYPE_NFIELDS (type); f += 1)
8251 {
8252 if (ada_is_variant_part (type, f))
8253 return f;
8254 }
8255 return -1;
8256 }
8257
8258 /* A record type with no fields. */
8259
8260 static struct type *
8261 empty_record (struct type *templ)
8262 {
8263 struct type *type = alloc_type_copy (templ);
8264
8265 TYPE_CODE (type) = TYPE_CODE_STRUCT;
8266 TYPE_NFIELDS (type) = 0;
8267 TYPE_FIELDS (type) = NULL;
8268 INIT_CPLUS_SPECIFIC (type);
8269 TYPE_NAME (type) = "<empty>";
8270 TYPE_LENGTH (type) = 0;
8271 return type;
8272 }
8273
8274 /* An ordinary record type (with fixed-length fields) that describes
8275 the value of type TYPE at VALADDR or ADDRESS (see comments at
8276 the beginning of this section) VAL according to GNAT conventions.
8277 DVAL0 should describe the (portion of a) record that contains any
8278 necessary discriminants. It should be NULL if value_type (VAL) is
8279 an outer-level type (i.e., as opposed to a branch of a variant.) A
8280 variant field (unless unchecked) is replaced by a particular branch
8281 of the variant.
8282
8283 If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
8284 length are not statically known are discarded. As a consequence,
8285 VALADDR, ADDRESS and DVAL0 are ignored.
8286
8287 NOTE: Limitations: For now, we assume that dynamic fields and
8288 variants occupy whole numbers of bytes. However, they need not be
8289 byte-aligned. */
8290
8291 struct type *
8292 ada_template_to_fixed_record_type_1 (struct type *type,
8293 const gdb_byte *valaddr,
8294 CORE_ADDR address, struct value *dval0,
8295 int keep_dynamic_fields)
8296 {
8297 struct value *mark = value_mark ();
8298 struct value *dval;
8299 struct type *rtype;
8300 int nfields, bit_len;
8301 int variant_field;
8302 long off;
8303 int fld_bit_len;
8304 int f;
8305
8306 /* Compute the number of fields in this record type that are going
8307 to be processed: unless keep_dynamic_fields, this includes only
8308 fields whose position and length are static will be processed. */
8309 if (keep_dynamic_fields)
8310 nfields = TYPE_NFIELDS (type);
8311 else
8312 {
8313 nfields = 0;
8314 while (nfields < TYPE_NFIELDS (type)
8315 && !ada_is_variant_part (type, nfields)
8316 && !is_dynamic_field (type, nfields))
8317 nfields++;
8318 }
8319
8320 rtype = alloc_type_copy (type);
8321 TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
8322 INIT_CPLUS_SPECIFIC (rtype);
8323 TYPE_NFIELDS (rtype) = nfields;
8324 TYPE_FIELDS (rtype) = (struct field *)
8325 TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8326 memset (TYPE_FIELDS (rtype), 0, sizeof (struct field) * nfields);
8327 TYPE_NAME (rtype) = ada_type_name (type);
8328 TYPE_FIXED_INSTANCE (rtype) = 1;
8329
8330 off = 0;
8331 bit_len = 0;
8332 variant_field = -1;
8333
8334 for (f = 0; f < nfields; f += 1)
8335 {
8336 off = align_value (off, field_alignment (type, f))
8337 + TYPE_FIELD_BITPOS (type, f);
8338 SET_FIELD_BITPOS (TYPE_FIELD (rtype, f), off);
8339 TYPE_FIELD_BITSIZE (rtype, f) = 0;
8340
8341 if (ada_is_variant_part (type, f))
8342 {
8343 variant_field = f;
8344 fld_bit_len = 0;
8345 }
8346 else if (is_dynamic_field (type, f))
8347 {
8348 const gdb_byte *field_valaddr = valaddr;
8349 CORE_ADDR field_address = address;
8350 struct type *field_type =
8351 TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, f));
8352
8353 if (dval0 == NULL)
8354 {
8355 /* rtype's length is computed based on the run-time
8356 value of discriminants. If the discriminants are not
8357 initialized, the type size may be completely bogus and
8358 GDB may fail to allocate a value for it. So check the
8359 size first before creating the value. */
8360 ada_ensure_varsize_limit (rtype);
8361 /* Using plain value_from_contents_and_address here
8362 causes problems because we will end up trying to
8363 resolve a type that is currently being
8364 constructed. */
8365 dval = value_from_contents_and_address_unresolved (rtype,
8366 valaddr,
8367 address);
8368 rtype = value_type (dval);
8369 }
8370 else
8371 dval = dval0;
8372
8373 /* If the type referenced by this field is an aligner type, we need
8374 to unwrap that aligner type, because its size might not be set.
8375 Keeping the aligner type would cause us to compute the wrong
8376 size for this field, impacting the offset of the all the fields
8377 that follow this one. */
8378 if (ada_is_aligner_type (field_type))
8379 {
8380 long field_offset = TYPE_FIELD_BITPOS (field_type, f);
8381
8382 field_valaddr = cond_offset_host (field_valaddr, field_offset);
8383 field_address = cond_offset_target (field_address, field_offset);
8384 field_type = ada_aligned_type (field_type);
8385 }
8386
8387 field_valaddr = cond_offset_host (field_valaddr,
8388 off / TARGET_CHAR_BIT);
8389 field_address = cond_offset_target (field_address,
8390 off / TARGET_CHAR_BIT);
8391
8392 /* Get the fixed type of the field. Note that, in this case,
8393 we do not want to get the real type out of the tag: if
8394 the current field is the parent part of a tagged record,
8395 we will get the tag of the object. Clearly wrong: the real
8396 type of the parent is not the real type of the child. We
8397 would end up in an infinite loop. */
8398 field_type = ada_get_base_type (field_type);
8399 field_type = ada_to_fixed_type (field_type, field_valaddr,
8400 field_address, dval, 0);
8401 /* If the field size is already larger than the maximum
8402 object size, then the record itself will necessarily
8403 be larger than the maximum object size. We need to make
8404 this check now, because the size might be so ridiculously
8405 large (due to an uninitialized variable in the inferior)
8406 that it would cause an overflow when adding it to the
8407 record size. */
8408 ada_ensure_varsize_limit (field_type);
8409
8410 TYPE_FIELD_TYPE (rtype, f) = field_type;
8411 TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
8412 /* The multiplication can potentially overflow. But because
8413 the field length has been size-checked just above, and
8414 assuming that the maximum size is a reasonable value,
8415 an overflow should not happen in practice. So rather than
8416 adding overflow recovery code to this already complex code,
8417 we just assume that it's not going to happen. */
8418 fld_bit_len =
8419 TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
8420 }
8421 else
8422 {
8423 /* Note: If this field's type is a typedef, it is important
8424 to preserve the typedef layer.
8425
8426 Otherwise, we might be transforming a typedef to a fat
8427 pointer (encoding a pointer to an unconstrained array),
8428 into a basic fat pointer (encoding an unconstrained
8429 array). As both types are implemented using the same
8430 structure, the typedef is the only clue which allows us
8431 to distinguish between the two options. Stripping it
8432 would prevent us from printing this field appropriately. */
8433 TYPE_FIELD_TYPE (rtype, f) = TYPE_FIELD_TYPE (type, f);
8434 TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
8435 if (TYPE_FIELD_BITSIZE (type, f) > 0)
8436 fld_bit_len =
8437 TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
8438 else
8439 {
8440 struct type *field_type = TYPE_FIELD_TYPE (type, f);
8441
8442 /* We need to be careful of typedefs when computing
8443 the length of our field. If this is a typedef,
8444 get the length of the target type, not the length
8445 of the typedef. */
8446 if (TYPE_CODE (field_type) == TYPE_CODE_TYPEDEF)
8447 field_type = ada_typedef_target_type (field_type);
8448
8449 fld_bit_len =
8450 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
8451 }
8452 }
8453 if (off + fld_bit_len > bit_len)
8454 bit_len = off + fld_bit_len;
8455 off += fld_bit_len;
8456 TYPE_LENGTH (rtype) =
8457 align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
8458 }
8459
8460 /* We handle the variant part, if any, at the end because of certain
8461 odd cases in which it is re-ordered so as NOT to be the last field of
8462 the record. This can happen in the presence of representation
8463 clauses. */
8464 if (variant_field >= 0)
8465 {
8466 struct type *branch_type;
8467
8468 off = TYPE_FIELD_BITPOS (rtype, variant_field);
8469
8470 if (dval0 == NULL)
8471 {
8472 /* Using plain value_from_contents_and_address here causes
8473 problems because we will end up trying to resolve a type
8474 that is currently being constructed. */
8475 dval = value_from_contents_and_address_unresolved (rtype, valaddr,
8476 address);
8477 rtype = value_type (dval);
8478 }
8479 else
8480 dval = dval0;
8481
8482 branch_type =
8483 to_fixed_variant_branch_type
8484 (TYPE_FIELD_TYPE (type, variant_field),
8485 cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
8486 cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
8487 if (branch_type == NULL)
8488 {
8489 for (f = variant_field + 1; f < TYPE_NFIELDS (rtype); f += 1)
8490 TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
8491 TYPE_NFIELDS (rtype) -= 1;
8492 }
8493 else
8494 {
8495 TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
8496 TYPE_FIELD_NAME (rtype, variant_field) = "S";
8497 fld_bit_len =
8498 TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, variant_field)) *
8499 TARGET_CHAR_BIT;
8500 if (off + fld_bit_len > bit_len)
8501 bit_len = off + fld_bit_len;
8502 TYPE_LENGTH (rtype) =
8503 align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
8504 }
8505 }
8506
8507 /* According to exp_dbug.ads, the size of TYPE for variable-size records
8508 should contain the alignment of that record, which should be a strictly
8509 positive value. If null or negative, then something is wrong, most
8510 probably in the debug info. In that case, we don't round up the size
8511 of the resulting type. If this record is not part of another structure,
8512 the current RTYPE length might be good enough for our purposes. */
8513 if (TYPE_LENGTH (type) <= 0)
8514 {
8515 if (TYPE_NAME (rtype))
8516 warning (_("Invalid type size for `%s' detected: %s."),
8517 TYPE_NAME (rtype), pulongest (TYPE_LENGTH (type)));
8518 else
8519 warning (_("Invalid type size for <unnamed> detected: %s."),
8520 pulongest (TYPE_LENGTH (type)));
8521 }
8522 else
8523 {
8524 TYPE_LENGTH (rtype) = align_value (TYPE_LENGTH (rtype),
8525 TYPE_LENGTH (type));
8526 }
8527
8528 value_free_to_mark (mark);
8529 if (TYPE_LENGTH (rtype) > varsize_limit)
8530 error (_("record type with dynamic size is larger than varsize-limit"));
8531 return rtype;
8532 }
8533
8534 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
8535 of 1. */
8536
8537 static struct type *
8538 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
8539 CORE_ADDR address, struct value *dval0)
8540 {
8541 return ada_template_to_fixed_record_type_1 (type, valaddr,
8542 address, dval0, 1);
8543 }
8544
8545 /* An ordinary record type in which ___XVL-convention fields and
8546 ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
8547 static approximations, containing all possible fields. Uses
8548 no runtime values. Useless for use in values, but that's OK,
8549 since the results are used only for type determinations. Works on both
8550 structs and unions. Representation note: to save space, we memorize
8551 the result of this function in the TYPE_TARGET_TYPE of the
8552 template type. */
8553
8554 static struct type *
8555 template_to_static_fixed_type (struct type *type0)
8556 {
8557 struct type *type;
8558 int nfields;
8559 int f;
8560
8561 /* No need no do anything if the input type is already fixed. */
8562 if (TYPE_FIXED_INSTANCE (type0))
8563 return type0;
8564
8565 /* Likewise if we already have computed the static approximation. */
8566 if (TYPE_TARGET_TYPE (type0) != NULL)
8567 return TYPE_TARGET_TYPE (type0);
8568
8569 /* Don't clone TYPE0 until we are sure we are going to need a copy. */
8570 type = type0;
8571 nfields = TYPE_NFIELDS (type0);
8572
8573 /* Whether or not we cloned TYPE0, cache the result so that we don't do
8574 recompute all over next time. */
8575 TYPE_TARGET_TYPE (type0) = type;
8576
8577 for (f = 0; f < nfields; f += 1)
8578 {
8579 struct type *field_type = TYPE_FIELD_TYPE (type0, f);
8580 struct type *new_type;
8581
8582 if (is_dynamic_field (type0, f))
8583 {
8584 field_type = ada_check_typedef (field_type);
8585 new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
8586 }
8587 else
8588 new_type = static_unwrap_type (field_type);
8589
8590 if (new_type != field_type)
8591 {
8592 /* Clone TYPE0 only the first time we get a new field type. */
8593 if (type == type0)
8594 {
8595 TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
8596 TYPE_CODE (type) = TYPE_CODE (type0);
8597 INIT_CPLUS_SPECIFIC (type);
8598 TYPE_NFIELDS (type) = nfields;
8599 TYPE_FIELDS (type) = (struct field *)
8600 TYPE_ALLOC (type, nfields * sizeof (struct field));
8601 memcpy (TYPE_FIELDS (type), TYPE_FIELDS (type0),
8602 sizeof (struct field) * nfields);
8603 TYPE_NAME (type) = ada_type_name (type0);
8604 TYPE_FIXED_INSTANCE (type) = 1;
8605 TYPE_LENGTH (type) = 0;
8606 }
8607 TYPE_FIELD_TYPE (type, f) = new_type;
8608 TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
8609 }
8610 }
8611
8612 return type;
8613 }
8614
8615 /* Given an object of type TYPE whose contents are at VALADDR and
8616 whose address in memory is ADDRESS, returns a revision of TYPE,
8617 which should be a non-dynamic-sized record, in which the variant
8618 part, if any, is replaced with the appropriate branch. Looks
8619 for discriminant values in DVAL0, which can be NULL if the record
8620 contains the necessary discriminant values. */
8621
8622 static struct type *
8623 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
8624 CORE_ADDR address, struct value *dval0)
8625 {
8626 struct value *mark = value_mark ();
8627 struct value *dval;
8628 struct type *rtype;
8629 struct type *branch_type;
8630 int nfields = TYPE_NFIELDS (type);
8631 int variant_field = variant_field_index (type);
8632
8633 if (variant_field == -1)
8634 return type;
8635
8636 if (dval0 == NULL)
8637 {
8638 dval = value_from_contents_and_address (type, valaddr, address);
8639 type = value_type (dval);
8640 }
8641 else
8642 dval = dval0;
8643
8644 rtype = alloc_type_copy (type);
8645 TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
8646 INIT_CPLUS_SPECIFIC (rtype);
8647 TYPE_NFIELDS (rtype) = nfields;
8648 TYPE_FIELDS (rtype) =
8649 (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
8650 memcpy (TYPE_FIELDS (rtype), TYPE_FIELDS (type),
8651 sizeof (struct field) * nfields);
8652 TYPE_NAME (rtype) = ada_type_name (type);
8653 TYPE_FIXED_INSTANCE (rtype) = 1;
8654 TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
8655
8656 branch_type = to_fixed_variant_branch_type
8657 (TYPE_FIELD_TYPE (type, variant_field),
8658 cond_offset_host (valaddr,
8659 TYPE_FIELD_BITPOS (type, variant_field)
8660 / TARGET_CHAR_BIT),
8661 cond_offset_target (address,
8662 TYPE_FIELD_BITPOS (type, variant_field)
8663 / TARGET_CHAR_BIT), dval);
8664 if (branch_type == NULL)
8665 {
8666 int f;
8667
8668 for (f = variant_field + 1; f < nfields; f += 1)
8669 TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
8670 TYPE_NFIELDS (rtype) -= 1;
8671 }
8672 else
8673 {
8674 TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
8675 TYPE_FIELD_NAME (rtype, variant_field) = "S";
8676 TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
8677 TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
8678 }
8679 TYPE_LENGTH (rtype) -= TYPE_LENGTH (TYPE_FIELD_TYPE (type, variant_field));
8680
8681 value_free_to_mark (mark);
8682 return rtype;
8683 }
8684
8685 /* An ordinary record type (with fixed-length fields) that describes
8686 the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
8687 beginning of this section]. Any necessary discriminants' values
8688 should be in DVAL, a record value; it may be NULL if the object
8689 at ADDR itself contains any necessary discriminant values.
8690 Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
8691 values from the record are needed. Except in the case that DVAL,
8692 VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
8693 unchecked) is replaced by a particular branch of the variant.
8694
8695 NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
8696 is questionable and may be removed. It can arise during the
8697 processing of an unconstrained-array-of-record type where all the
8698 variant branches have exactly the same size. This is because in
8699 such cases, the compiler does not bother to use the XVS convention
8700 when encoding the record. I am currently dubious of this
8701 shortcut and suspect the compiler should be altered. FIXME. */
8702
8703 static struct type *
8704 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
8705 CORE_ADDR address, struct value *dval)
8706 {
8707 struct type *templ_type;
8708
8709 if (TYPE_FIXED_INSTANCE (type0))
8710 return type0;
8711
8712 templ_type = dynamic_template_type (type0);
8713
8714 if (templ_type != NULL)
8715 return template_to_fixed_record_type (templ_type, valaddr, address, dval);
8716 else if (variant_field_index (type0) >= 0)
8717 {
8718 if (dval == NULL && valaddr == NULL && address == 0)
8719 return type0;
8720 return to_record_with_fixed_variant_part (type0, valaddr, address,
8721 dval);
8722 }
8723 else
8724 {
8725 TYPE_FIXED_INSTANCE (type0) = 1;
8726 return type0;
8727 }
8728
8729 }
8730
8731 /* An ordinary record type (with fixed-length fields) that describes
8732 the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
8733 union type. Any necessary discriminants' values should be in DVAL,
8734 a record value. That is, this routine selects the appropriate
8735 branch of the union at ADDR according to the discriminant value
8736 indicated in the union's type name. Returns VAR_TYPE0 itself if
8737 it represents a variant subject to a pragma Unchecked_Union. */
8738
8739 static struct type *
8740 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
8741 CORE_ADDR address, struct value *dval)
8742 {
8743 int which;
8744 struct type *templ_type;
8745 struct type *var_type;
8746
8747 if (TYPE_CODE (var_type0) == TYPE_CODE_PTR)
8748 var_type = TYPE_TARGET_TYPE (var_type0);
8749 else
8750 var_type = var_type0;
8751
8752 templ_type = ada_find_parallel_type (var_type, "___XVU");
8753
8754 if (templ_type != NULL)
8755 var_type = templ_type;
8756
8757 if (is_unchecked_variant (var_type, value_type (dval)))
8758 return var_type0;
8759 which =
8760 ada_which_variant_applies (var_type,
8761 value_type (dval), value_contents (dval));
8762
8763 if (which < 0)
8764 return empty_record (var_type);
8765 else if (is_dynamic_field (var_type, which))
8766 return to_fixed_record_type
8767 (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (var_type, which)),
8768 valaddr, address, dval);
8769 else if (variant_field_index (TYPE_FIELD_TYPE (var_type, which)) >= 0)
8770 return
8771 to_fixed_record_type
8772 (TYPE_FIELD_TYPE (var_type, which), valaddr, address, dval);
8773 else
8774 return TYPE_FIELD_TYPE (var_type, which);
8775 }
8776
8777 /* Assuming RANGE_TYPE is a TYPE_CODE_RANGE, return nonzero if
8778 ENCODING_TYPE, a type following the GNAT conventions for discrete
8779 type encodings, only carries redundant information. */
8780
8781 static int
8782 ada_is_redundant_range_encoding (struct type *range_type,
8783 struct type *encoding_type)
8784 {
8785 const char *bounds_str;
8786 int n;
8787 LONGEST lo, hi;
8788
8789 gdb_assert (TYPE_CODE (range_type) == TYPE_CODE_RANGE);
8790
8791 if (TYPE_CODE (get_base_type (range_type))
8792 != TYPE_CODE (get_base_type (encoding_type)))
8793 {
8794 /* The compiler probably used a simple base type to describe
8795 the range type instead of the range's actual base type,
8796 expecting us to get the real base type from the encoding
8797 anyway. In this situation, the encoding cannot be ignored
8798 as redundant. */
8799 return 0;
8800 }
8801
8802 if (is_dynamic_type (range_type))
8803 return 0;
8804
8805 if (TYPE_NAME (encoding_type) == NULL)
8806 return 0;
8807
8808 bounds_str = strstr (TYPE_NAME (encoding_type), "___XDLU_");
8809 if (bounds_str == NULL)
8810 return 0;
8811
8812 n = 8; /* Skip "___XDLU_". */
8813 if (!ada_scan_number (bounds_str, n, &lo, &n))
8814 return 0;
8815 if (TYPE_LOW_BOUND (range_type) != lo)
8816 return 0;
8817
8818 n += 2; /* Skip the "__" separator between the two bounds. */
8819 if (!ada_scan_number (bounds_str, n, &hi, &n))
8820 return 0;
8821 if (TYPE_HIGH_BOUND (range_type) != hi)
8822 return 0;
8823
8824 return 1;
8825 }
8826
8827 /* Given the array type ARRAY_TYPE, return nonzero if DESC_TYPE,
8828 a type following the GNAT encoding for describing array type
8829 indices, only carries redundant information. */
8830
8831 static int
8832 ada_is_redundant_index_type_desc (struct type *array_type,
8833 struct type *desc_type)
8834 {
8835 struct type *this_layer = check_typedef (array_type);
8836 int i;
8837
8838 for (i = 0; i < TYPE_NFIELDS (desc_type); i++)
8839 {
8840 if (!ada_is_redundant_range_encoding (TYPE_INDEX_TYPE (this_layer),
8841 TYPE_FIELD_TYPE (desc_type, i)))
8842 return 0;
8843 this_layer = check_typedef (TYPE_TARGET_TYPE (this_layer));
8844 }
8845
8846 return 1;
8847 }
8848
8849 /* Assuming that TYPE0 is an array type describing the type of a value
8850 at ADDR, and that DVAL describes a record containing any
8851 discriminants used in TYPE0, returns a type for the value that
8852 contains no dynamic components (that is, no components whose sizes
8853 are determined by run-time quantities). Unless IGNORE_TOO_BIG is
8854 true, gives an error message if the resulting type's size is over
8855 varsize_limit. */
8856
8857 static struct type *
8858 to_fixed_array_type (struct type *type0, struct value *dval,
8859 int ignore_too_big)
8860 {
8861 struct type *index_type_desc;
8862 struct type *result;
8863 int constrained_packed_array_p;
8864 static const char *xa_suffix = "___XA";
8865
8866 type0 = ada_check_typedef (type0);
8867 if (TYPE_FIXED_INSTANCE (type0))
8868 return type0;
8869
8870 constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
8871 if (constrained_packed_array_p)
8872 type0 = decode_constrained_packed_array_type (type0);
8873
8874 index_type_desc = ada_find_parallel_type (type0, xa_suffix);
8875
8876 /* As mentioned in exp_dbug.ads, for non bit-packed arrays an
8877 encoding suffixed with 'P' may still be generated. If so,
8878 it should be used to find the XA type. */
8879
8880 if (index_type_desc == NULL)
8881 {
8882 const char *type_name = ada_type_name (type0);
8883
8884 if (type_name != NULL)
8885 {
8886 const int len = strlen (type_name);
8887 char *name = (char *) alloca (len + strlen (xa_suffix));
8888
8889 if (type_name[len - 1] == 'P')
8890 {
8891 strcpy (name, type_name);
8892 strcpy (name + len - 1, xa_suffix);
8893 index_type_desc = ada_find_parallel_type_with_name (type0, name);
8894 }
8895 }
8896 }
8897
8898 ada_fixup_array_indexes_type (index_type_desc);
8899 if (index_type_desc != NULL
8900 && ada_is_redundant_index_type_desc (type0, index_type_desc))
8901 {
8902 /* Ignore this ___XA parallel type, as it does not bring any
8903 useful information. This allows us to avoid creating fixed
8904 versions of the array's index types, which would be identical
8905 to the original ones. This, in turn, can also help avoid
8906 the creation of fixed versions of the array itself. */
8907 index_type_desc = NULL;
8908 }
8909
8910 if (index_type_desc == NULL)
8911 {
8912 struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
8913
8914 /* NOTE: elt_type---the fixed version of elt_type0---should never
8915 depend on the contents of the array in properly constructed
8916 debugging data. */
8917 /* Create a fixed version of the array element type.
8918 We're not providing the address of an element here,
8919 and thus the actual object value cannot be inspected to do
8920 the conversion. This should not be a problem, since arrays of
8921 unconstrained objects are not allowed. In particular, all
8922 the elements of an array of a tagged type should all be of
8923 the same type specified in the debugging info. No need to
8924 consult the object tag. */
8925 struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
8926
8927 /* Make sure we always create a new array type when dealing with
8928 packed array types, since we're going to fix-up the array
8929 type length and element bitsize a little further down. */
8930 if (elt_type0 == elt_type && !constrained_packed_array_p)
8931 result = type0;
8932 else
8933 result = create_array_type (alloc_type_copy (type0),
8934 elt_type, TYPE_INDEX_TYPE (type0));
8935 }
8936 else
8937 {
8938 int i;
8939 struct type *elt_type0;
8940
8941 elt_type0 = type0;
8942 for (i = TYPE_NFIELDS (index_type_desc); i > 0; i -= 1)
8943 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8944
8945 /* NOTE: result---the fixed version of elt_type0---should never
8946 depend on the contents of the array in properly constructed
8947 debugging data. */
8948 /* Create a fixed version of the array element type.
8949 We're not providing the address of an element here,
8950 and thus the actual object value cannot be inspected to do
8951 the conversion. This should not be a problem, since arrays of
8952 unconstrained objects are not allowed. In particular, all
8953 the elements of an array of a tagged type should all be of
8954 the same type specified in the debugging info. No need to
8955 consult the object tag. */
8956 result =
8957 ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
8958
8959 elt_type0 = type0;
8960 for (i = TYPE_NFIELDS (index_type_desc) - 1; i >= 0; i -= 1)
8961 {
8962 struct type *range_type =
8963 to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, i), dval);
8964
8965 result = create_array_type (alloc_type_copy (elt_type0),
8966 result, range_type);
8967 elt_type0 = TYPE_TARGET_TYPE (elt_type0);
8968 }
8969 if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
8970 error (_("array type with dynamic size is larger than varsize-limit"));
8971 }
8972
8973 /* We want to preserve the type name. This can be useful when
8974 trying to get the type name of a value that has already been
8975 printed (for instance, if the user did "print VAR; whatis $". */
8976 TYPE_NAME (result) = TYPE_NAME (type0);
8977
8978 if (constrained_packed_array_p)
8979 {
8980 /* So far, the resulting type has been created as if the original
8981 type was a regular (non-packed) array type. As a result, the
8982 bitsize of the array elements needs to be set again, and the array
8983 length needs to be recomputed based on that bitsize. */
8984 int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
8985 int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
8986
8987 TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
8988 TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
8989 if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
8990 TYPE_LENGTH (result)++;
8991 }
8992
8993 TYPE_FIXED_INSTANCE (result) = 1;
8994 return result;
8995 }
8996
8997
8998 /* A standard type (containing no dynamically sized components)
8999 corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
9000 DVAL describes a record containing any discriminants used in TYPE0,
9001 and may be NULL if there are none, or if the object of type TYPE at
9002 ADDRESS or in VALADDR contains these discriminants.
9003
9004 If CHECK_TAG is not null, in the case of tagged types, this function
9005 attempts to locate the object's tag and use it to compute the actual
9006 type. However, when ADDRESS is null, we cannot use it to determine the
9007 location of the tag, and therefore compute the tagged type's actual type.
9008 So we return the tagged type without consulting the tag. */
9009
9010 static struct type *
9011 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
9012 CORE_ADDR address, struct value *dval, int check_tag)
9013 {
9014 type = ada_check_typedef (type);
9015 switch (TYPE_CODE (type))
9016 {
9017 default:
9018 return type;
9019 case TYPE_CODE_STRUCT:
9020 {
9021 struct type *static_type = to_static_fixed_type (type);
9022 struct type *fixed_record_type =
9023 to_fixed_record_type (type, valaddr, address, NULL);
9024
9025 /* If STATIC_TYPE is a tagged type and we know the object's address,
9026 then we can determine its tag, and compute the object's actual
9027 type from there. Note that we have to use the fixed record
9028 type (the parent part of the record may have dynamic fields
9029 and the way the location of _tag is expressed may depend on
9030 them). */
9031
9032 if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
9033 {
9034 struct value *tag =
9035 value_tag_from_contents_and_address
9036 (fixed_record_type,
9037 valaddr,
9038 address);
9039 struct type *real_type = type_from_tag (tag);
9040 struct value *obj =
9041 value_from_contents_and_address (fixed_record_type,
9042 valaddr,
9043 address);
9044 fixed_record_type = value_type (obj);
9045 if (real_type != NULL)
9046 return to_fixed_record_type
9047 (real_type, NULL,
9048 value_address (ada_tag_value_at_base_address (obj)), NULL);
9049 }
9050
9051 /* Check to see if there is a parallel ___XVZ variable.
9052 If there is, then it provides the actual size of our type. */
9053 else if (ada_type_name (fixed_record_type) != NULL)
9054 {
9055 const char *name = ada_type_name (fixed_record_type);
9056 char *xvz_name
9057 = (char *) alloca (strlen (name) + 7 /* "___XVZ\0" */);
9058 bool xvz_found = false;
9059 LONGEST size;
9060
9061 xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
9062 TRY
9063 {
9064 xvz_found = get_int_var_value (xvz_name, size);
9065 }
9066 CATCH (except, RETURN_MASK_ERROR)
9067 {
9068 /* We found the variable, but somehow failed to read
9069 its value. Rethrow the same error, but with a little
9070 bit more information, to help the user understand
9071 what went wrong (Eg: the variable might have been
9072 optimized out). */
9073 throw_error (except.error,
9074 _("unable to read value of %s (%s)"),
9075 xvz_name, except.message);
9076 }
9077 END_CATCH
9078
9079 if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
9080 {
9081 fixed_record_type = copy_type (fixed_record_type);
9082 TYPE_LENGTH (fixed_record_type) = size;
9083
9084 /* The FIXED_RECORD_TYPE may have be a stub. We have
9085 observed this when the debugging info is STABS, and
9086 apparently it is something that is hard to fix.
9087
9088 In practice, we don't need the actual type definition
9089 at all, because the presence of the XVZ variable allows us
9090 to assume that there must be a XVS type as well, which we
9091 should be able to use later, when we need the actual type
9092 definition.
9093
9094 In the meantime, pretend that the "fixed" type we are
9095 returning is NOT a stub, because this can cause trouble
9096 when using this type to create new types targeting it.
9097 Indeed, the associated creation routines often check
9098 whether the target type is a stub and will try to replace
9099 it, thus using a type with the wrong size. This, in turn,
9100 might cause the new type to have the wrong size too.
9101 Consider the case of an array, for instance, where the size
9102 of the array is computed from the number of elements in
9103 our array multiplied by the size of its element. */
9104 TYPE_STUB (fixed_record_type) = 0;
9105 }
9106 }
9107 return fixed_record_type;
9108 }
9109 case TYPE_CODE_ARRAY:
9110 return to_fixed_array_type (type, dval, 1);
9111 case TYPE_CODE_UNION:
9112 if (dval == NULL)
9113 return type;
9114 else
9115 return to_fixed_variant_branch_type (type, valaddr, address, dval);
9116 }
9117 }
9118
9119 /* The same as ada_to_fixed_type_1, except that it preserves the type
9120 if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
9121
9122 The typedef layer needs be preserved in order to differentiate between
9123 arrays and array pointers when both types are implemented using the same
9124 fat pointer. In the array pointer case, the pointer is encoded as
9125 a typedef of the pointer type. For instance, considering:
9126
9127 type String_Access is access String;
9128 S1 : String_Access := null;
9129
9130 To the debugger, S1 is defined as a typedef of type String. But
9131 to the user, it is a pointer. So if the user tries to print S1,
9132 we should not dereference the array, but print the array address
9133 instead.
9134
9135 If we didn't preserve the typedef layer, we would lose the fact that
9136 the type is to be presented as a pointer (needs de-reference before
9137 being printed). And we would also use the source-level type name. */
9138
9139 struct type *
9140 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
9141 CORE_ADDR address, struct value *dval, int check_tag)
9142
9143 {
9144 struct type *fixed_type =
9145 ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
9146
9147 /* If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
9148 then preserve the typedef layer.
9149
9150 Implementation note: We can only check the main-type portion of
9151 the TYPE and FIXED_TYPE, because eliminating the typedef layer
9152 from TYPE now returns a type that has the same instance flags
9153 as TYPE. For instance, if TYPE is a "typedef const", and its
9154 target type is a "struct", then the typedef elimination will return
9155 a "const" version of the target type. See check_typedef for more
9156 details about how the typedef layer elimination is done.
9157
9158 brobecker/2010-11-19: It seems to me that the only case where it is
9159 useful to preserve the typedef layer is when dealing with fat pointers.
9160 Perhaps, we could add a check for that and preserve the typedef layer
9161 only in that situation. But this seems unecessary so far, probably
9162 because we call check_typedef/ada_check_typedef pretty much everywhere.
9163 */
9164 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
9165 && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
9166 == TYPE_MAIN_TYPE (fixed_type)))
9167 return type;
9168
9169 return fixed_type;
9170 }
9171
9172 /* A standard (static-sized) type corresponding as well as possible to
9173 TYPE0, but based on no runtime data. */
9174
9175 static struct type *
9176 to_static_fixed_type (struct type *type0)
9177 {
9178 struct type *type;
9179
9180 if (type0 == NULL)
9181 return NULL;
9182
9183 if (TYPE_FIXED_INSTANCE (type0))
9184 return type0;
9185
9186 type0 = ada_check_typedef (type0);
9187
9188 switch (TYPE_CODE (type0))
9189 {
9190 default:
9191 return type0;
9192 case TYPE_CODE_STRUCT:
9193 type = dynamic_template_type (type0);
9194 if (type != NULL)
9195 return template_to_static_fixed_type (type);
9196 else
9197 return template_to_static_fixed_type (type0);
9198 case TYPE_CODE_UNION:
9199 type = ada_find_parallel_type (type0, "___XVU");
9200 if (type != NULL)
9201 return template_to_static_fixed_type (type);
9202 else
9203 return template_to_static_fixed_type (type0);
9204 }
9205 }
9206
9207 /* A static approximation of TYPE with all type wrappers removed. */
9208
9209 static struct type *
9210 static_unwrap_type (struct type *type)
9211 {
9212 if (ada_is_aligner_type (type))
9213 {
9214 struct type *type1 = TYPE_FIELD_TYPE (ada_check_typedef (type), 0);
9215 if (ada_type_name (type1) == NULL)
9216 TYPE_NAME (type1) = ada_type_name (type);
9217
9218 return static_unwrap_type (type1);
9219 }
9220 else
9221 {
9222 struct type *raw_real_type = ada_get_base_type (type);
9223
9224 if (raw_real_type == type)
9225 return type;
9226 else
9227 return to_static_fixed_type (raw_real_type);
9228 }
9229 }
9230
9231 /* In some cases, incomplete and private types require
9232 cross-references that are not resolved as records (for example,
9233 type Foo;
9234 type FooP is access Foo;
9235 V: FooP;
9236 type Foo is array ...;
9237 ). In these cases, since there is no mechanism for producing
9238 cross-references to such types, we instead substitute for FooP a
9239 stub enumeration type that is nowhere resolved, and whose tag is
9240 the name of the actual type. Call these types "non-record stubs". */
9241
9242 /* A type equivalent to TYPE that is not a non-record stub, if one
9243 exists, otherwise TYPE. */
9244
9245 struct type *
9246 ada_check_typedef (struct type *type)
9247 {
9248 if (type == NULL)
9249 return NULL;
9250
9251 /* If our type is an access to an unconstrained array, which is encoded
9252 as a TYPE_CODE_TYPEDEF of a fat pointer, then we're done.
9253 We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
9254 what allows us to distinguish between fat pointers that represent
9255 array types, and fat pointers that represent array access types
9256 (in both cases, the compiler implements them as fat pointers). */
9257 if (ada_is_access_to_unconstrained_array (type))
9258 return type;
9259
9260 type = check_typedef (type);
9261 if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
9262 || !TYPE_STUB (type)
9263 || TYPE_NAME (type) == NULL)
9264 return type;
9265 else
9266 {
9267 const char *name = TYPE_NAME (type);
9268 struct type *type1 = ada_find_any_type (name);
9269
9270 if (type1 == NULL)
9271 return type;
9272
9273 /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
9274 stubs pointing to arrays, as we don't create symbols for array
9275 types, only for the typedef-to-array types). If that's the case,
9276 strip the typedef layer. */
9277 if (TYPE_CODE (type1) == TYPE_CODE_TYPEDEF)
9278 type1 = ada_check_typedef (type1);
9279
9280 return type1;
9281 }
9282 }
9283
9284 /* A value representing the data at VALADDR/ADDRESS as described by
9285 type TYPE0, but with a standard (static-sized) type that correctly
9286 describes it. If VAL0 is not NULL and TYPE0 already is a standard
9287 type, then return VAL0 [this feature is simply to avoid redundant
9288 creation of struct values]. */
9289
9290 static struct value *
9291 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
9292 struct value *val0)
9293 {
9294 struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
9295
9296 if (type == type0 && val0 != NULL)
9297 return val0;
9298
9299 if (VALUE_LVAL (val0) != lval_memory)
9300 {
9301 /* Our value does not live in memory; it could be a convenience
9302 variable, for instance. Create a not_lval value using val0's
9303 contents. */
9304 return value_from_contents (type, value_contents (val0));
9305 }
9306
9307 return value_from_contents_and_address (type, 0, address);
9308 }
9309
9310 /* A value representing VAL, but with a standard (static-sized) type
9311 that correctly describes it. Does not necessarily create a new
9312 value. */
9313
9314 struct value *
9315 ada_to_fixed_value (struct value *val)
9316 {
9317 val = unwrap_value (val);
9318 val = ada_to_fixed_value_create (value_type (val), value_address (val), val);
9319 return val;
9320 }
9321 \f
9322
9323 /* Attributes */
9324
9325 /* Table mapping attribute numbers to names.
9326 NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h. */
9327
9328 static const char *attribute_names[] = {
9329 "<?>",
9330
9331 "first",
9332 "last",
9333 "length",
9334 "image",
9335 "max",
9336 "min",
9337 "modulus",
9338 "pos",
9339 "size",
9340 "tag",
9341 "val",
9342 0
9343 };
9344
9345 const char *
9346 ada_attribute_name (enum exp_opcode n)
9347 {
9348 if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
9349 return attribute_names[n - OP_ATR_FIRST + 1];
9350 else
9351 return attribute_names[0];
9352 }
9353
9354 /* Evaluate the 'POS attribute applied to ARG. */
9355
9356 static LONGEST
9357 pos_atr (struct value *arg)
9358 {
9359 struct value *val = coerce_ref (arg);
9360 struct type *type = value_type (val);
9361 LONGEST result;
9362
9363 if (!discrete_type_p (type))
9364 error (_("'POS only defined on discrete types"));
9365
9366 if (!discrete_position (type, value_as_long (val), &result))
9367 error (_("enumeration value is invalid: can't find 'POS"));
9368
9369 return result;
9370 }
9371
9372 static struct value *
9373 value_pos_atr (struct type *type, struct value *arg)
9374 {
9375 return value_from_longest (type, pos_atr (arg));
9376 }
9377
9378 /* Evaluate the TYPE'VAL attribute applied to ARG. */
9379
9380 static struct value *
9381 value_val_atr (struct type *type, struct value *arg)
9382 {
9383 if (!discrete_type_p (type))
9384 error (_("'VAL only defined on discrete types"));
9385 if (!integer_type_p (value_type (arg)))
9386 error (_("'VAL requires integral argument"));
9387
9388 if (TYPE_CODE (type) == TYPE_CODE_ENUM)
9389 {
9390 long pos = value_as_long (arg);
9391
9392 if (pos < 0 || pos >= TYPE_NFIELDS (type))
9393 error (_("argument to 'VAL out of range"));
9394 return value_from_longest (type, TYPE_FIELD_ENUMVAL (type, pos));
9395 }
9396 else
9397 return value_from_longest (type, value_as_long (arg));
9398 }
9399 \f
9400
9401 /* Evaluation */
9402
9403 /* True if TYPE appears to be an Ada character type.
9404 [At the moment, this is true only for Character and Wide_Character;
9405 It is a heuristic test that could stand improvement]. */
9406
9407 int
9408 ada_is_character_type (struct type *type)
9409 {
9410 const char *name;
9411
9412 /* If the type code says it's a character, then assume it really is,
9413 and don't check any further. */
9414 if (TYPE_CODE (type) == TYPE_CODE_CHAR)
9415 return 1;
9416
9417 /* Otherwise, assume it's a character type iff it is a discrete type
9418 with a known character type name. */
9419 name = ada_type_name (type);
9420 return (name != NULL
9421 && (TYPE_CODE (type) == TYPE_CODE_INT
9422 || TYPE_CODE (type) == TYPE_CODE_RANGE)
9423 && (strcmp (name, "character") == 0
9424 || strcmp (name, "wide_character") == 0
9425 || strcmp (name, "wide_wide_character") == 0
9426 || strcmp (name, "unsigned char") == 0));
9427 }
9428
9429 /* True if TYPE appears to be an Ada string type. */
9430
9431 int
9432 ada_is_string_type (struct type *type)
9433 {
9434 type = ada_check_typedef (type);
9435 if (type != NULL
9436 && TYPE_CODE (type) != TYPE_CODE_PTR
9437 && (ada_is_simple_array_type (type)
9438 || ada_is_array_descriptor_type (type))
9439 && ada_array_arity (type) == 1)
9440 {
9441 struct type *elttype = ada_array_element_type (type, 1);
9442
9443 return ada_is_character_type (elttype);
9444 }
9445 else
9446 return 0;
9447 }
9448
9449 /* The compiler sometimes provides a parallel XVS type for a given
9450 PAD type. Normally, it is safe to follow the PAD type directly,
9451 but older versions of the compiler have a bug that causes the offset
9452 of its "F" field to be wrong. Following that field in that case
9453 would lead to incorrect results, but this can be worked around
9454 by ignoring the PAD type and using the associated XVS type instead.
9455
9456 Set to True if the debugger should trust the contents of PAD types.
9457 Otherwise, ignore the PAD type if there is a parallel XVS type. */
9458 static int trust_pad_over_xvs = 1;
9459
9460 /* True if TYPE is a struct type introduced by the compiler to force the
9461 alignment of a value. Such types have a single field with a
9462 distinctive name. */
9463
9464 int
9465 ada_is_aligner_type (struct type *type)
9466 {
9467 type = ada_check_typedef (type);
9468
9469 if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
9470 return 0;
9471
9472 return (TYPE_CODE (type) == TYPE_CODE_STRUCT
9473 && TYPE_NFIELDS (type) == 1
9474 && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
9475 }
9476
9477 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
9478 the parallel type. */
9479
9480 struct type *
9481 ada_get_base_type (struct type *raw_type)
9482 {
9483 struct type *real_type_namer;
9484 struct type *raw_real_type;
9485
9486 if (raw_type == NULL || TYPE_CODE (raw_type) != TYPE_CODE_STRUCT)
9487 return raw_type;
9488
9489 if (ada_is_aligner_type (raw_type))
9490 /* The encoding specifies that we should always use the aligner type.
9491 So, even if this aligner type has an associated XVS type, we should
9492 simply ignore it.
9493
9494 According to the compiler gurus, an XVS type parallel to an aligner
9495 type may exist because of a stabs limitation. In stabs, aligner
9496 types are empty because the field has a variable-sized type, and
9497 thus cannot actually be used as an aligner type. As a result,
9498 we need the associated parallel XVS type to decode the type.
9499 Since the policy in the compiler is to not change the internal
9500 representation based on the debugging info format, we sometimes
9501 end up having a redundant XVS type parallel to the aligner type. */
9502 return raw_type;
9503
9504 real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
9505 if (real_type_namer == NULL
9506 || TYPE_CODE (real_type_namer) != TYPE_CODE_STRUCT
9507 || TYPE_NFIELDS (real_type_namer) != 1)
9508 return raw_type;
9509
9510 if (TYPE_CODE (TYPE_FIELD_TYPE (real_type_namer, 0)) != TYPE_CODE_REF)
9511 {
9512 /* This is an older encoding form where the base type needs to be
9513 looked up by name. We prefer the newer enconding because it is
9514 more efficient. */
9515 raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
9516 if (raw_real_type == NULL)
9517 return raw_type;
9518 else
9519 return raw_real_type;
9520 }
9521
9522 /* The field in our XVS type is a reference to the base type. */
9523 return TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (real_type_namer, 0));
9524 }
9525
9526 /* The type of value designated by TYPE, with all aligners removed. */
9527
9528 struct type *
9529 ada_aligned_type (struct type *type)
9530 {
9531 if (ada_is_aligner_type (type))
9532 return ada_aligned_type (TYPE_FIELD_TYPE (type, 0));
9533 else
9534 return ada_get_base_type (type);
9535 }
9536
9537
9538 /* The address of the aligned value in an object at address VALADDR
9539 having type TYPE. Assumes ada_is_aligner_type (TYPE). */
9540
9541 const gdb_byte *
9542 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
9543 {
9544 if (ada_is_aligner_type (type))
9545 return ada_aligned_value_addr (TYPE_FIELD_TYPE (type, 0),
9546 valaddr +
9547 TYPE_FIELD_BITPOS (type,
9548 0) / TARGET_CHAR_BIT);
9549 else
9550 return valaddr;
9551 }
9552
9553
9554
9555 /* The printed representation of an enumeration literal with encoded
9556 name NAME. The value is good to the next call of ada_enum_name. */
9557 const char *
9558 ada_enum_name (const char *name)
9559 {
9560 static char *result;
9561 static size_t result_len = 0;
9562 const char *tmp;
9563
9564 /* First, unqualify the enumeration name:
9565 1. Search for the last '.' character. If we find one, then skip
9566 all the preceding characters, the unqualified name starts
9567 right after that dot.
9568 2. Otherwise, we may be debugging on a target where the compiler
9569 translates dots into "__". Search forward for double underscores,
9570 but stop searching when we hit an overloading suffix, which is
9571 of the form "__" followed by digits. */
9572
9573 tmp = strrchr (name, '.');
9574 if (tmp != NULL)
9575 name = tmp + 1;
9576 else
9577 {
9578 while ((tmp = strstr (name, "__")) != NULL)
9579 {
9580 if (isdigit (tmp[2]))
9581 break;
9582 else
9583 name = tmp + 2;
9584 }
9585 }
9586
9587 if (name[0] == 'Q')
9588 {
9589 int v;
9590
9591 if (name[1] == 'U' || name[1] == 'W')
9592 {
9593 if (sscanf (name + 2, "%x", &v) != 1)
9594 return name;
9595 }
9596 else
9597 return name;
9598
9599 GROW_VECT (result, result_len, 16);
9600 if (isascii (v) && isprint (v))
9601 xsnprintf (result, result_len, "'%c'", v);
9602 else if (name[1] == 'U')
9603 xsnprintf (result, result_len, "[\"%02x\"]", v);
9604 else
9605 xsnprintf (result, result_len, "[\"%04x\"]", v);
9606
9607 return result;
9608 }
9609 else
9610 {
9611 tmp = strstr (name, "__");
9612 if (tmp == NULL)
9613 tmp = strstr (name, "$");
9614 if (tmp != NULL)
9615 {
9616 GROW_VECT (result, result_len, tmp - name + 1);
9617 strncpy (result, name, tmp - name);
9618 result[tmp - name] = '\0';
9619 return result;
9620 }
9621
9622 return name;
9623 }
9624 }
9625
9626 /* Evaluate the subexpression of EXP starting at *POS as for
9627 evaluate_type, updating *POS to point just past the evaluated
9628 expression. */
9629
9630 static struct value *
9631 evaluate_subexp_type (struct expression *exp, int *pos)
9632 {
9633 return evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
9634 }
9635
9636 /* If VAL is wrapped in an aligner or subtype wrapper, return the
9637 value it wraps. */
9638
9639 static struct value *
9640 unwrap_value (struct value *val)
9641 {
9642 struct type *type = ada_check_typedef (value_type (val));
9643
9644 if (ada_is_aligner_type (type))
9645 {
9646 struct value *v = ada_value_struct_elt (val, "F", 0);
9647 struct type *val_type = ada_check_typedef (value_type (v));
9648
9649 if (ada_type_name (val_type) == NULL)
9650 TYPE_NAME (val_type) = ada_type_name (type);
9651
9652 return unwrap_value (v);
9653 }
9654 else
9655 {
9656 struct type *raw_real_type =
9657 ada_check_typedef (ada_get_base_type (type));
9658
9659 /* If there is no parallel XVS or XVE type, then the value is
9660 already unwrapped. Return it without further modification. */
9661 if ((type == raw_real_type)
9662 && ada_find_parallel_type (type, "___XVE") == NULL)
9663 return val;
9664
9665 return
9666 coerce_unspec_val_to_type
9667 (val, ada_to_fixed_type (raw_real_type, 0,
9668 value_address (val),
9669 NULL, 1));
9670 }
9671 }
9672
9673 static struct value *
9674 cast_from_fixed (struct type *type, struct value *arg)
9675 {
9676 struct value *scale = ada_scaling_factor (value_type (arg));
9677 arg = value_cast (value_type (scale), arg);
9678
9679 arg = value_binop (arg, scale, BINOP_MUL);
9680 return value_cast (type, arg);
9681 }
9682
9683 static struct value *
9684 cast_to_fixed (struct type *type, struct value *arg)
9685 {
9686 if (type == value_type (arg))
9687 return arg;
9688
9689 struct value *scale = ada_scaling_factor (type);
9690 if (ada_is_fixed_point_type (value_type (arg)))
9691 arg = cast_from_fixed (value_type (scale), arg);
9692 else
9693 arg = value_cast (value_type (scale), arg);
9694
9695 arg = value_binop (arg, scale, BINOP_DIV);
9696 return value_cast (type, arg);
9697 }
9698
9699 /* Given two array types T1 and T2, return nonzero iff both arrays
9700 contain the same number of elements. */
9701
9702 static int
9703 ada_same_array_size_p (struct type *t1, struct type *t2)
9704 {
9705 LONGEST lo1, hi1, lo2, hi2;
9706
9707 /* Get the array bounds in order to verify that the size of
9708 the two arrays match. */
9709 if (!get_array_bounds (t1, &lo1, &hi1)
9710 || !get_array_bounds (t2, &lo2, &hi2))
9711 error (_("unable to determine array bounds"));
9712
9713 /* To make things easier for size comparison, normalize a bit
9714 the case of empty arrays by making sure that the difference
9715 between upper bound and lower bound is always -1. */
9716 if (lo1 > hi1)
9717 hi1 = lo1 - 1;
9718 if (lo2 > hi2)
9719 hi2 = lo2 - 1;
9720
9721 return (hi1 - lo1 == hi2 - lo2);
9722 }
9723
9724 /* Assuming that VAL is an array of integrals, and TYPE represents
9725 an array with the same number of elements, but with wider integral
9726 elements, return an array "casted" to TYPE. In practice, this
9727 means that the returned array is built by casting each element
9728 of the original array into TYPE's (wider) element type. */
9729
9730 static struct value *
9731 ada_promote_array_of_integrals (struct type *type, struct value *val)
9732 {
9733 struct type *elt_type = TYPE_TARGET_TYPE (type);
9734 LONGEST lo, hi;
9735 struct value *res;
9736 LONGEST i;
9737
9738 /* Verify that both val and type are arrays of scalars, and
9739 that the size of val's elements is smaller than the size
9740 of type's element. */
9741 gdb_assert (TYPE_CODE (type) == TYPE_CODE_ARRAY);
9742 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
9743 gdb_assert (TYPE_CODE (value_type (val)) == TYPE_CODE_ARRAY);
9744 gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
9745 gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
9746 > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));
9747
9748 if (!get_array_bounds (type, &lo, &hi))
9749 error (_("unable to determine array bounds"));
9750
9751 res = allocate_value (type);
9752
9753 /* Promote each array element. */
9754 for (i = 0; i < hi - lo + 1; i++)
9755 {
9756 struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
9757
9758 memcpy (value_contents_writeable (res) + (i * TYPE_LENGTH (elt_type)),
9759 value_contents_all (elt), TYPE_LENGTH (elt_type));
9760 }
9761
9762 return res;
9763 }
9764
9765 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
9766 return the converted value. */
9767
9768 static struct value *
9769 coerce_for_assign (struct type *type, struct value *val)
9770 {
9771 struct type *type2 = value_type (val);
9772
9773 if (type == type2)
9774 return val;
9775
9776 type2 = ada_check_typedef (type2);
9777 type = ada_check_typedef (type);
9778
9779 if (TYPE_CODE (type2) == TYPE_CODE_PTR
9780 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
9781 {
9782 val = ada_value_ind (val);
9783 type2 = value_type (val);
9784 }
9785
9786 if (TYPE_CODE (type2) == TYPE_CODE_ARRAY
9787 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
9788 {
9789 if (!ada_same_array_size_p (type, type2))
9790 error (_("cannot assign arrays of different length"));
9791
9792 if (is_integral_type (TYPE_TARGET_TYPE (type))
9793 && is_integral_type (TYPE_TARGET_TYPE (type2))
9794 && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9795 < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9796 {
9797 /* Allow implicit promotion of the array elements to
9798 a wider type. */
9799 return ada_promote_array_of_integrals (type, val);
9800 }
9801
9802 if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
9803 != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
9804 error (_("Incompatible types in assignment"));
9805 deprecated_set_value_type (val, type);
9806 }
9807 return val;
9808 }
9809
9810 static struct value *
9811 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
9812 {
9813 struct value *val;
9814 struct type *type1, *type2;
9815 LONGEST v, v1, v2;
9816
9817 arg1 = coerce_ref (arg1);
9818 arg2 = coerce_ref (arg2);
9819 type1 = get_base_type (ada_check_typedef (value_type (arg1)));
9820 type2 = get_base_type (ada_check_typedef (value_type (arg2)));
9821
9822 if (TYPE_CODE (type1) != TYPE_CODE_INT
9823 || TYPE_CODE (type2) != TYPE_CODE_INT)
9824 return value_binop (arg1, arg2, op);
9825
9826 switch (op)
9827 {
9828 case BINOP_MOD:
9829 case BINOP_DIV:
9830 case BINOP_REM:
9831 break;
9832 default:
9833 return value_binop (arg1, arg2, op);
9834 }
9835
9836 v2 = value_as_long (arg2);
9837 if (v2 == 0)
9838 error (_("second operand of %s must not be zero."), op_string (op));
9839
9840 if (TYPE_UNSIGNED (type1) || op == BINOP_MOD)
9841 return value_binop (arg1, arg2, op);
9842
9843 v1 = value_as_long (arg1);
9844 switch (op)
9845 {
9846 case BINOP_DIV:
9847 v = v1 / v2;
9848 if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
9849 v += v > 0 ? -1 : 1;
9850 break;
9851 case BINOP_REM:
9852 v = v1 % v2;
9853 if (v * v1 < 0)
9854 v -= v2;
9855 break;
9856 default:
9857 /* Should not reach this point. */
9858 v = 0;
9859 }
9860
9861 val = allocate_value (type1);
9862 store_unsigned_integer (value_contents_raw (val),
9863 TYPE_LENGTH (value_type (val)),
9864 gdbarch_byte_order (get_type_arch (type1)), v);
9865 return val;
9866 }
9867
9868 static int
9869 ada_value_equal (struct value *arg1, struct value *arg2)
9870 {
9871 if (ada_is_direct_array_type (value_type (arg1))
9872 || ada_is_direct_array_type (value_type (arg2)))
9873 {
9874 struct type *arg1_type, *arg2_type;
9875
9876 /* Automatically dereference any array reference before
9877 we attempt to perform the comparison. */
9878 arg1 = ada_coerce_ref (arg1);
9879 arg2 = ada_coerce_ref (arg2);
9880
9881 arg1 = ada_coerce_to_simple_array (arg1);
9882 arg2 = ada_coerce_to_simple_array (arg2);
9883
9884 arg1_type = ada_check_typedef (value_type (arg1));
9885 arg2_type = ada_check_typedef (value_type (arg2));
9886
9887 if (TYPE_CODE (arg1_type) != TYPE_CODE_ARRAY
9888 || TYPE_CODE (arg2_type) != TYPE_CODE_ARRAY)
9889 error (_("Attempt to compare array with non-array"));
9890 /* FIXME: The following works only for types whose
9891 representations use all bits (no padding or undefined bits)
9892 and do not have user-defined equality. */
9893 return (TYPE_LENGTH (arg1_type) == TYPE_LENGTH (arg2_type)
9894 && memcmp (value_contents (arg1), value_contents (arg2),
9895 TYPE_LENGTH (arg1_type)) == 0);
9896 }
9897 return value_equal (arg1, arg2);
9898 }
9899
9900 /* Total number of component associations in the aggregate starting at
9901 index PC in EXP. Assumes that index PC is the start of an
9902 OP_AGGREGATE. */
9903
9904 static int
9905 num_component_specs (struct expression *exp, int pc)
9906 {
9907 int n, m, i;
9908
9909 m = exp->elts[pc + 1].longconst;
9910 pc += 3;
9911 n = 0;
9912 for (i = 0; i < m; i += 1)
9913 {
9914 switch (exp->elts[pc].opcode)
9915 {
9916 default:
9917 n += 1;
9918 break;
9919 case OP_CHOICES:
9920 n += exp->elts[pc + 1].longconst;
9921 break;
9922 }
9923 ada_evaluate_subexp (NULL, exp, &pc, EVAL_SKIP);
9924 }
9925 return n;
9926 }
9927
9928 /* Assign the result of evaluating EXP starting at *POS to the INDEXth
9929 component of LHS (a simple array or a record), updating *POS past
9930 the expression, assuming that LHS is contained in CONTAINER. Does
9931 not modify the inferior's memory, nor does it modify LHS (unless
9932 LHS == CONTAINER). */
9933
9934 static void
9935 assign_component (struct value *container, struct value *lhs, LONGEST index,
9936 struct expression *exp, int *pos)
9937 {
9938 struct value *mark = value_mark ();
9939 struct value *elt;
9940 struct type *lhs_type = check_typedef (value_type (lhs));
9941
9942 if (TYPE_CODE (lhs_type) == TYPE_CODE_ARRAY)
9943 {
9944 struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
9945 struct value *index_val = value_from_longest (index_type, index);
9946
9947 elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
9948 }
9949 else
9950 {
9951 elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
9952 elt = ada_to_fixed_value (elt);
9953 }
9954
9955 if (exp->elts[*pos].opcode == OP_AGGREGATE)
9956 assign_aggregate (container, elt, exp, pos, EVAL_NORMAL);
9957 else
9958 value_assign_to_component (container, elt,
9959 ada_evaluate_subexp (NULL, exp, pos,
9960 EVAL_NORMAL));
9961
9962 value_free_to_mark (mark);
9963 }
9964
9965 /* Assuming that LHS represents an lvalue having a record or array
9966 type, and EXP->ELTS[*POS] is an OP_AGGREGATE, evaluate an assignment
9967 of that aggregate's value to LHS, advancing *POS past the
9968 aggregate. NOSIDE is as for evaluate_subexp. CONTAINER is an
9969 lvalue containing LHS (possibly LHS itself). Does not modify
9970 the inferior's memory, nor does it modify the contents of
9971 LHS (unless == CONTAINER). Returns the modified CONTAINER. */
9972
9973 static struct value *
9974 assign_aggregate (struct value *container,
9975 struct value *lhs, struct expression *exp,
9976 int *pos, enum noside noside)
9977 {
9978 struct type *lhs_type;
9979 int n = exp->elts[*pos+1].longconst;
9980 LONGEST low_index, high_index;
9981 int num_specs;
9982 LONGEST *indices;
9983 int max_indices, num_indices;
9984 int i;
9985
9986 *pos += 3;
9987 if (noside != EVAL_NORMAL)
9988 {
9989 for (i = 0; i < n; i += 1)
9990 ada_evaluate_subexp (NULL, exp, pos, noside);
9991 return container;
9992 }
9993
9994 container = ada_coerce_ref (container);
9995 if (ada_is_direct_array_type (value_type (container)))
9996 container = ada_coerce_to_simple_array (container);
9997 lhs = ada_coerce_ref (lhs);
9998 if (!deprecated_value_modifiable (lhs))
9999 error (_("Left operand of assignment is not a modifiable lvalue."));
10000
10001 lhs_type = check_typedef (value_type (lhs));
10002 if (ada_is_direct_array_type (lhs_type))
10003 {
10004 lhs = ada_coerce_to_simple_array (lhs);
10005 lhs_type = check_typedef (value_type (lhs));
10006 low_index = TYPE_ARRAY_LOWER_BOUND_VALUE (lhs_type);
10007 high_index = TYPE_ARRAY_UPPER_BOUND_VALUE (lhs_type);
10008 }
10009 else if (TYPE_CODE (lhs_type) == TYPE_CODE_STRUCT)
10010 {
10011 low_index = 0;
10012 high_index = num_visible_fields (lhs_type) - 1;
10013 }
10014 else
10015 error (_("Left-hand side must be array or record."));
10016
10017 num_specs = num_component_specs (exp, *pos - 3);
10018 max_indices = 4 * num_specs + 4;
10019 indices = XALLOCAVEC (LONGEST, max_indices);
10020 indices[0] = indices[1] = low_index - 1;
10021 indices[2] = indices[3] = high_index + 1;
10022 num_indices = 4;
10023
10024 for (i = 0; i < n; i += 1)
10025 {
10026 switch (exp->elts[*pos].opcode)
10027 {
10028 case OP_CHOICES:
10029 aggregate_assign_from_choices (container, lhs, exp, pos, indices,
10030 &num_indices, max_indices,
10031 low_index, high_index);
10032 break;
10033 case OP_POSITIONAL:
10034 aggregate_assign_positional (container, lhs, exp, pos, indices,
10035 &num_indices, max_indices,
10036 low_index, high_index);
10037 break;
10038 case OP_OTHERS:
10039 if (i != n-1)
10040 error (_("Misplaced 'others' clause"));
10041 aggregate_assign_others (container, lhs, exp, pos, indices,
10042 num_indices, low_index, high_index);
10043 break;
10044 default:
10045 error (_("Internal error: bad aggregate clause"));
10046 }
10047 }
10048
10049 return container;
10050 }
10051
10052 /* Assign into the component of LHS indexed by the OP_POSITIONAL
10053 construct at *POS, updating *POS past the construct, given that
10054 the positions are relative to lower bound LOW, where HIGH is the
10055 upper bound. Record the position in INDICES[0 .. MAX_INDICES-1]
10056 updating *NUM_INDICES as needed. CONTAINER is as for
10057 assign_aggregate. */
10058 static void
10059 aggregate_assign_positional (struct value *container,
10060 struct value *lhs, struct expression *exp,
10061 int *pos, LONGEST *indices, int *num_indices,
10062 int max_indices, LONGEST low, LONGEST high)
10063 {
10064 LONGEST ind = longest_to_int (exp->elts[*pos + 1].longconst) + low;
10065
10066 if (ind - 1 == high)
10067 warning (_("Extra components in aggregate ignored."));
10068 if (ind <= high)
10069 {
10070 add_component_interval (ind, ind, indices, num_indices, max_indices);
10071 *pos += 3;
10072 assign_component (container, lhs, ind, exp, pos);
10073 }
10074 else
10075 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
10076 }
10077
10078 /* Assign into the components of LHS indexed by the OP_CHOICES
10079 construct at *POS, updating *POS past the construct, given that
10080 the allowable indices are LOW..HIGH. Record the indices assigned
10081 to in INDICES[0 .. MAX_INDICES-1], updating *NUM_INDICES as
10082 needed. CONTAINER is as for assign_aggregate. */
10083 static void
10084 aggregate_assign_from_choices (struct value *container,
10085 struct value *lhs, struct expression *exp,
10086 int *pos, LONGEST *indices, int *num_indices,
10087 int max_indices, LONGEST low, LONGEST high)
10088 {
10089 int j;
10090 int n_choices = longest_to_int (exp->elts[*pos+1].longconst);
10091 int choice_pos, expr_pc;
10092 int is_array = ada_is_direct_array_type (value_type (lhs));
10093
10094 choice_pos = *pos += 3;
10095
10096 for (j = 0; j < n_choices; j += 1)
10097 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
10098 expr_pc = *pos;
10099 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
10100
10101 for (j = 0; j < n_choices; j += 1)
10102 {
10103 LONGEST lower, upper;
10104 enum exp_opcode op = exp->elts[choice_pos].opcode;
10105
10106 if (op == OP_DISCRETE_RANGE)
10107 {
10108 choice_pos += 1;
10109 lower = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
10110 EVAL_NORMAL));
10111 upper = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
10112 EVAL_NORMAL));
10113 }
10114 else if (is_array)
10115 {
10116 lower = value_as_long (ada_evaluate_subexp (NULL, exp, &choice_pos,
10117 EVAL_NORMAL));
10118 upper = lower;
10119 }
10120 else
10121 {
10122 int ind;
10123 const char *name;
10124
10125 switch (op)
10126 {
10127 case OP_NAME:
10128 name = &exp->elts[choice_pos + 2].string;
10129 break;
10130 case OP_VAR_VALUE:
10131 name = SYMBOL_NATURAL_NAME (exp->elts[choice_pos + 2].symbol);
10132 break;
10133 default:
10134 error (_("Invalid record component association."));
10135 }
10136 ada_evaluate_subexp (NULL, exp, &choice_pos, EVAL_SKIP);
10137 ind = 0;
10138 if (! find_struct_field (name, value_type (lhs), 0,
10139 NULL, NULL, NULL, NULL, &ind))
10140 error (_("Unknown component name: %s."), name);
10141 lower = upper = ind;
10142 }
10143
10144 if (lower <= upper && (lower < low || upper > high))
10145 error (_("Index in component association out of bounds."));
10146
10147 add_component_interval (lower, upper, indices, num_indices,
10148 max_indices);
10149 while (lower <= upper)
10150 {
10151 int pos1;
10152
10153 pos1 = expr_pc;
10154 assign_component (container, lhs, lower, exp, &pos1);
10155 lower += 1;
10156 }
10157 }
10158 }
10159
10160 /* Assign the value of the expression in the OP_OTHERS construct in
10161 EXP at *POS into the components of LHS indexed from LOW .. HIGH that
10162 have not been previously assigned. The index intervals already assigned
10163 are in INDICES[0 .. NUM_INDICES-1]. Updates *POS to after the
10164 OP_OTHERS clause. CONTAINER is as for assign_aggregate. */
10165 static void
10166 aggregate_assign_others (struct value *container,
10167 struct value *lhs, struct expression *exp,
10168 int *pos, LONGEST *indices, int num_indices,
10169 LONGEST low, LONGEST high)
10170 {
10171 int i;
10172 int expr_pc = *pos + 1;
10173
10174 for (i = 0; i < num_indices - 2; i += 2)
10175 {
10176 LONGEST ind;
10177
10178 for (ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
10179 {
10180 int localpos;
10181
10182 localpos = expr_pc;
10183 assign_component (container, lhs, ind, exp, &localpos);
10184 }
10185 }
10186 ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
10187 }
10188
10189 /* Add the interval [LOW .. HIGH] to the sorted set of intervals
10190 [ INDICES[0] .. INDICES[1] ],..., [ INDICES[*SIZE-2] .. INDICES[*SIZE-1] ],
10191 modifying *SIZE as needed. It is an error if *SIZE exceeds
10192 MAX_SIZE. The resulting intervals do not overlap. */
10193 static void
10194 add_component_interval (LONGEST low, LONGEST high,
10195 LONGEST* indices, int *size, int max_size)
10196 {
10197 int i, j;
10198
10199 for (i = 0; i < *size; i += 2) {
10200 if (high >= indices[i] && low <= indices[i + 1])
10201 {
10202 int kh;
10203
10204 for (kh = i + 2; kh < *size; kh += 2)
10205 if (high < indices[kh])
10206 break;
10207 if (low < indices[i])
10208 indices[i] = low;
10209 indices[i + 1] = indices[kh - 1];
10210 if (high > indices[i + 1])
10211 indices[i + 1] = high;
10212 memcpy (indices + i + 2, indices + kh, *size - kh);
10213 *size -= kh - i - 2;
10214 return;
10215 }
10216 else if (high < indices[i])
10217 break;
10218 }
10219
10220 if (*size == max_size)
10221 error (_("Internal error: miscounted aggregate components."));
10222 *size += 2;
10223 for (j = *size-1; j >= i+2; j -= 1)
10224 indices[j] = indices[j - 2];
10225 indices[i] = low;
10226 indices[i + 1] = high;
10227 }
10228
10229 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
10230 is different. */
10231
10232 static struct value *
10233 ada_value_cast (struct type *type, struct value *arg2)
10234 {
10235 if (type == ada_check_typedef (value_type (arg2)))
10236 return arg2;
10237
10238 if (ada_is_fixed_point_type (type))
10239 return cast_to_fixed (type, arg2);
10240
10241 if (ada_is_fixed_point_type (value_type (arg2)))
10242 return cast_from_fixed (type, arg2);
10243
10244 return value_cast (type, arg2);
10245 }
10246
10247 /* Evaluating Ada expressions, and printing their result.
10248 ------------------------------------------------------
10249
10250 1. Introduction:
10251 ----------------
10252
10253 We usually evaluate an Ada expression in order to print its value.
10254 We also evaluate an expression in order to print its type, which
10255 happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
10256 but we'll focus mostly on the EVAL_NORMAL phase. In practice, the
10257 EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
10258 the evaluation compared to the EVAL_NORMAL, but is otherwise very
10259 similar.
10260
10261 Evaluating expressions is a little more complicated for Ada entities
10262 than it is for entities in languages such as C. The main reason for
10263 this is that Ada provides types whose definition might be dynamic.
10264 One example of such types is variant records. Or another example
10265 would be an array whose bounds can only be known at run time.
10266
10267 The following description is a general guide as to what should be
10268 done (and what should NOT be done) in order to evaluate an expression
10269 involving such types, and when. This does not cover how the semantic
10270 information is encoded by GNAT as this is covered separatly. For the
10271 document used as the reference for the GNAT encoding, see exp_dbug.ads
10272 in the GNAT sources.
10273
10274 Ideally, we should embed each part of this description next to its
10275 associated code. Unfortunately, the amount of code is so vast right
10276 now that it's hard to see whether the code handling a particular
10277 situation might be duplicated or not. One day, when the code is
10278 cleaned up, this guide might become redundant with the comments
10279 inserted in the code, and we might want to remove it.
10280
10281 2. ``Fixing'' an Entity, the Simple Case:
10282 -----------------------------------------
10283
10284 When evaluating Ada expressions, the tricky issue is that they may
10285 reference entities whose type contents and size are not statically
10286 known. Consider for instance a variant record:
10287
10288 type Rec (Empty : Boolean := True) is record
10289 case Empty is
10290 when True => null;
10291 when False => Value : Integer;
10292 end case;
10293 end record;
10294 Yes : Rec := (Empty => False, Value => 1);
10295 No : Rec := (empty => True);
10296
10297 The size and contents of that record depends on the value of the
10298 descriminant (Rec.Empty). At this point, neither the debugging
10299 information nor the associated type structure in GDB are able to
10300 express such dynamic types. So what the debugger does is to create
10301 "fixed" versions of the type that applies to the specific object.
10302 We also informally refer to this opperation as "fixing" an object,
10303 which means creating its associated fixed type.
10304
10305 Example: when printing the value of variable "Yes" above, its fixed
10306 type would look like this:
10307
10308 type Rec is record
10309 Empty : Boolean;
10310 Value : Integer;
10311 end record;
10312
10313 On the other hand, if we printed the value of "No", its fixed type
10314 would become:
10315
10316 type Rec is record
10317 Empty : Boolean;
10318 end record;
10319
10320 Things become a little more complicated when trying to fix an entity
10321 with a dynamic type that directly contains another dynamic type,
10322 such as an array of variant records, for instance. There are
10323 two possible cases: Arrays, and records.
10324
10325 3. ``Fixing'' Arrays:
10326 ---------------------
10327
10328 The type structure in GDB describes an array in terms of its bounds,
10329 and the type of its elements. By design, all elements in the array
10330 have the same type and we cannot represent an array of variant elements
10331 using the current type structure in GDB. When fixing an array,
10332 we cannot fix the array element, as we would potentially need one
10333 fixed type per element of the array. As a result, the best we can do
10334 when fixing an array is to produce an array whose bounds and size
10335 are correct (allowing us to read it from memory), but without having
10336 touched its element type. Fixing each element will be done later,
10337 when (if) necessary.
10338
10339 Arrays are a little simpler to handle than records, because the same
10340 amount of memory is allocated for each element of the array, even if
10341 the amount of space actually used by each element differs from element
10342 to element. Consider for instance the following array of type Rec:
10343
10344 type Rec_Array is array (1 .. 2) of Rec;
10345
10346 The actual amount of memory occupied by each element might be different
10347 from element to element, depending on the value of their discriminant.
10348 But the amount of space reserved for each element in the array remains
10349 fixed regardless. So we simply need to compute that size using
10350 the debugging information available, from which we can then determine
10351 the array size (we multiply the number of elements of the array by
10352 the size of each element).
10353
10354 The simplest case is when we have an array of a constrained element
10355 type. For instance, consider the following type declarations:
10356
10357 type Bounded_String (Max_Size : Integer) is
10358 Length : Integer;
10359 Buffer : String (1 .. Max_Size);
10360 end record;
10361 type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
10362
10363 In this case, the compiler describes the array as an array of
10364 variable-size elements (identified by its XVS suffix) for which
10365 the size can be read in the parallel XVZ variable.
10366
10367 In the case of an array of an unconstrained element type, the compiler
10368 wraps the array element inside a private PAD type. This type should not
10369 be shown to the user, and must be "unwrap"'ed before printing. Note
10370 that we also use the adjective "aligner" in our code to designate
10371 these wrapper types.
10372
10373 In some cases, the size allocated for each element is statically
10374 known. In that case, the PAD type already has the correct size,
10375 and the array element should remain unfixed.
10376
10377 But there are cases when this size is not statically known.
10378 For instance, assuming that "Five" is an integer variable:
10379
10380 type Dynamic is array (1 .. Five) of Integer;
10381 type Wrapper (Has_Length : Boolean := False) is record
10382 Data : Dynamic;
10383 case Has_Length is
10384 when True => Length : Integer;
10385 when False => null;
10386 end case;
10387 end record;
10388 type Wrapper_Array is array (1 .. 2) of Wrapper;
10389
10390 Hello : Wrapper_Array := (others => (Has_Length => True,
10391 Data => (others => 17),
10392 Length => 1));
10393
10394
10395 The debugging info would describe variable Hello as being an
10396 array of a PAD type. The size of that PAD type is not statically
10397 known, but can be determined using a parallel XVZ variable.
10398 In that case, a copy of the PAD type with the correct size should
10399 be used for the fixed array.
10400
10401 3. ``Fixing'' record type objects:
10402 ----------------------------------
10403
10404 Things are slightly different from arrays in the case of dynamic
10405 record types. In this case, in order to compute the associated
10406 fixed type, we need to determine the size and offset of each of
10407 its components. This, in turn, requires us to compute the fixed
10408 type of each of these components.
10409
10410 Consider for instance the example:
10411
10412 type Bounded_String (Max_Size : Natural) is record
10413 Str : String (1 .. Max_Size);
10414 Length : Natural;
10415 end record;
10416 My_String : Bounded_String (Max_Size => 10);
10417
10418 In that case, the position of field "Length" depends on the size
10419 of field Str, which itself depends on the value of the Max_Size
10420 discriminant. In order to fix the type of variable My_String,
10421 we need to fix the type of field Str. Therefore, fixing a variant
10422 record requires us to fix each of its components.
10423
10424 However, if a component does not have a dynamic size, the component
10425 should not be fixed. In particular, fields that use a PAD type
10426 should not fixed. Here is an example where this might happen
10427 (assuming type Rec above):
10428
10429 type Container (Big : Boolean) is record
10430 First : Rec;
10431 After : Integer;
10432 case Big is
10433 when True => Another : Integer;
10434 when False => null;
10435 end case;
10436 end record;
10437 My_Container : Container := (Big => False,
10438 First => (Empty => True),
10439 After => 42);
10440
10441 In that example, the compiler creates a PAD type for component First,
10442 whose size is constant, and then positions the component After just
10443 right after it. The offset of component After is therefore constant
10444 in this case.
10445
10446 The debugger computes the position of each field based on an algorithm
10447 that uses, among other things, the actual position and size of the field
10448 preceding it. Let's now imagine that the user is trying to print
10449 the value of My_Container. If the type fixing was recursive, we would
10450 end up computing the offset of field After based on the size of the
10451 fixed version of field First. And since in our example First has
10452 only one actual field, the size of the fixed type is actually smaller
10453 than the amount of space allocated to that field, and thus we would
10454 compute the wrong offset of field After.
10455
10456 To make things more complicated, we need to watch out for dynamic
10457 components of variant records (identified by the ___XVL suffix in
10458 the component name). Even if the target type is a PAD type, the size
10459 of that type might not be statically known. So the PAD type needs
10460 to be unwrapped and the resulting type needs to be fixed. Otherwise,
10461 we might end up with the wrong size for our component. This can be
10462 observed with the following type declarations:
10463
10464 type Octal is new Integer range 0 .. 7;
10465 type Octal_Array is array (Positive range <>) of Octal;
10466 pragma Pack (Octal_Array);
10467
10468 type Octal_Buffer (Size : Positive) is record
10469 Buffer : Octal_Array (1 .. Size);
10470 Length : Integer;
10471 end record;
10472
10473 In that case, Buffer is a PAD type whose size is unset and needs
10474 to be computed by fixing the unwrapped type.
10475
10476 4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
10477 ----------------------------------------------------------
10478
10479 Lastly, when should the sub-elements of an entity that remained unfixed
10480 thus far, be actually fixed?
10481
10482 The answer is: Only when referencing that element. For instance
10483 when selecting one component of a record, this specific component
10484 should be fixed at that point in time. Or when printing the value
10485 of a record, each component should be fixed before its value gets
10486 printed. Similarly for arrays, the element of the array should be
10487 fixed when printing each element of the array, or when extracting
10488 one element out of that array. On the other hand, fixing should
10489 not be performed on the elements when taking a slice of an array!
10490
10491 Note that one of the side effects of miscomputing the offset and
10492 size of each field is that we end up also miscomputing the size
10493 of the containing type. This can have adverse results when computing
10494 the value of an entity. GDB fetches the value of an entity based
10495 on the size of its type, and thus a wrong size causes GDB to fetch
10496 the wrong amount of memory. In the case where the computed size is
10497 too small, GDB fetches too little data to print the value of our
10498 entity. Results in this case are unpredictable, as we usually read
10499 past the buffer containing the data =:-o. */
10500
10501 /* Evaluate a subexpression of EXP, at index *POS, and return a value
10502 for that subexpression cast to TO_TYPE. Advance *POS over the
10503 subexpression. */
10504
10505 static value *
10506 ada_evaluate_subexp_for_cast (expression *exp, int *pos,
10507 enum noside noside, struct type *to_type)
10508 {
10509 int pc = *pos;
10510
10511 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE
10512 || exp->elts[pc].opcode == OP_VAR_VALUE)
10513 {
10514 (*pos) += 4;
10515
10516 value *val;
10517 if (exp->elts[pc].opcode == OP_VAR_MSYM_VALUE)
10518 {
10519 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10520 return value_zero (to_type, not_lval);
10521
10522 val = evaluate_var_msym_value (noside,
10523 exp->elts[pc + 1].objfile,
10524 exp->elts[pc + 2].msymbol);
10525 }
10526 else
10527 val = evaluate_var_value (noside,
10528 exp->elts[pc + 1].block,
10529 exp->elts[pc + 2].symbol);
10530
10531 if (noside == EVAL_SKIP)
10532 return eval_skip_value (exp);
10533
10534 val = ada_value_cast (to_type, val);
10535
10536 /* Follow the Ada language semantics that do not allow taking
10537 an address of the result of a cast (view conversion in Ada). */
10538 if (VALUE_LVAL (val) == lval_memory)
10539 {
10540 if (value_lazy (val))
10541 value_fetch_lazy (val);
10542 VALUE_LVAL (val) = not_lval;
10543 }
10544 return val;
10545 }
10546
10547 value *val = evaluate_subexp (to_type, exp, pos, noside);
10548 if (noside == EVAL_SKIP)
10549 return eval_skip_value (exp);
10550 return ada_value_cast (to_type, val);
10551 }
10552
10553 /* Implement the evaluate_exp routine in the exp_descriptor structure
10554 for the Ada language. */
10555
10556 static struct value *
10557 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
10558 int *pos, enum noside noside)
10559 {
10560 enum exp_opcode op;
10561 int tem;
10562 int pc;
10563 int preeval_pos;
10564 struct value *arg1 = NULL, *arg2 = NULL, *arg3;
10565 struct type *type;
10566 int nargs, oplen;
10567 struct value **argvec;
10568
10569 pc = *pos;
10570 *pos += 1;
10571 op = exp->elts[pc].opcode;
10572
10573 switch (op)
10574 {
10575 default:
10576 *pos -= 1;
10577 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
10578
10579 if (noside == EVAL_NORMAL)
10580 arg1 = unwrap_value (arg1);
10581
10582 /* If evaluating an OP_FLOAT and an EXPECT_TYPE was provided,
10583 then we need to perform the conversion manually, because
10584 evaluate_subexp_standard doesn't do it. This conversion is
10585 necessary in Ada because the different kinds of float/fixed
10586 types in Ada have different representations.
10587
10588 Similarly, we need to perform the conversion from OP_LONG
10589 ourselves. */
10590 if ((op == OP_FLOAT || op == OP_LONG) && expect_type != NULL)
10591 arg1 = ada_value_cast (expect_type, arg1);
10592
10593 return arg1;
10594
10595 case OP_STRING:
10596 {
10597 struct value *result;
10598
10599 *pos -= 1;
10600 result = evaluate_subexp_standard (expect_type, exp, pos, noside);
10601 /* The result type will have code OP_STRING, bashed there from
10602 OP_ARRAY. Bash it back. */
10603 if (TYPE_CODE (value_type (result)) == TYPE_CODE_STRING)
10604 TYPE_CODE (value_type (result)) = TYPE_CODE_ARRAY;
10605 return result;
10606 }
10607
10608 case UNOP_CAST:
10609 (*pos) += 2;
10610 type = exp->elts[pc + 1].type;
10611 return ada_evaluate_subexp_for_cast (exp, pos, noside, type);
10612
10613 case UNOP_QUAL:
10614 (*pos) += 2;
10615 type = exp->elts[pc + 1].type;
10616 return ada_evaluate_subexp (type, exp, pos, noside);
10617
10618 case BINOP_ASSIGN:
10619 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10620 if (exp->elts[*pos].opcode == OP_AGGREGATE)
10621 {
10622 arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
10623 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
10624 return arg1;
10625 return ada_value_assign (arg1, arg1);
10626 }
10627 /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
10628 except if the lhs of our assignment is a convenience variable.
10629 In the case of assigning to a convenience variable, the lhs
10630 should be exactly the result of the evaluation of the rhs. */
10631 type = value_type (arg1);
10632 if (VALUE_LVAL (arg1) == lval_internalvar)
10633 type = NULL;
10634 arg2 = evaluate_subexp (type, exp, pos, noside);
10635 if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
10636 return arg1;
10637 if (ada_is_fixed_point_type (value_type (arg1)))
10638 arg2 = cast_to_fixed (value_type (arg1), arg2);
10639 else if (ada_is_fixed_point_type (value_type (arg2)))
10640 error
10641 (_("Fixed-point values must be assigned to fixed-point variables"));
10642 else
10643 arg2 = coerce_for_assign (value_type (arg1), arg2);
10644 return ada_value_assign (arg1, arg2);
10645
10646 case BINOP_ADD:
10647 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
10648 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
10649 if (noside == EVAL_SKIP)
10650 goto nosideret;
10651 if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
10652 return (value_from_longest
10653 (value_type (arg1),
10654 value_as_long (arg1) + value_as_long (arg2)));
10655 if (TYPE_CODE (value_type (arg2)) == TYPE_CODE_PTR)
10656 return (value_from_longest
10657 (value_type (arg2),
10658 value_as_long (arg1) + value_as_long (arg2)));
10659 if ((ada_is_fixed_point_type (value_type (arg1))
10660 || ada_is_fixed_point_type (value_type (arg2)))
10661 && value_type (arg1) != value_type (arg2))
10662 error (_("Operands of fixed-point addition must have the same type"));
10663 /* Do the addition, and cast the result to the type of the first
10664 argument. We cannot cast the result to a reference type, so if
10665 ARG1 is a reference type, find its underlying type. */
10666 type = value_type (arg1);
10667 while (TYPE_CODE (type) == TYPE_CODE_REF)
10668 type = TYPE_TARGET_TYPE (type);
10669 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10670 return value_cast (type, value_binop (arg1, arg2, BINOP_ADD));
10671
10672 case BINOP_SUB:
10673 arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
10674 arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
10675 if (noside == EVAL_SKIP)
10676 goto nosideret;
10677 if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
10678 return (value_from_longest
10679 (value_type (arg1),
10680 value_as_long (arg1) - value_as_long (arg2)));
10681 if (TYPE_CODE (value_type (arg2)) == TYPE_CODE_PTR)
10682 return (value_from_longest
10683 (value_type (arg2),
10684 value_as_long (arg1) - value_as_long (arg2)));
10685 if ((ada_is_fixed_point_type (value_type (arg1))
10686 || ada_is_fixed_point_type (value_type (arg2)))
10687 && value_type (arg1) != value_type (arg2))
10688 error (_("Operands of fixed-point subtraction "
10689 "must have the same type"));
10690 /* Do the substraction, and cast the result to the type of the first
10691 argument. We cannot cast the result to a reference type, so if
10692 ARG1 is a reference type, find its underlying type. */
10693 type = value_type (arg1);
10694 while (TYPE_CODE (type) == TYPE_CODE_REF)
10695 type = TYPE_TARGET_TYPE (type);
10696 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10697 return value_cast (type, value_binop (arg1, arg2, BINOP_SUB));
10698
10699 case BINOP_MUL:
10700 case BINOP_DIV:
10701 case BINOP_REM:
10702 case BINOP_MOD:
10703 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10704 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10705 if (noside == EVAL_SKIP)
10706 goto nosideret;
10707 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10708 {
10709 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10710 return value_zero (value_type (arg1), not_lval);
10711 }
10712 else
10713 {
10714 type = builtin_type (exp->gdbarch)->builtin_double;
10715 if (ada_is_fixed_point_type (value_type (arg1)))
10716 arg1 = cast_from_fixed (type, arg1);
10717 if (ada_is_fixed_point_type (value_type (arg2)))
10718 arg2 = cast_from_fixed (type, arg2);
10719 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10720 return ada_value_binop (arg1, arg2, op);
10721 }
10722
10723 case BINOP_EQUAL:
10724 case BINOP_NOTEQUAL:
10725 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10726 arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
10727 if (noside == EVAL_SKIP)
10728 goto nosideret;
10729 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10730 tem = 0;
10731 else
10732 {
10733 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10734 tem = ada_value_equal (arg1, arg2);
10735 }
10736 if (op == BINOP_NOTEQUAL)
10737 tem = !tem;
10738 type = language_bool_type (exp->language_defn, exp->gdbarch);
10739 return value_from_longest (type, (LONGEST) tem);
10740
10741 case UNOP_NEG:
10742 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10743 if (noside == EVAL_SKIP)
10744 goto nosideret;
10745 else if (ada_is_fixed_point_type (value_type (arg1)))
10746 return value_cast (value_type (arg1), value_neg (arg1));
10747 else
10748 {
10749 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10750 return value_neg (arg1);
10751 }
10752
10753 case BINOP_LOGICAL_AND:
10754 case BINOP_LOGICAL_OR:
10755 case UNOP_LOGICAL_NOT:
10756 {
10757 struct value *val;
10758
10759 *pos -= 1;
10760 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
10761 type = language_bool_type (exp->language_defn, exp->gdbarch);
10762 return value_cast (type, val);
10763 }
10764
10765 case BINOP_BITWISE_AND:
10766 case BINOP_BITWISE_IOR:
10767 case BINOP_BITWISE_XOR:
10768 {
10769 struct value *val;
10770
10771 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
10772 *pos = pc;
10773 val = evaluate_subexp_standard (expect_type, exp, pos, noside);
10774
10775 return value_cast (value_type (arg1), val);
10776 }
10777
10778 case OP_VAR_VALUE:
10779 *pos -= 1;
10780
10781 if (noside == EVAL_SKIP)
10782 {
10783 *pos += 4;
10784 goto nosideret;
10785 }
10786
10787 if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
10788 /* Only encountered when an unresolved symbol occurs in a
10789 context other than a function call, in which case, it is
10790 invalid. */
10791 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10792 SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
10793
10794 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10795 {
10796 type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
10797 /* Check to see if this is a tagged type. We also need to handle
10798 the case where the type is a reference to a tagged type, but
10799 we have to be careful to exclude pointers to tagged types.
10800 The latter should be shown as usual (as a pointer), whereas
10801 a reference should mostly be transparent to the user. */
10802 if (ada_is_tagged_type (type, 0)
10803 || (TYPE_CODE (type) == TYPE_CODE_REF
10804 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
10805 {
10806 /* Tagged types are a little special in the fact that the real
10807 type is dynamic and can only be determined by inspecting the
10808 object's tag. This means that we need to get the object's
10809 value first (EVAL_NORMAL) and then extract the actual object
10810 type from its tag.
10811
10812 Note that we cannot skip the final step where we extract
10813 the object type from its tag, because the EVAL_NORMAL phase
10814 results in dynamic components being resolved into fixed ones.
10815 This can cause problems when trying to print the type
10816 description of tagged types whose parent has a dynamic size:
10817 We use the type name of the "_parent" component in order
10818 to print the name of the ancestor type in the type description.
10819 If that component had a dynamic size, the resolution into
10820 a fixed type would result in the loss of that type name,
10821 thus preventing us from printing the name of the ancestor
10822 type in the type description. */
10823 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_NORMAL);
10824
10825 if (TYPE_CODE (type) != TYPE_CODE_REF)
10826 {
10827 struct type *actual_type;
10828
10829 actual_type = type_from_tag (ada_value_tag (arg1));
10830 if (actual_type == NULL)
10831 /* If, for some reason, we were unable to determine
10832 the actual type from the tag, then use the static
10833 approximation that we just computed as a fallback.
10834 This can happen if the debugging information is
10835 incomplete, for instance. */
10836 actual_type = type;
10837 return value_zero (actual_type, not_lval);
10838 }
10839 else
10840 {
10841 /* In the case of a ref, ada_coerce_ref takes care
10842 of determining the actual type. But the evaluation
10843 should return a ref as it should be valid to ask
10844 for its address; so rebuild a ref after coerce. */
10845 arg1 = ada_coerce_ref (arg1);
10846 return value_ref (arg1, TYPE_CODE_REF);
10847 }
10848 }
10849
10850 /* Records and unions for which GNAT encodings have been
10851 generated need to be statically fixed as well.
10852 Otherwise, non-static fixing produces a type where
10853 all dynamic properties are removed, which prevents "ptype"
10854 from being able to completely describe the type.
10855 For instance, a case statement in a variant record would be
10856 replaced by the relevant components based on the actual
10857 value of the discriminants. */
10858 if ((TYPE_CODE (type) == TYPE_CODE_STRUCT
10859 && dynamic_template_type (type) != NULL)
10860 || (TYPE_CODE (type) == TYPE_CODE_UNION
10861 && ada_find_parallel_type (type, "___XVU") != NULL))
10862 {
10863 *pos += 4;
10864 return value_zero (to_static_fixed_type (type), not_lval);
10865 }
10866 }
10867
10868 arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
10869 return ada_to_fixed_value (arg1);
10870
10871 case OP_FUNCALL:
10872 (*pos) += 2;
10873
10874 /* Allocate arg vector, including space for the function to be
10875 called in argvec[0] and a terminating NULL. */
10876 nargs = longest_to_int (exp->elts[pc + 1].longconst);
10877 argvec = XALLOCAVEC (struct value *, nargs + 2);
10878
10879 if (exp->elts[*pos].opcode == OP_VAR_VALUE
10880 && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
10881 error (_("Unexpected unresolved symbol, %s, during evaluation"),
10882 SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
10883 else
10884 {
10885 for (tem = 0; tem <= nargs; tem += 1)
10886 argvec[tem] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10887 argvec[tem] = 0;
10888
10889 if (noside == EVAL_SKIP)
10890 goto nosideret;
10891 }
10892
10893 if (ada_is_constrained_packed_array_type
10894 (desc_base_type (value_type (argvec[0]))))
10895 argvec[0] = ada_coerce_to_simple_array (argvec[0]);
10896 else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
10897 && TYPE_FIELD_BITSIZE (value_type (argvec[0]), 0) != 0)
10898 /* This is a packed array that has already been fixed, and
10899 therefore already coerced to a simple array. Nothing further
10900 to do. */
10901 ;
10902 else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_REF)
10903 {
10904 /* Make sure we dereference references so that all the code below
10905 feels like it's really handling the referenced value. Wrapping
10906 types (for alignment) may be there, so make sure we strip them as
10907 well. */
10908 argvec[0] = ada_to_fixed_value (coerce_ref (argvec[0]));
10909 }
10910 else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
10911 && VALUE_LVAL (argvec[0]) == lval_memory)
10912 argvec[0] = value_addr (argvec[0]);
10913
10914 type = ada_check_typedef (value_type (argvec[0]));
10915
10916 /* Ada allows us to implicitly dereference arrays when subscripting
10917 them. So, if this is an array typedef (encoding use for array
10918 access types encoded as fat pointers), strip it now. */
10919 if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
10920 type = ada_typedef_target_type (type);
10921
10922 if (TYPE_CODE (type) == TYPE_CODE_PTR)
10923 {
10924 switch (TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type))))
10925 {
10926 case TYPE_CODE_FUNC:
10927 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10928 break;
10929 case TYPE_CODE_ARRAY:
10930 break;
10931 case TYPE_CODE_STRUCT:
10932 if (noside != EVAL_AVOID_SIDE_EFFECTS)
10933 argvec[0] = ada_value_ind (argvec[0]);
10934 type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10935 break;
10936 default:
10937 error (_("cannot subscript or call something of type `%s'"),
10938 ada_type_name (value_type (argvec[0])));
10939 break;
10940 }
10941 }
10942
10943 switch (TYPE_CODE (type))
10944 {
10945 case TYPE_CODE_FUNC:
10946 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10947 {
10948 if (TYPE_TARGET_TYPE (type) == NULL)
10949 error_call_unknown_return_type (NULL);
10950 return allocate_value (TYPE_TARGET_TYPE (type));
10951 }
10952 return call_function_by_hand (argvec[0], NULL,
10953 gdb::make_array_view (argvec + 1,
10954 nargs));
10955 case TYPE_CODE_INTERNAL_FUNCTION:
10956 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10957 /* We don't know anything about what the internal
10958 function might return, but we have to return
10959 something. */
10960 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10961 not_lval);
10962 else
10963 return call_internal_function (exp->gdbarch, exp->language_defn,
10964 argvec[0], nargs, argvec + 1);
10965
10966 case TYPE_CODE_STRUCT:
10967 {
10968 int arity;
10969
10970 arity = ada_array_arity (type);
10971 type = ada_array_element_type (type, nargs);
10972 if (type == NULL)
10973 error (_("cannot subscript or call a record"));
10974 if (arity != nargs)
10975 error (_("wrong number of subscripts; expecting %d"), arity);
10976 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10977 return value_zero (ada_aligned_type (type), lval_memory);
10978 return
10979 unwrap_value (ada_value_subscript
10980 (argvec[0], nargs, argvec + 1));
10981 }
10982 case TYPE_CODE_ARRAY:
10983 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10984 {
10985 type = ada_array_element_type (type, nargs);
10986 if (type == NULL)
10987 error (_("element type of array unknown"));
10988 else
10989 return value_zero (ada_aligned_type (type), lval_memory);
10990 }
10991 return
10992 unwrap_value (ada_value_subscript
10993 (ada_coerce_to_simple_array (argvec[0]),
10994 nargs, argvec + 1));
10995 case TYPE_CODE_PTR: /* Pointer to array */
10996 if (noside == EVAL_AVOID_SIDE_EFFECTS)
10997 {
10998 type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
10999 type = ada_array_element_type (type, nargs);
11000 if (type == NULL)
11001 error (_("element type of array unknown"));
11002 else
11003 return value_zero (ada_aligned_type (type), lval_memory);
11004 }
11005 return
11006 unwrap_value (ada_value_ptr_subscript (argvec[0],
11007 nargs, argvec + 1));
11008
11009 default:
11010 error (_("Attempt to index or call something other than an "
11011 "array or function"));
11012 }
11013
11014 case TERNOP_SLICE:
11015 {
11016 struct value *array = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11017 struct value *low_bound_val =
11018 evaluate_subexp (NULL_TYPE, exp, pos, noside);
11019 struct value *high_bound_val =
11020 evaluate_subexp (NULL_TYPE, exp, pos, noside);
11021 LONGEST low_bound;
11022 LONGEST high_bound;
11023
11024 low_bound_val = coerce_ref (low_bound_val);
11025 high_bound_val = coerce_ref (high_bound_val);
11026 low_bound = value_as_long (low_bound_val);
11027 high_bound = value_as_long (high_bound_val);
11028
11029 if (noside == EVAL_SKIP)
11030 goto nosideret;
11031
11032 /* If this is a reference to an aligner type, then remove all
11033 the aligners. */
11034 if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
11035 && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
11036 TYPE_TARGET_TYPE (value_type (array)) =
11037 ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
11038
11039 if (ada_is_constrained_packed_array_type (value_type (array)))
11040 error (_("cannot slice a packed array"));
11041
11042 /* If this is a reference to an array or an array lvalue,
11043 convert to a pointer. */
11044 if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
11045 || (TYPE_CODE (value_type (array)) == TYPE_CODE_ARRAY
11046 && VALUE_LVAL (array) == lval_memory))
11047 array = value_addr (array);
11048
11049 if (noside == EVAL_AVOID_SIDE_EFFECTS
11050 && ada_is_array_descriptor_type (ada_check_typedef
11051 (value_type (array))))
11052 return empty_array (ada_type_of_array (array, 0), low_bound,
11053 high_bound);
11054
11055 array = ada_coerce_to_simple_array_ptr (array);
11056
11057 /* If we have more than one level of pointer indirection,
11058 dereference the value until we get only one level. */
11059 while (TYPE_CODE (value_type (array)) == TYPE_CODE_PTR
11060 && (TYPE_CODE (TYPE_TARGET_TYPE (value_type (array)))
11061 == TYPE_CODE_PTR))
11062 array = value_ind (array);
11063
11064 /* Make sure we really do have an array type before going further,
11065 to avoid a SEGV when trying to get the index type or the target
11066 type later down the road if the debug info generated by
11067 the compiler is incorrect or incomplete. */
11068 if (!ada_is_simple_array_type (value_type (array)))
11069 error (_("cannot take slice of non-array"));
11070
11071 if (TYPE_CODE (ada_check_typedef (value_type (array)))
11072 == TYPE_CODE_PTR)
11073 {
11074 struct type *type0 = ada_check_typedef (value_type (array));
11075
11076 if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
11077 return empty_array (TYPE_TARGET_TYPE (type0), low_bound, high_bound);
11078 else
11079 {
11080 struct type *arr_type0 =
11081 to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
11082
11083 return ada_value_slice_from_ptr (array, arr_type0,
11084 longest_to_int (low_bound),
11085 longest_to_int (high_bound));
11086 }
11087 }
11088 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11089 return array;
11090 else if (high_bound < low_bound)
11091 return empty_array (value_type (array), low_bound, high_bound);
11092 else
11093 return ada_value_slice (array, longest_to_int (low_bound),
11094 longest_to_int (high_bound));
11095 }
11096
11097 case UNOP_IN_RANGE:
11098 (*pos) += 2;
11099 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11100 type = check_typedef (exp->elts[pc + 1].type);
11101
11102 if (noside == EVAL_SKIP)
11103 goto nosideret;
11104
11105 switch (TYPE_CODE (type))
11106 {
11107 default:
11108 lim_warning (_("Membership test incompletely implemented; "
11109 "always returns true"));
11110 type = language_bool_type (exp->language_defn, exp->gdbarch);
11111 return value_from_longest (type, (LONGEST) 1);
11112
11113 case TYPE_CODE_RANGE:
11114 arg2 = value_from_longest (type, TYPE_LOW_BOUND (type));
11115 arg3 = value_from_longest (type, TYPE_HIGH_BOUND (type));
11116 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11117 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
11118 type = language_bool_type (exp->language_defn, exp->gdbarch);
11119 return
11120 value_from_longest (type,
11121 (value_less (arg1, arg3)
11122 || value_equal (arg1, arg3))
11123 && (value_less (arg2, arg1)
11124 || value_equal (arg2, arg1)));
11125 }
11126
11127 case BINOP_IN_BOUNDS:
11128 (*pos) += 2;
11129 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11130 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11131
11132 if (noside == EVAL_SKIP)
11133 goto nosideret;
11134
11135 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11136 {
11137 type = language_bool_type (exp->language_defn, exp->gdbarch);
11138 return value_zero (type, not_lval);
11139 }
11140
11141 tem = longest_to_int (exp->elts[pc + 1].longconst);
11142
11143 type = ada_index_type (value_type (arg2), tem, "range");
11144 if (!type)
11145 type = value_type (arg1);
11146
11147 arg3 = value_from_longest (type, ada_array_bound (arg2, tem, 1));
11148 arg2 = value_from_longest (type, ada_array_bound (arg2, tem, 0));
11149
11150 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11151 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
11152 type = language_bool_type (exp->language_defn, exp->gdbarch);
11153 return
11154 value_from_longest (type,
11155 (value_less (arg1, arg3)
11156 || value_equal (arg1, arg3))
11157 && (value_less (arg2, arg1)
11158 || value_equal (arg2, arg1)));
11159
11160 case TERNOP_IN_RANGE:
11161 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11162 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11163 arg3 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11164
11165 if (noside == EVAL_SKIP)
11166 goto nosideret;
11167
11168 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11169 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
11170 type = language_bool_type (exp->language_defn, exp->gdbarch);
11171 return
11172 value_from_longest (type,
11173 (value_less (arg1, arg3)
11174 || value_equal (arg1, arg3))
11175 && (value_less (arg2, arg1)
11176 || value_equal (arg2, arg1)));
11177
11178 case OP_ATR_FIRST:
11179 case OP_ATR_LAST:
11180 case OP_ATR_LENGTH:
11181 {
11182 struct type *type_arg;
11183
11184 if (exp->elts[*pos].opcode == OP_TYPE)
11185 {
11186 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11187 arg1 = NULL;
11188 type_arg = check_typedef (exp->elts[pc + 2].type);
11189 }
11190 else
11191 {
11192 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11193 type_arg = NULL;
11194 }
11195
11196 if (exp->elts[*pos].opcode != OP_LONG)
11197 error (_("Invalid operand to '%s"), ada_attribute_name (op));
11198 tem = longest_to_int (exp->elts[*pos + 2].longconst);
11199 *pos += 4;
11200
11201 if (noside == EVAL_SKIP)
11202 goto nosideret;
11203
11204 if (type_arg == NULL)
11205 {
11206 arg1 = ada_coerce_ref (arg1);
11207
11208 if (ada_is_constrained_packed_array_type (value_type (arg1)))
11209 arg1 = ada_coerce_to_simple_array (arg1);
11210
11211 if (op == OP_ATR_LENGTH)
11212 type = builtin_type (exp->gdbarch)->builtin_int;
11213 else
11214 {
11215 type = ada_index_type (value_type (arg1), tem,
11216 ada_attribute_name (op));
11217 if (type == NULL)
11218 type = builtin_type (exp->gdbarch)->builtin_int;
11219 }
11220
11221 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11222 return allocate_value (type);
11223
11224 switch (op)
11225 {
11226 default: /* Should never happen. */
11227 error (_("unexpected attribute encountered"));
11228 case OP_ATR_FIRST:
11229 return value_from_longest
11230 (type, ada_array_bound (arg1, tem, 0));
11231 case OP_ATR_LAST:
11232 return value_from_longest
11233 (type, ada_array_bound (arg1, tem, 1));
11234 case OP_ATR_LENGTH:
11235 return value_from_longest
11236 (type, ada_array_length (arg1, tem));
11237 }
11238 }
11239 else if (discrete_type_p (type_arg))
11240 {
11241 struct type *range_type;
11242 const char *name = ada_type_name (type_arg);
11243
11244 range_type = NULL;
11245 if (name != NULL && TYPE_CODE (type_arg) != TYPE_CODE_ENUM)
11246 range_type = to_fixed_range_type (type_arg, NULL);
11247 if (range_type == NULL)
11248 range_type = type_arg;
11249 switch (op)
11250 {
11251 default:
11252 error (_("unexpected attribute encountered"));
11253 case OP_ATR_FIRST:
11254 return value_from_longest
11255 (range_type, ada_discrete_type_low_bound (range_type));
11256 case OP_ATR_LAST:
11257 return value_from_longest
11258 (range_type, ada_discrete_type_high_bound (range_type));
11259 case OP_ATR_LENGTH:
11260 error (_("the 'length attribute applies only to array types"));
11261 }
11262 }
11263 else if (TYPE_CODE (type_arg) == TYPE_CODE_FLT)
11264 error (_("unimplemented type attribute"));
11265 else
11266 {
11267 LONGEST low, high;
11268
11269 if (ada_is_constrained_packed_array_type (type_arg))
11270 type_arg = decode_constrained_packed_array_type (type_arg);
11271
11272 if (op == OP_ATR_LENGTH)
11273 type = builtin_type (exp->gdbarch)->builtin_int;
11274 else
11275 {
11276 type = ada_index_type (type_arg, tem, ada_attribute_name (op));
11277 if (type == NULL)
11278 type = builtin_type (exp->gdbarch)->builtin_int;
11279 }
11280
11281 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11282 return allocate_value (type);
11283
11284 switch (op)
11285 {
11286 default:
11287 error (_("unexpected attribute encountered"));
11288 case OP_ATR_FIRST:
11289 low = ada_array_bound_from_type (type_arg, tem, 0);
11290 return value_from_longest (type, low);
11291 case OP_ATR_LAST:
11292 high = ada_array_bound_from_type (type_arg, tem, 1);
11293 return value_from_longest (type, high);
11294 case OP_ATR_LENGTH:
11295 low = ada_array_bound_from_type (type_arg, tem, 0);
11296 high = ada_array_bound_from_type (type_arg, tem, 1);
11297 return value_from_longest (type, high - low + 1);
11298 }
11299 }
11300 }
11301
11302 case OP_ATR_TAG:
11303 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11304 if (noside == EVAL_SKIP)
11305 goto nosideret;
11306
11307 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11308 return value_zero (ada_tag_type (arg1), not_lval);
11309
11310 return ada_value_tag (arg1);
11311
11312 case OP_ATR_MIN:
11313 case OP_ATR_MAX:
11314 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11315 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11316 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11317 if (noside == EVAL_SKIP)
11318 goto nosideret;
11319 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11320 return value_zero (value_type (arg1), not_lval);
11321 else
11322 {
11323 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11324 return value_binop (arg1, arg2,
11325 op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
11326 }
11327
11328 case OP_ATR_MODULUS:
11329 {
11330 struct type *type_arg = check_typedef (exp->elts[pc + 2].type);
11331
11332 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11333 if (noside == EVAL_SKIP)
11334 goto nosideret;
11335
11336 if (!ada_is_modular_type (type_arg))
11337 error (_("'modulus must be applied to modular type"));
11338
11339 return value_from_longest (TYPE_TARGET_TYPE (type_arg),
11340 ada_modulus (type_arg));
11341 }
11342
11343
11344 case OP_ATR_POS:
11345 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11346 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11347 if (noside == EVAL_SKIP)
11348 goto nosideret;
11349 type = builtin_type (exp->gdbarch)->builtin_int;
11350 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11351 return value_zero (type, not_lval);
11352 else
11353 return value_pos_atr (type, arg1);
11354
11355 case OP_ATR_SIZE:
11356 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11357 type = value_type (arg1);
11358
11359 /* If the argument is a reference, then dereference its type, since
11360 the user is really asking for the size of the actual object,
11361 not the size of the pointer. */
11362 if (TYPE_CODE (type) == TYPE_CODE_REF)
11363 type = TYPE_TARGET_TYPE (type);
11364
11365 if (noside == EVAL_SKIP)
11366 goto nosideret;
11367 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11368 return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
11369 else
11370 return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
11371 TARGET_CHAR_BIT * TYPE_LENGTH (type));
11372
11373 case OP_ATR_VAL:
11374 evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
11375 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11376 type = exp->elts[pc + 2].type;
11377 if (noside == EVAL_SKIP)
11378 goto nosideret;
11379 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11380 return value_zero (type, not_lval);
11381 else
11382 return value_val_atr (type, arg1);
11383
11384 case BINOP_EXP:
11385 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11386 arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11387 if (noside == EVAL_SKIP)
11388 goto nosideret;
11389 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11390 return value_zero (value_type (arg1), not_lval);
11391 else
11392 {
11393 /* For integer exponentiation operations,
11394 only promote the first argument. */
11395 if (is_integral_type (value_type (arg2)))
11396 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
11397 else
11398 binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
11399
11400 return value_binop (arg1, arg2, op);
11401 }
11402
11403 case UNOP_PLUS:
11404 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11405 if (noside == EVAL_SKIP)
11406 goto nosideret;
11407 else
11408 return arg1;
11409
11410 case UNOP_ABS:
11411 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11412 if (noside == EVAL_SKIP)
11413 goto nosideret;
11414 unop_promote (exp->language_defn, exp->gdbarch, &arg1);
11415 if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
11416 return value_neg (arg1);
11417 else
11418 return arg1;
11419
11420 case UNOP_IND:
11421 preeval_pos = *pos;
11422 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11423 if (noside == EVAL_SKIP)
11424 goto nosideret;
11425 type = ada_check_typedef (value_type (arg1));
11426 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11427 {
11428 if (ada_is_array_descriptor_type (type))
11429 /* GDB allows dereferencing GNAT array descriptors. */
11430 {
11431 struct type *arrType = ada_type_of_array (arg1, 0);
11432
11433 if (arrType == NULL)
11434 error (_("Attempt to dereference null array pointer."));
11435 return value_at_lazy (arrType, 0);
11436 }
11437 else if (TYPE_CODE (type) == TYPE_CODE_PTR
11438 || TYPE_CODE (type) == TYPE_CODE_REF
11439 /* In C you can dereference an array to get the 1st elt. */
11440 || TYPE_CODE (type) == TYPE_CODE_ARRAY)
11441 {
11442 /* As mentioned in the OP_VAR_VALUE case, tagged types can
11443 only be determined by inspecting the object's tag.
11444 This means that we need to evaluate completely the
11445 expression in order to get its type. */
11446
11447 if ((TYPE_CODE (type) == TYPE_CODE_REF
11448 || TYPE_CODE (type) == TYPE_CODE_PTR)
11449 && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0))
11450 {
11451 arg1 = evaluate_subexp (NULL_TYPE, exp, &preeval_pos,
11452 EVAL_NORMAL);
11453 type = value_type (ada_value_ind (arg1));
11454 }
11455 else
11456 {
11457 type = to_static_fixed_type
11458 (ada_aligned_type
11459 (ada_check_typedef (TYPE_TARGET_TYPE (type))));
11460 }
11461 ada_ensure_varsize_limit (type);
11462 return value_zero (type, lval_memory);
11463 }
11464 else if (TYPE_CODE (type) == TYPE_CODE_INT)
11465 {
11466 /* GDB allows dereferencing an int. */
11467 if (expect_type == NULL)
11468 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
11469 lval_memory);
11470 else
11471 {
11472 expect_type =
11473 to_static_fixed_type (ada_aligned_type (expect_type));
11474 return value_zero (expect_type, lval_memory);
11475 }
11476 }
11477 else
11478 error (_("Attempt to take contents of a non-pointer value."));
11479 }
11480 arg1 = ada_coerce_ref (arg1); /* FIXME: What is this for?? */
11481 type = ada_check_typedef (value_type (arg1));
11482
11483 if (TYPE_CODE (type) == TYPE_CODE_INT)
11484 /* GDB allows dereferencing an int. If we were given
11485 the expect_type, then use that as the target type.
11486 Otherwise, assume that the target type is an int. */
11487 {
11488 if (expect_type != NULL)
11489 return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
11490 arg1));
11491 else
11492 return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
11493 (CORE_ADDR) value_as_address (arg1));
11494 }
11495
11496 if (ada_is_array_descriptor_type (type))
11497 /* GDB allows dereferencing GNAT array descriptors. */
11498 return ada_coerce_to_simple_array (arg1);
11499 else
11500 return ada_value_ind (arg1);
11501
11502 case STRUCTOP_STRUCT:
11503 tem = longest_to_int (exp->elts[pc + 1].longconst);
11504 (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
11505 preeval_pos = *pos;
11506 arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
11507 if (noside == EVAL_SKIP)
11508 goto nosideret;
11509 if (noside == EVAL_AVOID_SIDE_EFFECTS)
11510 {
11511 struct type *type1 = value_type (arg1);
11512
11513 if (ada_is_tagged_type (type1, 1))
11514 {
11515 type = ada_lookup_struct_elt_type (type1,
11516 &exp->elts[pc + 2].string,
11517 1, 1);
11518
11519 /* If the field is not found, check if it exists in the
11520 extension of this object's type. This means that we
11521 need to evaluate completely the expression. */
11522
11523 if (type == NULL)
11524 {
11525 arg1 = evaluate_subexp (NULL_TYPE, exp, &preeval_pos,
11526 EVAL_NORMAL);
11527 arg1 = ada_value_struct_elt (arg1,
11528 &exp->elts[pc + 2].string,
11529 0);
11530 arg1 = unwrap_value (arg1);
11531 type = value_type (ada_to_fixed_value (arg1));
11532 }
11533 }
11534 else
11535 type =
11536 ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
11537 0);
11538
11539 return value_zero (ada_aligned_type (type), lval_memory);
11540 }
11541 else
11542 {
11543 arg1 = ada_value_struct_elt (arg1, &exp->elts[pc + 2].string, 0);
11544 arg1 = unwrap_value (arg1);
11545 return ada_to_fixed_value (arg1);
11546 }
11547
11548 case OP_TYPE:
11549 /* The value is not supposed to be used. This is here to make it
11550 easier to accommodate expressions that contain types. */
11551 (*pos) += 2;
11552 if (noside == EVAL_SKIP)
11553 goto nosideret;
11554 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
11555 return allocate_value (exp->elts[pc + 1].type);
11556 else
11557 error (_("Attempt to use a type name as an expression"));
11558
11559 case OP_AGGREGATE:
11560 case OP_CHOICES:
11561 case OP_OTHERS:
11562 case OP_DISCRETE_RANGE:
11563 case OP_POSITIONAL:
11564 case OP_NAME:
11565 if (noside == EVAL_NORMAL)
11566 switch (op)
11567 {
11568 case OP_NAME:
11569 error (_("Undefined name, ambiguous name, or renaming used in "
11570 "component association: %s."), &exp->elts[pc+2].string);
11571 case OP_AGGREGATE:
11572 error (_("Aggregates only allowed on the right of an assignment"));
11573 default:
11574 internal_error (__FILE__, __LINE__,
11575 _("aggregate apparently mangled"));
11576 }
11577
11578 ada_forward_operator_length (exp, pc, &oplen, &nargs);
11579 *pos += oplen - 1;
11580 for (tem = 0; tem < nargs; tem += 1)
11581 ada_evaluate_subexp (NULL, exp, pos, noside);
11582 goto nosideret;
11583 }
11584
11585 nosideret:
11586 return eval_skip_value (exp);
11587 }
11588 \f
11589
11590 /* Fixed point */
11591
11592 /* If TYPE encodes an Ada fixed-point type, return the suffix of the
11593 type name that encodes the 'small and 'delta information.
11594 Otherwise, return NULL. */
11595
11596 static const char *
11597 fixed_type_info (struct type *type)
11598 {
11599 const char *name = ada_type_name (type);
11600 enum type_code code = (type == NULL) ? TYPE_CODE_UNDEF : TYPE_CODE (type);
11601
11602 if ((code == TYPE_CODE_INT || code == TYPE_CODE_RANGE) && name != NULL)
11603 {
11604 const char *tail = strstr (name, "___XF_");
11605
11606 if (tail == NULL)
11607 return NULL;
11608 else
11609 return tail + 5;
11610 }
11611 else if (code == TYPE_CODE_RANGE && TYPE_TARGET_TYPE (type) != type)
11612 return fixed_type_info (TYPE_TARGET_TYPE (type));
11613 else
11614 return NULL;
11615 }
11616
11617 /* Returns non-zero iff TYPE represents an Ada fixed-point type. */
11618
11619 int
11620 ada_is_fixed_point_type (struct type *type)
11621 {
11622 return fixed_type_info (type) != NULL;
11623 }
11624
11625 /* Return non-zero iff TYPE represents a System.Address type. */
11626
11627 int
11628 ada_is_system_address_type (struct type *type)
11629 {
11630 return (TYPE_NAME (type)
11631 && strcmp (TYPE_NAME (type), "system__address") == 0);
11632 }
11633
11634 /* Assuming that TYPE is the representation of an Ada fixed-point
11635 type, return the target floating-point type to be used to represent
11636 of this type during internal computation. */
11637
11638 static struct type *
11639 ada_scaling_type (struct type *type)
11640 {
11641 return builtin_type (get_type_arch (type))->builtin_long_double;
11642 }
11643
11644 /* Assuming that TYPE is the representation of an Ada fixed-point
11645 type, return its delta, or NULL if the type is malformed and the
11646 delta cannot be determined. */
11647
11648 struct value *
11649 ada_delta (struct type *type)
11650 {
11651 const char *encoding = fixed_type_info (type);
11652 struct type *scale_type = ada_scaling_type (type);
11653
11654 long long num, den;
11655
11656 if (sscanf (encoding, "_%lld_%lld", &num, &den) < 2)
11657 return nullptr;
11658 else
11659 return value_binop (value_from_longest (scale_type, num),
11660 value_from_longest (scale_type, den), BINOP_DIV);
11661 }
11662
11663 /* Assuming that ada_is_fixed_point_type (TYPE), return the scaling
11664 factor ('SMALL value) associated with the type. */
11665
11666 struct value *
11667 ada_scaling_factor (struct type *type)
11668 {
11669 const char *encoding = fixed_type_info (type);
11670 struct type *scale_type = ada_scaling_type (type);
11671
11672 long long num0, den0, num1, den1;
11673 int n;
11674
11675 n = sscanf (encoding, "_%lld_%lld_%lld_%lld",
11676 &num0, &den0, &num1, &den1);
11677
11678 if (n < 2)
11679 return value_from_longest (scale_type, 1);
11680 else if (n == 4)
11681 return value_binop (value_from_longest (scale_type, num1),
11682 value_from_longest (scale_type, den1), BINOP_DIV);
11683 else
11684 return value_binop (value_from_longest (scale_type, num0),
11685 value_from_longest (scale_type, den0), BINOP_DIV);
11686 }
11687
11688 \f
11689
11690 /* Range types */
11691
11692 /* Scan STR beginning at position K for a discriminant name, and
11693 return the value of that discriminant field of DVAL in *PX. If
11694 PNEW_K is not null, put the position of the character beyond the
11695 name scanned in *PNEW_K. Return 1 if successful; return 0 and do
11696 not alter *PX and *PNEW_K if unsuccessful. */
11697
11698 static int
11699 scan_discrim_bound (const char *str, int k, struct value *dval, LONGEST * px,
11700 int *pnew_k)
11701 {
11702 static char *bound_buffer = NULL;
11703 static size_t bound_buffer_len = 0;
11704 const char *pstart, *pend, *bound;
11705 struct value *bound_val;
11706
11707 if (dval == NULL || str == NULL || str[k] == '\0')
11708 return 0;
11709
11710 pstart = str + k;
11711 pend = strstr (pstart, "__");
11712 if (pend == NULL)
11713 {
11714 bound = pstart;
11715 k += strlen (bound);
11716 }
11717 else
11718 {
11719 int len = pend - pstart;
11720
11721 /* Strip __ and beyond. */
11722 GROW_VECT (bound_buffer, bound_buffer_len, len + 1);
11723 strncpy (bound_buffer, pstart, len);
11724 bound_buffer[len] = '\0';
11725
11726 bound = bound_buffer;
11727 k = pend - str;
11728 }
11729
11730 bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
11731 if (bound_val == NULL)
11732 return 0;
11733
11734 *px = value_as_long (bound_val);
11735 if (pnew_k != NULL)
11736 *pnew_k = k;
11737 return 1;
11738 }
11739
11740 /* Value of variable named NAME in the current environment. If
11741 no such variable found, then if ERR_MSG is null, returns 0, and
11742 otherwise causes an error with message ERR_MSG. */
11743
11744 static struct value *
11745 get_var_value (const char *name, const char *err_msg)
11746 {
11747 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
11748
11749 std::vector<struct block_symbol> syms;
11750 int nsyms = ada_lookup_symbol_list_worker (lookup_name,
11751 get_selected_block (0),
11752 VAR_DOMAIN, &syms, 1);
11753
11754 if (nsyms != 1)
11755 {
11756 if (err_msg == NULL)
11757 return 0;
11758 else
11759 error (("%s"), err_msg);
11760 }
11761
11762 return value_of_variable (syms[0].symbol, syms[0].block);
11763 }
11764
11765 /* Value of integer variable named NAME in the current environment.
11766 If no such variable is found, returns false. Otherwise, sets VALUE
11767 to the variable's value and returns true. */
11768
11769 bool
11770 get_int_var_value (const char *name, LONGEST &value)
11771 {
11772 struct value *var_val = get_var_value (name, 0);
11773
11774 if (var_val == 0)
11775 return false;
11776
11777 value = value_as_long (var_val);
11778 return true;
11779 }
11780
11781
11782 /* Return a range type whose base type is that of the range type named
11783 NAME in the current environment, and whose bounds are calculated
11784 from NAME according to the GNAT range encoding conventions.
11785 Extract discriminant values, if needed, from DVAL. ORIG_TYPE is the
11786 corresponding range type from debug information; fall back to using it
11787 if symbol lookup fails. If a new type must be created, allocate it
11788 like ORIG_TYPE was. The bounds information, in general, is encoded
11789 in NAME, the base type given in the named range type. */
11790
11791 static struct type *
11792 to_fixed_range_type (struct type *raw_type, struct value *dval)
11793 {
11794 const char *name;
11795 struct type *base_type;
11796 const char *subtype_info;
11797
11798 gdb_assert (raw_type != NULL);
11799 gdb_assert (TYPE_NAME (raw_type) != NULL);
11800
11801 if (TYPE_CODE (raw_type) == TYPE_CODE_RANGE)
11802 base_type = TYPE_TARGET_TYPE (raw_type);
11803 else
11804 base_type = raw_type;
11805
11806 name = TYPE_NAME (raw_type);
11807 subtype_info = strstr (name, "___XD");
11808 if (subtype_info == NULL)
11809 {
11810 LONGEST L = ada_discrete_type_low_bound (raw_type);
11811 LONGEST U = ada_discrete_type_high_bound (raw_type);
11812
11813 if (L < INT_MIN || U > INT_MAX)
11814 return raw_type;
11815 else
11816 return create_static_range_type (alloc_type_copy (raw_type), raw_type,
11817 L, U);
11818 }
11819 else
11820 {
11821 static char *name_buf = NULL;
11822 static size_t name_len = 0;
11823 int prefix_len = subtype_info - name;
11824 LONGEST L, U;
11825 struct type *type;
11826 const char *bounds_str;
11827 int n;
11828
11829 GROW_VECT (name_buf, name_len, prefix_len + 5);
11830 strncpy (name_buf, name, prefix_len);
11831 name_buf[prefix_len] = '\0';
11832
11833 subtype_info += 5;
11834 bounds_str = strchr (subtype_info, '_');
11835 n = 1;
11836
11837 if (*subtype_info == 'L')
11838 {
11839 if (!ada_scan_number (bounds_str, n, &L, &n)
11840 && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
11841 return raw_type;
11842 if (bounds_str[n] == '_')
11843 n += 2;
11844 else if (bounds_str[n] == '.') /* FIXME? SGI Workshop kludge. */
11845 n += 1;
11846 subtype_info += 1;
11847 }
11848 else
11849 {
11850 strcpy (name_buf + prefix_len, "___L");
11851 if (!get_int_var_value (name_buf, L))
11852 {
11853 lim_warning (_("Unknown lower bound, using 1."));
11854 L = 1;
11855 }
11856 }
11857
11858 if (*subtype_info == 'U')
11859 {
11860 if (!ada_scan_number (bounds_str, n, &U, &n)
11861 && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
11862 return raw_type;
11863 }
11864 else
11865 {
11866 strcpy (name_buf + prefix_len, "___U");
11867 if (!get_int_var_value (name_buf, U))
11868 {
11869 lim_warning (_("Unknown upper bound, using %ld."), (long) L);
11870 U = L;
11871 }
11872 }
11873
11874 type = create_static_range_type (alloc_type_copy (raw_type),
11875 base_type, L, U);
11876 /* create_static_range_type alters the resulting type's length
11877 to match the size of the base_type, which is not what we want.
11878 Set it back to the original range type's length. */
11879 TYPE_LENGTH (type) = TYPE_LENGTH (raw_type);
11880 TYPE_NAME (type) = name;
11881 return type;
11882 }
11883 }
11884
11885 /* True iff NAME is the name of a range type. */
11886
11887 int
11888 ada_is_range_type_name (const char *name)
11889 {
11890 return (name != NULL && strstr (name, "___XD"));
11891 }
11892 \f
11893
11894 /* Modular types */
11895
11896 /* True iff TYPE is an Ada modular type. */
11897
11898 int
11899 ada_is_modular_type (struct type *type)
11900 {
11901 struct type *subranged_type = get_base_type (type);
11902
11903 return (subranged_type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE
11904 && TYPE_CODE (subranged_type) == TYPE_CODE_INT
11905 && TYPE_UNSIGNED (subranged_type));
11906 }
11907
11908 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE. */
11909
11910 ULONGEST
11911 ada_modulus (struct type *type)
11912 {
11913 return (ULONGEST) TYPE_HIGH_BOUND (type) + 1;
11914 }
11915 \f
11916
11917 /* Ada exception catchpoint support:
11918 ---------------------------------
11919
11920 We support 3 kinds of exception catchpoints:
11921 . catchpoints on Ada exceptions
11922 . catchpoints on unhandled Ada exceptions
11923 . catchpoints on failed assertions
11924
11925 Exceptions raised during failed assertions, or unhandled exceptions
11926 could perfectly be caught with the general catchpoint on Ada exceptions.
11927 However, we can easily differentiate these two special cases, and having
11928 the option to distinguish these two cases from the rest can be useful
11929 to zero-in on certain situations.
11930
11931 Exception catchpoints are a specialized form of breakpoint,
11932 since they rely on inserting breakpoints inside known routines
11933 of the GNAT runtime. The implementation therefore uses a standard
11934 breakpoint structure of the BP_BREAKPOINT type, but with its own set
11935 of breakpoint_ops.
11936
11937 Support in the runtime for exception catchpoints have been changed
11938 a few times already, and these changes affect the implementation
11939 of these catchpoints. In order to be able to support several
11940 variants of the runtime, we use a sniffer that will determine
11941 the runtime variant used by the program being debugged. */
11942
11943 /* Ada's standard exceptions.
11944
11945 The Ada 83 standard also defined Numeric_Error. But there so many
11946 situations where it was unclear from the Ada 83 Reference Manual
11947 (RM) whether Constraint_Error or Numeric_Error should be raised,
11948 that the ARG (Ada Rapporteur Group) eventually issued a Binding
11949 Interpretation saying that anytime the RM says that Numeric_Error
11950 should be raised, the implementation may raise Constraint_Error.
11951 Ada 95 went one step further and pretty much removed Numeric_Error
11952 from the list of standard exceptions (it made it a renaming of
11953 Constraint_Error, to help preserve compatibility when compiling
11954 an Ada83 compiler). As such, we do not include Numeric_Error from
11955 this list of standard exceptions. */
11956
11957 static const char *standard_exc[] = {
11958 "constraint_error",
11959 "program_error",
11960 "storage_error",
11961 "tasking_error"
11962 };
11963
11964 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
11965
11966 /* A structure that describes how to support exception catchpoints
11967 for a given executable. */
11968
11969 struct exception_support_info
11970 {
11971 /* The name of the symbol to break on in order to insert
11972 a catchpoint on exceptions. */
11973 const char *catch_exception_sym;
11974
11975 /* The name of the symbol to break on in order to insert
11976 a catchpoint on unhandled exceptions. */
11977 const char *catch_exception_unhandled_sym;
11978
11979 /* The name of the symbol to break on in order to insert
11980 a catchpoint on failed assertions. */
11981 const char *catch_assert_sym;
11982
11983 /* The name of the symbol to break on in order to insert
11984 a catchpoint on exception handling. */
11985 const char *catch_handlers_sym;
11986
11987 /* Assuming that the inferior just triggered an unhandled exception
11988 catchpoint, this function is responsible for returning the address
11989 in inferior memory where the name of that exception is stored.
11990 Return zero if the address could not be computed. */
11991 ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11992 };
11993
11994 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11995 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11996
11997 /* The following exception support info structure describes how to
11998 implement exception catchpoints with the latest version of the
11999 Ada runtime (as of 2007-03-06). */
12000
12001 static const struct exception_support_info default_exception_support_info =
12002 {
12003 "__gnat_debug_raise_exception", /* catch_exception_sym */
12004 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
12005 "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
12006 "__gnat_begin_handler", /* catch_handlers_sym */
12007 ada_unhandled_exception_name_addr
12008 };
12009
12010 /* The following exception support info structure describes how to
12011 implement exception catchpoints with a slightly older version
12012 of the Ada runtime. */
12013
12014 static const struct exception_support_info exception_support_info_fallback =
12015 {
12016 "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
12017 "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
12018 "system__assertions__raise_assert_failure", /* catch_assert_sym */
12019 "__gnat_begin_handler", /* catch_handlers_sym */
12020 ada_unhandled_exception_name_addr_from_raise
12021 };
12022
12023 /* Return nonzero if we can detect the exception support routines
12024 described in EINFO.
12025
12026 This function errors out if an abnormal situation is detected
12027 (for instance, if we find the exception support routines, but
12028 that support is found to be incomplete). */
12029
12030 static int
12031 ada_has_this_exception_support (const struct exception_support_info *einfo)
12032 {
12033 struct symbol *sym;
12034
12035 /* The symbol we're looking up is provided by a unit in the GNAT runtime
12036 that should be compiled with debugging information. As a result, we
12037 expect to find that symbol in the symtabs. */
12038
12039 sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
12040 if (sym == NULL)
12041 {
12042 /* Perhaps we did not find our symbol because the Ada runtime was
12043 compiled without debugging info, or simply stripped of it.
12044 It happens on some GNU/Linux distributions for instance, where
12045 users have to install a separate debug package in order to get
12046 the runtime's debugging info. In that situation, let the user
12047 know why we cannot insert an Ada exception catchpoint.
12048
12049 Note: Just for the purpose of inserting our Ada exception
12050 catchpoint, we could rely purely on the associated minimal symbol.
12051 But we would be operating in degraded mode anyway, since we are
12052 still lacking the debugging info needed later on to extract
12053 the name of the exception being raised (this name is printed in
12054 the catchpoint message, and is also used when trying to catch
12055 a specific exception). We do not handle this case for now. */
12056 struct bound_minimal_symbol msym
12057 = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
12058
12059 if (msym.minsym && MSYMBOL_TYPE (msym.minsym) != mst_solib_trampoline)
12060 error (_("Your Ada runtime appears to be missing some debugging "
12061 "information.\nCannot insert Ada exception catchpoint "
12062 "in this configuration."));
12063
12064 return 0;
12065 }
12066
12067 /* Make sure that the symbol we found corresponds to a function. */
12068
12069 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
12070 error (_("Symbol \"%s\" is not a function (class = %d)"),
12071 SYMBOL_LINKAGE_NAME (sym), SYMBOL_CLASS (sym));
12072
12073 return 1;
12074 }
12075
12076 /* Inspect the Ada runtime and determine which exception info structure
12077 should be used to provide support for exception catchpoints.
12078
12079 This function will always set the per-inferior exception_info,
12080 or raise an error. */
12081
12082 static void
12083 ada_exception_support_info_sniffer (void)
12084 {
12085 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12086
12087 /* If the exception info is already known, then no need to recompute it. */
12088 if (data->exception_info != NULL)
12089 return;
12090
12091 /* Check the latest (default) exception support info. */
12092 if (ada_has_this_exception_support (&default_exception_support_info))
12093 {
12094 data->exception_info = &default_exception_support_info;
12095 return;
12096 }
12097
12098 /* Try our fallback exception suport info. */
12099 if (ada_has_this_exception_support (&exception_support_info_fallback))
12100 {
12101 data->exception_info = &exception_support_info_fallback;
12102 return;
12103 }
12104
12105 /* Sometimes, it is normal for us to not be able to find the routine
12106 we are looking for. This happens when the program is linked with
12107 the shared version of the GNAT runtime, and the program has not been
12108 started yet. Inform the user of these two possible causes if
12109 applicable. */
12110
12111 if (ada_update_initial_language (language_unknown) != language_ada)
12112 error (_("Unable to insert catchpoint. Is this an Ada main program?"));
12113
12114 /* If the symbol does not exist, then check that the program is
12115 already started, to make sure that shared libraries have been
12116 loaded. If it is not started, this may mean that the symbol is
12117 in a shared library. */
12118
12119 if (inferior_ptid.pid () == 0)
12120 error (_("Unable to insert catchpoint. Try to start the program first."));
12121
12122 /* At this point, we know that we are debugging an Ada program and
12123 that the inferior has been started, but we still are not able to
12124 find the run-time symbols. That can mean that we are in
12125 configurable run time mode, or that a-except as been optimized
12126 out by the linker... In any case, at this point it is not worth
12127 supporting this feature. */
12128
12129 error (_("Cannot insert Ada exception catchpoints in this configuration."));
12130 }
12131
12132 /* True iff FRAME is very likely to be that of a function that is
12133 part of the runtime system. This is all very heuristic, but is
12134 intended to be used as advice as to what frames are uninteresting
12135 to most users. */
12136
12137 static int
12138 is_known_support_routine (struct frame_info *frame)
12139 {
12140 enum language func_lang;
12141 int i;
12142 const char *fullname;
12143
12144 /* If this code does not have any debugging information (no symtab),
12145 This cannot be any user code. */
12146
12147 symtab_and_line sal = find_frame_sal (frame);
12148 if (sal.symtab == NULL)
12149 return 1;
12150
12151 /* If there is a symtab, but the associated source file cannot be
12152 located, then assume this is not user code: Selecting a frame
12153 for which we cannot display the code would not be very helpful
12154 for the user. This should also take care of case such as VxWorks
12155 where the kernel has some debugging info provided for a few units. */
12156
12157 fullname = symtab_to_fullname (sal.symtab);
12158 if (access (fullname, R_OK) != 0)
12159 return 1;
12160
12161 /* Check the unit filename againt the Ada runtime file naming.
12162 We also check the name of the objfile against the name of some
12163 known system libraries that sometimes come with debugging info
12164 too. */
12165
12166 for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
12167 {
12168 re_comp (known_runtime_file_name_patterns[i]);
12169 if (re_exec (lbasename (sal.symtab->filename)))
12170 return 1;
12171 if (SYMTAB_OBJFILE (sal.symtab) != NULL
12172 && re_exec (objfile_name (SYMTAB_OBJFILE (sal.symtab))))
12173 return 1;
12174 }
12175
12176 /* Check whether the function is a GNAT-generated entity. */
12177
12178 gdb::unique_xmalloc_ptr<char> func_name
12179 = find_frame_funname (frame, &func_lang, NULL);
12180 if (func_name == NULL)
12181 return 1;
12182
12183 for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
12184 {
12185 re_comp (known_auxiliary_function_name_patterns[i]);
12186 if (re_exec (func_name.get ()))
12187 return 1;
12188 }
12189
12190 return 0;
12191 }
12192
12193 /* Find the first frame that contains debugging information and that is not
12194 part of the Ada run-time, starting from FI and moving upward. */
12195
12196 void
12197 ada_find_printable_frame (struct frame_info *fi)
12198 {
12199 for (; fi != NULL; fi = get_prev_frame (fi))
12200 {
12201 if (!is_known_support_routine (fi))
12202 {
12203 select_frame (fi);
12204 break;
12205 }
12206 }
12207
12208 }
12209
12210 /* Assuming that the inferior just triggered an unhandled exception
12211 catchpoint, return the address in inferior memory where the name
12212 of the exception is stored.
12213
12214 Return zero if the address could not be computed. */
12215
12216 static CORE_ADDR
12217 ada_unhandled_exception_name_addr (void)
12218 {
12219 return parse_and_eval_address ("e.full_name");
12220 }
12221
12222 /* Same as ada_unhandled_exception_name_addr, except that this function
12223 should be used when the inferior uses an older version of the runtime,
12224 where the exception name needs to be extracted from a specific frame
12225 several frames up in the callstack. */
12226
12227 static CORE_ADDR
12228 ada_unhandled_exception_name_addr_from_raise (void)
12229 {
12230 int frame_level;
12231 struct frame_info *fi;
12232 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12233
12234 /* To determine the name of this exception, we need to select
12235 the frame corresponding to RAISE_SYM_NAME. This frame is
12236 at least 3 levels up, so we simply skip the first 3 frames
12237 without checking the name of their associated function. */
12238 fi = get_current_frame ();
12239 for (frame_level = 0; frame_level < 3; frame_level += 1)
12240 if (fi != NULL)
12241 fi = get_prev_frame (fi);
12242
12243 while (fi != NULL)
12244 {
12245 enum language func_lang;
12246
12247 gdb::unique_xmalloc_ptr<char> func_name
12248 = find_frame_funname (fi, &func_lang, NULL);
12249 if (func_name != NULL)
12250 {
12251 if (strcmp (func_name.get (),
12252 data->exception_info->catch_exception_sym) == 0)
12253 break; /* We found the frame we were looking for... */
12254 }
12255 fi = get_prev_frame (fi);
12256 }
12257
12258 if (fi == NULL)
12259 return 0;
12260
12261 select_frame (fi);
12262 return parse_and_eval_address ("id.full_name");
12263 }
12264
12265 /* Assuming the inferior just triggered an Ada exception catchpoint
12266 (of any type), return the address in inferior memory where the name
12267 of the exception is stored, if applicable.
12268
12269 Assumes the selected frame is the current frame.
12270
12271 Return zero if the address could not be computed, or if not relevant. */
12272
12273 static CORE_ADDR
12274 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
12275 struct breakpoint *b)
12276 {
12277 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12278
12279 switch (ex)
12280 {
12281 case ada_catch_exception:
12282 return (parse_and_eval_address ("e.full_name"));
12283 break;
12284
12285 case ada_catch_exception_unhandled:
12286 return data->exception_info->unhandled_exception_name_addr ();
12287 break;
12288
12289 case ada_catch_handlers:
12290 return 0; /* The runtimes does not provide access to the exception
12291 name. */
12292 break;
12293
12294 case ada_catch_assert:
12295 return 0; /* Exception name is not relevant in this case. */
12296 break;
12297
12298 default:
12299 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12300 break;
12301 }
12302
12303 return 0; /* Should never be reached. */
12304 }
12305
12306 /* Assuming the inferior is stopped at an exception catchpoint,
12307 return the message which was associated to the exception, if
12308 available. Return NULL if the message could not be retrieved.
12309
12310 Note: The exception message can be associated to an exception
12311 either through the use of the Raise_Exception function, or
12312 more simply (Ada 2005 and later), via:
12313
12314 raise Exception_Name with "exception message";
12315
12316 */
12317
12318 static gdb::unique_xmalloc_ptr<char>
12319 ada_exception_message_1 (void)
12320 {
12321 struct value *e_msg_val;
12322 int e_msg_len;
12323
12324 /* For runtimes that support this feature, the exception message
12325 is passed as an unbounded string argument called "message". */
12326 e_msg_val = parse_and_eval ("message");
12327 if (e_msg_val == NULL)
12328 return NULL; /* Exception message not supported. */
12329
12330 e_msg_val = ada_coerce_to_simple_array (e_msg_val);
12331 gdb_assert (e_msg_val != NULL);
12332 e_msg_len = TYPE_LENGTH (value_type (e_msg_val));
12333
12334 /* If the message string is empty, then treat it as if there was
12335 no exception message. */
12336 if (e_msg_len <= 0)
12337 return NULL;
12338
12339 gdb::unique_xmalloc_ptr<char> e_msg ((char *) xmalloc (e_msg_len + 1));
12340 read_memory_string (value_address (e_msg_val), e_msg.get (), e_msg_len + 1);
12341 e_msg.get ()[e_msg_len] = '\0';
12342
12343 return e_msg;
12344 }
12345
12346 /* Same as ada_exception_message_1, except that all exceptions are
12347 contained here (returning NULL instead). */
12348
12349 static gdb::unique_xmalloc_ptr<char>
12350 ada_exception_message (void)
12351 {
12352 gdb::unique_xmalloc_ptr<char> e_msg;
12353
12354 TRY
12355 {
12356 e_msg = ada_exception_message_1 ();
12357 }
12358 CATCH (e, RETURN_MASK_ERROR)
12359 {
12360 e_msg.reset (nullptr);
12361 }
12362 END_CATCH
12363
12364 return e_msg;
12365 }
12366
12367 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
12368 any error that ada_exception_name_addr_1 might cause to be thrown.
12369 When an error is intercepted, a warning with the error message is printed,
12370 and zero is returned. */
12371
12372 static CORE_ADDR
12373 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
12374 struct breakpoint *b)
12375 {
12376 CORE_ADDR result = 0;
12377
12378 TRY
12379 {
12380 result = ada_exception_name_addr_1 (ex, b);
12381 }
12382
12383 CATCH (e, RETURN_MASK_ERROR)
12384 {
12385 warning (_("failed to get exception name: %s"), e.message);
12386 return 0;
12387 }
12388 END_CATCH
12389
12390 return result;
12391 }
12392
12393 static std::string ada_exception_catchpoint_cond_string
12394 (const char *excep_string,
12395 enum ada_exception_catchpoint_kind ex);
12396
12397 /* Ada catchpoints.
12398
12399 In the case of catchpoints on Ada exceptions, the catchpoint will
12400 stop the target on every exception the program throws. When a user
12401 specifies the name of a specific exception, we translate this
12402 request into a condition expression (in text form), and then parse
12403 it into an expression stored in each of the catchpoint's locations.
12404 We then use this condition to check whether the exception that was
12405 raised is the one the user is interested in. If not, then the
12406 target is resumed again. We store the name of the requested
12407 exception, in order to be able to re-set the condition expression
12408 when symbols change. */
12409
12410 /* An instance of this type is used to represent an Ada catchpoint
12411 breakpoint location. */
12412
12413 class ada_catchpoint_location : public bp_location
12414 {
12415 public:
12416 ada_catchpoint_location (breakpoint *owner)
12417 : bp_location (owner)
12418 {}
12419
12420 /* The condition that checks whether the exception that was raised
12421 is the specific exception the user specified on catchpoint
12422 creation. */
12423 expression_up excep_cond_expr;
12424 };
12425
12426 /* An instance of this type is used to represent an Ada catchpoint. */
12427
12428 struct ada_catchpoint : public breakpoint
12429 {
12430 /* The name of the specific exception the user specified. */
12431 std::string excep_string;
12432 };
12433
12434 /* Parse the exception condition string in the context of each of the
12435 catchpoint's locations, and store them for later evaluation. */
12436
12437 static void
12438 create_excep_cond_exprs (struct ada_catchpoint *c,
12439 enum ada_exception_catchpoint_kind ex)
12440 {
12441 struct bp_location *bl;
12442
12443 /* Nothing to do if there's no specific exception to catch. */
12444 if (c->excep_string.empty ())
12445 return;
12446
12447 /* Same if there are no locations... */
12448 if (c->loc == NULL)
12449 return;
12450
12451 /* Compute the condition expression in text form, from the specific
12452 expection we want to catch. */
12453 std::string cond_string
12454 = ada_exception_catchpoint_cond_string (c->excep_string.c_str (), ex);
12455
12456 /* Iterate over all the catchpoint's locations, and parse an
12457 expression for each. */
12458 for (bl = c->loc; bl != NULL; bl = bl->next)
12459 {
12460 struct ada_catchpoint_location *ada_loc
12461 = (struct ada_catchpoint_location *) bl;
12462 expression_up exp;
12463
12464 if (!bl->shlib_disabled)
12465 {
12466 const char *s;
12467
12468 s = cond_string.c_str ();
12469 TRY
12470 {
12471 exp = parse_exp_1 (&s, bl->address,
12472 block_for_pc (bl->address),
12473 0);
12474 }
12475 CATCH (e, RETURN_MASK_ERROR)
12476 {
12477 warning (_("failed to reevaluate internal exception condition "
12478 "for catchpoint %d: %s"),
12479 c->number, e.message);
12480 }
12481 END_CATCH
12482 }
12483
12484 ada_loc->excep_cond_expr = std::move (exp);
12485 }
12486 }
12487
12488 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
12489 structure for all exception catchpoint kinds. */
12490
12491 static struct bp_location *
12492 allocate_location_exception (enum ada_exception_catchpoint_kind ex,
12493 struct breakpoint *self)
12494 {
12495 return new ada_catchpoint_location (self);
12496 }
12497
12498 /* Implement the RE_SET method in the breakpoint_ops structure for all
12499 exception catchpoint kinds. */
12500
12501 static void
12502 re_set_exception (enum ada_exception_catchpoint_kind ex, struct breakpoint *b)
12503 {
12504 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12505
12506 /* Call the base class's method. This updates the catchpoint's
12507 locations. */
12508 bkpt_breakpoint_ops.re_set (b);
12509
12510 /* Reparse the exception conditional expressions. One for each
12511 location. */
12512 create_excep_cond_exprs (c, ex);
12513 }
12514
12515 /* Returns true if we should stop for this breakpoint hit. If the
12516 user specified a specific exception, we only want to cause a stop
12517 if the program thrown that exception. */
12518
12519 static int
12520 should_stop_exception (const struct bp_location *bl)
12521 {
12522 struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
12523 const struct ada_catchpoint_location *ada_loc
12524 = (const struct ada_catchpoint_location *) bl;
12525 int stop;
12526
12527 /* With no specific exception, should always stop. */
12528 if (c->excep_string.empty ())
12529 return 1;
12530
12531 if (ada_loc->excep_cond_expr == NULL)
12532 {
12533 /* We will have a NULL expression if back when we were creating
12534 the expressions, this location's had failed to parse. */
12535 return 1;
12536 }
12537
12538 stop = 1;
12539 TRY
12540 {
12541 struct value *mark;
12542
12543 mark = value_mark ();
12544 stop = value_true (evaluate_expression (ada_loc->excep_cond_expr.get ()));
12545 value_free_to_mark (mark);
12546 }
12547 CATCH (ex, RETURN_MASK_ALL)
12548 {
12549 exception_fprintf (gdb_stderr, ex,
12550 _("Error in testing exception condition:\n"));
12551 }
12552 END_CATCH
12553
12554 return stop;
12555 }
12556
12557 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
12558 for all exception catchpoint kinds. */
12559
12560 static void
12561 check_status_exception (enum ada_exception_catchpoint_kind ex, bpstat bs)
12562 {
12563 bs->stop = should_stop_exception (bs->bp_location_at);
12564 }
12565
12566 /* Implement the PRINT_IT method in the breakpoint_ops structure
12567 for all exception catchpoint kinds. */
12568
12569 static enum print_stop_action
12570 print_it_exception (enum ada_exception_catchpoint_kind ex, bpstat bs)
12571 {
12572 struct ui_out *uiout = current_uiout;
12573 struct breakpoint *b = bs->breakpoint_at;
12574
12575 annotate_catchpoint (b->number);
12576
12577 if (uiout->is_mi_like_p ())
12578 {
12579 uiout->field_string ("reason",
12580 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12581 uiout->field_string ("disp", bpdisp_text (b->disposition));
12582 }
12583
12584 uiout->text (b->disposition == disp_del
12585 ? "\nTemporary catchpoint " : "\nCatchpoint ");
12586 uiout->field_int ("bkptno", b->number);
12587 uiout->text (", ");
12588
12589 /* ada_exception_name_addr relies on the selected frame being the
12590 current frame. Need to do this here because this function may be
12591 called more than once when printing a stop, and below, we'll
12592 select the first frame past the Ada run-time (see
12593 ada_find_printable_frame). */
12594 select_frame (get_current_frame ());
12595
12596 switch (ex)
12597 {
12598 case ada_catch_exception:
12599 case ada_catch_exception_unhandled:
12600 case ada_catch_handlers:
12601 {
12602 const CORE_ADDR addr = ada_exception_name_addr (ex, b);
12603 char exception_name[256];
12604
12605 if (addr != 0)
12606 {
12607 read_memory (addr, (gdb_byte *) exception_name,
12608 sizeof (exception_name) - 1);
12609 exception_name [sizeof (exception_name) - 1] = '\0';
12610 }
12611 else
12612 {
12613 /* For some reason, we were unable to read the exception
12614 name. This could happen if the Runtime was compiled
12615 without debugging info, for instance. In that case,
12616 just replace the exception name by the generic string
12617 "exception" - it will read as "an exception" in the
12618 notification we are about to print. */
12619 memcpy (exception_name, "exception", sizeof ("exception"));
12620 }
12621 /* In the case of unhandled exception breakpoints, we print
12622 the exception name as "unhandled EXCEPTION_NAME", to make
12623 it clearer to the user which kind of catchpoint just got
12624 hit. We used ui_out_text to make sure that this extra
12625 info does not pollute the exception name in the MI case. */
12626 if (ex == ada_catch_exception_unhandled)
12627 uiout->text ("unhandled ");
12628 uiout->field_string ("exception-name", exception_name);
12629 }
12630 break;
12631 case ada_catch_assert:
12632 /* In this case, the name of the exception is not really
12633 important. Just print "failed assertion" to make it clearer
12634 that his program just hit an assertion-failure catchpoint.
12635 We used ui_out_text because this info does not belong in
12636 the MI output. */
12637 uiout->text ("failed assertion");
12638 break;
12639 }
12640
12641 gdb::unique_xmalloc_ptr<char> exception_message = ada_exception_message ();
12642 if (exception_message != NULL)
12643 {
12644 uiout->text (" (");
12645 uiout->field_string ("exception-message", exception_message.get ());
12646 uiout->text (")");
12647 }
12648
12649 uiout->text (" at ");
12650 ada_find_printable_frame (get_current_frame ());
12651
12652 return PRINT_SRC_AND_LOC;
12653 }
12654
12655 /* Implement the PRINT_ONE method in the breakpoint_ops structure
12656 for all exception catchpoint kinds. */
12657
12658 static void
12659 print_one_exception (enum ada_exception_catchpoint_kind ex,
12660 struct breakpoint *b, struct bp_location **last_loc)
12661 {
12662 struct ui_out *uiout = current_uiout;
12663 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12664 struct value_print_options opts;
12665
12666 get_user_print_options (&opts);
12667 if (opts.addressprint)
12668 {
12669 annotate_field (4);
12670 uiout->field_core_addr ("addr", b->loc->gdbarch, b->loc->address);
12671 }
12672
12673 annotate_field (5);
12674 *last_loc = b->loc;
12675 switch (ex)
12676 {
12677 case ada_catch_exception:
12678 if (!c->excep_string.empty ())
12679 {
12680 std::string msg = string_printf (_("`%s' Ada exception"),
12681 c->excep_string.c_str ());
12682
12683 uiout->field_string ("what", msg);
12684 }
12685 else
12686 uiout->field_string ("what", "all Ada exceptions");
12687
12688 break;
12689
12690 case ada_catch_exception_unhandled:
12691 uiout->field_string ("what", "unhandled Ada exceptions");
12692 break;
12693
12694 case ada_catch_handlers:
12695 if (!c->excep_string.empty ())
12696 {
12697 uiout->field_fmt ("what",
12698 _("`%s' Ada exception handlers"),
12699 c->excep_string.c_str ());
12700 }
12701 else
12702 uiout->field_string ("what", "all Ada exceptions handlers");
12703 break;
12704
12705 case ada_catch_assert:
12706 uiout->field_string ("what", "failed Ada assertions");
12707 break;
12708
12709 default:
12710 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12711 break;
12712 }
12713 }
12714
12715 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
12716 for all exception catchpoint kinds. */
12717
12718 static void
12719 print_mention_exception (enum ada_exception_catchpoint_kind ex,
12720 struct breakpoint *b)
12721 {
12722 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12723 struct ui_out *uiout = current_uiout;
12724
12725 uiout->text (b->disposition == disp_del ? _("Temporary catchpoint ")
12726 : _("Catchpoint "));
12727 uiout->field_int ("bkptno", b->number);
12728 uiout->text (": ");
12729
12730 switch (ex)
12731 {
12732 case ada_catch_exception:
12733 if (!c->excep_string.empty ())
12734 {
12735 std::string info = string_printf (_("`%s' Ada exception"),
12736 c->excep_string.c_str ());
12737 uiout->text (info.c_str ());
12738 }
12739 else
12740 uiout->text (_("all Ada exceptions"));
12741 break;
12742
12743 case ada_catch_exception_unhandled:
12744 uiout->text (_("unhandled Ada exceptions"));
12745 break;
12746
12747 case ada_catch_handlers:
12748 if (!c->excep_string.empty ())
12749 {
12750 std::string info
12751 = string_printf (_("`%s' Ada exception handlers"),
12752 c->excep_string.c_str ());
12753 uiout->text (info.c_str ());
12754 }
12755 else
12756 uiout->text (_("all Ada exceptions handlers"));
12757 break;
12758
12759 case ada_catch_assert:
12760 uiout->text (_("failed Ada assertions"));
12761 break;
12762
12763 default:
12764 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12765 break;
12766 }
12767 }
12768
12769 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
12770 for all exception catchpoint kinds. */
12771
12772 static void
12773 print_recreate_exception (enum ada_exception_catchpoint_kind ex,
12774 struct breakpoint *b, struct ui_file *fp)
12775 {
12776 struct ada_catchpoint *c = (struct ada_catchpoint *) b;
12777
12778 switch (ex)
12779 {
12780 case ada_catch_exception:
12781 fprintf_filtered (fp, "catch exception");
12782 if (!c->excep_string.empty ())
12783 fprintf_filtered (fp, " %s", c->excep_string.c_str ());
12784 break;
12785
12786 case ada_catch_exception_unhandled:
12787 fprintf_filtered (fp, "catch exception unhandled");
12788 break;
12789
12790 case ada_catch_handlers:
12791 fprintf_filtered (fp, "catch handlers");
12792 break;
12793
12794 case ada_catch_assert:
12795 fprintf_filtered (fp, "catch assert");
12796 break;
12797
12798 default:
12799 internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
12800 }
12801 print_recreate_thread (b, fp);
12802 }
12803
12804 /* Virtual table for "catch exception" breakpoints. */
12805
12806 static struct bp_location *
12807 allocate_location_catch_exception (struct breakpoint *self)
12808 {
12809 return allocate_location_exception (ada_catch_exception, self);
12810 }
12811
12812 static void
12813 re_set_catch_exception (struct breakpoint *b)
12814 {
12815 re_set_exception (ada_catch_exception, b);
12816 }
12817
12818 static void
12819 check_status_catch_exception (bpstat bs)
12820 {
12821 check_status_exception (ada_catch_exception, bs);
12822 }
12823
12824 static enum print_stop_action
12825 print_it_catch_exception (bpstat bs)
12826 {
12827 return print_it_exception (ada_catch_exception, bs);
12828 }
12829
12830 static void
12831 print_one_catch_exception (struct breakpoint *b, struct bp_location **last_loc)
12832 {
12833 print_one_exception (ada_catch_exception, b, last_loc);
12834 }
12835
12836 static void
12837 print_mention_catch_exception (struct breakpoint *b)
12838 {
12839 print_mention_exception (ada_catch_exception, b);
12840 }
12841
12842 static void
12843 print_recreate_catch_exception (struct breakpoint *b, struct ui_file *fp)
12844 {
12845 print_recreate_exception (ada_catch_exception, b, fp);
12846 }
12847
12848 static struct breakpoint_ops catch_exception_breakpoint_ops;
12849
12850 /* Virtual table for "catch exception unhandled" breakpoints. */
12851
12852 static struct bp_location *
12853 allocate_location_catch_exception_unhandled (struct breakpoint *self)
12854 {
12855 return allocate_location_exception (ada_catch_exception_unhandled, self);
12856 }
12857
12858 static void
12859 re_set_catch_exception_unhandled (struct breakpoint *b)
12860 {
12861 re_set_exception (ada_catch_exception_unhandled, b);
12862 }
12863
12864 static void
12865 check_status_catch_exception_unhandled (bpstat bs)
12866 {
12867 check_status_exception (ada_catch_exception_unhandled, bs);
12868 }
12869
12870 static enum print_stop_action
12871 print_it_catch_exception_unhandled (bpstat bs)
12872 {
12873 return print_it_exception (ada_catch_exception_unhandled, bs);
12874 }
12875
12876 static void
12877 print_one_catch_exception_unhandled (struct breakpoint *b,
12878 struct bp_location **last_loc)
12879 {
12880 print_one_exception (ada_catch_exception_unhandled, b, last_loc);
12881 }
12882
12883 static void
12884 print_mention_catch_exception_unhandled (struct breakpoint *b)
12885 {
12886 print_mention_exception (ada_catch_exception_unhandled, b);
12887 }
12888
12889 static void
12890 print_recreate_catch_exception_unhandled (struct breakpoint *b,
12891 struct ui_file *fp)
12892 {
12893 print_recreate_exception (ada_catch_exception_unhandled, b, fp);
12894 }
12895
12896 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;
12897
12898 /* Virtual table for "catch assert" breakpoints. */
12899
12900 static struct bp_location *
12901 allocate_location_catch_assert (struct breakpoint *self)
12902 {
12903 return allocate_location_exception (ada_catch_assert, self);
12904 }
12905
12906 static void
12907 re_set_catch_assert (struct breakpoint *b)
12908 {
12909 re_set_exception (ada_catch_assert, b);
12910 }
12911
12912 static void
12913 check_status_catch_assert (bpstat bs)
12914 {
12915 check_status_exception (ada_catch_assert, bs);
12916 }
12917
12918 static enum print_stop_action
12919 print_it_catch_assert (bpstat bs)
12920 {
12921 return print_it_exception (ada_catch_assert, bs);
12922 }
12923
12924 static void
12925 print_one_catch_assert (struct breakpoint *b, struct bp_location **last_loc)
12926 {
12927 print_one_exception (ada_catch_assert, b, last_loc);
12928 }
12929
12930 static void
12931 print_mention_catch_assert (struct breakpoint *b)
12932 {
12933 print_mention_exception (ada_catch_assert, b);
12934 }
12935
12936 static void
12937 print_recreate_catch_assert (struct breakpoint *b, struct ui_file *fp)
12938 {
12939 print_recreate_exception (ada_catch_assert, b, fp);
12940 }
12941
12942 static struct breakpoint_ops catch_assert_breakpoint_ops;
12943
12944 /* Virtual table for "catch handlers" breakpoints. */
12945
12946 static struct bp_location *
12947 allocate_location_catch_handlers (struct breakpoint *self)
12948 {
12949 return allocate_location_exception (ada_catch_handlers, self);
12950 }
12951
12952 static void
12953 re_set_catch_handlers (struct breakpoint *b)
12954 {
12955 re_set_exception (ada_catch_handlers, b);
12956 }
12957
12958 static void
12959 check_status_catch_handlers (bpstat bs)
12960 {
12961 check_status_exception (ada_catch_handlers, bs);
12962 }
12963
12964 static enum print_stop_action
12965 print_it_catch_handlers (bpstat bs)
12966 {
12967 return print_it_exception (ada_catch_handlers, bs);
12968 }
12969
12970 static void
12971 print_one_catch_handlers (struct breakpoint *b,
12972 struct bp_location **last_loc)
12973 {
12974 print_one_exception (ada_catch_handlers, b, last_loc);
12975 }
12976
12977 static void
12978 print_mention_catch_handlers (struct breakpoint *b)
12979 {
12980 print_mention_exception (ada_catch_handlers, b);
12981 }
12982
12983 static void
12984 print_recreate_catch_handlers (struct breakpoint *b,
12985 struct ui_file *fp)
12986 {
12987 print_recreate_exception (ada_catch_handlers, b, fp);
12988 }
12989
12990 static struct breakpoint_ops catch_handlers_breakpoint_ops;
12991
12992 /* Split the arguments specified in a "catch exception" command.
12993 Set EX to the appropriate catchpoint type.
12994 Set EXCEP_STRING to the name of the specific exception if
12995 specified by the user.
12996 IS_CATCH_HANDLERS_CMD: True if the arguments are for a
12997 "catch handlers" command. False otherwise.
12998 If a condition is found at the end of the arguments, the condition
12999 expression is stored in COND_STRING (memory must be deallocated
13000 after use). Otherwise COND_STRING is set to NULL. */
13001
13002 static void
13003 catch_ada_exception_command_split (const char *args,
13004 bool is_catch_handlers_cmd,
13005 enum ada_exception_catchpoint_kind *ex,
13006 std::string *excep_string,
13007 std::string *cond_string)
13008 {
13009 std::string exception_name;
13010
13011 exception_name = extract_arg (&args);
13012 if (exception_name == "if")
13013 {
13014 /* This is not an exception name; this is the start of a condition
13015 expression for a catchpoint on all exceptions. So, "un-get"
13016 this token, and set exception_name to NULL. */
13017 exception_name.clear ();
13018 args -= 2;
13019 }
13020
13021 /* Check to see if we have a condition. */
13022
13023 args = skip_spaces (args);
13024 if (startswith (args, "if")
13025 && (isspace (args[2]) || args[2] == '\0'))
13026 {
13027 args += 2;
13028 args = skip_spaces (args);
13029
13030 if (args[0] == '\0')
13031 error (_("Condition missing after `if' keyword"));
13032 *cond_string = args;
13033
13034 args += strlen (args);
13035 }
13036
13037 /* Check that we do not have any more arguments. Anything else
13038 is unexpected. */
13039
13040 if (args[0] != '\0')
13041 error (_("Junk at end of expression"));
13042
13043 if (is_catch_handlers_cmd)
13044 {
13045 /* Catch handling of exceptions. */
13046 *ex = ada_catch_handlers;
13047 *excep_string = exception_name;
13048 }
13049 else if (exception_name.empty ())
13050 {
13051 /* Catch all exceptions. */
13052 *ex = ada_catch_exception;
13053 excep_string->clear ();
13054 }
13055 else if (exception_name == "unhandled")
13056 {
13057 /* Catch unhandled exceptions. */
13058 *ex = ada_catch_exception_unhandled;
13059 excep_string->clear ();
13060 }
13061 else
13062 {
13063 /* Catch a specific exception. */
13064 *ex = ada_catch_exception;
13065 *excep_string = exception_name;
13066 }
13067 }
13068
13069 /* Return the name of the symbol on which we should break in order to
13070 implement a catchpoint of the EX kind. */
13071
13072 static const char *
13073 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
13074 {
13075 struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
13076
13077 gdb_assert (data->exception_info != NULL);
13078
13079 switch (ex)
13080 {
13081 case ada_catch_exception:
13082 return (data->exception_info->catch_exception_sym);
13083 break;
13084 case ada_catch_exception_unhandled:
13085 return (data->exception_info->catch_exception_unhandled_sym);
13086 break;
13087 case ada_catch_assert:
13088 return (data->exception_info->catch_assert_sym);
13089 break;
13090 case ada_catch_handlers:
13091 return (data->exception_info->catch_handlers_sym);
13092 break;
13093 default:
13094 internal_error (__FILE__, __LINE__,
13095 _("unexpected catchpoint kind (%d)"), ex);
13096 }
13097 }
13098
13099 /* Return the breakpoint ops "virtual table" used for catchpoints
13100 of the EX kind. */
13101
13102 static const struct breakpoint_ops *
13103 ada_exception_breakpoint_ops (enum ada_exception_catchpoint_kind ex)
13104 {
13105 switch (ex)
13106 {
13107 case ada_catch_exception:
13108 return (&catch_exception_breakpoint_ops);
13109 break;
13110 case ada_catch_exception_unhandled:
13111 return (&catch_exception_unhandled_breakpoint_ops);
13112 break;
13113 case ada_catch_assert:
13114 return (&catch_assert_breakpoint_ops);
13115 break;
13116 case ada_catch_handlers:
13117 return (&catch_handlers_breakpoint_ops);
13118 break;
13119 default:
13120 internal_error (__FILE__, __LINE__,
13121 _("unexpected catchpoint kind (%d)"), ex);
13122 }
13123 }
13124
13125 /* Return the condition that will be used to match the current exception
13126 being raised with the exception that the user wants to catch. This
13127 assumes that this condition is used when the inferior just triggered
13128 an exception catchpoint.
13129 EX: the type of catchpoints used for catching Ada exceptions. */
13130
13131 static std::string
13132 ada_exception_catchpoint_cond_string (const char *excep_string,
13133 enum ada_exception_catchpoint_kind ex)
13134 {
13135 int i;
13136 bool is_standard_exc = false;
13137 std::string result;
13138
13139 if (ex == ada_catch_handlers)
13140 {
13141 /* For exception handlers catchpoints, the condition string does
13142 not use the same parameter as for the other exceptions. */
13143 result = ("long_integer (GNAT_GCC_exception_Access"
13144 "(gcc_exception).all.occurrence.id)");
13145 }
13146 else
13147 result = "long_integer (e)";
13148
13149 /* The standard exceptions are a special case. They are defined in
13150 runtime units that have been compiled without debugging info; if
13151 EXCEP_STRING is the not-fully-qualified name of a standard
13152 exception (e.g. "constraint_error") then, during the evaluation
13153 of the condition expression, the symbol lookup on this name would
13154 *not* return this standard exception. The catchpoint condition
13155 may then be set only on user-defined exceptions which have the
13156 same not-fully-qualified name (e.g. my_package.constraint_error).
13157
13158 To avoid this unexcepted behavior, these standard exceptions are
13159 systematically prefixed by "standard". This means that "catch
13160 exception constraint_error" is rewritten into "catch exception
13161 standard.constraint_error".
13162
13163 If an exception named contraint_error is defined in another package of
13164 the inferior program, then the only way to specify this exception as a
13165 breakpoint condition is to use its fully-qualified named:
13166 e.g. my_package.constraint_error. */
13167
13168 for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
13169 {
13170 if (strcmp (standard_exc [i], excep_string) == 0)
13171 {
13172 is_standard_exc = true;
13173 break;
13174 }
13175 }
13176
13177 result += " = ";
13178
13179 if (is_standard_exc)
13180 string_appendf (result, "long_integer (&standard.%s)", excep_string);
13181 else
13182 string_appendf (result, "long_integer (&%s)", excep_string);
13183
13184 return result;
13185 }
13186
13187 /* Return the symtab_and_line that should be used to insert an exception
13188 catchpoint of the TYPE kind.
13189
13190 ADDR_STRING returns the name of the function where the real
13191 breakpoint that implements the catchpoints is set, depending on the
13192 type of catchpoint we need to create. */
13193
13194 static struct symtab_and_line
13195 ada_exception_sal (enum ada_exception_catchpoint_kind ex,
13196 std::string *addr_string, const struct breakpoint_ops **ops)
13197 {
13198 const char *sym_name;
13199 struct symbol *sym;
13200
13201 /* First, find out which exception support info to use. */
13202 ada_exception_support_info_sniffer ();
13203
13204 /* Then lookup the function on which we will break in order to catch
13205 the Ada exceptions requested by the user. */
13206 sym_name = ada_exception_sym_name (ex);
13207 sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
13208
13209 if (sym == NULL)
13210 error (_("Catchpoint symbol not found: %s"), sym_name);
13211
13212 if (SYMBOL_CLASS (sym) != LOC_BLOCK)
13213 error (_("Unable to insert catchpoint. %s is not a function."), sym_name);
13214
13215 /* Set ADDR_STRING. */
13216 *addr_string = sym_name;
13217
13218 /* Set OPS. */
13219 *ops = ada_exception_breakpoint_ops (ex);
13220
13221 return find_function_start_sal (sym, 1);
13222 }
13223
13224 /* Create an Ada exception catchpoint.
13225
13226 EX_KIND is the kind of exception catchpoint to be created.
13227
13228 If EXCEPT_STRING is empty, this catchpoint is expected to trigger
13229 for all exceptions. Otherwise, EXCEPT_STRING indicates the name
13230 of the exception to which this catchpoint applies.
13231
13232 COND_STRING, if not empty, is the catchpoint condition.
13233
13234 TEMPFLAG, if nonzero, means that the underlying breakpoint
13235 should be temporary.
13236
13237 FROM_TTY is the usual argument passed to all commands implementations. */
13238
13239 void
13240 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
13241 enum ada_exception_catchpoint_kind ex_kind,
13242 const std::string &excep_string,
13243 const std::string &cond_string,
13244 int tempflag,
13245 int disabled,
13246 int from_tty)
13247 {
13248 std::string addr_string;
13249 const struct breakpoint_ops *ops = NULL;
13250 struct symtab_and_line sal = ada_exception_sal (ex_kind, &addr_string, &ops);
13251
13252 std::unique_ptr<ada_catchpoint> c (new ada_catchpoint ());
13253 init_ada_exception_breakpoint (c.get (), gdbarch, sal, addr_string.c_str (),
13254 ops, tempflag, disabled, from_tty);
13255 c->excep_string = excep_string;
13256 create_excep_cond_exprs (c.get (), ex_kind);
13257 if (!cond_string.empty ())
13258 set_breakpoint_condition (c.get (), cond_string.c_str (), from_tty);
13259 install_breakpoint (0, std::move (c), 1);
13260 }
13261
13262 /* Implement the "catch exception" command. */
13263
13264 static void
13265 catch_ada_exception_command (const char *arg_entry, int from_tty,
13266 struct cmd_list_element *command)
13267 {
13268 const char *arg = arg_entry;
13269 struct gdbarch *gdbarch = get_current_arch ();
13270 int tempflag;
13271 enum ada_exception_catchpoint_kind ex_kind;
13272 std::string excep_string;
13273 std::string cond_string;
13274
13275 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13276
13277 if (!arg)
13278 arg = "";
13279 catch_ada_exception_command_split (arg, false, &ex_kind, &excep_string,
13280 &cond_string);
13281 create_ada_exception_catchpoint (gdbarch, ex_kind,
13282 excep_string, cond_string,
13283 tempflag, 1 /* enabled */,
13284 from_tty);
13285 }
13286
13287 /* Implement the "catch handlers" command. */
13288
13289 static void
13290 catch_ada_handlers_command (const char *arg_entry, int from_tty,
13291 struct cmd_list_element *command)
13292 {
13293 const char *arg = arg_entry;
13294 struct gdbarch *gdbarch = get_current_arch ();
13295 int tempflag;
13296 enum ada_exception_catchpoint_kind ex_kind;
13297 std::string excep_string;
13298 std::string cond_string;
13299
13300 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13301
13302 if (!arg)
13303 arg = "";
13304 catch_ada_exception_command_split (arg, true, &ex_kind, &excep_string,
13305 &cond_string);
13306 create_ada_exception_catchpoint (gdbarch, ex_kind,
13307 excep_string, cond_string,
13308 tempflag, 1 /* enabled */,
13309 from_tty);
13310 }
13311
13312 /* Split the arguments specified in a "catch assert" command.
13313
13314 ARGS contains the command's arguments (or the empty string if
13315 no arguments were passed).
13316
13317 If ARGS contains a condition, set COND_STRING to that condition
13318 (the memory needs to be deallocated after use). */
13319
13320 static void
13321 catch_ada_assert_command_split (const char *args, std::string &cond_string)
13322 {
13323 args = skip_spaces (args);
13324
13325 /* Check whether a condition was provided. */
13326 if (startswith (args, "if")
13327 && (isspace (args[2]) || args[2] == '\0'))
13328 {
13329 args += 2;
13330 args = skip_spaces (args);
13331 if (args[0] == '\0')
13332 error (_("condition missing after `if' keyword"));
13333 cond_string.assign (args);
13334 }
13335
13336 /* Otherwise, there should be no other argument at the end of
13337 the command. */
13338 else if (args[0] != '\0')
13339 error (_("Junk at end of arguments."));
13340 }
13341
13342 /* Implement the "catch assert" command. */
13343
13344 static void
13345 catch_assert_command (const char *arg_entry, int from_tty,
13346 struct cmd_list_element *command)
13347 {
13348 const char *arg = arg_entry;
13349 struct gdbarch *gdbarch = get_current_arch ();
13350 int tempflag;
13351 std::string cond_string;
13352
13353 tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
13354
13355 if (!arg)
13356 arg = "";
13357 catch_ada_assert_command_split (arg, cond_string);
13358 create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
13359 "", cond_string,
13360 tempflag, 1 /* enabled */,
13361 from_tty);
13362 }
13363
13364 /* Return non-zero if the symbol SYM is an Ada exception object. */
13365
13366 static int
13367 ada_is_exception_sym (struct symbol *sym)
13368 {
13369 const char *type_name = TYPE_NAME (SYMBOL_TYPE (sym));
13370
13371 return (SYMBOL_CLASS (sym) != LOC_TYPEDEF
13372 && SYMBOL_CLASS (sym) != LOC_BLOCK
13373 && SYMBOL_CLASS (sym) != LOC_CONST
13374 && SYMBOL_CLASS (sym) != LOC_UNRESOLVED
13375 && type_name != NULL && strcmp (type_name, "exception") == 0);
13376 }
13377
13378 /* Given a global symbol SYM, return non-zero iff SYM is a non-standard
13379 Ada exception object. This matches all exceptions except the ones
13380 defined by the Ada language. */
13381
13382 static int
13383 ada_is_non_standard_exception_sym (struct symbol *sym)
13384 {
13385 int i;
13386
13387 if (!ada_is_exception_sym (sym))
13388 return 0;
13389
13390 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13391 if (strcmp (SYMBOL_LINKAGE_NAME (sym), standard_exc[i]) == 0)
13392 return 0; /* A standard exception. */
13393
13394 /* Numeric_Error is also a standard exception, so exclude it.
13395 See the STANDARD_EXC description for more details as to why
13396 this exception is not listed in that array. */
13397 if (strcmp (SYMBOL_LINKAGE_NAME (sym), "numeric_error") == 0)
13398 return 0;
13399
13400 return 1;
13401 }
13402
13403 /* A helper function for std::sort, comparing two struct ada_exc_info
13404 objects.
13405
13406 The comparison is determined first by exception name, and then
13407 by exception address. */
13408
13409 bool
13410 ada_exc_info::operator< (const ada_exc_info &other) const
13411 {
13412 int result;
13413
13414 result = strcmp (name, other.name);
13415 if (result < 0)
13416 return true;
13417 if (result == 0 && addr < other.addr)
13418 return true;
13419 return false;
13420 }
13421
13422 bool
13423 ada_exc_info::operator== (const ada_exc_info &other) const
13424 {
13425 return addr == other.addr && strcmp (name, other.name) == 0;
13426 }
13427
13428 /* Sort EXCEPTIONS using compare_ada_exception_info as the comparison
13429 routine, but keeping the first SKIP elements untouched.
13430
13431 All duplicates are also removed. */
13432
13433 static void
13434 sort_remove_dups_ada_exceptions_list (std::vector<ada_exc_info> *exceptions,
13435 int skip)
13436 {
13437 std::sort (exceptions->begin () + skip, exceptions->end ());
13438 exceptions->erase (std::unique (exceptions->begin () + skip, exceptions->end ()),
13439 exceptions->end ());
13440 }
13441
13442 /* Add all exceptions defined by the Ada standard whose name match
13443 a regular expression.
13444
13445 If PREG is not NULL, then this regexp_t object is used to
13446 perform the symbol name matching. Otherwise, no name-based
13447 filtering is performed.
13448
13449 EXCEPTIONS is a vector of exceptions to which matching exceptions
13450 gets pushed. */
13451
13452 static void
13453 ada_add_standard_exceptions (compiled_regex *preg,
13454 std::vector<ada_exc_info> *exceptions)
13455 {
13456 int i;
13457
13458 for (i = 0; i < ARRAY_SIZE (standard_exc); i++)
13459 {
13460 if (preg == NULL
13461 || preg->exec (standard_exc[i], 0, NULL, 0) == 0)
13462 {
13463 struct bound_minimal_symbol msymbol
13464 = ada_lookup_simple_minsym (standard_exc[i]);
13465
13466 if (msymbol.minsym != NULL)
13467 {
13468 struct ada_exc_info info
13469 = {standard_exc[i], BMSYMBOL_VALUE_ADDRESS (msymbol)};
13470
13471 exceptions->push_back (info);
13472 }
13473 }
13474 }
13475 }
13476
13477 /* Add all Ada exceptions defined locally and accessible from the given
13478 FRAME.
13479
13480 If PREG is not NULL, then this regexp_t object is used to
13481 perform the symbol name matching. Otherwise, no name-based
13482 filtering is performed.
13483
13484 EXCEPTIONS is a vector of exceptions to which matching exceptions
13485 gets pushed. */
13486
13487 static void
13488 ada_add_exceptions_from_frame (compiled_regex *preg,
13489 struct frame_info *frame,
13490 std::vector<ada_exc_info> *exceptions)
13491 {
13492 const struct block *block = get_frame_block (frame, 0);
13493
13494 while (block != 0)
13495 {
13496 struct block_iterator iter;
13497 struct symbol *sym;
13498
13499 ALL_BLOCK_SYMBOLS (block, iter, sym)
13500 {
13501 switch (SYMBOL_CLASS (sym))
13502 {
13503 case LOC_TYPEDEF:
13504 case LOC_BLOCK:
13505 case LOC_CONST:
13506 break;
13507 default:
13508 if (ada_is_exception_sym (sym))
13509 {
13510 struct ada_exc_info info = {SYMBOL_PRINT_NAME (sym),
13511 SYMBOL_VALUE_ADDRESS (sym)};
13512
13513 exceptions->push_back (info);
13514 }
13515 }
13516 }
13517 if (BLOCK_FUNCTION (block) != NULL)
13518 break;
13519 block = BLOCK_SUPERBLOCK (block);
13520 }
13521 }
13522
13523 /* Return true if NAME matches PREG or if PREG is NULL. */
13524
13525 static bool
13526 name_matches_regex (const char *name, compiled_regex *preg)
13527 {
13528 return (preg == NULL
13529 || preg->exec (ada_decode (name), 0, NULL, 0) == 0);
13530 }
13531
13532 /* Add all exceptions defined globally whose name name match
13533 a regular expression, excluding standard exceptions.
13534
13535 The reason we exclude standard exceptions is that they need
13536 to be handled separately: Standard exceptions are defined inside
13537 a runtime unit which is normally not compiled with debugging info,
13538 and thus usually do not show up in our symbol search. However,
13539 if the unit was in fact built with debugging info, we need to
13540 exclude them because they would duplicate the entry we found
13541 during the special loop that specifically searches for those
13542 standard exceptions.
13543
13544 If PREG is not NULL, then this regexp_t object is used to
13545 perform the symbol name matching. Otherwise, no name-based
13546 filtering is performed.
13547
13548 EXCEPTIONS is a vector of exceptions to which matching exceptions
13549 gets pushed. */
13550
13551 static void
13552 ada_add_global_exceptions (compiled_regex *preg,
13553 std::vector<ada_exc_info> *exceptions)
13554 {
13555 /* In Ada, the symbol "search name" is a linkage name, whereas the
13556 regular expression used to do the matching refers to the natural
13557 name. So match against the decoded name. */
13558 expand_symtabs_matching (NULL,
13559 lookup_name_info::match_any (),
13560 [&] (const char *search_name)
13561 {
13562 const char *decoded = ada_decode (search_name);
13563 return name_matches_regex (decoded, preg);
13564 },
13565 NULL,
13566 VARIABLES_DOMAIN);
13567
13568 for (objfile *objfile : current_program_space->objfiles ())
13569 {
13570 for (compunit_symtab *s : objfile->compunits ())
13571 {
13572 const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (s);
13573 int i;
13574
13575 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
13576 {
13577 const struct block *b = BLOCKVECTOR_BLOCK (bv, i);
13578 struct block_iterator iter;
13579 struct symbol *sym;
13580
13581 ALL_BLOCK_SYMBOLS (b, iter, sym)
13582 if (ada_is_non_standard_exception_sym (sym)
13583 && name_matches_regex (SYMBOL_NATURAL_NAME (sym), preg))
13584 {
13585 struct ada_exc_info info
13586 = {SYMBOL_PRINT_NAME (sym), SYMBOL_VALUE_ADDRESS (sym)};
13587
13588 exceptions->push_back (info);
13589 }
13590 }
13591 }
13592 }
13593 }
13594
13595 /* Implements ada_exceptions_list with the regular expression passed
13596 as a regex_t, rather than a string.
13597
13598 If not NULL, PREG is used to filter out exceptions whose names
13599 do not match. Otherwise, all exceptions are listed. */
13600
13601 static std::vector<ada_exc_info>
13602 ada_exceptions_list_1 (compiled_regex *preg)
13603 {
13604 std::vector<ada_exc_info> result;
13605 int prev_len;
13606
13607 /* First, list the known standard exceptions. These exceptions
13608 need to be handled separately, as they are usually defined in
13609 runtime units that have been compiled without debugging info. */
13610
13611 ada_add_standard_exceptions (preg, &result);
13612
13613 /* Next, find all exceptions whose scope is local and accessible
13614 from the currently selected frame. */
13615
13616 if (has_stack_frames ())
13617 {
13618 prev_len = result.size ();
13619 ada_add_exceptions_from_frame (preg, get_selected_frame (NULL),
13620 &result);
13621 if (result.size () > prev_len)
13622 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13623 }
13624
13625 /* Add all exceptions whose scope is global. */
13626
13627 prev_len = result.size ();
13628 ada_add_global_exceptions (preg, &result);
13629 if (result.size () > prev_len)
13630 sort_remove_dups_ada_exceptions_list (&result, prev_len);
13631
13632 return result;
13633 }
13634
13635 /* Return a vector of ada_exc_info.
13636
13637 If REGEXP is NULL, all exceptions are included in the result.
13638 Otherwise, it should contain a valid regular expression,
13639 and only the exceptions whose names match that regular expression
13640 are included in the result.
13641
13642 The exceptions are sorted in the following order:
13643 - Standard exceptions (defined by the Ada language), in
13644 alphabetical order;
13645 - Exceptions only visible from the current frame, in
13646 alphabetical order;
13647 - Exceptions whose scope is global, in alphabetical order. */
13648
13649 std::vector<ada_exc_info>
13650 ada_exceptions_list (const char *regexp)
13651 {
13652 if (regexp == NULL)
13653 return ada_exceptions_list_1 (NULL);
13654
13655 compiled_regex reg (regexp, REG_NOSUB, _("invalid regular expression"));
13656 return ada_exceptions_list_1 (&reg);
13657 }
13658
13659 /* Implement the "info exceptions" command. */
13660
13661 static void
13662 info_exceptions_command (const char *regexp, int from_tty)
13663 {
13664 struct gdbarch *gdbarch = get_current_arch ();
13665
13666 std::vector<ada_exc_info> exceptions = ada_exceptions_list (regexp);
13667
13668 if (regexp != NULL)
13669 printf_filtered
13670 (_("All Ada exceptions matching regular expression \"%s\":\n"), regexp);
13671 else
13672 printf_filtered (_("All defined Ada exceptions:\n"));
13673
13674 for (const ada_exc_info &info : exceptions)
13675 printf_filtered ("%s: %s\n", info.name, paddress (gdbarch, info.addr));
13676 }
13677
13678 /* Operators */
13679 /* Information about operators given special treatment in functions
13680 below. */
13681 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>). */
13682
13683 #define ADA_OPERATORS \
13684 OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
13685 OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
13686 OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
13687 OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
13688 OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
13689 OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
13690 OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
13691 OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
13692 OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
13693 OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
13694 OP_DEFN (OP_ATR_POS, 1, 2, 0) \
13695 OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
13696 OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
13697 OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
13698 OP_DEFN (UNOP_QUAL, 3, 1, 0) \
13699 OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
13700 OP_DEFN (OP_OTHERS, 1, 1, 0) \
13701 OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
13702 OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)
13703
13704 static void
13705 ada_operator_length (const struct expression *exp, int pc, int *oplenp,
13706 int *argsp)
13707 {
13708 switch (exp->elts[pc - 1].opcode)
13709 {
13710 default:
13711 operator_length_standard (exp, pc, oplenp, argsp);
13712 break;
13713
13714 #define OP_DEFN(op, len, args, binop) \
13715 case op: *oplenp = len; *argsp = args; break;
13716 ADA_OPERATORS;
13717 #undef OP_DEFN
13718
13719 case OP_AGGREGATE:
13720 *oplenp = 3;
13721 *argsp = longest_to_int (exp->elts[pc - 2].longconst);
13722 break;
13723
13724 case OP_CHOICES:
13725 *oplenp = 3;
13726 *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
13727 break;
13728 }
13729 }
13730
13731 /* Implementation of the exp_descriptor method operator_check. */
13732
13733 static int
13734 ada_operator_check (struct expression *exp, int pos,
13735 int (*objfile_func) (struct objfile *objfile, void *data),
13736 void *data)
13737 {
13738 const union exp_element *const elts = exp->elts;
13739 struct type *type = NULL;
13740
13741 switch (elts[pos].opcode)
13742 {
13743 case UNOP_IN_RANGE:
13744 case UNOP_QUAL:
13745 type = elts[pos + 1].type;
13746 break;
13747
13748 default:
13749 return operator_check_standard (exp, pos, objfile_func, data);
13750 }
13751
13752 /* Invoke callbacks for TYPE and OBJFILE if they were set as non-NULL. */
13753
13754 if (type && TYPE_OBJFILE (type)
13755 && (*objfile_func) (TYPE_OBJFILE (type), data))
13756 return 1;
13757
13758 return 0;
13759 }
13760
13761 static const char *
13762 ada_op_name (enum exp_opcode opcode)
13763 {
13764 switch (opcode)
13765 {
13766 default:
13767 return op_name_standard (opcode);
13768
13769 #define OP_DEFN(op, len, args, binop) case op: return #op;
13770 ADA_OPERATORS;
13771 #undef OP_DEFN
13772
13773 case OP_AGGREGATE:
13774 return "OP_AGGREGATE";
13775 case OP_CHOICES:
13776 return "OP_CHOICES";
13777 case OP_NAME:
13778 return "OP_NAME";
13779 }
13780 }
13781
13782 /* As for operator_length, but assumes PC is pointing at the first
13783 element of the operator, and gives meaningful results only for the
13784 Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise. */
13785
13786 static void
13787 ada_forward_operator_length (struct expression *exp, int pc,
13788 int *oplenp, int *argsp)
13789 {
13790 switch (exp->elts[pc].opcode)
13791 {
13792 default:
13793 *oplenp = *argsp = 0;
13794 break;
13795
13796 #define OP_DEFN(op, len, args, binop) \
13797 case op: *oplenp = len; *argsp = args; break;
13798 ADA_OPERATORS;
13799 #undef OP_DEFN
13800
13801 case OP_AGGREGATE:
13802 *oplenp = 3;
13803 *argsp = longest_to_int (exp->elts[pc + 1].longconst);
13804 break;
13805
13806 case OP_CHOICES:
13807 *oplenp = 3;
13808 *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
13809 break;
13810
13811 case OP_STRING:
13812 case OP_NAME:
13813 {
13814 int len = longest_to_int (exp->elts[pc + 1].longconst);
13815
13816 *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
13817 *argsp = 0;
13818 break;
13819 }
13820 }
13821 }
13822
13823 static int
13824 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
13825 {
13826 enum exp_opcode op = exp->elts[elt].opcode;
13827 int oplen, nargs;
13828 int pc = elt;
13829 int i;
13830
13831 ada_forward_operator_length (exp, elt, &oplen, &nargs);
13832
13833 switch (op)
13834 {
13835 /* Ada attributes ('Foo). */
13836 case OP_ATR_FIRST:
13837 case OP_ATR_LAST:
13838 case OP_ATR_LENGTH:
13839 case OP_ATR_IMAGE:
13840 case OP_ATR_MAX:
13841 case OP_ATR_MIN:
13842 case OP_ATR_MODULUS:
13843 case OP_ATR_POS:
13844 case OP_ATR_SIZE:
13845 case OP_ATR_TAG:
13846 case OP_ATR_VAL:
13847 break;
13848
13849 case UNOP_IN_RANGE:
13850 case UNOP_QUAL:
13851 /* XXX: gdb_sprint_host_address, type_sprint */
13852 fprintf_filtered (stream, _("Type @"));
13853 gdb_print_host_address (exp->elts[pc + 1].type, stream);
13854 fprintf_filtered (stream, " (");
13855 type_print (exp->elts[pc + 1].type, NULL, stream, 0);
13856 fprintf_filtered (stream, ")");
13857 break;
13858 case BINOP_IN_BOUNDS:
13859 fprintf_filtered (stream, " (%d)",
13860 longest_to_int (exp->elts[pc + 2].longconst));
13861 break;
13862 case TERNOP_IN_RANGE:
13863 break;
13864
13865 case OP_AGGREGATE:
13866 case OP_OTHERS:
13867 case OP_DISCRETE_RANGE:
13868 case OP_POSITIONAL:
13869 case OP_CHOICES:
13870 break;
13871
13872 case OP_NAME:
13873 case OP_STRING:
13874 {
13875 char *name = &exp->elts[elt + 2].string;
13876 int len = longest_to_int (exp->elts[elt + 1].longconst);
13877
13878 fprintf_filtered (stream, "Text: `%.*s'", len, name);
13879 break;
13880 }
13881
13882 default:
13883 return dump_subexp_body_standard (exp, stream, elt);
13884 }
13885
13886 elt += oplen;
13887 for (i = 0; i < nargs; i += 1)
13888 elt = dump_subexp (exp, stream, elt);
13889
13890 return elt;
13891 }
13892
13893 /* The Ada extension of print_subexp (q.v.). */
13894
13895 static void
13896 ada_print_subexp (struct expression *exp, int *pos,
13897 struct ui_file *stream, enum precedence prec)
13898 {
13899 int oplen, nargs, i;
13900 int pc = *pos;
13901 enum exp_opcode op = exp->elts[pc].opcode;
13902
13903 ada_forward_operator_length (exp, pc, &oplen, &nargs);
13904
13905 *pos += oplen;
13906 switch (op)
13907 {
13908 default:
13909 *pos -= oplen;
13910 print_subexp_standard (exp, pos, stream, prec);
13911 return;
13912
13913 case OP_VAR_VALUE:
13914 fputs_filtered (SYMBOL_NATURAL_NAME (exp->elts[pc + 2].symbol), stream);
13915 return;
13916
13917 case BINOP_IN_BOUNDS:
13918 /* XXX: sprint_subexp */
13919 print_subexp (exp, pos, stream, PREC_SUFFIX);
13920 fputs_filtered (" in ", stream);
13921 print_subexp (exp, pos, stream, PREC_SUFFIX);
13922 fputs_filtered ("'range", stream);
13923 if (exp->elts[pc + 1].longconst > 1)
13924 fprintf_filtered (stream, "(%ld)",
13925 (long) exp->elts[pc + 1].longconst);
13926 return;
13927
13928 case TERNOP_IN_RANGE:
13929 if (prec >= PREC_EQUAL)
13930 fputs_filtered ("(", stream);
13931 /* XXX: sprint_subexp */
13932 print_subexp (exp, pos, stream, PREC_SUFFIX);
13933 fputs_filtered (" in ", stream);
13934 print_subexp (exp, pos, stream, PREC_EQUAL);
13935 fputs_filtered (" .. ", stream);
13936 print_subexp (exp, pos, stream, PREC_EQUAL);
13937 if (prec >= PREC_EQUAL)
13938 fputs_filtered (")", stream);
13939 return;
13940
13941 case OP_ATR_FIRST:
13942 case OP_ATR_LAST:
13943 case OP_ATR_LENGTH:
13944 case OP_ATR_IMAGE:
13945 case OP_ATR_MAX:
13946 case OP_ATR_MIN:
13947 case OP_ATR_MODULUS:
13948 case OP_ATR_POS:
13949 case OP_ATR_SIZE:
13950 case OP_ATR_TAG:
13951 case OP_ATR_VAL:
13952 if (exp->elts[*pos].opcode == OP_TYPE)
13953 {
13954 if (TYPE_CODE (exp->elts[*pos + 1].type) != TYPE_CODE_VOID)
13955 LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0,
13956 &type_print_raw_options);
13957 *pos += 3;
13958 }
13959 else
13960 print_subexp (exp, pos, stream, PREC_SUFFIX);
13961 fprintf_filtered (stream, "'%s", ada_attribute_name (op));
13962 if (nargs > 1)
13963 {
13964 int tem;
13965
13966 for (tem = 1; tem < nargs; tem += 1)
13967 {
13968 fputs_filtered ((tem == 1) ? " (" : ", ", stream);
13969 print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
13970 }
13971 fputs_filtered (")", stream);
13972 }
13973 return;
13974
13975 case UNOP_QUAL:
13976 type_print (exp->elts[pc + 1].type, "", stream, 0);
13977 fputs_filtered ("'(", stream);
13978 print_subexp (exp, pos, stream, PREC_PREFIX);
13979 fputs_filtered (")", stream);
13980 return;
13981
13982 case UNOP_IN_RANGE:
13983 /* XXX: sprint_subexp */
13984 print_subexp (exp, pos, stream, PREC_SUFFIX);
13985 fputs_filtered (" in ", stream);
13986 LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0,
13987 &type_print_raw_options);
13988 return;
13989
13990 case OP_DISCRETE_RANGE:
13991 print_subexp (exp, pos, stream, PREC_SUFFIX);
13992 fputs_filtered ("..", stream);
13993 print_subexp (exp, pos, stream, PREC_SUFFIX);
13994 return;
13995
13996 case OP_OTHERS:
13997 fputs_filtered ("others => ", stream);
13998 print_subexp (exp, pos, stream, PREC_SUFFIX);
13999 return;
14000
14001 case OP_CHOICES:
14002 for (i = 0; i < nargs-1; i += 1)
14003 {
14004 if (i > 0)
14005 fputs_filtered ("|", stream);
14006 print_subexp (exp, pos, stream, PREC_SUFFIX);
14007 }
14008 fputs_filtered (" => ", stream);
14009 print_subexp (exp, pos, stream, PREC_SUFFIX);
14010 return;
14011
14012 case OP_POSITIONAL:
14013 print_subexp (exp, pos, stream, PREC_SUFFIX);
14014 return;
14015
14016 case OP_AGGREGATE:
14017 fputs_filtered ("(", stream);
14018 for (i = 0; i < nargs; i += 1)
14019 {
14020 if (i > 0)
14021 fputs_filtered (", ", stream);
14022 print_subexp (exp, pos, stream, PREC_SUFFIX);
14023 }
14024 fputs_filtered (")", stream);
14025 return;
14026 }
14027 }
14028
14029 /* Table mapping opcodes into strings for printing operators
14030 and precedences of the operators. */
14031
14032 static const struct op_print ada_op_print_tab[] = {
14033 {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
14034 {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
14035 {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
14036 {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
14037 {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
14038 {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
14039 {"=", BINOP_EQUAL, PREC_EQUAL, 0},
14040 {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
14041 {"<=", BINOP_LEQ, PREC_ORDER, 0},
14042 {">=", BINOP_GEQ, PREC_ORDER, 0},
14043 {">", BINOP_GTR, PREC_ORDER, 0},
14044 {"<", BINOP_LESS, PREC_ORDER, 0},
14045 {">>", BINOP_RSH, PREC_SHIFT, 0},
14046 {"<<", BINOP_LSH, PREC_SHIFT, 0},
14047 {"+", BINOP_ADD, PREC_ADD, 0},
14048 {"-", BINOP_SUB, PREC_ADD, 0},
14049 {"&", BINOP_CONCAT, PREC_ADD, 0},
14050 {"*", BINOP_MUL, PREC_MUL, 0},
14051 {"/", BINOP_DIV, PREC_MUL, 0},
14052 {"rem", BINOP_REM, PREC_MUL, 0},
14053 {"mod", BINOP_MOD, PREC_MUL, 0},
14054 {"**", BINOP_EXP, PREC_REPEAT, 0},
14055 {"@", BINOP_REPEAT, PREC_REPEAT, 0},
14056 {"-", UNOP_NEG, PREC_PREFIX, 0},
14057 {"+", UNOP_PLUS, PREC_PREFIX, 0},
14058 {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
14059 {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
14060 {"abs ", UNOP_ABS, PREC_PREFIX, 0},
14061 {".all", UNOP_IND, PREC_SUFFIX, 1},
14062 {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
14063 {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
14064 {NULL, OP_NULL, PREC_SUFFIX, 0}
14065 };
14066 \f
14067 enum ada_primitive_types {
14068 ada_primitive_type_int,
14069 ada_primitive_type_long,
14070 ada_primitive_type_short,
14071 ada_primitive_type_char,
14072 ada_primitive_type_float,
14073 ada_primitive_type_double,
14074 ada_primitive_type_void,
14075 ada_primitive_type_long_long,
14076 ada_primitive_type_long_double,
14077 ada_primitive_type_natural,
14078 ada_primitive_type_positive,
14079 ada_primitive_type_system_address,
14080 ada_primitive_type_storage_offset,
14081 nr_ada_primitive_types
14082 };
14083
14084 static void
14085 ada_language_arch_info (struct gdbarch *gdbarch,
14086 struct language_arch_info *lai)
14087 {
14088 const struct builtin_type *builtin = builtin_type (gdbarch);
14089
14090 lai->primitive_type_vector
14091 = GDBARCH_OBSTACK_CALLOC (gdbarch, nr_ada_primitive_types + 1,
14092 struct type *);
14093
14094 lai->primitive_type_vector [ada_primitive_type_int]
14095 = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14096 0, "integer");
14097 lai->primitive_type_vector [ada_primitive_type_long]
14098 = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
14099 0, "long_integer");
14100 lai->primitive_type_vector [ada_primitive_type_short]
14101 = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
14102 0, "short_integer");
14103 lai->string_char_type
14104 = lai->primitive_type_vector [ada_primitive_type_char]
14105 = arch_character_type (gdbarch, TARGET_CHAR_BIT, 0, "character");
14106 lai->primitive_type_vector [ada_primitive_type_float]
14107 = arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
14108 "float", gdbarch_float_format (gdbarch));
14109 lai->primitive_type_vector [ada_primitive_type_double]
14110 = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
14111 "long_float", gdbarch_double_format (gdbarch));
14112 lai->primitive_type_vector [ada_primitive_type_long_long]
14113 = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
14114 0, "long_long_integer");
14115 lai->primitive_type_vector [ada_primitive_type_long_double]
14116 = arch_float_type (gdbarch, gdbarch_long_double_bit (gdbarch),
14117 "long_long_float", gdbarch_long_double_format (gdbarch));
14118 lai->primitive_type_vector [ada_primitive_type_natural]
14119 = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14120 0, "natural");
14121 lai->primitive_type_vector [ada_primitive_type_positive]
14122 = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
14123 0, "positive");
14124 lai->primitive_type_vector [ada_primitive_type_void]
14125 = builtin->builtin_void;
14126
14127 lai->primitive_type_vector [ada_primitive_type_system_address]
14128 = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, TARGET_CHAR_BIT,
14129 "void"));
14130 TYPE_NAME (lai->primitive_type_vector [ada_primitive_type_system_address])
14131 = "system__address";
14132
14133 /* Create the equivalent of the System.Storage_Elements.Storage_Offset
14134 type. This is a signed integral type whose size is the same as
14135 the size of addresses. */
14136 {
14137 unsigned int addr_length = TYPE_LENGTH
14138 (lai->primitive_type_vector [ada_primitive_type_system_address]);
14139
14140 lai->primitive_type_vector [ada_primitive_type_storage_offset]
14141 = arch_integer_type (gdbarch, addr_length * HOST_CHAR_BIT, 0,
14142 "storage_offset");
14143 }
14144
14145 lai->bool_type_symbol = NULL;
14146 lai->bool_type_default = builtin->builtin_bool;
14147 }
14148 \f
14149 /* Language vector */
14150
14151 /* Not really used, but needed in the ada_language_defn. */
14152
14153 static void
14154 emit_char (int c, struct type *type, struct ui_file *stream, int quoter)
14155 {
14156 ada_emit_char (c, type, stream, quoter, 1);
14157 }
14158
14159 static int
14160 parse (struct parser_state *ps)
14161 {
14162 warnings_issued = 0;
14163 return ada_parse (ps);
14164 }
14165
14166 static const struct exp_descriptor ada_exp_descriptor = {
14167 ada_print_subexp,
14168 ada_operator_length,
14169 ada_operator_check,
14170 ada_op_name,
14171 ada_dump_subexp_body,
14172 ada_evaluate_subexp
14173 };
14174
14175 /* symbol_name_matcher_ftype adapter for wild_match. */
14176
14177 static bool
14178 do_wild_match (const char *symbol_search_name,
14179 const lookup_name_info &lookup_name,
14180 completion_match_result *comp_match_res)
14181 {
14182 return wild_match (symbol_search_name, ada_lookup_name (lookup_name));
14183 }
14184
14185 /* symbol_name_matcher_ftype adapter for full_match. */
14186
14187 static bool
14188 do_full_match (const char *symbol_search_name,
14189 const lookup_name_info &lookup_name,
14190 completion_match_result *comp_match_res)
14191 {
14192 return full_match (symbol_search_name, ada_lookup_name (lookup_name));
14193 }
14194
14195 /* symbol_name_matcher_ftype for exact (verbatim) matches. */
14196
14197 static bool
14198 do_exact_match (const char *symbol_search_name,
14199 const lookup_name_info &lookup_name,
14200 completion_match_result *comp_match_res)
14201 {
14202 return strcmp (symbol_search_name, ada_lookup_name (lookup_name)) == 0;
14203 }
14204
14205 /* Build the Ada lookup name for LOOKUP_NAME. */
14206
14207 ada_lookup_name_info::ada_lookup_name_info (const lookup_name_info &lookup_name)
14208 {
14209 const std::string &user_name = lookup_name.name ();
14210
14211 if (user_name[0] == '<')
14212 {
14213 if (user_name.back () == '>')
14214 m_encoded_name = user_name.substr (1, user_name.size () - 2);
14215 else
14216 m_encoded_name = user_name.substr (1, user_name.size () - 1);
14217 m_encoded_p = true;
14218 m_verbatim_p = true;
14219 m_wild_match_p = false;
14220 m_standard_p = false;
14221 }
14222 else
14223 {
14224 m_verbatim_p = false;
14225
14226 m_encoded_p = user_name.find ("__") != std::string::npos;
14227
14228 if (!m_encoded_p)
14229 {
14230 const char *folded = ada_fold_name (user_name.c_str ());
14231 const char *encoded = ada_encode_1 (folded, false);
14232 if (encoded != NULL)
14233 m_encoded_name = encoded;
14234 else
14235 m_encoded_name = user_name;
14236 }
14237 else
14238 m_encoded_name = user_name;
14239
14240 /* Handle the 'package Standard' special case. See description
14241 of m_standard_p. */
14242 if (startswith (m_encoded_name.c_str (), "standard__"))
14243 {
14244 m_encoded_name = m_encoded_name.substr (sizeof ("standard__") - 1);
14245 m_standard_p = true;
14246 }
14247 else
14248 m_standard_p = false;
14249
14250 /* If the name contains a ".", then the user is entering a fully
14251 qualified entity name, and the match must not be done in wild
14252 mode. Similarly, if the user wants to complete what looks
14253 like an encoded name, the match must not be done in wild
14254 mode. Also, in the standard__ special case always do
14255 non-wild matching. */
14256 m_wild_match_p
14257 = (lookup_name.match_type () != symbol_name_match_type::FULL
14258 && !m_encoded_p
14259 && !m_standard_p
14260 && user_name.find ('.') == std::string::npos);
14261 }
14262 }
14263
14264 /* symbol_name_matcher_ftype method for Ada. This only handles
14265 completion mode. */
14266
14267 static bool
14268 ada_symbol_name_matches (const char *symbol_search_name,
14269 const lookup_name_info &lookup_name,
14270 completion_match_result *comp_match_res)
14271 {
14272 return lookup_name.ada ().matches (symbol_search_name,
14273 lookup_name.match_type (),
14274 comp_match_res);
14275 }
14276
14277 /* A name matcher that matches the symbol name exactly, with
14278 strcmp. */
14279
14280 static bool
14281 literal_symbol_name_matcher (const char *symbol_search_name,
14282 const lookup_name_info &lookup_name,
14283 completion_match_result *comp_match_res)
14284 {
14285 const std::string &name = lookup_name.name ();
14286
14287 int cmp = (lookup_name.completion_mode ()
14288 ? strncmp (symbol_search_name, name.c_str (), name.size ())
14289 : strcmp (symbol_search_name, name.c_str ()));
14290 if (cmp == 0)
14291 {
14292 if (comp_match_res != NULL)
14293 comp_match_res->set_match (symbol_search_name);
14294 return true;
14295 }
14296 else
14297 return false;
14298 }
14299
14300 /* Implement the "la_get_symbol_name_matcher" language_defn method for
14301 Ada. */
14302
14303 static symbol_name_matcher_ftype *
14304 ada_get_symbol_name_matcher (const lookup_name_info &lookup_name)
14305 {
14306 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
14307 return literal_symbol_name_matcher;
14308
14309 if (lookup_name.completion_mode ())
14310 return ada_symbol_name_matches;
14311 else
14312 {
14313 if (lookup_name.ada ().wild_match_p ())
14314 return do_wild_match;
14315 else if (lookup_name.ada ().verbatim_p ())
14316 return do_exact_match;
14317 else
14318 return do_full_match;
14319 }
14320 }
14321
14322 /* Implement the "la_read_var_value" language_defn method for Ada. */
14323
14324 static struct value *
14325 ada_read_var_value (struct symbol *var, const struct block *var_block,
14326 struct frame_info *frame)
14327 {
14328 const struct block *frame_block = NULL;
14329 struct symbol *renaming_sym = NULL;
14330
14331 /* The only case where default_read_var_value is not sufficient
14332 is when VAR is a renaming... */
14333 if (frame)
14334 frame_block = get_frame_block (frame, NULL);
14335 if (frame_block)
14336 renaming_sym = ada_find_renaming_symbol (var, frame_block);
14337 if (renaming_sym != NULL)
14338 return ada_read_renaming_var_value (renaming_sym, frame_block);
14339
14340 /* This is a typical case where we expect the default_read_var_value
14341 function to work. */
14342 return default_read_var_value (var, var_block, frame);
14343 }
14344
14345 static const char *ada_extensions[] =
14346 {
14347 ".adb", ".ads", ".a", ".ada", ".dg", NULL
14348 };
14349
14350 extern const struct language_defn ada_language_defn = {
14351 "ada", /* Language name */
14352 "Ada",
14353 language_ada,
14354 range_check_off,
14355 case_sensitive_on, /* Yes, Ada is case-insensitive, but
14356 that's not quite what this means. */
14357 array_row_major,
14358 macro_expansion_no,
14359 ada_extensions,
14360 &ada_exp_descriptor,
14361 parse,
14362 resolve,
14363 ada_printchar, /* Print a character constant */
14364 ada_printstr, /* Function to print string constant */
14365 emit_char, /* Function to print single char (not used) */
14366 ada_print_type, /* Print a type using appropriate syntax */
14367 ada_print_typedef, /* Print a typedef using appropriate syntax */
14368 ada_val_print, /* Print a value using appropriate syntax */
14369 ada_value_print, /* Print a top-level value */
14370 ada_read_var_value, /* la_read_var_value */
14371 NULL, /* Language specific skip_trampoline */
14372 NULL, /* name_of_this */
14373 true, /* la_store_sym_names_in_linkage_form_p */
14374 ada_lookup_symbol_nonlocal, /* Looking up non-local symbols. */
14375 basic_lookup_transparent_type, /* lookup_transparent_type */
14376 ada_la_decode, /* Language specific symbol demangler */
14377 ada_sniff_from_mangled_name,
14378 NULL, /* Language specific
14379 class_name_from_physname */
14380 ada_op_print_tab, /* expression operators for printing */
14381 0, /* c-style arrays */
14382 1, /* String lower bound */
14383 ada_get_gdb_completer_word_break_characters,
14384 ada_collect_symbol_completion_matches,
14385 ada_language_arch_info,
14386 ada_print_array_index,
14387 default_pass_by_reference,
14388 c_get_string,
14389 ada_watch_location_expression,
14390 ada_get_symbol_name_matcher, /* la_get_symbol_name_matcher */
14391 ada_iterate_over_symbols,
14392 default_search_name_hash,
14393 &ada_varobj_ops,
14394 NULL,
14395 NULL,
14396 LANG_MAGIC
14397 };
14398
14399 /* Command-list for the "set/show ada" prefix command. */
14400 static struct cmd_list_element *set_ada_list;
14401 static struct cmd_list_element *show_ada_list;
14402
14403 /* Implement the "set ada" prefix command. */
14404
14405 static void
14406 set_ada_command (const char *arg, int from_tty)
14407 {
14408 printf_unfiltered (_(\
14409 "\"set ada\" must be followed by the name of a setting.\n"));
14410 help_list (set_ada_list, "set ada ", all_commands, gdb_stdout);
14411 }
14412
14413 /* Implement the "show ada" prefix command. */
14414
14415 static void
14416 show_ada_command (const char *args, int from_tty)
14417 {
14418 cmd_show_list (show_ada_list, from_tty, "");
14419 }
14420
14421 static void
14422 initialize_ada_catchpoint_ops (void)
14423 {
14424 struct breakpoint_ops *ops;
14425
14426 initialize_breakpoint_ops ();
14427
14428 ops = &catch_exception_breakpoint_ops;
14429 *ops = bkpt_breakpoint_ops;
14430 ops->allocate_location = allocate_location_catch_exception;
14431 ops->re_set = re_set_catch_exception;
14432 ops->check_status = check_status_catch_exception;
14433 ops->print_it = print_it_catch_exception;
14434 ops->print_one = print_one_catch_exception;
14435 ops->print_mention = print_mention_catch_exception;
14436 ops->print_recreate = print_recreate_catch_exception;
14437
14438 ops = &catch_exception_unhandled_breakpoint_ops;
14439 *ops = bkpt_breakpoint_ops;
14440 ops->allocate_location = allocate_location_catch_exception_unhandled;
14441 ops->re_set = re_set_catch_exception_unhandled;
14442 ops->check_status = check_status_catch_exception_unhandled;
14443 ops->print_it = print_it_catch_exception_unhandled;
14444 ops->print_one = print_one_catch_exception_unhandled;
14445 ops->print_mention = print_mention_catch_exception_unhandled;
14446 ops->print_recreate = print_recreate_catch_exception_unhandled;
14447
14448 ops = &catch_assert_breakpoint_ops;
14449 *ops = bkpt_breakpoint_ops;
14450 ops->allocate_location = allocate_location_catch_assert;
14451 ops->re_set = re_set_catch_assert;
14452 ops->check_status = check_status_catch_assert;
14453 ops->print_it = print_it_catch_assert;
14454 ops->print_one = print_one_catch_assert;
14455 ops->print_mention = print_mention_catch_assert;
14456 ops->print_recreate = print_recreate_catch_assert;
14457
14458 ops = &catch_handlers_breakpoint_ops;
14459 *ops = bkpt_breakpoint_ops;
14460 ops->allocate_location = allocate_location_catch_handlers;
14461 ops->re_set = re_set_catch_handlers;
14462 ops->check_status = check_status_catch_handlers;
14463 ops->print_it = print_it_catch_handlers;
14464 ops->print_one = print_one_catch_handlers;
14465 ops->print_mention = print_mention_catch_handlers;
14466 ops->print_recreate = print_recreate_catch_handlers;
14467 }
14468
14469 /* This module's 'new_objfile' observer. */
14470
14471 static void
14472 ada_new_objfile_observer (struct objfile *objfile)
14473 {
14474 ada_clear_symbol_cache ();
14475 }
14476
14477 /* This module's 'free_objfile' observer. */
14478
14479 static void
14480 ada_free_objfile_observer (struct objfile *objfile)
14481 {
14482 ada_clear_symbol_cache ();
14483 }
14484
14485 void
14486 _initialize_ada_language (void)
14487 {
14488 initialize_ada_catchpoint_ops ();
14489
14490 add_prefix_cmd ("ada", no_class, set_ada_command,
14491 _("Prefix command for changing Ada-specific settings"),
14492 &set_ada_list, "set ada ", 0, &setlist);
14493
14494 add_prefix_cmd ("ada", no_class, show_ada_command,
14495 _("Generic command for showing Ada-specific settings."),
14496 &show_ada_list, "show ada ", 0, &showlist);
14497
14498 add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
14499 &trust_pad_over_xvs, _("\
14500 Enable or disable an optimization trusting PAD types over XVS types"), _("\
14501 Show whether an optimization trusting PAD types over XVS types is activated"),
14502 _("\
14503 This is related to the encoding used by the GNAT compiler. The debugger\n\
14504 should normally trust the contents of PAD types, but certain older versions\n\
14505 of GNAT have a bug that sometimes causes the information in the PAD type\n\
14506 to be incorrect. Turning this setting \"off\" allows the debugger to\n\
14507 work around this bug. It is always safe to turn this option \"off\", but\n\
14508 this incurs a slight performance penalty, so it is recommended to NOT change\n\
14509 this option to \"off\" unless necessary."),
14510 NULL, NULL, &set_ada_list, &show_ada_list);
14511
14512 add_setshow_boolean_cmd ("print-signatures", class_vars,
14513 &print_signatures, _("\
14514 Enable or disable the output of formal and return types for functions in the \
14515 overloads selection menu"), _("\
14516 Show whether the output of formal and return types for functions in the \
14517 overloads selection menu is activated"),
14518 NULL, NULL, NULL, &set_ada_list, &show_ada_list);
14519
14520 add_catch_command ("exception", _("\
14521 Catch Ada exceptions, when raised.\n\
14522 Usage: catch exception [ ARG ]\n\
14523 \n\
14524 Without any argument, stop when any Ada exception is raised.\n\
14525 If ARG is \"unhandled\" (without the quotes), only stop when the exception\n\
14526 being raised does not have a handler (and will therefore lead to the task's\n\
14527 termination).\n\
14528 Otherwise, the catchpoint only stops when the name of the exception being\n\
14529 raised is the same as ARG."),
14530 catch_ada_exception_command,
14531 NULL,
14532 CATCH_PERMANENT,
14533 CATCH_TEMPORARY);
14534
14535 add_catch_command ("handlers", _("\
14536 Catch Ada exceptions, when handled.\n\
14537 With an argument, catch only exceptions with the given name."),
14538 catch_ada_handlers_command,
14539 NULL,
14540 CATCH_PERMANENT,
14541 CATCH_TEMPORARY);
14542 add_catch_command ("assert", _("\
14543 Catch failed Ada assertions, when raised.\n\
14544 With an argument, catch only exceptions with the given name."),
14545 catch_assert_command,
14546 NULL,
14547 CATCH_PERMANENT,
14548 CATCH_TEMPORARY);
14549
14550 varsize_limit = 65536;
14551 add_setshow_uinteger_cmd ("varsize-limit", class_support,
14552 &varsize_limit, _("\
14553 Set the maximum number of bytes allowed in a variable-size object."), _("\
14554 Show the maximum number of bytes allowed in a variable-size object."), _("\
14555 Attempts to access an object whose size is not a compile-time constant\n\
14556 and exceeds this limit will cause an error."),
14557 NULL, NULL, &setlist, &showlist);
14558
14559 add_info ("exceptions", info_exceptions_command,
14560 _("\
14561 List all Ada exception names.\n\
14562 If a regular expression is passed as an argument, only those matching\n\
14563 the regular expression are listed."));
14564
14565 add_prefix_cmd ("ada", class_maintenance, maint_set_ada_cmd,
14566 _("Set Ada maintenance-related variables."),
14567 &maint_set_ada_cmdlist, "maintenance set ada ",
14568 0/*allow-unknown*/, &maintenance_set_cmdlist);
14569
14570 add_prefix_cmd ("ada", class_maintenance, maint_show_ada_cmd,
14571 _("Show Ada maintenance-related variables"),
14572 &maint_show_ada_cmdlist, "maintenance show ada ",
14573 0/*allow-unknown*/, &maintenance_show_cmdlist);
14574
14575 add_setshow_boolean_cmd
14576 ("ignore-descriptive-types", class_maintenance,
14577 &ada_ignore_descriptive_types_p,
14578 _("Set whether descriptive types generated by GNAT should be ignored."),
14579 _("Show whether descriptive types generated by GNAT should be ignored."),
14580 _("\
14581 When enabled, the debugger will stop using the DW_AT_GNAT_descriptive_type\n\
14582 DWARF attribute."),
14583 NULL, NULL, &maint_set_ada_cmdlist, &maint_show_ada_cmdlist);
14584
14585 decoded_names_store = htab_create_alloc (256, htab_hash_string, streq_hash,
14586 NULL, xcalloc, xfree);
14587
14588 /* The ada-lang observers. */
14589 gdb::observers::new_objfile.attach (ada_new_objfile_observer);
14590 gdb::observers::free_objfile.attach (ada_free_objfile_observer);
14591 gdb::observers::inferior_exit.attach (ada_inferior_exit);
14592
14593 /* Setup various context-specific data. */
14594 ada_inferior_data
14595 = register_inferior_data_with_cleanup (NULL, ada_inferior_data_cleanup);
14596 ada_pspace_data_handle
14597 = register_program_space_data_with_cleanup (NULL, ada_pspace_data_cleanup);
14598 }
This page took 0.48756 seconds and 5 git commands to generate.