Minor simplification in tui_default_win_viewport_height
[external/binutils.git] / gdb / target-descriptions.c
1 /* Target description support for GDB.
2
3    Copyright (C) 2006-2019 Free Software Foundation, Inc.
4
5    Contributed by CodeSourcery.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "arch-utils.h"
24 #include "gdbcmd.h"
25 #include "gdbtypes.h"
26 #include "reggroups.h"
27 #include "target.h"
28 #include "target-descriptions.h"
29 #include "gdbsupport/vec.h"
30 #include "xml-support.h"
31 #include "xml-tdesc.h"
32 #include "osabi.h"
33
34 #include "gdb_obstack.h"
35 #include "hashtab.h"
36 #include "inferior.h"
37 #include <algorithm>
38 #include "completer.h"
39 #include "readline/tilde.h" /* tilde_expand */
40
41 /* Types.  */
42
43 struct property
44 {
45   property (const std::string &key_, const std::string &value_)
46   : key (key_), value (value_)
47   {}
48
49   std::string key;
50   std::string value;
51 };
52
53 /* Convert a tdesc_type to a gdb type.  */
54
55 static type *
56 make_gdb_type (struct gdbarch *gdbarch, struct tdesc_type *ttype)
57 {
58   class gdb_type_creator : public tdesc_element_visitor
59   {
60   public:
61     gdb_type_creator (struct gdbarch *gdbarch)
62       : m_gdbarch (gdbarch)
63     {}
64
65     type *get_type ()
66     {
67       return m_type;
68     }
69
70     void visit (const tdesc_type_builtin *e) override
71     {
72       switch (e->kind)
73         {
74           /* Predefined types.  */
75         case TDESC_TYPE_BOOL:
76           m_type = builtin_type (m_gdbarch)->builtin_bool;
77           return;
78         case TDESC_TYPE_INT8:
79           m_type = builtin_type (m_gdbarch)->builtin_int8;
80           return;
81         case TDESC_TYPE_INT16:
82           m_type = builtin_type (m_gdbarch)->builtin_int16;
83           return;
84         case TDESC_TYPE_INT32:
85           m_type = builtin_type (m_gdbarch)->builtin_int32;
86           return;
87         case TDESC_TYPE_INT64:
88           m_type = builtin_type (m_gdbarch)->builtin_int64;
89           return;
90         case TDESC_TYPE_INT128:
91           m_type = builtin_type (m_gdbarch)->builtin_int128;
92           return;
93         case TDESC_TYPE_UINT8:
94           m_type = builtin_type (m_gdbarch)->builtin_uint8;
95           return;
96         case TDESC_TYPE_UINT16:
97           m_type = builtin_type (m_gdbarch)->builtin_uint16;
98           return;
99         case TDESC_TYPE_UINT32:
100           m_type = builtin_type (m_gdbarch)->builtin_uint32;
101           return;
102         case TDESC_TYPE_UINT64:
103           m_type = builtin_type (m_gdbarch)->builtin_uint64;
104           return;
105         case TDESC_TYPE_UINT128:
106           m_type = builtin_type (m_gdbarch)->builtin_uint128;
107           return;
108         case TDESC_TYPE_CODE_PTR:
109           m_type = builtin_type (m_gdbarch)->builtin_func_ptr;
110           return;
111         case TDESC_TYPE_DATA_PTR:
112           m_type = builtin_type (m_gdbarch)->builtin_data_ptr;
113           return;
114         }
115
116       m_type = tdesc_find_type (m_gdbarch, e->name.c_str ());
117       if (m_type != NULL)
118         return;
119
120       switch (e->kind)
121         {
122         case TDESC_TYPE_IEEE_HALF:
123           m_type = arch_float_type (m_gdbarch, -1, "builtin_type_ieee_half",
124                                     floatformats_ieee_half);
125           return;
126
127         case TDESC_TYPE_IEEE_SINGLE:
128           m_type = arch_float_type (m_gdbarch, -1, "builtin_type_ieee_single",
129                                     floatformats_ieee_single);
130           return;
131
132         case TDESC_TYPE_IEEE_DOUBLE:
133           m_type = arch_float_type (m_gdbarch, -1, "builtin_type_ieee_double",
134                                     floatformats_ieee_double);
135           return;
136         case TDESC_TYPE_ARM_FPA_EXT:
137           m_type = arch_float_type (m_gdbarch, -1, "builtin_type_arm_ext",
138                                     floatformats_arm_ext);
139           return;
140
141         case TDESC_TYPE_I387_EXT:
142           m_type = arch_float_type (m_gdbarch, -1, "builtin_type_i387_ext",
143                                     floatformats_i387_ext);
144           return;
145         }
146
147       internal_error (__FILE__, __LINE__,
148                       "Type \"%s\" has an unknown kind %d",
149                       e->name.c_str (), e->kind);
150     }
151
152     void visit (const tdesc_type_vector *e) override
153     {
154       m_type = tdesc_find_type (m_gdbarch, e->name.c_str ());
155       if (m_type != NULL)
156         return;
157
158       type *element_gdb_type = make_gdb_type (m_gdbarch, e->element_type);
159       m_type = init_vector_type (element_gdb_type, e->count);
160       TYPE_NAME (m_type) = xstrdup (e->name.c_str ());
161       return;
162     }
163
164     void visit (const tdesc_type_with_fields *e) override
165     {
166       m_type = tdesc_find_type (m_gdbarch, e->name.c_str ());
167       if (m_type != NULL)
168         return;
169
170       switch (e->kind)
171         {
172         case TDESC_TYPE_STRUCT:
173           make_gdb_type_struct (e);
174           return;
175         case TDESC_TYPE_UNION:
176           make_gdb_type_union (e);
177           return;
178         case TDESC_TYPE_FLAGS:
179           make_gdb_type_flags (e);
180           return;
181         case TDESC_TYPE_ENUM:
182           make_gdb_type_enum (e);
183           return;
184         }
185
186       internal_error (__FILE__, __LINE__,
187                       "Type \"%s\" has an unknown kind %d",
188                       e->name.c_str (), e->kind);
189     }
190
191   private:
192
193     void make_gdb_type_struct (const tdesc_type_with_fields *e)
194     {
195       m_type = arch_composite_type (m_gdbarch, NULL, TYPE_CODE_STRUCT);
196       TYPE_NAME (m_type) = xstrdup (e->name.c_str ());
197
198       for (const tdesc_type_field &f : e->fields)
199         {
200           if (f.start != -1 && f.end != -1)
201             {
202               /* Bitfield.  */
203               struct field *fld;
204               struct type *field_gdb_type;
205               int bitsize, total_size;
206
207               /* This invariant should be preserved while creating types.  */
208               gdb_assert (e->size != 0);
209               if (f.type != NULL)
210                 field_gdb_type = make_gdb_type (m_gdbarch, f.type);
211               else if (e->size > 4)
212                 field_gdb_type = builtin_type (m_gdbarch)->builtin_uint64;
213               else
214                 field_gdb_type = builtin_type (m_gdbarch)->builtin_uint32;
215
216               fld = append_composite_type_field_raw
217                       (m_type, xstrdup (f.name.c_str ()), field_gdb_type);
218
219               /* For little-endian, BITPOS counts from the LSB of
220                  the structure and marks the LSB of the field.  For
221                  big-endian, BITPOS counts from the MSB of the
222                  structure and marks the MSB of the field.  Either
223                  way, it is the number of bits to the "left" of the
224                  field.  To calculate this in big-endian, we need
225                  the total size of the structure.  */
226               bitsize = f.end - f.start + 1;
227               total_size = e->size * TARGET_CHAR_BIT;
228               if (gdbarch_bits_big_endian (m_gdbarch))
229                 SET_FIELD_BITPOS (fld[0], total_size - f.start - bitsize);
230               else
231                 SET_FIELD_BITPOS (fld[0], f.start);
232               FIELD_BITSIZE (fld[0]) = bitsize;
233             }
234           else
235             {
236               gdb_assert (f.start == -1 && f.end == -1);
237               type *field_gdb_type = make_gdb_type (m_gdbarch, f.type);
238               append_composite_type_field (m_type,
239                                            xstrdup (f.name.c_str ()),
240                                            field_gdb_type);
241             }
242         }
243
244       if (e->size != 0)
245         TYPE_LENGTH (m_type) = e->size;
246     }
247
248     void make_gdb_type_union (const tdesc_type_with_fields *e)
249     {
250       m_type = arch_composite_type (m_gdbarch, NULL, TYPE_CODE_UNION);
251       TYPE_NAME (m_type) = xstrdup (e->name.c_str ());
252
253       for (const tdesc_type_field &f : e->fields)
254         {
255           type* field_gdb_type = make_gdb_type (m_gdbarch, f.type);
256           append_composite_type_field (m_type, xstrdup (f.name.c_str ()),
257                                        field_gdb_type);
258
259           /* If any of the children of a union are vectors, flag the
260              union as a vector also.  This allows e.g. a union of two
261              vector types to show up automatically in "info vector".  */
262           if (TYPE_VECTOR (field_gdb_type))
263             TYPE_VECTOR (m_type) = 1;
264         }
265     }
266
267     void make_gdb_type_flags (const tdesc_type_with_fields *e)
268     {
269       m_type = arch_flags_type (m_gdbarch, e->name.c_str (),
270                                 e->size * TARGET_CHAR_BIT);
271
272       for (const tdesc_type_field &f : e->fields)
273         {
274           int bitsize = f.end - f.start + 1;
275
276           gdb_assert (f.type != NULL);
277           type *field_gdb_type = make_gdb_type (m_gdbarch, f.type);
278           append_flags_type_field (m_type, f.start, bitsize,
279                                    field_gdb_type, f.name.c_str ());
280         }
281     }
282
283     void make_gdb_type_enum (const tdesc_type_with_fields *e)
284     {
285       m_type = arch_type (m_gdbarch, TYPE_CODE_ENUM, e->size * TARGET_CHAR_BIT,
286                           e->name.c_str ());
287
288       TYPE_UNSIGNED (m_type) = 1;
289       for (const tdesc_type_field &f : e->fields)
290         {
291           struct field *fld
292             = append_composite_type_field_raw (m_type,
293                                                xstrdup (f.name.c_str ()),
294                                                NULL);
295
296           SET_FIELD_BITPOS (fld[0], f.start);
297         }
298     }
299
300     /* The gdbarch used.  */
301     struct gdbarch *m_gdbarch;
302
303     /* The type created.  */
304     type *m_type;
305   };
306
307   gdb_type_creator gdb_type (gdbarch);
308   ttype->accept (gdb_type);
309   return gdb_type.get_type ();
310 }
311
312 /* A target description.  */
313
314 struct target_desc : tdesc_element
315 {
316   target_desc ()
317   {}
318
319   virtual ~target_desc () = default;
320
321   target_desc (const target_desc &) = delete;
322   void operator= (const target_desc &) = delete;
323
324   /* The architecture reported by the target, if any.  */
325   const struct bfd_arch_info *arch = NULL;
326
327   /* The osabi reported by the target, if any; GDB_OSABI_UNKNOWN
328      otherwise.  */
329   enum gdb_osabi osabi = GDB_OSABI_UNKNOWN;
330
331   /* The list of compatible architectures reported by the target.  */
332   std::vector<const bfd_arch_info *> compatible;
333
334   /* Any architecture-specific properties specified by the target.  */
335   std::vector<property> properties;
336
337   /* The features associated with this target.  */
338   std::vector<tdesc_feature_up> features;
339
340   /* Used to cache the generated xml version of the target description.  */
341   mutable char *xmltarget = nullptr;
342
343   void accept (tdesc_element_visitor &v) const override
344   {
345     v.visit_pre (this);
346
347     for (const tdesc_feature_up &feature : features)
348       feature->accept (v);
349
350     v.visit_post (this);
351   }
352
353   bool operator== (const target_desc &other) const
354   {
355     if (arch != other.arch)
356       return false;
357
358     if (osabi != other.osabi)
359       return false;
360
361     if (features.size () != other.features.size ())
362       return false;
363
364     for (int ix = 0; ix < features.size (); ix++)
365       {
366         const tdesc_feature_up &feature1 = features[ix];
367         const tdesc_feature_up &feature2 = other.features[ix];
368
369         if (feature1 != feature2 && *feature1 != *feature2)
370           return false;
371       }
372
373     return true;
374   }
375
376   bool operator!= (const target_desc &other) const
377   {
378     return !(*this == other);
379   }
380 };
381
382 /* Per-architecture data associated with a target description.  The
383    target description may be shared by multiple architectures, but
384    this data is private to one gdbarch.  */
385
386 struct tdesc_arch_reg
387 {
388   tdesc_arch_reg (tdesc_reg *reg_, struct type *type_)
389   : reg (reg_), type (type_)
390   {}
391
392   struct tdesc_reg *reg;
393   struct type *type;
394 };
395
396 struct tdesc_arch_data
397 {
398   /* A list of register/type pairs, indexed by GDB's internal register number.
399      During initialization of the gdbarch this list is used to store
400      registers which the architecture assigns a fixed register number.
401      Registers which are NULL in this array, or off the end, are
402      treated as zero-sized and nameless (i.e. placeholders in the
403      numbering).  */
404   std::vector<tdesc_arch_reg> arch_regs;
405
406   /* Functions which report the register name, type, and reggroups for
407      pseudo-registers.  */
408   gdbarch_register_name_ftype *pseudo_register_name = NULL;
409   gdbarch_register_type_ftype *pseudo_register_type = NULL;
410   gdbarch_register_reggroup_p_ftype *pseudo_register_reggroup_p = NULL;
411 };
412
413 /* Info about an inferior's target description.  There's one of these
414    for each inferior.  */
415
416 struct target_desc_info
417 {
418   /* A flag indicating that a description has already been fetched
419      from the target, so it should not be queried again.  */
420
421   int fetched;
422
423   /* The description fetched from the target, or NULL if the target
424      did not supply any description.  Only valid when
425      target_desc_fetched is set.  Only the description initialization
426      code should access this; normally, the description should be
427      accessed through the gdbarch object.  */
428
429   const struct target_desc *tdesc;
430
431   /* The filename to read a target description from, as set by "set
432      tdesc filename ..."  */
433
434   char *filename;
435 };
436
437 /* Get the inferior INF's target description info, allocating one on
438    the stop if necessary.  */
439
440 static struct target_desc_info *
441 get_tdesc_info (struct inferior *inf)
442 {
443   if (inf->tdesc_info == NULL)
444     inf->tdesc_info = XCNEW (struct target_desc_info);
445   return inf->tdesc_info;
446 }
447
448 /* A handle for architecture-specific data associated with the
449    target description (see struct tdesc_arch_data).  */
450
451 static struct gdbarch_data *tdesc_data;
452
453 /* See target-descriptions.h.  */
454
455 int
456 target_desc_info_from_user_p (struct target_desc_info *info)
457 {
458   return info != NULL && info->filename != NULL;
459 }
460
461 /* See target-descriptions.h.  */
462
463 void
464 copy_inferior_target_desc_info (struct inferior *destinf, struct inferior *srcinf)
465 {
466   struct target_desc_info *src = get_tdesc_info (srcinf);
467   struct target_desc_info *dest = get_tdesc_info (destinf);
468
469   dest->fetched = src->fetched;
470   dest->tdesc = src->tdesc;
471   dest->filename = src->filename != NULL ? xstrdup (src->filename) : NULL;
472 }
473
474 /* See target-descriptions.h.  */
475
476 void
477 target_desc_info_free (struct target_desc_info *tdesc_info)
478 {
479   if (tdesc_info != NULL)
480     {
481       xfree (tdesc_info->filename);
482       xfree (tdesc_info);
483     }
484 }
485
486 /* Convenience helper macros.  */
487
488 #define target_desc_fetched \
489   get_tdesc_info (current_inferior ())->fetched
490 #define current_target_desc \
491   get_tdesc_info (current_inferior ())->tdesc
492 #define target_description_filename \
493   get_tdesc_info (current_inferior ())->filename
494
495 /* The string manipulated by the "set tdesc filename ..." command.  */
496
497 static char *tdesc_filename_cmd_string;
498
499 /* Fetch the current target's description, and switch the current
500    architecture to one which incorporates that description.  */
501
502 void
503 target_find_description (void)
504 {
505   /* If we've already fetched a description from the target, don't do
506      it again.  This allows a target to fetch the description early,
507      during its to_open or to_create_inferior, if it needs extra
508      information about the target to initialize.  */
509   if (target_desc_fetched)
510     return;
511
512   /* The current architecture should not have any target description
513      specified.  It should have been cleared, e.g. when we
514      disconnected from the previous target.  */
515   gdb_assert (gdbarch_target_desc (target_gdbarch ()) == NULL);
516
517   /* First try to fetch an XML description from the user-specified
518      file.  */
519   current_target_desc = NULL;
520   if (target_description_filename != NULL
521       && *target_description_filename != '\0')
522     current_target_desc
523       = file_read_description_xml (target_description_filename);
524
525   /* Next try to read the description from the current target using
526      target objects.  */
527   if (current_target_desc == NULL)
528     current_target_desc = target_read_description_xml (current_top_target ());
529
530   /* If that failed try a target-specific hook.  */
531   if (current_target_desc == NULL)
532     current_target_desc = target_read_description (current_top_target ());
533
534   /* If a non-NULL description was returned, then update the current
535      architecture.  */
536   if (current_target_desc)
537     {
538       struct gdbarch_info info;
539
540       gdbarch_info_init (&info);
541       info.target_desc = current_target_desc;
542       if (!gdbarch_update_p (info))
543         warning (_("Architecture rejected target-supplied description"));
544       else
545         {
546           struct tdesc_arch_data *data;
547
548           data = ((struct tdesc_arch_data *)
549                   gdbarch_data (target_gdbarch (), tdesc_data));
550           if (tdesc_has_registers (current_target_desc)
551               && data->arch_regs.empty ())
552             warning (_("Target-supplied registers are not supported "
553                        "by the current architecture"));
554         }
555     }
556
557   /* Now that we know this description is usable, record that we
558      fetched it.  */
559   target_desc_fetched = 1;
560 }
561
562 /* Discard any description fetched from the current target, and switch
563    the current architecture to one with no target description.  */
564
565 void
566 target_clear_description (void)
567 {
568   struct gdbarch_info info;
569
570   if (!target_desc_fetched)
571     return;
572
573   target_desc_fetched = 0;
574   current_target_desc = NULL;
575
576   gdbarch_info_init (&info);
577   if (!gdbarch_update_p (info))
578     internal_error (__FILE__, __LINE__,
579                     _("Could not remove target-supplied description"));
580 }
581
582 /* Return the global current target description.  This should only be
583    used by gdbarch initialization code; most access should be through
584    an existing gdbarch.  */
585
586 const struct target_desc *
587 target_current_description (void)
588 {
589   if (target_desc_fetched)
590     return current_target_desc;
591
592   return NULL;
593 }
594
595 /* Return non-zero if this target description is compatible
596    with the given BFD architecture.  */
597
598 int
599 tdesc_compatible_p (const struct target_desc *target_desc,
600                     const struct bfd_arch_info *arch)
601 {
602   for (const bfd_arch_info *compat : target_desc->compatible)
603     {
604       if (compat == arch
605           || arch->compatible (arch, compat)
606           || compat->compatible (compat, arch))
607         return 1;
608     }
609
610   return 0;
611 }
612 \f
613
614 /* Direct accessors for target descriptions.  */
615
616 /* Return the string value of a property named KEY, or NULL if the
617    property was not specified.  */
618
619 const char *
620 tdesc_property (const struct target_desc *target_desc, const char *key)
621 {
622   for (const property &prop : target_desc->properties)
623     if (prop.key == key)
624       return prop.value.c_str ();
625
626   return NULL;
627 }
628
629 /* Return the BFD architecture associated with this target
630    description, or NULL if no architecture was specified.  */
631
632 const struct bfd_arch_info *
633 tdesc_architecture (const struct target_desc *target_desc)
634 {
635   return target_desc->arch;
636 }
637
638 /* See gdbsupport/tdesc.h.  */
639
640 const char *
641 tdesc_architecture_name (const struct target_desc *target_desc)
642 {
643   return target_desc->arch->printable_name;
644 }
645
646 /* Return the OSABI associated with this target description, or
647    GDB_OSABI_UNKNOWN if no osabi was specified.  */
648
649 enum gdb_osabi
650 tdesc_osabi (const struct target_desc *target_desc)
651 {
652   return target_desc->osabi;
653 }
654
655 /* See gdbsupport/tdesc.h.  */
656
657 const char *
658 tdesc_osabi_name (const struct target_desc *target_desc)
659 {
660   enum gdb_osabi osabi = tdesc_osabi (target_desc);
661   if (osabi > GDB_OSABI_UNKNOWN && osabi < GDB_OSABI_INVALID)
662     return gdbarch_osabi_name (osabi);
663   return nullptr;
664 }
665
666 /* Return 1 if this target description includes any registers.  */
667
668 int
669 tdesc_has_registers (const struct target_desc *target_desc)
670 {
671   if (target_desc == NULL)
672     return 0;
673
674   for (const tdesc_feature_up &feature : target_desc->features)
675     if (!feature->registers.empty ())
676       return 1;
677
678   return 0;
679 }
680
681 /* Return the feature with the given name, if present, or NULL if
682    the named feature is not found.  */
683
684 const struct tdesc_feature *
685 tdesc_find_feature (const struct target_desc *target_desc,
686                     const char *name)
687 {
688   for (const tdesc_feature_up &feature : target_desc->features)
689     if (feature->name == name)
690       return feature.get ();
691
692   return NULL;
693 }
694
695 /* Return the name of FEATURE.  */
696
697 const char *
698 tdesc_feature_name (const struct tdesc_feature *feature)
699 {
700   return feature->name.c_str ();
701 }
702
703 /* Lookup type associated with ID.  */
704
705 struct type *
706 tdesc_find_type (struct gdbarch *gdbarch, const char *id)
707 {
708   tdesc_arch_data *data
709     = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
710
711   for (const tdesc_arch_reg &reg : data->arch_regs)
712     {
713       if (reg.reg
714           && reg.reg->tdesc_type
715           && reg.type
716           && reg.reg->tdesc_type->name == id)
717         return reg.type;
718     }
719
720   return NULL;
721 }
722
723 /* Support for registers from target descriptions.  */
724
725 /* Construct the per-gdbarch data.  */
726
727 static void *
728 tdesc_data_init (struct obstack *obstack)
729 {
730   return obstack_new<tdesc_arch_data> (obstack);
731 }
732
733 /* Similar, but for the temporary copy used during architecture
734    initialization.  */
735
736 struct tdesc_arch_data *
737 tdesc_data_alloc (void)
738 {
739   return new tdesc_arch_data ();
740 }
741
742 /* Free something allocated by tdesc_data_alloc, if it is not going
743    to be used (for instance if it was unsuitable for the
744    architecture).  */
745
746 void
747 tdesc_data_cleanup (void *data_untyped)
748 {
749   struct tdesc_arch_data *data = (struct tdesc_arch_data *) data_untyped;
750
751   delete data;
752 }
753
754 /* Search FEATURE for a register named NAME.  */
755
756 static struct tdesc_reg *
757 tdesc_find_register_early (const struct tdesc_feature *feature,
758                            const char *name)
759 {
760   for (const tdesc_reg_up &reg : feature->registers)
761     if (strcasecmp (reg->name.c_str (), name) == 0)
762       return reg.get ();
763
764   return NULL;
765 }
766
767 /* Search FEATURE for a register named NAME.  Assign REGNO to it.  */
768
769 int
770 tdesc_numbered_register (const struct tdesc_feature *feature,
771                          struct tdesc_arch_data *data,
772                          int regno, const char *name)
773 {
774   struct tdesc_reg *reg = tdesc_find_register_early (feature, name);
775
776   if (reg == NULL)
777     return 0;
778
779   /* Make sure the vector includes a REGNO'th element.  */
780   while (regno >= data->arch_regs.size ())
781     data->arch_regs.emplace_back (nullptr, nullptr);
782
783   data->arch_regs[regno] = tdesc_arch_reg (reg, NULL);
784
785   return 1;
786 }
787
788 /* Search FEATURE for a register named NAME, but do not assign a fixed
789    register number to it.  */
790
791 int
792 tdesc_unnumbered_register (const struct tdesc_feature *feature,
793                            const char *name)
794 {
795   struct tdesc_reg *reg = tdesc_find_register_early (feature, name);
796
797   if (reg == NULL)
798     return 0;
799
800   return 1;
801 }
802
803 /* Search FEATURE for a register whose name is in NAMES and assign
804    REGNO to it.  */
805
806 int
807 tdesc_numbered_register_choices (const struct tdesc_feature *feature,
808                                  struct tdesc_arch_data *data,
809                                  int regno, const char *const names[])
810 {
811   int i;
812
813   for (i = 0; names[i] != NULL; i++)
814     if (tdesc_numbered_register (feature, data, regno, names[i]))
815       return 1;
816
817   return 0;
818 }
819
820 /* Search FEATURE for a register named NAME, and return its size in
821    bits.  The register must exist.  */
822
823 int
824 tdesc_register_bitsize (const struct tdesc_feature *feature, const char *name)
825 {
826   struct tdesc_reg *reg = tdesc_find_register_early (feature, name);
827
828   gdb_assert (reg != NULL);
829   return reg->bitsize;
830 }
831
832 /* Look up a register by its GDB internal register number.  */
833
834 static struct tdesc_arch_reg *
835 tdesc_find_arch_register (struct gdbarch *gdbarch, int regno)
836 {
837   struct tdesc_arch_data *data;
838
839   data = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
840   if (regno < data->arch_regs.size ())
841     return &data->arch_regs[regno];
842   else
843     return NULL;
844 }
845
846 static struct tdesc_reg *
847 tdesc_find_register (struct gdbarch *gdbarch, int regno)
848 {
849   struct tdesc_arch_reg *reg = tdesc_find_arch_register (gdbarch, regno);
850
851   return reg? reg->reg : NULL;
852 }
853
854 /* Return the name of register REGNO, from the target description or
855    from an architecture-provided pseudo_register_name method.  */
856
857 const char *
858 tdesc_register_name (struct gdbarch *gdbarch, int regno)
859 {
860   struct tdesc_reg *reg = tdesc_find_register (gdbarch, regno);
861   int num_regs = gdbarch_num_regs (gdbarch);
862
863   if (reg != NULL)
864     return reg->name.c_str ();
865
866   if (regno >= num_regs && regno < gdbarch_num_cooked_regs (gdbarch))
867     {
868       struct tdesc_arch_data *data
869         = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
870
871       gdb_assert (data->pseudo_register_name != NULL);
872       return data->pseudo_register_name (gdbarch, regno);
873     }
874
875   return "";
876 }
877
878 struct type *
879 tdesc_register_type (struct gdbarch *gdbarch, int regno)
880 {
881   struct tdesc_arch_reg *arch_reg = tdesc_find_arch_register (gdbarch, regno);
882   struct tdesc_reg *reg = arch_reg? arch_reg->reg : NULL;
883   int num_regs = gdbarch_num_regs (gdbarch);
884   int num_pseudo_regs = gdbarch_num_pseudo_regs (gdbarch);
885
886   if (reg == NULL && regno >= num_regs && regno < num_regs + num_pseudo_regs)
887     {
888       struct tdesc_arch_data *data
889         = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
890
891       gdb_assert (data->pseudo_register_type != NULL);
892       return data->pseudo_register_type (gdbarch, regno);
893     }
894
895   if (reg == NULL)
896     /* Return "int0_t", since "void" has a misleading size of one.  */
897     return builtin_type (gdbarch)->builtin_int0;
898
899   if (arch_reg->type == NULL)
900     {
901       /* First check for a predefined or target defined type.  */
902       if (reg->tdesc_type)
903         arch_reg->type = make_gdb_type (gdbarch, reg->tdesc_type);
904
905       /* Next try size-sensitive type shortcuts.  */
906       else if (reg->type == "float")
907         {
908           if (reg->bitsize == gdbarch_float_bit (gdbarch))
909             arch_reg->type = builtin_type (gdbarch)->builtin_float;
910           else if (reg->bitsize == gdbarch_double_bit (gdbarch))
911             arch_reg->type = builtin_type (gdbarch)->builtin_double;
912           else if (reg->bitsize == gdbarch_long_double_bit (gdbarch))
913             arch_reg->type = builtin_type (gdbarch)->builtin_long_double;
914           else
915             {
916               warning (_("Register \"%s\" has an unsupported size (%d bits)"),
917                        reg->name.c_str (), reg->bitsize);
918               arch_reg->type = builtin_type (gdbarch)->builtin_double;
919             }
920         }
921       else if (reg->type == "int")
922         {
923           if (reg->bitsize == gdbarch_long_bit (gdbarch))
924             arch_reg->type = builtin_type (gdbarch)->builtin_long;
925           else if (reg->bitsize == TARGET_CHAR_BIT)
926             arch_reg->type = builtin_type (gdbarch)->builtin_char;
927           else if (reg->bitsize == gdbarch_short_bit (gdbarch))
928             arch_reg->type = builtin_type (gdbarch)->builtin_short;
929           else if (reg->bitsize == gdbarch_int_bit (gdbarch))
930             arch_reg->type = builtin_type (gdbarch)->builtin_int;
931           else if (reg->bitsize == gdbarch_long_long_bit (gdbarch))
932             arch_reg->type = builtin_type (gdbarch)->builtin_long_long;
933           else if (reg->bitsize == gdbarch_ptr_bit (gdbarch))
934           /* A bit desperate by this point...  */
935             arch_reg->type = builtin_type (gdbarch)->builtin_data_ptr;
936           else
937             {
938               warning (_("Register \"%s\" has an unsupported size (%d bits)"),
939                        reg->name.c_str (), reg->bitsize);
940               arch_reg->type = builtin_type (gdbarch)->builtin_long;
941             }
942         }
943
944       if (arch_reg->type == NULL)
945         internal_error (__FILE__, __LINE__,
946                         "Register \"%s\" has an unknown type \"%s\"",
947                         reg->name.c_str (), reg->type.c_str ());
948     }
949
950   return arch_reg->type;
951 }
952
953 static int
954 tdesc_remote_register_number (struct gdbarch *gdbarch, int regno)
955 {
956   struct tdesc_reg *reg = tdesc_find_register (gdbarch, regno);
957
958   if (reg != NULL)
959     return reg->target_regnum;
960   else
961     return -1;
962 }
963
964 /* Check whether REGNUM is a member of REGGROUP.  Registers from the
965    target description may be classified as general, float, vector or other
966    register groups registered with reggroup_add().  Unlike a gdbarch
967    register_reggroup_p method, this function will return -1 if it does not
968    know; the caller should handle registers with no specified group.
969
970    The names of containing features are not used.  This might be extended
971    to display registers in some more useful groupings.
972
973    The save-restore flag is also implemented here.  */
974
975 int
976 tdesc_register_in_reggroup_p (struct gdbarch *gdbarch, int regno,
977                               struct reggroup *reggroup)
978 {
979   struct tdesc_reg *reg = tdesc_find_register (gdbarch, regno);
980
981   if (reg != NULL && !reg->group.empty ()
982       && (reg->group == reggroup_name (reggroup)))
983         return 1;
984
985   if (reg != NULL
986       && (reggroup == save_reggroup || reggroup == restore_reggroup))
987     return reg->save_restore;
988
989   return -1;
990 }
991
992 /* Check whether REGNUM is a member of REGGROUP.  Registers with no
993    group specified go to the default reggroup function and are handled
994    by type.  */
995
996 static int
997 tdesc_register_reggroup_p (struct gdbarch *gdbarch, int regno,
998                            struct reggroup *reggroup)
999 {
1000   int num_regs = gdbarch_num_regs (gdbarch);
1001   int num_pseudo_regs = gdbarch_num_pseudo_regs (gdbarch);
1002   int ret;
1003
1004   if (regno >= num_regs && regno < num_regs + num_pseudo_regs)
1005     {
1006       struct tdesc_arch_data *data
1007         = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
1008
1009       if (data->pseudo_register_reggroup_p != NULL)
1010         return data->pseudo_register_reggroup_p (gdbarch, regno, reggroup);
1011       /* Otherwise fall through to the default reggroup_p.  */
1012     }
1013
1014   ret = tdesc_register_in_reggroup_p (gdbarch, regno, reggroup);
1015   if (ret != -1)
1016     return ret;
1017
1018   return default_register_reggroup_p (gdbarch, regno, reggroup);
1019 }
1020
1021 /* Record architecture-specific functions to call for pseudo-register
1022    support.  */
1023
1024 void
1025 set_tdesc_pseudo_register_name (struct gdbarch *gdbarch,
1026                                 gdbarch_register_name_ftype *pseudo_name)
1027 {
1028   struct tdesc_arch_data *data
1029     = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
1030
1031   data->pseudo_register_name = pseudo_name;
1032 }
1033
1034 void
1035 set_tdesc_pseudo_register_type (struct gdbarch *gdbarch,
1036                                 gdbarch_register_type_ftype *pseudo_type)
1037 {
1038   struct tdesc_arch_data *data
1039     = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
1040
1041   data->pseudo_register_type = pseudo_type;
1042 }
1043
1044 void
1045 set_tdesc_pseudo_register_reggroup_p
1046   (struct gdbarch *gdbarch,
1047    gdbarch_register_reggroup_p_ftype *pseudo_reggroup_p)
1048 {
1049   struct tdesc_arch_data *data
1050     = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
1051
1052   data->pseudo_register_reggroup_p = pseudo_reggroup_p;
1053 }
1054
1055 /* Update GDBARCH to use the target description for registers.  */
1056
1057 void
1058 tdesc_use_registers (struct gdbarch *gdbarch,
1059                      const struct target_desc *target_desc,
1060                      struct tdesc_arch_data *early_data)
1061 {
1062   int num_regs = gdbarch_num_regs (gdbarch);
1063   struct tdesc_arch_data *data;
1064   htab_t reg_hash;
1065
1066   /* We can't use the description for registers if it doesn't describe
1067      any.  This function should only be called after validating
1068      registers, so the caller should know that registers are
1069      included.  */
1070   gdb_assert (tdesc_has_registers (target_desc));
1071
1072   data = (struct tdesc_arch_data *) gdbarch_data (gdbarch, tdesc_data);
1073   data->arch_regs = early_data->arch_regs;
1074   delete early_data;
1075
1076   /* Build up a set of all registers, so that we can assign register
1077      numbers where needed.  The hash table expands as necessary, so
1078      the initial size is arbitrary.  */
1079   reg_hash = htab_create (37, htab_hash_pointer, htab_eq_pointer, NULL);
1080   for (const tdesc_feature_up &feature : target_desc->features)
1081     for (const tdesc_reg_up &reg : feature->registers)
1082       {
1083         void **slot = htab_find_slot (reg_hash, reg.get (), INSERT);
1084
1085         *slot = reg.get ();
1086         /* Add reggroup if its new.  */
1087         if (!reg->group.empty ())
1088           if (reggroup_find (gdbarch, reg->group.c_str ()) == NULL)
1089             reggroup_add (gdbarch, reggroup_gdbarch_new (gdbarch,
1090                                                          reg->group.c_str (),
1091                                                          USER_REGGROUP));
1092       }
1093
1094   /* Remove any registers which were assigned numbers by the
1095      architecture.  */
1096   for (const tdesc_arch_reg &arch_reg : data->arch_regs)
1097     if (arch_reg.reg != NULL)
1098       htab_remove_elt (reg_hash, arch_reg.reg);
1099
1100   /* Assign numbers to the remaining registers and add them to the
1101      list of registers.  The new numbers are always above gdbarch_num_regs.
1102      Iterate over the features, not the hash table, so that the order
1103      matches that in the target description.  */
1104
1105   gdb_assert (data->arch_regs.size () <= num_regs);
1106   while (data->arch_regs.size () < num_regs)
1107     data->arch_regs.emplace_back (nullptr, nullptr);
1108
1109   for (const tdesc_feature_up &feature : target_desc->features)
1110     for (const tdesc_reg_up &reg : feature->registers)
1111       if (htab_find (reg_hash, reg.get ()) != NULL)
1112         {
1113           data->arch_regs.emplace_back (reg.get (), nullptr);
1114           num_regs++;
1115         }
1116
1117   htab_delete (reg_hash);
1118
1119   /* Update the architecture.  */
1120   set_gdbarch_num_regs (gdbarch, num_regs);
1121   set_gdbarch_register_name (gdbarch, tdesc_register_name);
1122   set_gdbarch_register_type (gdbarch, tdesc_register_type);
1123   set_gdbarch_remote_register_number (gdbarch,
1124                                       tdesc_remote_register_number);
1125   set_gdbarch_register_reggroup_p (gdbarch, tdesc_register_reggroup_p);
1126 }
1127
1128 /* See gdbsupport/tdesc.h.  */
1129
1130 struct tdesc_feature *
1131 tdesc_create_feature (struct target_desc *tdesc, const char *name)
1132 {
1133   struct tdesc_feature *new_feature = new tdesc_feature (name);
1134
1135   tdesc->features.emplace_back (new_feature);
1136
1137   return new_feature;
1138 }
1139
1140 struct target_desc *
1141 allocate_target_description (void)
1142 {
1143   return new target_desc ();
1144 }
1145
1146 void
1147 target_desc_deleter::operator() (struct target_desc *target_desc) const
1148 {
1149   delete target_desc;
1150 }
1151
1152 void
1153 tdesc_add_compatible (struct target_desc *target_desc,
1154                       const struct bfd_arch_info *compatible)
1155 {
1156   /* If this instance of GDB is compiled without BFD support for the
1157      compatible architecture, simply ignore it -- we would not be able
1158      to handle it anyway.  */
1159   if (compatible == NULL)
1160     return;
1161
1162   for (const bfd_arch_info *compat : target_desc->compatible)
1163     if (compat == compatible)
1164       internal_error (__FILE__, __LINE__,
1165                       _("Attempted to add duplicate "
1166                         "compatible architecture \"%s\""),
1167                       compatible->printable_name);
1168
1169   target_desc->compatible.push_back (compatible);
1170 }
1171
1172 void
1173 set_tdesc_property (struct target_desc *target_desc,
1174                     const char *key, const char *value)
1175 {
1176   gdb_assert (key != NULL && value != NULL);
1177
1178   if (tdesc_property (target_desc, key) != NULL)
1179     internal_error (__FILE__, __LINE__,
1180                     _("Attempted to add duplicate property \"%s\""), key);
1181
1182   target_desc->properties.emplace_back (key, value);
1183 }
1184
1185 /* See gdbsupport/tdesc.h.  */
1186
1187 void
1188 set_tdesc_architecture (struct target_desc *target_desc,
1189                         const char *name)
1190 {
1191   set_tdesc_architecture (target_desc, bfd_scan_arch (name));
1192 }
1193
1194 void
1195 set_tdesc_architecture (struct target_desc *target_desc,
1196                         const struct bfd_arch_info *arch)
1197 {
1198   target_desc->arch = arch;
1199 }
1200
1201 /* See gdbsupport/tdesc.h.  */
1202
1203 void
1204 set_tdesc_osabi (struct target_desc *target_desc, const char *name)
1205 {
1206   set_tdesc_osabi (target_desc, osabi_from_tdesc_string (name));
1207 }
1208
1209 void
1210 set_tdesc_osabi (struct target_desc *target_desc, enum gdb_osabi osabi)
1211 {
1212   target_desc->osabi = osabi;
1213 }
1214 \f
1215
1216 static struct cmd_list_element *tdesc_set_cmdlist, *tdesc_show_cmdlist;
1217 static struct cmd_list_element *tdesc_unset_cmdlist;
1218
1219 /* Helper functions for the CLI commands.  */
1220
1221 static void
1222 set_tdesc_cmd (const char *args, int from_tty)
1223 {
1224   help_list (tdesc_set_cmdlist, "set tdesc ", all_commands, gdb_stdout);
1225 }
1226
1227 static void
1228 show_tdesc_cmd (const char *args, int from_tty)
1229 {
1230   cmd_show_list (tdesc_show_cmdlist, from_tty, "");
1231 }
1232
1233 static void
1234 unset_tdesc_cmd (const char *args, int from_tty)
1235 {
1236   help_list (tdesc_unset_cmdlist, "unset tdesc ", all_commands, gdb_stdout);
1237 }
1238
1239 static void
1240 set_tdesc_filename_cmd (const char *args, int from_tty,
1241                         struct cmd_list_element *c)
1242 {
1243   xfree (target_description_filename);
1244   target_description_filename = xstrdup (tdesc_filename_cmd_string);
1245
1246   target_clear_description ();
1247   target_find_description ();
1248 }
1249
1250 static void
1251 show_tdesc_filename_cmd (struct ui_file *file, int from_tty,
1252                          struct cmd_list_element *c,
1253                          const char *value)
1254 {
1255   value = target_description_filename;
1256
1257   if (value != NULL && *value != '\0')
1258     printf_filtered (_("The target description will be read from \"%s\".\n"),
1259                      value);
1260   else
1261     printf_filtered (_("The target description will be "
1262                        "read from the target.\n"));
1263 }
1264
1265 static void
1266 unset_tdesc_filename_cmd (const char *args, int from_tty)
1267 {
1268   xfree (target_description_filename);
1269   target_description_filename = NULL;
1270   target_clear_description ();
1271   target_find_description ();
1272 }
1273
1274 /* Print target description in C.  */
1275
1276 class print_c_tdesc : public tdesc_element_visitor
1277 {
1278 public:
1279   print_c_tdesc (std::string &filename_after_features)
1280     : m_filename_after_features (filename_after_features)
1281   {
1282     const char *inp;
1283     char *outp;
1284     const char *filename = lbasename (m_filename_after_features.c_str ());
1285
1286     m_function = (char *) xmalloc (strlen (filename) + 1);
1287     for (inp = filename, outp = m_function; *inp != '\0'; inp++)
1288       if (*inp == '.')
1289         break;
1290       else if (*inp == '-')
1291         *outp++ = '_';
1292       else
1293         *outp++ = *inp;
1294     *outp = '\0';
1295
1296     /* Standard boilerplate.  */
1297     printf_unfiltered ("/* THIS FILE IS GENERATED.  "
1298                        "-*- buffer-read-only: t -*- vi"
1299                        ":set ro:\n");
1300   }
1301
1302   ~print_c_tdesc ()
1303   {
1304     xfree (m_function);
1305   }
1306
1307   void visit_pre (const target_desc *e) override
1308   {
1309     printf_unfiltered ("  Original: %s */\n\n",
1310                        lbasename (m_filename_after_features.c_str ()));
1311
1312     printf_unfiltered ("#include \"defs.h\"\n");
1313     printf_unfiltered ("#include \"osabi.h\"\n");
1314     printf_unfiltered ("#include \"target-descriptions.h\"\n");
1315     printf_unfiltered ("\n");
1316
1317     printf_unfiltered ("struct target_desc *tdesc_%s;\n", m_function);
1318     printf_unfiltered ("static void\n");
1319     printf_unfiltered ("initialize_tdesc_%s (void)\n", m_function);
1320     printf_unfiltered ("{\n");
1321     printf_unfiltered
1322       ("  struct target_desc *result = allocate_target_description ();\n");
1323
1324     if (tdesc_architecture (e) != NULL)
1325       {
1326         printf_unfiltered
1327           ("  set_tdesc_architecture (result, bfd_scan_arch (\"%s\"));\n",
1328            tdesc_architecture (e)->printable_name);
1329         printf_unfiltered ("\n");
1330       }
1331     if (tdesc_osabi (e) > GDB_OSABI_UNKNOWN
1332         && tdesc_osabi (e) < GDB_OSABI_INVALID)
1333       {
1334         printf_unfiltered
1335           ("  set_tdesc_osabi (result, osabi_from_tdesc_string (\"%s\"));\n",
1336            gdbarch_osabi_name (tdesc_osabi (e)));
1337         printf_unfiltered ("\n");
1338       }
1339
1340     for (const bfd_arch_info_type *compatible : e->compatible)
1341       printf_unfiltered
1342         ("  tdesc_add_compatible (result, bfd_scan_arch (\"%s\"));\n",
1343          compatible->printable_name);
1344
1345     if (!e->compatible.empty ())
1346       printf_unfiltered ("\n");
1347
1348     for (const property &prop : e->properties)
1349       printf_unfiltered ("  set_tdesc_property (result, \"%s\", \"%s\");\n",
1350                          prop.key.c_str (), prop.value.c_str ());
1351
1352     printf_unfiltered ("  struct tdesc_feature *feature;\n");
1353   }
1354
1355   void visit_pre (const tdesc_feature *e) override
1356   {
1357     printf_unfiltered ("\n  feature = tdesc_create_feature (result, \"%s\");\n",
1358                        e->name.c_str ());
1359   }
1360
1361   void visit_post (const tdesc_feature *e) override
1362   {}
1363
1364   void visit_post (const target_desc *e) override
1365   {
1366     printf_unfiltered ("\n  tdesc_%s = result;\n", m_function);
1367     printf_unfiltered ("}\n");
1368   }
1369
1370   void visit (const tdesc_type_builtin *type) override
1371   {
1372     error (_("C output is not supported type \"%s\"."), type->name.c_str ());
1373   }
1374
1375   void visit (const tdesc_type_vector *type) override
1376   {
1377     if (!m_printed_element_type)
1378       {
1379         printf_unfiltered ("  tdesc_type *element_type;\n");
1380         m_printed_element_type = true;
1381       }
1382
1383     printf_unfiltered
1384       ("  element_type = tdesc_named_type (feature, \"%s\");\n",
1385        type->element_type->name.c_str ());
1386     printf_unfiltered
1387       ("  tdesc_create_vector (feature, \"%s\", element_type, %d);\n",
1388        type->name.c_str (), type->count);
1389
1390     printf_unfiltered ("\n");
1391   }
1392
1393   void visit (const tdesc_type_with_fields *type) override
1394   {
1395     if (!m_printed_type_with_fields)
1396       {
1397         printf_unfiltered ("  tdesc_type_with_fields *type_with_fields;\n");
1398         m_printed_type_with_fields = true;
1399       }
1400
1401     switch (type->kind)
1402       {
1403       case TDESC_TYPE_STRUCT:
1404       case TDESC_TYPE_FLAGS:
1405         if (type->kind == TDESC_TYPE_STRUCT)
1406           {
1407             printf_unfiltered
1408               ("  type_with_fields = tdesc_create_struct (feature, \"%s\");\n",
1409                type->name.c_str ());
1410             if (type->size != 0)
1411               printf_unfiltered
1412                 ("  tdesc_set_struct_size (type_with_fields, %d);\n", type->size);
1413           }
1414         else
1415           {
1416             printf_unfiltered
1417               ("  type_with_fields = tdesc_create_flags (feature, \"%s\", %d);\n",
1418                type->name.c_str (), type->size);
1419           }
1420         for (const tdesc_type_field &f : type->fields)
1421           {
1422             const char *type_name;
1423
1424             gdb_assert (f.type != NULL);
1425             type_name = f.type->name.c_str ();
1426
1427             /* To minimize changes to generated files, don't emit type
1428                info for fields that have defaulted types.  */
1429             if (f.start != -1)
1430               {
1431                 gdb_assert (f.end != -1);
1432                 if (f.type->kind == TDESC_TYPE_BOOL)
1433                   {
1434                     gdb_assert (f.start == f.end);
1435                     printf_unfiltered
1436                       ("  tdesc_add_flag (type_with_fields, %d, \"%s\");\n",
1437                        f.start, f.name.c_str ());
1438                   }
1439                 else if ((type->size == 4 && f.type->kind == TDESC_TYPE_UINT32)
1440                          || (type->size == 8
1441                              && f.type->kind == TDESC_TYPE_UINT64))
1442                   {
1443                     printf_unfiltered
1444                       ("  tdesc_add_bitfield (type_with_fields, \"%s\", %d, %d);\n",
1445                        f.name.c_str (), f.start, f.end);
1446                   }
1447                 else
1448                   {
1449                     printf_field_type_assignment
1450                       ("tdesc_named_type (feature, \"%s\");\n",
1451                        type_name);
1452                     printf_unfiltered
1453                       ("  tdesc_add_typed_bitfield (type_with_fields, \"%s\","
1454                        " %d, %d, field_type);\n",
1455                        f.name.c_str (), f.start, f.end);
1456                   }
1457               }
1458             else /* Not a bitfield.  */
1459               {
1460                 gdb_assert (f.end == -1);
1461                 gdb_assert (type->kind == TDESC_TYPE_STRUCT);
1462                 printf_field_type_assignment
1463                   ("tdesc_named_type (feature, \"%s\");\n", type_name);
1464                 printf_unfiltered
1465                   ("  tdesc_add_field (type_with_fields, \"%s\", field_type);\n",
1466                    f.name.c_str ());
1467               }
1468           }
1469         break;
1470       case TDESC_TYPE_UNION:
1471         printf_unfiltered
1472           ("  type_with_fields = tdesc_create_union (feature, \"%s\");\n",
1473            type->name.c_str ());
1474         for (const tdesc_type_field &f : type->fields)
1475           {
1476             printf_field_type_assignment
1477               ("tdesc_named_type (feature, \"%s\");\n", f.type->name.c_str ());
1478             printf_unfiltered
1479               ("  tdesc_add_field (type_with_fields, \"%s\", field_type);\n",
1480                f.name.c_str ());
1481           }
1482         break;
1483       case TDESC_TYPE_ENUM:
1484         printf_unfiltered
1485           ("  type_with_fields = tdesc_create_enum (feature, \"%s\", %d);\n",
1486            type->name.c_str (), type->size);
1487         for (const tdesc_type_field &f : type->fields)
1488           printf_unfiltered
1489             ("  tdesc_add_enum_value (type_with_fields, %d, \"%s\");\n",
1490              f.start, f.name.c_str ());
1491         break;
1492       default:
1493         error (_("C output is not supported type \"%s\"."), type->name.c_str ());
1494       }
1495
1496     printf_unfiltered ("\n");
1497   }
1498
1499   void visit (const tdesc_reg *reg) override
1500   {
1501     printf_unfiltered ("  tdesc_create_reg (feature, \"%s\", %ld, %d, ",
1502                        reg->name.c_str (), reg->target_regnum,
1503                        reg->save_restore);
1504     if (!reg->group.empty ())
1505       printf_unfiltered ("\"%s\", ", reg->group.c_str ());
1506     else
1507       printf_unfiltered ("NULL, ");
1508     printf_unfiltered ("%d, \"%s\");\n", reg->bitsize, reg->type.c_str ());
1509   }
1510
1511 protected:
1512   std::string m_filename_after_features;
1513
1514 private:
1515
1516   /* Print an assignment to the field_type variable.  Print the declaration
1517      of field_type if that has not been done yet.  */
1518   ATTRIBUTE_PRINTF (2, 3)
1519   void printf_field_type_assignment (const char *fmt, ...)
1520   {
1521     if (!m_printed_field_type)
1522       {
1523         printf_unfiltered ("  tdesc_type *field_type;\n");
1524         m_printed_field_type = true;
1525       }
1526
1527     printf_unfiltered ("  field_type = ");
1528
1529     va_list args;
1530     va_start (args, fmt);
1531     vprintf_unfiltered (fmt, args);
1532     va_end (args);
1533   }
1534
1535   char *m_function;
1536
1537   /* Did we print "struct tdesc_type *element_type;" yet?  */
1538   bool m_printed_element_type = false;
1539
1540   /* Did we print "struct tdesc_type_with_fields *element_type;" yet?  */
1541   bool m_printed_type_with_fields = false;
1542
1543   /* Did we print "struct tdesc_type *field_type;" yet?  */
1544   bool m_printed_field_type = false;
1545 };
1546
1547 /* Print target description feature in C.  */
1548
1549 class print_c_feature : public print_c_tdesc
1550 {
1551 public:
1552   print_c_feature (std::string &file)
1553     : print_c_tdesc (file)
1554   {
1555     /* Trim ".tmp".  */
1556     auto const pos = m_filename_after_features.find_last_of ('.');
1557
1558     m_filename_after_features = m_filename_after_features.substr (0, pos);
1559   }
1560
1561   void visit_pre (const target_desc *e) override
1562   {
1563     printf_unfiltered ("  Original: %s */\n\n",
1564                        lbasename (m_filename_after_features.c_str ()));
1565
1566     printf_unfiltered ("#include \"gdbsupport/tdesc.h\"\n");
1567     printf_unfiltered ("\n");
1568   }
1569
1570   void visit_post (const target_desc *e) override
1571   {}
1572
1573   void visit_pre (const tdesc_feature *e) override
1574   {
1575     std::string name (m_filename_after_features);
1576
1577     auto pos = name.find_first_of ('.');
1578
1579     name = name.substr (0, pos);
1580     std::replace (name.begin (), name.end (), '/', '_');
1581     std::replace (name.begin (), name.end (), '-', '_');
1582
1583     printf_unfiltered ("static int\n");
1584     printf_unfiltered ("create_feature_%s ", name.c_str ());
1585     printf_unfiltered ("(struct target_desc *result, long regnum)\n");
1586
1587     printf_unfiltered ("{\n");
1588     printf_unfiltered ("  struct tdesc_feature *feature;\n");
1589
1590     printf_unfiltered
1591       ("\n  feature = tdesc_create_feature (result, \"%s\");\n",
1592        e->name.c_str ());
1593   }
1594
1595   void visit_post (const tdesc_feature *e) override
1596   {
1597     printf_unfiltered ("  return regnum;\n");
1598     printf_unfiltered ("}\n");
1599   }
1600
1601   void visit (const tdesc_reg *reg) override
1602   {
1603     /* Most "reg" in XML target descriptions don't have "regnum"
1604        attribute, so the register number is allocated sequentially.
1605        In case that reg has "regnum" attribute, register number
1606        should be set by that explicitly.  */
1607
1608     if (reg->target_regnum < m_next_regnum)
1609       {
1610         /* The integrity check, it can catch some errors on register
1611            number collision, like this,
1612
1613           <reg name="x0" bitsize="32"/>
1614           <reg name="x1" bitsize="32"/>
1615           <reg name="x2" bitsize="32"/>
1616           <reg name="x3" bitsize="32"/>
1617           <reg name="ps" bitsize="32" regnum="3"/>
1618
1619           but it also has false negatives.  The target description
1620           below is correct,
1621
1622           <reg name="x1" bitsize="32" regnum="1"/>
1623           <reg name="x3" bitsize="32" regnum="3"/>
1624           <reg name="x2" bitsize="32" regnum="2"/>
1625           <reg name="x4" bitsize="32" regnum="4"/>
1626
1627           but it is not a good practice, so still error on this,
1628           and also print the message so that it can be saved in the
1629           generated c file.  */
1630
1631         printf_unfiltered ("ERROR: \"regnum\" attribute %ld ",
1632                            reg->target_regnum);
1633         printf_unfiltered ("is not the largest number (%d).\n",
1634                            m_next_regnum);
1635         error (_("\"regnum\" attribute %ld is not the largest number (%d)."),
1636                reg->target_regnum, m_next_regnum);
1637       }
1638
1639     if (reg->target_regnum > m_next_regnum)
1640       {
1641         printf_unfiltered ("  regnum = %ld;\n", reg->target_regnum);
1642         m_next_regnum = reg->target_regnum;
1643       }
1644
1645     printf_unfiltered ("  tdesc_create_reg (feature, \"%s\", regnum++, %d, ",
1646                        reg->name.c_str (), reg->save_restore);
1647     if (!reg->group.empty ())
1648       printf_unfiltered ("\"%s\", ", reg->group.c_str ());
1649     else
1650       printf_unfiltered ("NULL, ");
1651     printf_unfiltered ("%d, \"%s\");\n", reg->bitsize, reg->type.c_str ());
1652
1653     m_next_regnum++;
1654   }
1655
1656 private:
1657   /* The register number to use for the next register we see.  */
1658   int m_next_regnum = 0;
1659 };
1660
1661 /* See gdbsupport/tdesc.h.  */
1662
1663 const char *
1664 tdesc_get_features_xml (const target_desc *tdesc)
1665 {
1666   if (tdesc->xmltarget == nullptr)
1667     {
1668       std::string buffer ("@");
1669       print_xml_feature v (&buffer);
1670       tdesc->accept (v);
1671       tdesc->xmltarget = xstrdup (buffer.c_str ());
1672     }
1673   return tdesc->xmltarget;
1674 }
1675
1676 static void
1677 maint_print_c_tdesc_cmd (const char *args, int from_tty)
1678 {
1679   const struct target_desc *tdesc;
1680   const char *filename;
1681
1682   if (args == NULL)
1683     {
1684       /* Use the global target-supplied description, not the current
1685          architecture's.  This lets a GDB for one architecture generate C
1686          for another architecture's description, even though the gdbarch
1687          initialization code will reject the new description.  */
1688       tdesc = current_target_desc;
1689       filename = target_description_filename;
1690     }
1691   else
1692     {
1693       /* Use the target description from the XML file.  */
1694       filename = args;
1695       tdesc = file_read_description_xml (filename);
1696     }
1697
1698   if (tdesc == NULL)
1699     error (_("There is no target description to print."));
1700
1701   if (filename == NULL)
1702     error (_("The current target description did not come from an XML file."));
1703
1704   std::string filename_after_features (filename);
1705   auto loc = filename_after_features.rfind ("/features/");
1706
1707   if (loc != std::string::npos)
1708     filename_after_features = filename_after_features.substr (loc + 10);
1709
1710   /* Print c files for target features instead of target descriptions,
1711      because c files got from target features are more flexible than the
1712      counterparts.  */
1713   if (startswith (filename_after_features.c_str (), "i386/32bit-")
1714       || startswith (filename_after_features.c_str (), "i386/64bit-")
1715       || startswith (filename_after_features.c_str (), "i386/x32-core.xml")
1716       || startswith (filename_after_features.c_str (), "riscv/")
1717       || startswith (filename_after_features.c_str (), "tic6x-")
1718       || startswith (filename_after_features.c_str (), "aarch64")
1719       || startswith (filename_after_features.c_str (), "arm/"))
1720     {
1721       print_c_feature v (filename_after_features);
1722
1723       tdesc->accept (v);
1724     }
1725   else
1726     {
1727       print_c_tdesc v (filename_after_features);
1728
1729       tdesc->accept (v);
1730     }
1731 }
1732
1733 namespace selftests {
1734
1735 /* A reference target description, used for testing (see record_xml_tdesc).  */
1736
1737 struct xml_test_tdesc
1738 {
1739   xml_test_tdesc (const char *name, std::unique_ptr<const target_desc> &&tdesc)
1740     : name (name), tdesc (std::move (tdesc))
1741   {}
1742
1743   const char *name;
1744   std::unique_ptr<const target_desc> tdesc;
1745 };
1746
1747 static std::vector<xml_test_tdesc> xml_tdesc;
1748
1749 #if GDB_SELF_TEST
1750
1751 /* See target-descritpions.h.  */
1752
1753 void
1754 record_xml_tdesc (const char *xml_file, const struct target_desc *tdesc)
1755 {
1756   xml_tdesc.emplace_back (xml_file, std::unique_ptr<const target_desc> (tdesc));
1757 }
1758 #endif
1759
1760 }
1761
1762 /* Test the convesion process of a target description to/from xml: Take a target
1763    description TDESC, convert to xml, back to a description, and confirm the new
1764    tdesc is identical to the original.  */
1765 static bool
1766 maintenance_check_tdesc_xml_convert (const target_desc *tdesc, const char *name)
1767 {
1768   const char *xml = tdesc_get_features_xml (tdesc);
1769
1770   if (xml == nullptr || *xml != '@')
1771     {
1772       printf_filtered (_("Could not convert description for %s to xml.\n"),
1773                        name);
1774       return false;
1775     }
1776
1777   const target_desc *tdesc_trans = string_read_description_xml (xml + 1);
1778
1779   if (tdesc_trans == nullptr)
1780     {
1781       printf_filtered (_("Could not convert description for %s from xml.\n"),
1782                        name);
1783       return false;
1784     }
1785   else if (*tdesc != *tdesc_trans)
1786     {
1787       printf_filtered (_("Converted description for %s does not match.\n"),
1788                        name);
1789       return false;
1790     }
1791   return true;
1792 }
1793
1794
1795 /* Check that the target descriptions created dynamically by
1796    architecture-specific code equal the descriptions created from XML files
1797    found in the specified directory DIR.  */
1798
1799 static void
1800 maintenance_check_xml_descriptions (const char *dir, int from_tty)
1801 {
1802   if (dir == NULL)
1803     error (_("Missing dir name"));
1804
1805   gdb::unique_xmalloc_ptr<char> dir1 (tilde_expand (dir));
1806   std::string feature_dir (dir1.get ());
1807   unsigned int failed = 0;
1808
1809   for (auto const &e : selftests::xml_tdesc)
1810     {
1811       std::string tdesc_xml = (feature_dir + SLASH_STRING + e.name);
1812       const target_desc *tdesc
1813         = file_read_description_xml (tdesc_xml.data ());
1814
1815       if (tdesc == NULL || *tdesc != *e.tdesc)
1816         {
1817           printf_filtered ( _("Descriptions for %s do not match.\n"), e.name);
1818           failed++;
1819         }
1820       else if (!maintenance_check_tdesc_xml_convert (tdesc, e.name)
1821                || !maintenance_check_tdesc_xml_convert (e.tdesc.get (), e.name))
1822         failed++;
1823     }
1824   printf_filtered (_("Tested %lu XML files, %d failed\n"),
1825                    (long) selftests::xml_tdesc.size (), failed);
1826 }
1827
1828 void
1829 _initialize_target_descriptions (void)
1830 {
1831   tdesc_data = gdbarch_data_register_pre_init (tdesc_data_init);
1832
1833   add_prefix_cmd ("tdesc", class_maintenance, set_tdesc_cmd, _("\
1834 Set target description specific variables."),
1835                   &tdesc_set_cmdlist, "set tdesc ",
1836                   0 /* allow-unknown */, &setlist);
1837   add_prefix_cmd ("tdesc", class_maintenance, show_tdesc_cmd, _("\
1838 Show target description specific variables."),
1839                   &tdesc_show_cmdlist, "show tdesc ",
1840                   0 /* allow-unknown */, &showlist);
1841   add_prefix_cmd ("tdesc", class_maintenance, unset_tdesc_cmd, _("\
1842 Unset target description specific variables."),
1843                   &tdesc_unset_cmdlist, "unset tdesc ",
1844                   0 /* allow-unknown */, &unsetlist);
1845
1846   add_setshow_filename_cmd ("filename", class_obscure,
1847                             &tdesc_filename_cmd_string,
1848                             _("\
1849 Set the file to read for an XML target description."), _("\
1850 Show the file to read for an XML target description."), _("\
1851 When set, GDB will read the target description from a local\n\
1852 file instead of querying the remote target."),
1853                             set_tdesc_filename_cmd,
1854                             show_tdesc_filename_cmd,
1855                             &tdesc_set_cmdlist, &tdesc_show_cmdlist);
1856
1857   add_cmd ("filename", class_obscure, unset_tdesc_filename_cmd, _("\
1858 Unset the file to read for an XML target description.\n\
1859 When unset, GDB will read the description from the target."),
1860            &tdesc_unset_cmdlist);
1861
1862   add_cmd ("c-tdesc", class_maintenance, maint_print_c_tdesc_cmd, _("\
1863 Print the current target description as a C source file."),
1864            &maintenanceprintlist);
1865
1866   cmd_list_element *cmd;
1867
1868   cmd = add_cmd ("xml-descriptions", class_maintenance,
1869                  maintenance_check_xml_descriptions, _("\
1870 Check equality of GDB target descriptions and XML created descriptions.\n\
1871 Check the target descriptions created in GDB equal the descriptions\n\
1872 created from XML files in the directory.\n\
1873 The parameter is the directory name."),
1874                  &maintenancechecklist);
1875   set_cmd_completer (cmd, filename_completer);
1876 }