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