Home | History | Annotate | Line # | Download | only in libctf
ctf-open.c revision 1.1.1.1
      1 /* Opening CTF files.
      2    Copyright (C) 2019-2020 Free Software Foundation, Inc.
      3 
      4    This file is part of libctf.
      5 
      6    libctf is free software; you can redistribute it and/or modify it under
      7    the terms of the GNU General Public License as published by the Free
      8    Software Foundation; either version 3, or (at your option) any later
      9    version.
     10 
     11    This program is distributed in the hope that it will be useful, but
     12    WITHOUT ANY WARRANTY; without even the implied warranty of
     13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     14    See the GNU General Public License for more details.
     15 
     16    You should have received a copy of the GNU General Public License
     17    along with this program; see the file COPYING.  If not see
     18    <http://www.gnu.org/licenses/>.  */
     19 
     20 #include <ctf-impl.h>
     21 #include <stddef.h>
     22 #include <string.h>
     23 #include <sys/types.h>
     24 #include <elf.h>
     25 #include <assert.h>
     26 #include "swap.h"
     27 #include <bfd.h>
     28 #include <zlib.h>
     29 
     30 #include "elf-bfd.h"
     31 
     32 static const ctf_dmodel_t _libctf_models[] = {
     33   {"ILP32", CTF_MODEL_ILP32, 4, 1, 2, 4, 4},
     34   {"LP64", CTF_MODEL_LP64, 8, 1, 2, 4, 8},
     35   {NULL, 0, 0, 0, 0, 0, 0}
     36 };
     37 
     38 const char _CTF_SECTION[] = ".ctf";
     39 const char _CTF_NULLSTR[] = "";
     40 
     41 /* Version-sensitive accessors.  */
     42 
     43 static uint32_t
     44 get_kind_v1 (uint32_t info)
     45 {
     46   return (CTF_V1_INFO_KIND (info));
     47 }
     48 
     49 static uint32_t
     50 get_root_v1 (uint32_t info)
     51 {
     52   return (CTF_V1_INFO_ISROOT (info));
     53 }
     54 
     55 static uint32_t
     56 get_vlen_v1 (uint32_t info)
     57 {
     58   return (CTF_V1_INFO_VLEN (info));
     59 }
     60 
     61 static uint32_t
     62 get_kind_v2 (uint32_t info)
     63 {
     64   return (CTF_V2_INFO_KIND (info));
     65 }
     66 
     67 static uint32_t
     68 get_root_v2 (uint32_t info)
     69 {
     70   return (CTF_V2_INFO_ISROOT (info));
     71 }
     72 
     73 static uint32_t
     74 get_vlen_v2 (uint32_t info)
     75 {
     76   return (CTF_V2_INFO_VLEN (info));
     77 }
     78 
     79 static inline ssize_t
     80 get_ctt_size_common (const ctf_file_t *fp _libctf_unused_,
     81 		     const ctf_type_t *tp _libctf_unused_,
     82 		     ssize_t *sizep, ssize_t *incrementp, size_t lsize,
     83 		     size_t csize, size_t ctf_type_size,
     84 		     size_t ctf_stype_size, size_t ctf_lsize_sent)
     85 {
     86   ssize_t size, increment;
     87 
     88   if (csize == ctf_lsize_sent)
     89     {
     90       size = lsize;
     91       increment = ctf_type_size;
     92     }
     93   else
     94     {
     95       size = csize;
     96       increment = ctf_stype_size;
     97     }
     98 
     99   if (sizep)
    100     *sizep = size;
    101   if (incrementp)
    102     *incrementp = increment;
    103 
    104   return size;
    105 }
    106 
    107 static ssize_t
    108 get_ctt_size_v1 (const ctf_file_t *fp, const ctf_type_t *tp,
    109 		 ssize_t *sizep, ssize_t *incrementp)
    110 {
    111   ctf_type_v1_t *t1p = (ctf_type_v1_t *) tp;
    112 
    113   return (get_ctt_size_common (fp, tp, sizep, incrementp,
    114 			       CTF_TYPE_LSIZE (t1p), t1p->ctt_size,
    115 			       sizeof (ctf_type_v1_t), sizeof (ctf_stype_v1_t),
    116 			       CTF_LSIZE_SENT_V1));
    117 }
    118 
    119 /* Return the size that a v1 will be once it is converted to v2.  */
    120 
    121 static ssize_t
    122 get_ctt_size_v2_unconverted (const ctf_file_t *fp, const ctf_type_t *tp,
    123 			     ssize_t *sizep, ssize_t *incrementp)
    124 {
    125   ctf_type_v1_t *t1p = (ctf_type_v1_t *) tp;
    126 
    127   return (get_ctt_size_common (fp, tp, sizep, incrementp,
    128 			       CTF_TYPE_LSIZE (t1p), t1p->ctt_size,
    129 			       sizeof (ctf_type_t), sizeof (ctf_stype_t),
    130 			       CTF_LSIZE_SENT));
    131 }
    132 
    133 static ssize_t
    134 get_ctt_size_v2 (const ctf_file_t *fp, const ctf_type_t *tp,
    135 		 ssize_t *sizep, ssize_t *incrementp)
    136 {
    137   return (get_ctt_size_common (fp, tp, sizep, incrementp,
    138 			       CTF_TYPE_LSIZE (tp), tp->ctt_size,
    139 			       sizeof (ctf_type_t), sizeof (ctf_stype_t),
    140 			       CTF_LSIZE_SENT));
    141 }
    142 
    143 static ssize_t
    144 get_vbytes_common (ctf_file_t *fp, unsigned short kind,
    145 		   ssize_t size _libctf_unused_, size_t vlen)
    146 {
    147   switch (kind)
    148     {
    149     case CTF_K_INTEGER:
    150     case CTF_K_FLOAT:
    151       return (sizeof (uint32_t));
    152     case CTF_K_SLICE:
    153       return (sizeof (ctf_slice_t));
    154     case CTF_K_ENUM:
    155       return (sizeof (ctf_enum_t) * vlen);
    156     case CTF_K_FORWARD:
    157     case CTF_K_UNKNOWN:
    158     case CTF_K_POINTER:
    159     case CTF_K_TYPEDEF:
    160     case CTF_K_VOLATILE:
    161     case CTF_K_CONST:
    162     case CTF_K_RESTRICT:
    163       return 0;
    164     default:
    165       ctf_set_errno (fp, ECTF_CORRUPT);
    166       ctf_err_warn (fp, 0, 0, _("detected invalid CTF kind: %x"), kind);
    167       return -1;
    168     }
    169 }
    170 
    171 static ssize_t
    172 get_vbytes_v1 (ctf_file_t *fp, unsigned short kind, ssize_t size, size_t vlen)
    173 {
    174   switch (kind)
    175     {
    176     case CTF_K_ARRAY:
    177       return (sizeof (ctf_array_v1_t));
    178     case CTF_K_FUNCTION:
    179       return (sizeof (unsigned short) * (vlen + (vlen & 1)));
    180     case CTF_K_STRUCT:
    181     case CTF_K_UNION:
    182       if (size < CTF_LSTRUCT_THRESH_V1)
    183 	return (sizeof (ctf_member_v1_t) * vlen);
    184       else
    185 	return (sizeof (ctf_lmember_v1_t) * vlen);
    186     }
    187 
    188   return (get_vbytes_common (fp, kind, size, vlen));
    189 }
    190 
    191 static ssize_t
    192 get_vbytes_v2 (ctf_file_t *fp, unsigned short kind, ssize_t size, size_t vlen)
    193 {
    194   switch (kind)
    195     {
    196     case CTF_K_ARRAY:
    197       return (sizeof (ctf_array_t));
    198     case CTF_K_FUNCTION:
    199       return (sizeof (uint32_t) * (vlen + (vlen & 1)));
    200     case CTF_K_STRUCT:
    201     case CTF_K_UNION:
    202       if (size < CTF_LSTRUCT_THRESH)
    203 	return (sizeof (ctf_member_t) * vlen);
    204       else
    205 	return (sizeof (ctf_lmember_t) * vlen);
    206     }
    207 
    208   return (get_vbytes_common (fp, kind, size, vlen));
    209 }
    210 
    211 static const ctf_fileops_t ctf_fileops[] = {
    212   {NULL, NULL, NULL, NULL, NULL},
    213   /* CTF_VERSION_1 */
    214   {get_kind_v1, get_root_v1, get_vlen_v1, get_ctt_size_v1, get_vbytes_v1},
    215   /* CTF_VERSION_1_UPGRADED_3 */
    216   {get_kind_v2, get_root_v2, get_vlen_v2, get_ctt_size_v2, get_vbytes_v2},
    217   /* CTF_VERSION_2 */
    218   {get_kind_v2, get_root_v2, get_vlen_v2, get_ctt_size_v2, get_vbytes_v2},
    219   /* CTF_VERSION_3, identical to 2: only new type kinds */
    220   {get_kind_v2, get_root_v2, get_vlen_v2, get_ctt_size_v2, get_vbytes_v2},
    221 };
    222 
    223 /* Initialize the symtab translation table by filling each entry with the
    224   offset of the CTF type or function data corresponding to each STT_FUNC or
    225   STT_OBJECT entry in the symbol table.  */
    226 
    227 static int
    228 init_symtab (ctf_file_t *fp, const ctf_header_t *hp,
    229 	     const ctf_sect_t *sp, const ctf_sect_t *strp)
    230 {
    231   const unsigned char *symp = sp->cts_data;
    232   uint32_t *xp = fp->ctf_sxlate;
    233   uint32_t *xend = xp + fp->ctf_nsyms;
    234 
    235   uint32_t objtoff = hp->cth_objtoff;
    236   uint32_t funcoff = hp->cth_funcoff;
    237 
    238   uint32_t info, vlen;
    239   Elf64_Sym sym, *gsp;
    240   const char *name;
    241 
    242   /* The CTF data object and function type sections are ordered to match
    243      the relative order of the respective symbol types in the symtab.
    244      If no type information is available for a symbol table entry, a
    245      pad is inserted in the CTF section.  As a further optimization,
    246      anonymous or undefined symbols are omitted from the CTF data.  */
    247 
    248   for (; xp < xend; xp++, symp += sp->cts_entsize)
    249     {
    250       if (sp->cts_entsize == sizeof (Elf32_Sym))
    251 	gsp = ctf_sym_to_elf64 ((Elf32_Sym *) (uintptr_t) symp, &sym);
    252       else
    253 	gsp = (Elf64_Sym *) (uintptr_t) symp;
    254 
    255       if (gsp->st_name < strp->cts_size)
    256 	name = (const char *) strp->cts_data + gsp->st_name;
    257       else
    258 	name = _CTF_NULLSTR;
    259 
    260       if (gsp->st_name == 0 || gsp->st_shndx == SHN_UNDEF
    261 	  || strcmp (name, "_START_") == 0 || strcmp (name, "_END_") == 0)
    262 	{
    263 	  *xp = -1u;
    264 	  continue;
    265 	}
    266 
    267       switch (ELF64_ST_TYPE (gsp->st_info))
    268 	{
    269 	case STT_OBJECT:
    270 	  if (objtoff >= hp->cth_funcoff
    271 	      || (gsp->st_shndx == SHN_EXTABS && gsp->st_value == 0))
    272 	    {
    273 	      *xp = -1u;
    274 	      break;
    275 	    }
    276 
    277 	  *xp = objtoff;
    278 	  objtoff += sizeof (uint32_t);
    279 	  break;
    280 
    281 	case STT_FUNC:
    282 	  if (funcoff >= hp->cth_objtidxoff)
    283 	    {
    284 	      *xp = -1u;
    285 	      break;
    286 	    }
    287 
    288 	  *xp = funcoff;
    289 
    290 	  info = *(uint32_t *) ((uintptr_t) fp->ctf_buf + funcoff);
    291 	  vlen = LCTF_INFO_VLEN (fp, info);
    292 
    293 	  /* If we encounter a zero pad at the end, just skip it.  Otherwise
    294 	     skip over the function and its return type (+2) and the argument
    295 	     list (vlen).
    296 	   */
    297 	  if (LCTF_INFO_KIND (fp, info) == CTF_K_UNKNOWN && vlen == 0)
    298 	    funcoff += sizeof (uint32_t);	/* Skip pad.  */
    299 	  else
    300 	    funcoff += sizeof (uint32_t) * (vlen + 2);
    301 	  break;
    302 
    303 	default:
    304 	  *xp = -1u;
    305 	  break;
    306 	}
    307     }
    308 
    309   ctf_dprintf ("loaded %lu symtab entries\n", fp->ctf_nsyms);
    310   return 0;
    311 }
    312 
    313 /* Reset the CTF base pointer and derive the buf pointer from it, initializing
    314    everything in the ctf_file that depends on the base or buf pointers.
    315 
    316    The original gap between the buf and base pointers, if any -- the original,
    317    unconverted CTF header -- is kept, but its contents are not specified and are
    318    never used.  */
    319 
    320 static void
    321 ctf_set_base (ctf_file_t *fp, const ctf_header_t *hp, unsigned char *base)
    322 {
    323   fp->ctf_buf = base + (fp->ctf_buf - fp->ctf_base);
    324   fp->ctf_base = base;
    325   fp->ctf_vars = (ctf_varent_t *) ((const char *) fp->ctf_buf +
    326 				   hp->cth_varoff);
    327   fp->ctf_nvars = (hp->cth_typeoff - hp->cth_varoff) / sizeof (ctf_varent_t);
    328 
    329   fp->ctf_str[CTF_STRTAB_0].cts_strs = (const char *) fp->ctf_buf
    330     + hp->cth_stroff;
    331   fp->ctf_str[CTF_STRTAB_0].cts_len = hp->cth_strlen;
    332 
    333   /* If we have a parent container name and label, store the relocated
    334      string pointers in the CTF container for easy access later. */
    335 
    336   /* Note: before conversion, these will be set to values that will be
    337      immediately invalidated by the conversion process, but the conversion
    338      process will call ctf_set_base() again to fix things up.  */
    339 
    340   if (hp->cth_parlabel != 0)
    341     fp->ctf_parlabel = ctf_strptr (fp, hp->cth_parlabel);
    342   if (hp->cth_parname != 0)
    343     fp->ctf_parname = ctf_strptr (fp, hp->cth_parname);
    344   if (hp->cth_cuname != 0)
    345     fp->ctf_cuname = ctf_strptr (fp, hp->cth_cuname);
    346 
    347   if (fp->ctf_cuname)
    348     ctf_dprintf ("ctf_set_base: CU name %s\n", fp->ctf_cuname);
    349   if (fp->ctf_parname)
    350     ctf_dprintf ("ctf_set_base: parent name %s (label %s)\n",
    351 	       fp->ctf_parname,
    352 	       fp->ctf_parlabel ? fp->ctf_parlabel : "<NULL>");
    353 }
    354 
    355 /* Set the version of the CTF file. */
    356 
    357 /* When this is reset, LCTF_* changes behaviour, but there is no guarantee that
    358    the variable data list associated with each type has been upgraded: the
    359    caller must ensure this has been done in advance.  */
    360 
    361 static void
    362 ctf_set_version (ctf_file_t *fp, ctf_header_t *cth, int ctf_version)
    363 {
    364   fp->ctf_version = ctf_version;
    365   cth->cth_version = ctf_version;
    366   fp->ctf_fileops = &ctf_fileops[ctf_version];
    367 }
    368 
    369 
    370 /* Upgrade the header to CTF_VERSION_3.  The upgrade is done in-place.  */
    371 static void
    372 upgrade_header (ctf_header_t *hp)
    373 {
    374   ctf_header_v2_t *oldhp = (ctf_header_v2_t *) hp;
    375 
    376   hp->cth_strlen = oldhp->cth_strlen;
    377   hp->cth_stroff = oldhp->cth_stroff;
    378   hp->cth_typeoff = oldhp->cth_typeoff;
    379   hp->cth_varoff = oldhp->cth_varoff;
    380   hp->cth_funcidxoff = hp->cth_varoff;		/* No index sections.  */
    381   hp->cth_objtidxoff = hp->cth_funcidxoff;
    382   hp->cth_funcoff = oldhp->cth_funcoff;
    383   hp->cth_objtoff = oldhp->cth_objtoff;
    384   hp->cth_lbloff = oldhp->cth_lbloff;
    385   hp->cth_cuname = 0;				/* No CU name.  */
    386 }
    387 
    388 /* Upgrade the type table to CTF_VERSION_3 (really CTF_VERSION_1_UPGRADED_3)
    389    from CTF_VERSION_1.
    390 
    391    The upgrade is not done in-place: the ctf_base is moved.  ctf_strptr() must
    392    not be called before reallocation is complete.
    393 
    394    Sections not checked here due to nonexistence or nonpopulated state in older
    395    formats: objtidx, funcidx.
    396 
    397    Type kinds not checked here due to nonexistence in older formats:
    398       CTF_K_SLICE.  */
    399 static int
    400 upgrade_types_v1 (ctf_file_t *fp, ctf_header_t *cth)
    401 {
    402   const ctf_type_v1_t *tbuf;
    403   const ctf_type_v1_t *tend;
    404   unsigned char *ctf_base, *old_ctf_base = (unsigned char *) fp->ctf_dynbase;
    405   ctf_type_t *t2buf;
    406 
    407   ssize_t increase = 0, size, increment, v2increment, vbytes, v2bytes;
    408   const ctf_type_v1_t *tp;
    409   ctf_type_t *t2p;
    410 
    411   tbuf = (ctf_type_v1_t *) (fp->ctf_buf + cth->cth_typeoff);
    412   tend = (ctf_type_v1_t *) (fp->ctf_buf + cth->cth_stroff);
    413 
    414   /* Much like init_types(), this is a two-pass process.
    415 
    416      First, figure out the new type-section size needed.  (It is possible,
    417      in theory, for it to be less than the old size, but this is very
    418      unlikely.  It cannot be so small that cth_typeoff ends up of negative
    419      size.  We validate this with an assertion below.)
    420 
    421      We must cater not only for changes in vlen and types sizes but also
    422      for changes in 'increment', which happen because v2 places some types
    423      into ctf_stype_t where v1 would be forced to use the larger non-stype.  */
    424 
    425   for (tp = tbuf; tp < tend;
    426        tp = (ctf_type_v1_t *) ((uintptr_t) tp + increment + vbytes))
    427     {
    428       unsigned short kind = CTF_V1_INFO_KIND (tp->ctt_info);
    429       unsigned long vlen = CTF_V1_INFO_VLEN (tp->ctt_info);
    430 
    431       size = get_ctt_size_v1 (fp, (const ctf_type_t *) tp, NULL, &increment);
    432       vbytes = get_vbytes_v1 (fp, kind, size, vlen);
    433 
    434       get_ctt_size_v2_unconverted (fp, (const ctf_type_t *) tp, NULL,
    435 				   &v2increment);
    436       v2bytes = get_vbytes_v2 (fp, kind, size, vlen);
    437 
    438       if ((vbytes < 0) || (size < 0))
    439 	return ECTF_CORRUPT;
    440 
    441       increase += v2increment - increment;	/* May be negative.  */
    442       increase += v2bytes - vbytes;
    443     }
    444 
    445   /* Allocate enough room for the new buffer, then copy everything but the type
    446      section into place, and reset the base accordingly.  Leave the version
    447      number unchanged, so that LCTF_INFO_* still works on the
    448      as-yet-untranslated type info.  */
    449 
    450   if ((ctf_base = malloc (fp->ctf_size + increase)) == NULL)
    451     return ECTF_ZALLOC;
    452 
    453   /* Start at ctf_buf, not ctf_base, to squeeze out the original header: we
    454      never use it and it is unconverted.  */
    455 
    456   memcpy (ctf_base, fp->ctf_buf, cth->cth_typeoff);
    457   memcpy (ctf_base + cth->cth_stroff + increase,
    458 	  fp->ctf_buf + cth->cth_stroff, cth->cth_strlen);
    459 
    460   memset (ctf_base + cth->cth_typeoff, 0, cth->cth_stroff - cth->cth_typeoff
    461 	  + increase);
    462 
    463   cth->cth_stroff += increase;
    464   fp->ctf_size += increase;
    465   assert (cth->cth_stroff >= cth->cth_typeoff);
    466   fp->ctf_base = ctf_base;
    467   fp->ctf_buf = ctf_base;
    468   fp->ctf_dynbase = ctf_base;
    469   ctf_set_base (fp, cth, ctf_base);
    470 
    471   t2buf = (ctf_type_t *) (fp->ctf_buf + cth->cth_typeoff);
    472 
    473   /* Iterate through all the types again, upgrading them.
    474 
    475      Everything that hasn't changed can just be outright memcpy()ed.
    476      Things that have changed need field-by-field consideration.  */
    477 
    478   for (tp = tbuf, t2p = t2buf; tp < tend;
    479        tp = (ctf_type_v1_t *) ((uintptr_t) tp + increment + vbytes),
    480        t2p = (ctf_type_t *) ((uintptr_t) t2p + v2increment + v2bytes))
    481     {
    482       unsigned short kind = CTF_V1_INFO_KIND (tp->ctt_info);
    483       int isroot = CTF_V1_INFO_ISROOT (tp->ctt_info);
    484       unsigned long vlen = CTF_V1_INFO_VLEN (tp->ctt_info);
    485       ssize_t v2size;
    486       void *vdata, *v2data;
    487 
    488       size = get_ctt_size_v1 (fp, (const ctf_type_t *) tp, NULL, &increment);
    489       vbytes = get_vbytes_v1 (fp, kind, size, vlen);
    490 
    491       t2p->ctt_name = tp->ctt_name;
    492       t2p->ctt_info = CTF_TYPE_INFO (kind, isroot, vlen);
    493 
    494       switch (kind)
    495 	{
    496 	case CTF_K_FUNCTION:
    497 	case CTF_K_FORWARD:
    498 	case CTF_K_TYPEDEF:
    499 	case CTF_K_POINTER:
    500 	case CTF_K_VOLATILE:
    501 	case CTF_K_CONST:
    502 	case CTF_K_RESTRICT:
    503 	  t2p->ctt_type = tp->ctt_type;
    504 	  break;
    505 	case CTF_K_INTEGER:
    506 	case CTF_K_FLOAT:
    507 	case CTF_K_ARRAY:
    508 	case CTF_K_STRUCT:
    509 	case CTF_K_UNION:
    510 	case CTF_K_ENUM:
    511 	case CTF_K_UNKNOWN:
    512 	  if ((size_t) size <= CTF_MAX_SIZE)
    513 	    t2p->ctt_size = size;
    514 	  else
    515 	    {
    516 	      t2p->ctt_lsizehi = CTF_SIZE_TO_LSIZE_HI (size);
    517 	      t2p->ctt_lsizelo = CTF_SIZE_TO_LSIZE_LO (size);
    518 	    }
    519 	  break;
    520 	}
    521 
    522       v2size = get_ctt_size_v2 (fp, t2p, NULL, &v2increment);
    523       v2bytes = get_vbytes_v2 (fp, kind, v2size, vlen);
    524 
    525       /* Catch out-of-sync get_ctt_size_*().  The count goes wrong if
    526 	 these are not identical (and having them different makes no
    527 	 sense semantically).  */
    528 
    529       assert (size == v2size);
    530 
    531       /* Now the varlen info.  */
    532 
    533       vdata = (void *) ((uintptr_t) tp + increment);
    534       v2data = (void *) ((uintptr_t) t2p + v2increment);
    535 
    536       switch (kind)
    537 	{
    538 	case CTF_K_ARRAY:
    539 	  {
    540 	    const ctf_array_v1_t *ap = (const ctf_array_v1_t *) vdata;
    541 	    ctf_array_t *a2p = (ctf_array_t *) v2data;
    542 
    543 	    a2p->cta_contents = ap->cta_contents;
    544 	    a2p->cta_index = ap->cta_index;
    545 	    a2p->cta_nelems = ap->cta_nelems;
    546 	    break;
    547 	  }
    548 	case CTF_K_STRUCT:
    549 	case CTF_K_UNION:
    550 	  {
    551 	    ctf_member_t tmp;
    552 	    const ctf_member_v1_t *m1 = (const ctf_member_v1_t *) vdata;
    553 	    const ctf_lmember_v1_t *lm1 = (const ctf_lmember_v1_t *) m1;
    554 	    ctf_member_t *m2 = (ctf_member_t *) v2data;
    555 	    ctf_lmember_t *lm2 = (ctf_lmember_t *) m2;
    556 	    unsigned long i;
    557 
    558 	    /* We walk all four pointers forward, but only reference the two
    559 	       that are valid for the given size, to avoid quadruplicating all
    560 	       the code.  */
    561 
    562 	    for (i = vlen; i != 0; i--, m1++, lm1++, m2++, lm2++)
    563 	      {
    564 		size_t offset;
    565 		if (size < CTF_LSTRUCT_THRESH_V1)
    566 		  {
    567 		    offset = m1->ctm_offset;
    568 		    tmp.ctm_name = m1->ctm_name;
    569 		    tmp.ctm_type = m1->ctm_type;
    570 		  }
    571 		else
    572 		  {
    573 		    offset = CTF_LMEM_OFFSET (lm1);
    574 		    tmp.ctm_name = lm1->ctlm_name;
    575 		    tmp.ctm_type = lm1->ctlm_type;
    576 		  }
    577 		if (size < CTF_LSTRUCT_THRESH)
    578 		  {
    579 		    m2->ctm_name = tmp.ctm_name;
    580 		    m2->ctm_type = tmp.ctm_type;
    581 		    m2->ctm_offset = offset;
    582 		  }
    583 		else
    584 		  {
    585 		    lm2->ctlm_name = tmp.ctm_name;
    586 		    lm2->ctlm_type = tmp.ctm_type;
    587 		    lm2->ctlm_offsethi = CTF_OFFSET_TO_LMEMHI (offset);
    588 		    lm2->ctlm_offsetlo = CTF_OFFSET_TO_LMEMLO (offset);
    589 		  }
    590 	      }
    591 	    break;
    592 	  }
    593 	case CTF_K_FUNCTION:
    594 	  {
    595 	    unsigned long i;
    596 	    unsigned short *a1 = (unsigned short *) vdata;
    597 	    uint32_t *a2 = (uint32_t *) v2data;
    598 
    599 	    for (i = vlen; i != 0; i--, a1++, a2++)
    600 	      *a2 = *a1;
    601 	  }
    602 	/* FALLTHRU */
    603 	default:
    604 	  /* Catch out-of-sync get_vbytes_*().  */
    605 	  assert (vbytes == v2bytes);
    606 	  memcpy (v2data, vdata, vbytes);
    607 	}
    608     }
    609 
    610   /* Verify that the entire region was converted.  If not, we are either
    611      converting too much, or too little (leading to a buffer overrun either here
    612      or at read time, in init_types().) */
    613 
    614   assert ((size_t) t2p - (size_t) fp->ctf_buf == cth->cth_stroff);
    615 
    616   ctf_set_version (fp, cth, CTF_VERSION_1_UPGRADED_3);
    617   free (old_ctf_base);
    618 
    619   return 0;
    620 }
    621 
    622 /* Upgrade from any earlier version.  */
    623 static int
    624 upgrade_types (ctf_file_t *fp, ctf_header_t *cth)
    625 {
    626   switch (cth->cth_version)
    627     {
    628       /* v1 requires a full pass and reformatting.  */
    629     case CTF_VERSION_1:
    630       upgrade_types_v1 (fp, cth);
    631       /* FALLTHRU */
    632       /* Already-converted v1 is just like later versions except that its
    633 	 parent/child boundary is unchanged (and much lower).  */
    634 
    635     case CTF_VERSION_1_UPGRADED_3:
    636       fp->ctf_parmax = CTF_MAX_PTYPE_V1;
    637 
    638       /* v2 is just the same as v3 except for new types and sections:
    639 	 no upgrading required. */
    640     case CTF_VERSION_2: ;
    641       /* FALLTHRU */
    642     }
    643   return 0;
    644 }
    645 
    646 /* Initialize the type ID translation table with the byte offset of each type,
    647    and initialize the hash tables of each named type.  Upgrade the type table to
    648    the latest supported representation in the process, if needed, and if this
    649    recension of libctf supports upgrading.  */
    650 
    651 static int
    652 init_types (ctf_file_t *fp, ctf_header_t *cth)
    653 {
    654   const ctf_type_t *tbuf;
    655   const ctf_type_t *tend;
    656 
    657   unsigned long pop[CTF_K_MAX + 1] = { 0 };
    658   const ctf_type_t *tp;
    659   uint32_t id, dst;
    660   uint32_t *xp;
    661 
    662   /* We determine whether the container is a child or a parent based on
    663      the value of cth_parname.  */
    664 
    665   int child = cth->cth_parname != 0;
    666   int nlstructs = 0, nlunions = 0;
    667   int err;
    668 
    669   assert (!(fp->ctf_flags & LCTF_RDWR));
    670 
    671   if (_libctf_unlikely_ (fp->ctf_version == CTF_VERSION_1))
    672     {
    673       int err;
    674       if ((err = upgrade_types (fp, cth)) != 0)
    675 	return err;				/* Upgrade failed.  */
    676     }
    677 
    678   tbuf = (ctf_type_t *) (fp->ctf_buf + cth->cth_typeoff);
    679   tend = (ctf_type_t *) (fp->ctf_buf + cth->cth_stroff);
    680 
    681   /* We make two passes through the entire type section.  In this first
    682      pass, we count the number of each type and the total number of types.  */
    683 
    684   for (tp = tbuf; tp < tend; fp->ctf_typemax++)
    685     {
    686       unsigned short kind = LCTF_INFO_KIND (fp, tp->ctt_info);
    687       unsigned long vlen = LCTF_INFO_VLEN (fp, tp->ctt_info);
    688       ssize_t size, increment, vbytes;
    689 
    690       (void) ctf_get_ctt_size (fp, tp, &size, &increment);
    691       vbytes = LCTF_VBYTES (fp, kind, size, vlen);
    692 
    693       if (vbytes < 0)
    694 	return ECTF_CORRUPT;
    695 
    696       /* For forward declarations, ctt_type is the CTF_K_* kind for the tag,
    697 	 so bump that population count too.  */
    698       if (kind == CTF_K_FORWARD)
    699 	pop[tp->ctt_type]++;
    700 
    701       tp = (ctf_type_t *) ((uintptr_t) tp + increment + vbytes);
    702       pop[kind]++;
    703     }
    704 
    705   if (child)
    706     {
    707       ctf_dprintf ("CTF container %p is a child\n", (void *) fp);
    708       fp->ctf_flags |= LCTF_CHILD;
    709     }
    710   else
    711     ctf_dprintf ("CTF container %p is a parent\n", (void *) fp);
    712 
    713   /* Now that we've counted up the number of each type, we can allocate
    714      the hash tables, type translation table, and pointer table.  */
    715 
    716   if ((fp->ctf_structs.ctn_readonly
    717        = ctf_hash_create (pop[CTF_K_STRUCT], ctf_hash_string,
    718 			  ctf_hash_eq_string)) == NULL)
    719     return ENOMEM;
    720 
    721   if ((fp->ctf_unions.ctn_readonly
    722        = ctf_hash_create (pop[CTF_K_UNION], ctf_hash_string,
    723 			  ctf_hash_eq_string)) == NULL)
    724     return ENOMEM;
    725 
    726   if ((fp->ctf_enums.ctn_readonly
    727        = ctf_hash_create (pop[CTF_K_ENUM], ctf_hash_string,
    728 			  ctf_hash_eq_string)) == NULL)
    729     return ENOMEM;
    730 
    731   if ((fp->ctf_names.ctn_readonly
    732        = ctf_hash_create (pop[CTF_K_INTEGER] +
    733 			  pop[CTF_K_FLOAT] +
    734 			  pop[CTF_K_FUNCTION] +
    735 			  pop[CTF_K_TYPEDEF] +
    736 			  pop[CTF_K_POINTER] +
    737 			  pop[CTF_K_VOLATILE] +
    738 			  pop[CTF_K_CONST] +
    739 			  pop[CTF_K_RESTRICT],
    740 			  ctf_hash_string,
    741 			  ctf_hash_eq_string)) == NULL)
    742     return ENOMEM;
    743 
    744   fp->ctf_txlate = malloc (sizeof (uint32_t) * (fp->ctf_typemax + 1));
    745   fp->ctf_ptrtab_len = fp->ctf_typemax + 1;
    746   fp->ctf_ptrtab = malloc (sizeof (uint32_t) * fp->ctf_ptrtab_len);
    747 
    748   if (fp->ctf_txlate == NULL || fp->ctf_ptrtab == NULL)
    749     return ENOMEM;		/* Memory allocation failed.  */
    750 
    751   xp = fp->ctf_txlate;
    752   *xp++ = 0;			/* Type id 0 is used as a sentinel value.  */
    753 
    754   memset (fp->ctf_txlate, 0, sizeof (uint32_t) * (fp->ctf_typemax + 1));
    755   memset (fp->ctf_ptrtab, 0, sizeof (uint32_t) * (fp->ctf_typemax + 1));
    756 
    757   /* In the second pass through the types, we fill in each entry of the
    758      type and pointer tables and add names to the appropriate hashes.  */
    759 
    760   for (id = 1, tp = tbuf; tp < tend; xp++, id++)
    761     {
    762       unsigned short kind = LCTF_INFO_KIND (fp, tp->ctt_info);
    763       unsigned short isroot = LCTF_INFO_ISROOT (fp, tp->ctt_info);
    764       unsigned long vlen = LCTF_INFO_VLEN (fp, tp->ctt_info);
    765       ssize_t size, increment, vbytes;
    766 
    767       const char *name;
    768 
    769       (void) ctf_get_ctt_size (fp, tp, &size, &increment);
    770       name = ctf_strptr (fp, tp->ctt_name);
    771       /* Cannot fail: shielded by call in loop above.  */
    772       vbytes = LCTF_VBYTES (fp, kind, size, vlen);
    773 
    774       switch (kind)
    775 	{
    776 	case CTF_K_INTEGER:
    777 	case CTF_K_FLOAT:
    778 	  /* Names are reused by bit-fields, which are differentiated by their
    779 	     encodings, and so typically we'd record only the first instance of
    780 	     a given intrinsic.  However, we replace an existing type with a
    781 	     root-visible version so that we can be sure to find it when
    782 	     checking for conflicting definitions in ctf_add_type().  */
    783 
    784 	  if (((ctf_hash_lookup_type (fp->ctf_names.ctn_readonly,
    785 				      fp, name)) == 0)
    786 	      || isroot)
    787 	    {
    788 	      err = ctf_hash_define_type (fp->ctf_names.ctn_readonly, fp,
    789 					  LCTF_INDEX_TO_TYPE (fp, id, child),
    790 					  tp->ctt_name);
    791 	      if (err != 0)
    792 		return err;
    793 	    }
    794 	  break;
    795 
    796 	  /* These kinds have no name, so do not need interning into any
    797 	     hashtables.  */
    798 	case CTF_K_ARRAY:
    799 	case CTF_K_SLICE:
    800 	  break;
    801 
    802 	case CTF_K_FUNCTION:
    803 	  if (!isroot)
    804 	    break;
    805 
    806 	  err = ctf_hash_insert_type (fp->ctf_names.ctn_readonly, fp,
    807 				      LCTF_INDEX_TO_TYPE (fp, id, child),
    808 				      tp->ctt_name);
    809 	  if (err != 0)
    810 	    return err;
    811 	  break;
    812 
    813 	case CTF_K_STRUCT:
    814 	  if (size >= CTF_LSTRUCT_THRESH)
    815 	    nlstructs++;
    816 
    817 	  if (!isroot)
    818 	    break;
    819 
    820 	  err = ctf_hash_define_type (fp->ctf_structs.ctn_readonly, fp,
    821 				      LCTF_INDEX_TO_TYPE (fp, id, child),
    822 				      tp->ctt_name);
    823 
    824 	  if (err != 0)
    825 	    return err;
    826 
    827 	  break;
    828 
    829 	case CTF_K_UNION:
    830 	  if (size >= CTF_LSTRUCT_THRESH)
    831 	    nlunions++;
    832 
    833 	  if (!isroot)
    834 	    break;
    835 
    836 	  err = ctf_hash_define_type (fp->ctf_unions.ctn_readonly, fp,
    837 				      LCTF_INDEX_TO_TYPE (fp, id, child),
    838 				      tp->ctt_name);
    839 
    840 	  if (err != 0)
    841 	    return err;
    842 	  break;
    843 
    844 	case CTF_K_ENUM:
    845 	  if (!isroot)
    846 	    break;
    847 
    848 	  err = ctf_hash_define_type (fp->ctf_enums.ctn_readonly, fp,
    849 				      LCTF_INDEX_TO_TYPE (fp, id, child),
    850 				      tp->ctt_name);
    851 
    852 	  if (err != 0)
    853 	    return err;
    854 	  break;
    855 
    856 	case CTF_K_TYPEDEF:
    857 	  if (!isroot)
    858 	    break;
    859 
    860 	  err = ctf_hash_insert_type (fp->ctf_names.ctn_readonly, fp,
    861 				      LCTF_INDEX_TO_TYPE (fp, id, child),
    862 				      tp->ctt_name);
    863 	  if (err != 0)
    864 	    return err;
    865 	  break;
    866 
    867 	case CTF_K_FORWARD:
    868 	  {
    869 	    ctf_names_t *np = ctf_name_table (fp, tp->ctt_type);
    870 
    871 	    if (!isroot)
    872 	      break;
    873 
    874 	    /* Only insert forward tags into the given hash if the type or tag
    875 	       name is not already present.  */
    876 	    if (ctf_hash_lookup_type (np->ctn_readonly, fp, name) == 0)
    877 	      {
    878 		err = ctf_hash_insert_type (np->ctn_readonly, fp,
    879 					    LCTF_INDEX_TO_TYPE (fp, id, child),
    880 					    tp->ctt_name);
    881 		if (err != 0)
    882 		  return err;
    883 	      }
    884 	    break;
    885 	  }
    886 
    887 	case CTF_K_POINTER:
    888 	  /* If the type referenced by the pointer is in this CTF container,
    889 	     then store the index of the pointer type in
    890 	     fp->ctf_ptrtab[ index of referenced type ].  */
    891 
    892 	  if (LCTF_TYPE_ISCHILD (fp, tp->ctt_type) == child
    893 	      && LCTF_TYPE_TO_INDEX (fp, tp->ctt_type) <= fp->ctf_typemax)
    894 	    fp->ctf_ptrtab[LCTF_TYPE_TO_INDEX (fp, tp->ctt_type)] = id;
    895 	 /*FALLTHRU*/
    896 
    897 	case CTF_K_VOLATILE:
    898 	case CTF_K_CONST:
    899 	case CTF_K_RESTRICT:
    900 	  if (!isroot)
    901 	    break;
    902 
    903 	  err = ctf_hash_insert_type (fp->ctf_names.ctn_readonly, fp,
    904 				      LCTF_INDEX_TO_TYPE (fp, id, child),
    905 				      tp->ctt_name);
    906 	  if (err != 0)
    907 	    return err;
    908 	  break;
    909 	default:
    910 	  ctf_err_warn (fp, 0, ECTF_CORRUPT,
    911 			_("init_types(): unhandled CTF kind: %x"), kind);
    912 	  return ECTF_CORRUPT;
    913 	}
    914 
    915       *xp = (uint32_t) ((uintptr_t) tp - (uintptr_t) fp->ctf_buf);
    916       tp = (ctf_type_t *) ((uintptr_t) tp + increment + vbytes);
    917     }
    918 
    919   ctf_dprintf ("%lu total types processed\n", fp->ctf_typemax);
    920   ctf_dprintf ("%u enum names hashed\n",
    921 	       ctf_hash_size (fp->ctf_enums.ctn_readonly));
    922   ctf_dprintf ("%u struct names hashed (%d long)\n",
    923 	       ctf_hash_size (fp->ctf_structs.ctn_readonly), nlstructs);
    924   ctf_dprintf ("%u union names hashed (%d long)\n",
    925 	       ctf_hash_size (fp->ctf_unions.ctn_readonly), nlunions);
    926   ctf_dprintf ("%u base type names hashed\n",
    927 	       ctf_hash_size (fp->ctf_names.ctn_readonly));
    928 
    929   /* Make an additional pass through the pointer table to find pointers that
    930      point to anonymous typedef nodes.  If we find one, modify the pointer table
    931      so that the pointer is also known to point to the node that is referenced
    932      by the anonymous typedef node.  */
    933 
    934   for (id = 1; id <= fp->ctf_typemax; id++)
    935     {
    936       if ((dst = fp->ctf_ptrtab[id]) != 0)
    937 	{
    938 	  tp = LCTF_INDEX_TO_TYPEPTR (fp, id);
    939 
    940 	  if (LCTF_INFO_KIND (fp, tp->ctt_info) == CTF_K_TYPEDEF
    941 	      && strcmp (ctf_strptr (fp, tp->ctt_name), "") == 0
    942 	      && LCTF_TYPE_ISCHILD (fp, tp->ctt_type) == child
    943 	      && LCTF_TYPE_TO_INDEX (fp, tp->ctt_type) <= fp->ctf_typemax)
    944 	      fp->ctf_ptrtab[LCTF_TYPE_TO_INDEX (fp, tp->ctt_type)] = dst;
    945 	}
    946     }
    947 
    948   return 0;
    949 }
    950 
    951 /* Endianness-flipping routines.
    952 
    953    We flip everything, mindlessly, even 1-byte entities, so that future
    954    expansions do not require changes to this code.  */
    955 
    956 /* < C11? define away static assertions.  */
    957 
    958 #if !defined (__STDC_VERSION__) || __STDC_VERSION__ < 201112L
    959 #define _Static_assert(cond, err)
    960 #endif
    961 
    962 /* Swap the endianness of something.  */
    963 
    964 #define swap_thing(x)							\
    965   do {									\
    966     _Static_assert (sizeof (x) == 1 || (sizeof (x) % 2 == 0		\
    967 					&& sizeof (x) <= 8),		\
    968 		    "Invalid size, update endianness code");		\
    969     switch (sizeof (x)) {						\
    970     case 2: x = bswap_16 (x); break;					\
    971     case 4: x = bswap_32 (x); break;					\
    972     case 8: x = bswap_64 (x); break;					\
    973     case 1: /* Nothing needs doing */					\
    974       break;								\
    975     }									\
    976   } while (0);
    977 
    978 /* Flip the endianness of the CTF header.  */
    979 
    980 static void
    981 flip_header (ctf_header_t *cth)
    982 {
    983   swap_thing (cth->cth_preamble.ctp_magic);
    984   swap_thing (cth->cth_preamble.ctp_version);
    985   swap_thing (cth->cth_preamble.ctp_flags);
    986   swap_thing (cth->cth_parlabel);
    987   swap_thing (cth->cth_parname);
    988   swap_thing (cth->cth_cuname);
    989   swap_thing (cth->cth_objtoff);
    990   swap_thing (cth->cth_funcoff);
    991   swap_thing (cth->cth_objtidxoff);
    992   swap_thing (cth->cth_funcidxoff);
    993   swap_thing (cth->cth_varoff);
    994   swap_thing (cth->cth_typeoff);
    995   swap_thing (cth->cth_stroff);
    996   swap_thing (cth->cth_strlen);
    997 }
    998 
    999 /* Flip the endianness of the label section, an array of ctf_lblent_t.  */
   1000 
   1001 static void
   1002 flip_lbls (void *start, size_t len)
   1003 {
   1004   ctf_lblent_t *lbl = start;
   1005   ssize_t i;
   1006 
   1007   for (i = len / sizeof (struct ctf_lblent); i > 0; lbl++, i--)
   1008     {
   1009       swap_thing (lbl->ctl_label);
   1010       swap_thing (lbl->ctl_type);
   1011     }
   1012 }
   1013 
   1014 /* Flip the endianness of the data-object or function sections or their indexes,
   1015    all arrays of uint32_t.  (The function section has more internal structure,
   1016    but that structure is an array of uint32_t, so can be treated as one big
   1017    array for byte-swapping.)  */
   1018 
   1019 static void
   1020 flip_objts (void *start, size_t len)
   1021 {
   1022   uint32_t *obj = start;
   1023   ssize_t i;
   1024 
   1025   for (i = len / sizeof (uint32_t); i > 0; obj++, i--)
   1026       swap_thing (*obj);
   1027 }
   1028 
   1029 /* Flip the endianness of the variable section, an array of ctf_varent_t.  */
   1030 
   1031 static void
   1032 flip_vars (void *start, size_t len)
   1033 {
   1034   ctf_varent_t *var = start;
   1035   ssize_t i;
   1036 
   1037   for (i = len / sizeof (struct ctf_varent); i > 0; var++, i--)
   1038     {
   1039       swap_thing (var->ctv_name);
   1040       swap_thing (var->ctv_type);
   1041     }
   1042 }
   1043 
   1044 /* Flip the endianness of the type section, a tagged array of ctf_type or
   1045    ctf_stype followed by variable data.  */
   1046 
   1047 static int
   1048 flip_types (ctf_file_t *fp, void *start, size_t len)
   1049 {
   1050   ctf_type_t *t = start;
   1051 
   1052   while ((uintptr_t) t < ((uintptr_t) start) + len)
   1053     {
   1054       swap_thing (t->ctt_name);
   1055       swap_thing (t->ctt_info);
   1056       swap_thing (t->ctt_size);
   1057 
   1058       uint32_t kind = CTF_V2_INFO_KIND (t->ctt_info);
   1059       size_t size = t->ctt_size;
   1060       uint32_t vlen = CTF_V2_INFO_VLEN (t->ctt_info);
   1061       size_t vbytes = get_vbytes_v2 (fp, kind, size, vlen);
   1062 
   1063       if (_libctf_unlikely_ (size == CTF_LSIZE_SENT))
   1064 	{
   1065 	  swap_thing (t->ctt_lsizehi);
   1066 	  swap_thing (t->ctt_lsizelo);
   1067 	  size = CTF_TYPE_LSIZE (t);
   1068 	  t = (ctf_type_t *) ((uintptr_t) t + sizeof (ctf_type_t));
   1069 	}
   1070       else
   1071 	t = (ctf_type_t *) ((uintptr_t) t + sizeof (ctf_stype_t));
   1072 
   1073       switch (kind)
   1074 	{
   1075 	case CTF_K_FORWARD:
   1076 	case CTF_K_UNKNOWN:
   1077 	case CTF_K_POINTER:
   1078 	case CTF_K_TYPEDEF:
   1079 	case CTF_K_VOLATILE:
   1080 	case CTF_K_CONST:
   1081 	case CTF_K_RESTRICT:
   1082 	  /* These types have no vlen data to swap.  */
   1083 	  assert (vbytes == 0);
   1084 	  break;
   1085 
   1086 	case CTF_K_INTEGER:
   1087 	case CTF_K_FLOAT:
   1088 	  {
   1089 	    /* These types have a single uint32_t.  */
   1090 
   1091 	    uint32_t *item = (uint32_t *) t;
   1092 
   1093 	    swap_thing (*item);
   1094 	    break;
   1095 	  }
   1096 
   1097 	case CTF_K_FUNCTION:
   1098 	  {
   1099 	    /* This type has a bunch of uint32_ts.  */
   1100 
   1101 	    uint32_t *item = (uint32_t *) t;
   1102 	    ssize_t i;
   1103 
   1104 	    for (i = vlen; i > 0; item++, i--)
   1105 	      swap_thing (*item);
   1106 	    break;
   1107 	  }
   1108 
   1109 	case CTF_K_ARRAY:
   1110 	  {
   1111 	    /* This has a single ctf_array_t.  */
   1112 
   1113 	    ctf_array_t *a = (ctf_array_t *) t;
   1114 
   1115 	    assert (vbytes == sizeof (ctf_array_t));
   1116 	    swap_thing (a->cta_contents);
   1117 	    swap_thing (a->cta_index);
   1118 	    swap_thing (a->cta_nelems);
   1119 
   1120 	    break;
   1121 	  }
   1122 
   1123 	case CTF_K_SLICE:
   1124 	  {
   1125 	    /* This has a single ctf_slice_t.  */
   1126 
   1127 	    ctf_slice_t *s = (ctf_slice_t *) t;
   1128 
   1129 	    assert (vbytes == sizeof (ctf_slice_t));
   1130 	    swap_thing (s->cts_type);
   1131 	    swap_thing (s->cts_offset);
   1132 	    swap_thing (s->cts_bits);
   1133 
   1134 	    break;
   1135 	  }
   1136 
   1137 	case CTF_K_STRUCT:
   1138 	case CTF_K_UNION:
   1139 	  {
   1140 	    /* This has an array of ctf_member or ctf_lmember, depending on
   1141 	       size.  We could consider it to be a simple array of uint32_t,
   1142 	       but for safety's sake in case these structures ever acquire
   1143 	       non-uint32_t members, do it member by member.  */
   1144 
   1145 	    if (_libctf_unlikely_ (size >= CTF_LSTRUCT_THRESH))
   1146 	      {
   1147 		ctf_lmember_t *lm = (ctf_lmember_t *) t;
   1148 		ssize_t i;
   1149 		for (i = vlen; i > 0; i--, lm++)
   1150 		  {
   1151 		    swap_thing (lm->ctlm_name);
   1152 		    swap_thing (lm->ctlm_offsethi);
   1153 		    swap_thing (lm->ctlm_type);
   1154 		    swap_thing (lm->ctlm_offsetlo);
   1155 		  }
   1156 	      }
   1157 	    else
   1158 	      {
   1159 		ctf_member_t *m = (ctf_member_t *) t;
   1160 		ssize_t i;
   1161 		for (i = vlen; i > 0; i--, m++)
   1162 		  {
   1163 		    swap_thing (m->ctm_name);
   1164 		    swap_thing (m->ctm_offset);
   1165 		    swap_thing (m->ctm_type);
   1166 		  }
   1167 	      }
   1168 	    break;
   1169 	  }
   1170 
   1171 	case CTF_K_ENUM:
   1172 	  {
   1173 	    /* This has an array of ctf_enum_t.  */
   1174 
   1175 	    ctf_enum_t *item = (ctf_enum_t *) t;
   1176 	    ssize_t i;
   1177 
   1178 	    for (i = vlen; i > 0; item++, i--)
   1179 	      {
   1180 		swap_thing (item->cte_name);
   1181 		swap_thing (item->cte_value);
   1182 	      }
   1183 	    break;
   1184 	  }
   1185 	default:
   1186 	  ctf_err_warn (fp, 0, ECTF_CORRUPT,
   1187 			_("unhandled CTF kind in endianness conversion: %x"),
   1188 			kind);
   1189 	  return ECTF_CORRUPT;
   1190 	}
   1191 
   1192       t = (ctf_type_t *) ((uintptr_t) t + vbytes);
   1193     }
   1194 
   1195   return 0;
   1196 }
   1197 
   1198 /* Flip the endianness of BUF, given the offsets in the (already endian-
   1199    converted) CTH.
   1200 
   1201    All of this stuff happens before the header is fully initialized, so the
   1202    LCTF_*() macros cannot be used yet.  Since we do not try to endian-convert v1
   1203    data, this is no real loss.  */
   1204 
   1205 static int
   1206 flip_ctf (ctf_file_t *fp, ctf_header_t *cth, unsigned char *buf)
   1207 {
   1208   flip_lbls (buf + cth->cth_lbloff, cth->cth_objtoff - cth->cth_lbloff);
   1209   flip_objts (buf + cth->cth_objtoff, cth->cth_funcoff - cth->cth_objtoff);
   1210   flip_objts (buf + cth->cth_funcoff, cth->cth_objtidxoff - cth->cth_funcoff);
   1211   flip_objts (buf + cth->cth_objtidxoff, cth->cth_funcidxoff - cth->cth_objtidxoff);
   1212   flip_objts (buf + cth->cth_funcidxoff, cth->cth_varoff - cth->cth_funcidxoff);
   1213   flip_vars (buf + cth->cth_varoff, cth->cth_typeoff - cth->cth_varoff);
   1214   return flip_types (fp, buf + cth->cth_typeoff, cth->cth_stroff - cth->cth_typeoff);
   1215 }
   1216 
   1217 /* Set up the ctl hashes in a ctf_file_t.  Called by both writable and
   1218    non-writable dictionary initialization.  */
   1219 void ctf_set_ctl_hashes (ctf_file_t *fp)
   1220 {
   1221   /* Initialize the ctf_lookup_by_name top-level dictionary.  We keep an
   1222      array of type name prefixes and the corresponding ctf_hash to use.  */
   1223   fp->ctf_lookups[0].ctl_prefix = "struct";
   1224   fp->ctf_lookups[0].ctl_len = strlen (fp->ctf_lookups[0].ctl_prefix);
   1225   fp->ctf_lookups[0].ctl_hash = &fp->ctf_structs;
   1226   fp->ctf_lookups[1].ctl_prefix = "union";
   1227   fp->ctf_lookups[1].ctl_len = strlen (fp->ctf_lookups[1].ctl_prefix);
   1228   fp->ctf_lookups[1].ctl_hash = &fp->ctf_unions;
   1229   fp->ctf_lookups[2].ctl_prefix = "enum";
   1230   fp->ctf_lookups[2].ctl_len = strlen (fp->ctf_lookups[2].ctl_prefix);
   1231   fp->ctf_lookups[2].ctl_hash = &fp->ctf_enums;
   1232   fp->ctf_lookups[3].ctl_prefix = _CTF_NULLSTR;
   1233   fp->ctf_lookups[3].ctl_len = strlen (fp->ctf_lookups[3].ctl_prefix);
   1234   fp->ctf_lookups[3].ctl_hash = &fp->ctf_names;
   1235   fp->ctf_lookups[4].ctl_prefix = NULL;
   1236   fp->ctf_lookups[4].ctl_len = 0;
   1237   fp->ctf_lookups[4].ctl_hash = NULL;
   1238 }
   1239 
   1240 /* Open a CTF file, mocking up a suitable ctf_sect.  */
   1241 
   1242 ctf_file_t *ctf_simple_open (const char *ctfsect, size_t ctfsect_size,
   1243 			     const char *symsect, size_t symsect_size,
   1244 			     size_t symsect_entsize,
   1245 			     const char *strsect, size_t strsect_size,
   1246 			     int *errp)
   1247 {
   1248   return ctf_simple_open_internal (ctfsect, ctfsect_size, symsect, symsect_size,
   1249 				   symsect_entsize, strsect, strsect_size, NULL,
   1250 				   0, errp);
   1251 }
   1252 
   1253 /* Open a CTF file, mocking up a suitable ctf_sect and overriding the external
   1254    strtab with a synthetic one.  */
   1255 
   1256 ctf_file_t *ctf_simple_open_internal (const char *ctfsect, size_t ctfsect_size,
   1257 				      const char *symsect, size_t symsect_size,
   1258 				      size_t symsect_entsize,
   1259 				      const char *strsect, size_t strsect_size,
   1260 				      ctf_dynhash_t *syn_strtab, int writable,
   1261 				      int *errp)
   1262 {
   1263   ctf_sect_t skeleton;
   1264 
   1265   ctf_sect_t ctf_sect, sym_sect, str_sect;
   1266   ctf_sect_t *ctfsectp = NULL;
   1267   ctf_sect_t *symsectp = NULL;
   1268   ctf_sect_t *strsectp = NULL;
   1269 
   1270   skeleton.cts_name = _CTF_SECTION;
   1271   skeleton.cts_entsize = 1;
   1272 
   1273   if (ctfsect)
   1274     {
   1275       memcpy (&ctf_sect, &skeleton, sizeof (struct ctf_sect));
   1276       ctf_sect.cts_data = ctfsect;
   1277       ctf_sect.cts_size = ctfsect_size;
   1278       ctfsectp = &ctf_sect;
   1279     }
   1280 
   1281   if (symsect)
   1282     {
   1283       memcpy (&sym_sect, &skeleton, sizeof (struct ctf_sect));
   1284       sym_sect.cts_data = symsect;
   1285       sym_sect.cts_size = symsect_size;
   1286       sym_sect.cts_entsize = symsect_entsize;
   1287       symsectp = &sym_sect;
   1288     }
   1289 
   1290   if (strsect)
   1291     {
   1292       memcpy (&str_sect, &skeleton, sizeof (struct ctf_sect));
   1293       str_sect.cts_data = strsect;
   1294       str_sect.cts_size = strsect_size;
   1295       strsectp = &str_sect;
   1296     }
   1297 
   1298   return ctf_bufopen_internal (ctfsectp, symsectp, strsectp, syn_strtab,
   1299 			       writable, errp);
   1300 }
   1301 
   1302 /* Decode the specified CTF buffer and optional symbol table, and create a new
   1303    CTF container representing the symbolic debugging information.  This code can
   1304    be used directly by the debugger, or it can be used as the engine for
   1305    ctf_fdopen() or ctf_open(), below.  */
   1306 
   1307 ctf_file_t *
   1308 ctf_bufopen (const ctf_sect_t *ctfsect, const ctf_sect_t *symsect,
   1309 	     const ctf_sect_t *strsect, int *errp)
   1310 {
   1311   return ctf_bufopen_internal (ctfsect, symsect, strsect, NULL, 0, errp);
   1312 }
   1313 
   1314 /* Like ctf_bufopen, but overriding the external strtab with a synthetic one.  */
   1315 
   1316 ctf_file_t *
   1317 ctf_bufopen_internal (const ctf_sect_t *ctfsect, const ctf_sect_t *symsect,
   1318 		      const ctf_sect_t *strsect, ctf_dynhash_t *syn_strtab,
   1319 		      int writable, int *errp)
   1320 {
   1321   const ctf_preamble_t *pp;
   1322   size_t hdrsz = sizeof (ctf_header_t);
   1323   ctf_header_t *hp;
   1324   ctf_file_t *fp;
   1325   int foreign_endian = 0;
   1326   int err;
   1327 
   1328   libctf_init_debug();
   1329 
   1330   if ((ctfsect == NULL) || ((symsect != NULL) &&
   1331 			    ((strsect == NULL) && syn_strtab == NULL)))
   1332     return (ctf_set_open_errno (errp, EINVAL));
   1333 
   1334   if (symsect != NULL && symsect->cts_entsize != sizeof (Elf32_Sym) &&
   1335       symsect->cts_entsize != sizeof (Elf64_Sym))
   1336     return (ctf_set_open_errno (errp, ECTF_SYMTAB));
   1337 
   1338   if (symsect != NULL && symsect->cts_data == NULL)
   1339     return (ctf_set_open_errno (errp, ECTF_SYMBAD));
   1340 
   1341   if (strsect != NULL && strsect->cts_data == NULL)
   1342     return (ctf_set_open_errno (errp, ECTF_STRBAD));
   1343 
   1344   if (ctfsect->cts_size < sizeof (ctf_preamble_t))
   1345     return (ctf_set_open_errno (errp, ECTF_NOCTFBUF));
   1346 
   1347   pp = (const ctf_preamble_t *) ctfsect->cts_data;
   1348 
   1349   ctf_dprintf ("ctf_bufopen: magic=0x%x version=%u\n",
   1350 	       pp->ctp_magic, pp->ctp_version);
   1351 
   1352   /* Validate each part of the CTF header.
   1353 
   1354      First, we validate the preamble (common to all versions).  At that point,
   1355      we know the endianness and specific header version, and can validate the
   1356      version-specific parts including section offsets and alignments.
   1357 
   1358      We specifically do not support foreign-endian old versions.  */
   1359 
   1360   if (_libctf_unlikely_ (pp->ctp_magic != CTF_MAGIC))
   1361     {
   1362       if (pp->ctp_magic == bswap_16 (CTF_MAGIC))
   1363 	{
   1364 	  if (pp->ctp_version != CTF_VERSION_3)
   1365 	    return (ctf_set_open_errno (errp, ECTF_CTFVERS));
   1366 	  foreign_endian = 1;
   1367 	}
   1368       else
   1369 	return (ctf_set_open_errno (errp, ECTF_NOCTFBUF));
   1370     }
   1371 
   1372   if (_libctf_unlikely_ ((pp->ctp_version < CTF_VERSION_1)
   1373 			 || (pp->ctp_version > CTF_VERSION_3)))
   1374     return (ctf_set_open_errno (errp, ECTF_CTFVERS));
   1375 
   1376   if ((symsect != NULL) && (pp->ctp_version < CTF_VERSION_2))
   1377     {
   1378       /* The symtab can contain function entries which contain embedded ctf
   1379 	 info.  We do not support dynamically upgrading such entries (none
   1380 	 should exist in any case, since dwarf2ctf does not create them).  */
   1381 
   1382       ctf_err_warn (NULL, 0, 0, _("ctf_bufopen: CTF version %d symsect not "
   1383 				  "supported"), pp->ctp_version);
   1384       return (ctf_set_open_errno (errp, ECTF_NOTSUP));
   1385     }
   1386 
   1387   if (pp->ctp_version < CTF_VERSION_3)
   1388     hdrsz = sizeof (ctf_header_v2_t);
   1389 
   1390   if (_libctf_unlikely_ (pp->ctp_flags > CTF_F_MAX))
   1391     return (ctf_set_open_errno (errp, ECTF_FLAGS));
   1392 
   1393   if (ctfsect->cts_size < hdrsz)
   1394     return (ctf_set_open_errno (errp, ECTF_NOCTFBUF));
   1395 
   1396   if ((fp = malloc (sizeof (ctf_file_t))) == NULL)
   1397     return (ctf_set_open_errno (errp, ENOMEM));
   1398 
   1399   memset (fp, 0, sizeof (ctf_file_t));
   1400 
   1401   if (writable)
   1402     fp->ctf_flags |= LCTF_RDWR;
   1403 
   1404   if ((fp->ctf_header = malloc (sizeof (struct ctf_header))) == NULL)
   1405     {
   1406       free (fp);
   1407       return (ctf_set_open_errno (errp, ENOMEM));
   1408     }
   1409   hp = fp->ctf_header;
   1410   memcpy (hp, ctfsect->cts_data, hdrsz);
   1411   if (pp->ctp_version < CTF_VERSION_3)
   1412     upgrade_header (hp);
   1413 
   1414   if (foreign_endian)
   1415     flip_header (hp);
   1416   fp->ctf_openflags = hp->cth_flags;
   1417   fp->ctf_size = hp->cth_stroff + hp->cth_strlen;
   1418 
   1419   ctf_dprintf ("ctf_bufopen: uncompressed size=%lu\n",
   1420 	       (unsigned long) fp->ctf_size);
   1421 
   1422   if (hp->cth_lbloff > fp->ctf_size || hp->cth_objtoff > fp->ctf_size
   1423       || hp->cth_funcoff > fp->ctf_size || hp->cth_objtidxoff > fp->ctf_size
   1424       || hp->cth_funcidxoff > fp->ctf_size || hp->cth_typeoff > fp->ctf_size
   1425       || hp->cth_stroff > fp->ctf_size)
   1426     return (ctf_set_open_errno (errp, ECTF_CORRUPT));
   1427 
   1428   if (hp->cth_lbloff > hp->cth_objtoff
   1429       || hp->cth_objtoff > hp->cth_funcoff
   1430       || hp->cth_funcoff > hp->cth_typeoff
   1431       || hp->cth_funcoff > hp->cth_objtidxoff
   1432       || hp->cth_objtidxoff > hp->cth_funcidxoff
   1433       || hp->cth_funcidxoff > hp->cth_varoff
   1434       || hp->cth_varoff > hp->cth_typeoff || hp->cth_typeoff > hp->cth_stroff)
   1435     return (ctf_set_open_errno (errp, ECTF_CORRUPT));
   1436 
   1437   if ((hp->cth_lbloff & 3) || (hp->cth_objtoff & 2)
   1438       || (hp->cth_funcoff & 2) || (hp->cth_objtidxoff & 2)
   1439       || (hp->cth_funcidxoff & 2) || (hp->cth_varoff & 3)
   1440       || (hp->cth_typeoff & 3))
   1441     return (ctf_set_open_errno (errp, ECTF_CORRUPT));
   1442 
   1443   /* Once everything is determined to be valid, attempt to decompress the CTF
   1444      data buffer if it is compressed, or copy it into new storage if it is not
   1445      compressed but needs endian-flipping.  Otherwise we just put the data
   1446      section's buffer pointer into ctf_buf, below.  */
   1447 
   1448   /* Note: if this is a v1 buffer, it will be reallocated and expanded by
   1449      init_types().  */
   1450 
   1451   if (hp->cth_flags & CTF_F_COMPRESS)
   1452     {
   1453       size_t srclen;
   1454       uLongf dstlen;
   1455       const void *src;
   1456       int rc = Z_OK;
   1457 
   1458       /* We are allocating this ourselves, so we can drop the ctf header
   1459 	 copy in favour of ctf->ctf_header.  */
   1460 
   1461       if ((fp->ctf_base = malloc (fp->ctf_size)) == NULL)
   1462 	{
   1463 	  err = ECTF_ZALLOC;
   1464 	  goto bad;
   1465 	}
   1466       fp->ctf_dynbase = fp->ctf_base;
   1467       hp->cth_flags &= ~CTF_F_COMPRESS;
   1468 
   1469       src = (unsigned char *) ctfsect->cts_data + hdrsz;
   1470       srclen = ctfsect->cts_size - hdrsz;
   1471       dstlen = fp->ctf_size;
   1472       fp->ctf_buf = fp->ctf_base;
   1473 
   1474       if ((rc = uncompress (fp->ctf_base, &dstlen, src, srclen)) != Z_OK)
   1475 	{
   1476 	  ctf_err_warn (NULL, 0, ECTF_DECOMPRESS, _("zlib inflate err: %s"),
   1477 			zError (rc));
   1478 	  err = ECTF_DECOMPRESS;
   1479 	  goto bad;
   1480 	}
   1481 
   1482       if ((size_t) dstlen != fp->ctf_size)
   1483 	{
   1484 	  ctf_err_warn (NULL, 0, ECTF_CORRUPT,
   1485 			_("zlib inflate short: got %lu of %lu bytes"),
   1486 			(unsigned long) dstlen, (unsigned long) fp->ctf_size);
   1487 	  err = ECTF_CORRUPT;
   1488 	  goto bad;
   1489 	}
   1490     }
   1491   else if (foreign_endian)
   1492     {
   1493       if ((fp->ctf_base = malloc (fp->ctf_size)) == NULL)
   1494 	{
   1495 	  err = ECTF_ZALLOC;
   1496 	  goto bad;
   1497 	}
   1498       fp->ctf_dynbase = fp->ctf_base;
   1499       memcpy (fp->ctf_base, ((unsigned char *) ctfsect->cts_data) + hdrsz,
   1500 	      fp->ctf_size);
   1501       fp->ctf_buf = fp->ctf_base;
   1502     }
   1503   else
   1504     {
   1505       /* We are just using the section passed in -- but its header may be an old
   1506 	 version.  Point ctf_buf past the old header, and never touch it
   1507 	 again.  */
   1508       fp->ctf_base = (unsigned char *) ctfsect->cts_data;
   1509       fp->ctf_dynbase = NULL;
   1510       fp->ctf_buf = fp->ctf_base + hdrsz;
   1511     }
   1512 
   1513   /* Once we have uncompressed and validated the CTF data buffer, we can
   1514      proceed with initializing the ctf_file_t we allocated above.
   1515 
   1516      Nothing that depends on buf or base should be set directly in this function
   1517      before the init_types() call, because it may be reallocated during
   1518      transparent upgrade if this recension of libctf is so configured: see
   1519      ctf_set_base().  */
   1520 
   1521   ctf_set_version (fp, hp, hp->cth_version);
   1522   ctf_str_create_atoms (fp);
   1523   fp->ctf_parmax = CTF_MAX_PTYPE;
   1524   memcpy (&fp->ctf_data, ctfsect, sizeof (ctf_sect_t));
   1525 
   1526   if (symsect != NULL)
   1527     {
   1528       memcpy (&fp->ctf_symtab, symsect, sizeof (ctf_sect_t));
   1529       memcpy (&fp->ctf_strtab, strsect, sizeof (ctf_sect_t));
   1530     }
   1531 
   1532   if (fp->ctf_data.cts_name != NULL)
   1533     if ((fp->ctf_data.cts_name = strdup (fp->ctf_data.cts_name)) == NULL)
   1534       {
   1535 	err = ENOMEM;
   1536 	goto bad;
   1537       }
   1538   if (fp->ctf_symtab.cts_name != NULL)
   1539     if ((fp->ctf_symtab.cts_name = strdup (fp->ctf_symtab.cts_name)) == NULL)
   1540       {
   1541 	err = ENOMEM;
   1542 	goto bad;
   1543       }
   1544   if (fp->ctf_strtab.cts_name != NULL)
   1545     if ((fp->ctf_strtab.cts_name = strdup (fp->ctf_strtab.cts_name)) == NULL)
   1546       {
   1547 	err = ENOMEM;
   1548 	goto bad;
   1549       }
   1550 
   1551   if (fp->ctf_data.cts_name == NULL)
   1552     fp->ctf_data.cts_name = _CTF_NULLSTR;
   1553   if (fp->ctf_symtab.cts_name == NULL)
   1554     fp->ctf_symtab.cts_name = _CTF_NULLSTR;
   1555   if (fp->ctf_strtab.cts_name == NULL)
   1556     fp->ctf_strtab.cts_name = _CTF_NULLSTR;
   1557 
   1558   if (strsect != NULL)
   1559     {
   1560       fp->ctf_str[CTF_STRTAB_1].cts_strs = strsect->cts_data;
   1561       fp->ctf_str[CTF_STRTAB_1].cts_len = strsect->cts_size;
   1562     }
   1563   fp->ctf_syn_ext_strtab = syn_strtab;
   1564 
   1565   if (foreign_endian &&
   1566       (err = flip_ctf (fp, hp, fp->ctf_buf)) != 0)
   1567     {
   1568       /* We can be certain that flip_ctf() will have endian-flipped everything
   1569 	 other than the types table when we return.  In particular the header
   1570 	 is fine, so set it, to allow freeing to use the usual code path.  */
   1571 
   1572       ctf_set_base (fp, hp, fp->ctf_base);
   1573       goto bad;
   1574     }
   1575 
   1576   ctf_set_base (fp, hp, fp->ctf_base);
   1577 
   1578   /* No need to do anything else for dynamic containers: they do not support
   1579      symbol lookups, and the type table is maintained in the dthashes.  */
   1580   if (fp->ctf_flags & LCTF_RDWR)
   1581     {
   1582       fp->ctf_refcnt = 1;
   1583       return fp;
   1584     }
   1585 
   1586   if ((err = init_types (fp, hp)) != 0)
   1587     goto bad;
   1588 
   1589   /* If we have a symbol table section, allocate and initialize
   1590      the symtab translation table, pointed to by ctf_sxlate.  This table may be
   1591      too large for the actual size of the object and function info sections: if
   1592      so, ctf_nsyms will be adjusted and the excess will never be used.  */
   1593 
   1594   if (symsect != NULL)
   1595     {
   1596       fp->ctf_nsyms = symsect->cts_size / symsect->cts_entsize;
   1597       fp->ctf_sxlate = malloc (fp->ctf_nsyms * sizeof (uint32_t));
   1598 
   1599       if (fp->ctf_sxlate == NULL)
   1600 	{
   1601 	  err = ENOMEM;
   1602 	  goto bad;
   1603 	}
   1604 
   1605       if ((err = init_symtab (fp, hp, symsect, strsect)) != 0)
   1606 	goto bad;
   1607     }
   1608 
   1609   ctf_set_ctl_hashes (fp);
   1610 
   1611   if (symsect != NULL)
   1612     {
   1613       if (symsect->cts_entsize == sizeof (Elf64_Sym))
   1614 	(void) ctf_setmodel (fp, CTF_MODEL_LP64);
   1615       else
   1616 	(void) ctf_setmodel (fp, CTF_MODEL_ILP32);
   1617     }
   1618   else
   1619     (void) ctf_setmodel (fp, CTF_MODEL_NATIVE);
   1620 
   1621   fp->ctf_refcnt = 1;
   1622   return fp;
   1623 
   1624 bad:
   1625   ctf_set_open_errno (errp, err);
   1626   ctf_err_warn_to_open (fp);
   1627   ctf_file_close (fp);
   1628   return NULL;
   1629 }
   1630 
   1631 /* Bump the refcount on the specified CTF container, to allow export of
   1632    ctf_file_t's from iterators that open and close the ctf_file_t around the
   1633    loop.  (This does not extend their lifetime beyond that of the ctf_archive_t
   1634    in which they are contained.)  */
   1635 
   1636 void
   1637 ctf_ref (ctf_file_t *fp)
   1638 {
   1639   fp->ctf_refcnt++;
   1640 }
   1641 
   1642 /* Close the specified CTF container and free associated data structures.  Note
   1643    that ctf_file_close() is a reference counted operation: if the specified file
   1644    is the parent of other active containers, its reference count will be greater
   1645    than one and it will be freed later when no active children exist.  */
   1646 
   1647 void
   1648 ctf_file_close (ctf_file_t *fp)
   1649 {
   1650   ctf_dtdef_t *dtd, *ntd;
   1651   ctf_dvdef_t *dvd, *nvd;
   1652   ctf_err_warning_t *err, *nerr;
   1653 
   1654   if (fp == NULL)
   1655     return;		   /* Allow ctf_file_close(NULL) to simplify caller code.  */
   1656 
   1657   ctf_dprintf ("ctf_file_close(%p) refcnt=%u\n", (void *) fp, fp->ctf_refcnt);
   1658 
   1659   if (fp->ctf_refcnt > 1)
   1660     {
   1661       fp->ctf_refcnt--;
   1662       return;
   1663     }
   1664 
   1665   /* It is possible to recurse back in here, notably if dicts in the
   1666      ctf_link_inputs or ctf_link_outputs cite this dict as a parent without
   1667      using ctf_import_unref.  Do nothing in that case.  */
   1668   if (fp->ctf_refcnt == 0)
   1669     return;
   1670 
   1671   fp->ctf_refcnt--;
   1672   free (fp->ctf_dyncuname);
   1673   free (fp->ctf_dynparname);
   1674   if (fp->ctf_parent && !fp->ctf_parent_unreffed)
   1675     ctf_file_close (fp->ctf_parent);
   1676 
   1677   for (dtd = ctf_list_next (&fp->ctf_dtdefs); dtd != NULL; dtd = ntd)
   1678     {
   1679       ntd = ctf_list_next (dtd);
   1680       ctf_dtd_delete (fp, dtd);
   1681     }
   1682   ctf_dynhash_destroy (fp->ctf_dthash);
   1683   if (fp->ctf_flags & LCTF_RDWR)
   1684     {
   1685       ctf_dynhash_destroy (fp->ctf_structs.ctn_writable);
   1686       ctf_dynhash_destroy (fp->ctf_unions.ctn_writable);
   1687       ctf_dynhash_destroy (fp->ctf_enums.ctn_writable);
   1688       ctf_dynhash_destroy (fp->ctf_names.ctn_writable);
   1689     }
   1690   else
   1691     {
   1692       ctf_hash_destroy (fp->ctf_structs.ctn_readonly);
   1693       ctf_hash_destroy (fp->ctf_unions.ctn_readonly);
   1694       ctf_hash_destroy (fp->ctf_enums.ctn_readonly);
   1695       ctf_hash_destroy (fp->ctf_names.ctn_readonly);
   1696     }
   1697 
   1698   for (dvd = ctf_list_next (&fp->ctf_dvdefs); dvd != NULL; dvd = nvd)
   1699     {
   1700       nvd = ctf_list_next (dvd);
   1701       ctf_dvd_delete (fp, dvd);
   1702     }
   1703   ctf_dynhash_destroy (fp->ctf_dvhash);
   1704   ctf_str_free_atoms (fp);
   1705   free (fp->ctf_tmp_typeslice);
   1706 
   1707   if (fp->ctf_data.cts_name != _CTF_NULLSTR)
   1708     free ((char *) fp->ctf_data.cts_name);
   1709 
   1710   if (fp->ctf_symtab.cts_name != _CTF_NULLSTR)
   1711     free ((char *) fp->ctf_symtab.cts_name);
   1712 
   1713   if (fp->ctf_strtab.cts_name != _CTF_NULLSTR)
   1714     free ((char *) fp->ctf_strtab.cts_name);
   1715   else if (fp->ctf_data_mmapped)
   1716     ctf_munmap (fp->ctf_data_mmapped, fp->ctf_data_mmapped_len);
   1717 
   1718   free (fp->ctf_dynbase);
   1719 
   1720   ctf_dynhash_destroy (fp->ctf_syn_ext_strtab);
   1721   ctf_dynhash_destroy (fp->ctf_link_inputs);
   1722   ctf_dynhash_destroy (fp->ctf_link_outputs);
   1723   ctf_dynhash_destroy (fp->ctf_link_type_mapping);
   1724   ctf_dynhash_destroy (fp->ctf_link_in_cu_mapping);
   1725   ctf_dynhash_destroy (fp->ctf_link_out_cu_mapping);
   1726   ctf_dynhash_destroy (fp->ctf_add_processing);
   1727   ctf_dedup_fini (fp, NULL, 0);
   1728   ctf_dynset_destroy (fp->ctf_dedup_atoms_alloc);
   1729 
   1730   for (err = ctf_list_next (&fp->ctf_errs_warnings); err != NULL; err = nerr)
   1731     {
   1732       nerr = ctf_list_next (err);
   1733       ctf_list_delete (&fp->ctf_errs_warnings, err);
   1734       free (err->cew_text);
   1735       free (err);
   1736     }
   1737 
   1738   free (fp->ctf_sxlate);
   1739   free (fp->ctf_txlate);
   1740   free (fp->ctf_ptrtab);
   1741 
   1742   free (fp->ctf_header);
   1743   free (fp);
   1744 }
   1745 
   1746 /* The converse of ctf_open().  ctf_open() disguises whatever it opens as an
   1747    archive, so closing one is just like closing an archive.  */
   1748 void
   1749 ctf_close (ctf_archive_t *arc)
   1750 {
   1751   ctf_arc_close (arc);
   1752 }
   1753 
   1754 /* Get the CTF archive from which this ctf_file_t is derived.  */
   1755 ctf_archive_t *
   1756 ctf_get_arc (const ctf_file_t *fp)
   1757 {
   1758   return fp->ctf_archive;
   1759 }
   1760 
   1761 /* Return the ctfsect out of the core ctf_impl.  Useful for freeing the
   1762    ctfsect's data * after ctf_file_close(), which is why we return the actual
   1763    structure, not a pointer to it, since that is likely to become a pointer to
   1764    freed data before the return value is used under the expected use case of
   1765    ctf_getsect()/ ctf_file_close()/free().  */
   1766 ctf_sect_t
   1767 ctf_getdatasect (const ctf_file_t *fp)
   1768 {
   1769   return fp->ctf_data;
   1770 }
   1771 
   1772 /* Return the CTF handle for the parent CTF container, if one exists.
   1773    Otherwise return NULL to indicate this container has no imported parent.  */
   1774 ctf_file_t *
   1775 ctf_parent_file (ctf_file_t *fp)
   1776 {
   1777   return fp->ctf_parent;
   1778 }
   1779 
   1780 /* Return the name of the parent CTF container, if one exists.  Otherwise
   1781    return NULL to indicate this container is a root container.  */
   1782 const char *
   1783 ctf_parent_name (ctf_file_t *fp)
   1784 {
   1785   return fp->ctf_parname;
   1786 }
   1787 
   1788 /* Set the parent name.  It is an error to call this routine without calling
   1789    ctf_import() at some point.  */
   1790 int
   1791 ctf_parent_name_set (ctf_file_t *fp, const char *name)
   1792 {
   1793   if (fp->ctf_dynparname != NULL)
   1794     free (fp->ctf_dynparname);
   1795 
   1796   if ((fp->ctf_dynparname = strdup (name)) == NULL)
   1797     return (ctf_set_errno (fp, ENOMEM));
   1798   fp->ctf_parname = fp->ctf_dynparname;
   1799   return 0;
   1800 }
   1801 
   1802 /* Return the name of the compilation unit this CTF file applies to.  Usually
   1803    non-NULL only for non-parent containers.  */
   1804 const char *
   1805 ctf_cuname (ctf_file_t *fp)
   1806 {
   1807   return fp->ctf_cuname;
   1808 }
   1809 
   1810 /* Set the compilation unit name.  */
   1811 int
   1812 ctf_cuname_set (ctf_file_t *fp, const char *name)
   1813 {
   1814   if (fp->ctf_dyncuname != NULL)
   1815     free (fp->ctf_dyncuname);
   1816 
   1817   if ((fp->ctf_dyncuname = strdup (name)) == NULL)
   1818     return (ctf_set_errno (fp, ENOMEM));
   1819   fp->ctf_cuname = fp->ctf_dyncuname;
   1820   return 0;
   1821 }
   1822 
   1823 /* Import the types from the specified parent container by storing a pointer
   1824    to it in ctf_parent and incrementing its reference count.  Only one parent
   1825    is allowed: if a parent already exists, it is replaced by the new parent.  */
   1826 int
   1827 ctf_import (ctf_file_t *fp, ctf_file_t *pfp)
   1828 {
   1829   if (fp == NULL || fp == pfp || (pfp != NULL && pfp->ctf_refcnt == 0))
   1830     return (ctf_set_errno (fp, EINVAL));
   1831 
   1832   if (pfp != NULL && pfp->ctf_dmodel != fp->ctf_dmodel)
   1833     return (ctf_set_errno (fp, ECTF_DMODEL));
   1834 
   1835   if (fp->ctf_parent && !fp->ctf_parent_unreffed)
   1836     ctf_file_close (fp->ctf_parent);
   1837   fp->ctf_parent = NULL;
   1838 
   1839   if (pfp != NULL)
   1840     {
   1841       int err;
   1842 
   1843       if (fp->ctf_parname == NULL)
   1844 	if ((err = ctf_parent_name_set (fp, "PARENT")) < 0)
   1845 	  return err;
   1846 
   1847       fp->ctf_flags |= LCTF_CHILD;
   1848       pfp->ctf_refcnt++;
   1849       fp->ctf_parent_unreffed = 0;
   1850     }
   1851 
   1852   fp->ctf_parent = pfp;
   1853   return 0;
   1854 }
   1855 
   1856 /* Like ctf_import, but does not increment the refcount on the imported parent
   1857    or close it at any point: as a result it can go away at any time and the
   1858    caller must do all freeing itself.  Used internally to avoid refcount
   1859    loops.  */
   1860 int
   1861 ctf_import_unref (ctf_file_t *fp, ctf_file_t *pfp)
   1862 {
   1863   if (fp == NULL || fp == pfp || (pfp != NULL && pfp->ctf_refcnt == 0))
   1864     return (ctf_set_errno (fp, EINVAL));
   1865 
   1866   if (pfp != NULL && pfp->ctf_dmodel != fp->ctf_dmodel)
   1867     return (ctf_set_errno (fp, ECTF_DMODEL));
   1868 
   1869   if (fp->ctf_parent && !fp->ctf_parent_unreffed)
   1870     ctf_file_close (fp->ctf_parent);
   1871   fp->ctf_parent = NULL;
   1872 
   1873   if (pfp != NULL)
   1874     {
   1875       int err;
   1876 
   1877       if (fp->ctf_parname == NULL)
   1878 	if ((err = ctf_parent_name_set (fp, "PARENT")) < 0)
   1879 	  return err;
   1880 
   1881       fp->ctf_flags |= LCTF_CHILD;
   1882       fp->ctf_parent_unreffed = 1;
   1883     }
   1884 
   1885   fp->ctf_parent = pfp;
   1886   return 0;
   1887 }
   1888 
   1889 /* Set the data model constant for the CTF container.  */
   1890 int
   1891 ctf_setmodel (ctf_file_t *fp, int model)
   1892 {
   1893   const ctf_dmodel_t *dp;
   1894 
   1895   for (dp = _libctf_models; dp->ctd_name != NULL; dp++)
   1896     {
   1897       if (dp->ctd_code == model)
   1898 	{
   1899 	  fp->ctf_dmodel = dp;
   1900 	  return 0;
   1901 	}
   1902     }
   1903 
   1904   return (ctf_set_errno (fp, EINVAL));
   1905 }
   1906 
   1907 /* Return the data model constant for the CTF container.  */
   1908 int
   1909 ctf_getmodel (ctf_file_t *fp)
   1910 {
   1911   return fp->ctf_dmodel->ctd_code;
   1912 }
   1913 
   1914 /* The caller can hang an arbitrary pointer off each ctf_file_t using this
   1915    function.  */
   1916 void
   1917 ctf_setspecific (ctf_file_t *fp, void *data)
   1918 {
   1919   fp->ctf_specific = data;
   1920 }
   1921 
   1922 /* Retrieve the arbitrary pointer again.  */
   1923 void *
   1924 ctf_getspecific (ctf_file_t *fp)
   1925 {
   1926   return fp->ctf_specific;
   1927 }
   1928