Home | History | Annotate | Download | only in bfd
      1 /* BFD back-end for archive files (libraries).
      2    Copyright (C) 1990-2016 Free Software Foundation, Inc.
      3    Written by Cygnus Support.  Mostly Gumby Henkel-Wallace's fault.
      4 
      5    This file is part of BFD, the Binary File Descriptor library.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program; if not, write to the Free Software
     19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.  */
     20 
     21 /*
     22 @setfilename archive-info
     23 SECTION
     24 	Archives
     25 
     26 DESCRIPTION
     27 	An archive (or library) is just another BFD.  It has a symbol
     28 	table, although there's not much a user program will do with it.
     29 
     30 	The big difference between an archive BFD and an ordinary BFD
     31 	is that the archive doesn't have sections.  Instead it has a
     32 	chain of BFDs that are considered its contents.  These BFDs can
     33 	be manipulated like any other.  The BFDs contained in an
     34 	archive opened for reading will all be opened for reading.  You
     35 	may put either input or output BFDs into an archive opened for
     36 	output; they will be handled correctly when the archive is closed.
     37 
     38 	Use <<bfd_openr_next_archived_file>> to step through
     39 	the contents of an archive opened for input.  You don't
     40 	have to read the entire archive if you don't want
     41 	to!  Read it until you find what you want.
     42 
     43 	A BFD returned by <<bfd_openr_next_archived_file>> can be
     44 	closed manually with <<bfd_close>>.  If you do not close it,
     45 	then a second iteration through the members of an archive may
     46 	return the same BFD.  If you close the archive BFD, then all
     47 	the member BFDs will automatically be closed as well.
     48 
     49 	Archive contents of output BFDs are chained through the
     50 	<<archive_next>> pointer in a BFD.  The first one is findable
     51 	through the <<archive_head>> slot of the archive.  Set it with
     52 	<<bfd_set_archive_head>> (q.v.).  A given BFD may be in only
     53 	one open output archive at a time.
     54 
     55 	As expected, the BFD archive code is more general than the
     56 	archive code of any given environment.  BFD archives may
     57 	contain files of different formats (e.g., a.out and coff) and
     58 	even different architectures.  You may even place archives
     59 	recursively into archives!
     60 
     61 	This can cause unexpected confusion, since some archive
     62 	formats are more expressive than others.  For instance, Intel
     63 	COFF archives can preserve long filenames; SunOS a.out archives
     64 	cannot.  If you move a file from the first to the second
     65 	format and back again, the filename may be truncated.
     66 	Likewise, different a.out environments have different
     67 	conventions as to how they truncate filenames, whether they
     68 	preserve directory names in filenames, etc.  When
     69 	interoperating with native tools, be sure your files are
     70 	homogeneous.
     71 
     72 	Beware: most of these formats do not react well to the
     73 	presence of spaces in filenames.  We do the best we can, but
     74 	can't always handle this case due to restrictions in the format of
     75 	archives.  Many Unix utilities are braindead in regards to
     76 	spaces and such in filenames anyway, so this shouldn't be much
     77 	of a restriction.
     78 
     79 	Archives are supported in BFD in <<archive.c>>.
     80 
     81 SUBSECTION
     82 	Archive functions
     83 */
     84 
     85 /* Assumes:
     86    o - all archive elements start on an even boundary, newline padded;
     87    o - all arch headers are char *;
     88    o - all arch headers are the same size (across architectures).
     89 */
     90 
     91 /* Some formats provide a way to cram a long filename into the short
     92    (16 chars) space provided by a BSD archive.  The trick is: make a
     93    special "file" in the front of the archive, sort of like the SYMDEF
     94    entry.  If the filename is too long to fit, put it in the extended
     95    name table, and use its index as the filename.  To prevent
     96    confusion prepend the index with a space.  This means you can't
     97    have filenames that start with a space, but then again, many Unix
     98    utilities can't handle that anyway.
     99 
    100    This scheme unfortunately requires that you stand on your head in
    101    order to write an archive since you need to put a magic file at the
    102    front, and need to touch every entry to do so.  C'est la vie.
    103 
    104    We support two variants of this idea:
    105    The SVR4 format (extended name table is named "//"),
    106    and an extended pseudo-BSD variant (extended name table is named
    107    "ARFILENAMES/").  The origin of the latter format is uncertain.
    108 
    109    BSD 4.4 uses a third scheme:  It writes a long filename
    110    directly after the header.  This allows 'ar q' to work.
    111 */
    112 
    113 /* Summary of archive member names:
    114 
    115  Symbol table (must be first):
    116  "__.SYMDEF       " - Symbol table, Berkeley style, produced by ranlib.
    117  "/               " - Symbol table, system 5 style.
    118 
    119  Long name table (must be before regular file members):
    120  "//              " - Long name table, System 5 R4 style.
    121  "ARFILENAMES/    " - Long name table, non-standard extended BSD (not BSD 4.4).
    122 
    123  Regular file members with short names:
    124  "filename.o/     " - Regular file, System 5 style (embedded spaces ok).
    125  "filename.o      " - Regular file, Berkeley style (no embedded spaces).
    126 
    127  Regular files with long names (or embedded spaces, for BSD variants):
    128  "/18             " - SVR4 style, name at offset 18 in name table.
    129  "#1/23           " - Long name (or embedded spaces) 23 characters long,
    130 		      BSD 4.4 style, full name follows header.
    131  " 18             " - Long name 18 characters long, extended pseudo-BSD.
    132  */
    133 
    134 #include "sysdep.h"
    135 #include "bfd.h"
    136 #include "libiberty.h"
    137 #include "libbfd.h"
    138 #include "aout/ar.h"
    139 #include "aout/ranlib.h"
    140 #include "safe-ctype.h"
    141 #include "hashtab.h"
    142 #include "filenames.h"
    143 #include "bfdlink.h"
    144 
    145 #ifndef errno
    146 extern int errno;
    147 #endif
    148 
    149 /* We keep a cache of archive filepointers to archive elements to
    150    speed up searching the archive by filepos.  We only add an entry to
    151    the cache when we actually read one.  We also don't sort the cache;
    152    it's generally short enough to search linearly.
    153    Note that the pointers here point to the front of the ar_hdr, not
    154    to the front of the contents!  */
    155 struct ar_cache
    156 {
    157   file_ptr ptr;
    158   bfd *arbfd;
    159 };
    160 
    161 #define ar_padchar(abfd) ((abfd)->xvec->ar_pad_char)
    162 #define ar_maxnamelen(abfd) ((abfd)->xvec->ar_max_namelen)
    163 
    164 #define arch_eltdata(bfd) ((struct areltdata *) ((bfd)->arelt_data))
    165 #define arch_hdr(bfd) ((struct ar_hdr *) arch_eltdata (bfd)->arch_header)
    166 
    167 /* True iff NAME designated a BSD 4.4 extended name.  */
    168 
    169 #define is_bsd44_extended_name(NAME) \
    170   (NAME[0] == '#'  && NAME[1] == '1' && NAME[2] == '/' && ISDIGIT (NAME[3]))
    171 
    172 void
    174 _bfd_ar_spacepad (char *p, size_t n, const char *fmt, long val)
    175 {
    176   static char buf[20];
    177   size_t len;
    178 
    179   snprintf (buf, sizeof (buf), fmt, val);
    180   len = strlen (buf);
    181   if (len < n)
    182     {
    183       memcpy (p, buf, len);
    184       memset (p + len, ' ', n - len);
    185     }
    186   else
    187     memcpy (p, buf, n);
    188 }
    189 
    190 bfd_boolean
    191 _bfd_ar_sizepad (char *p, size_t n, bfd_size_type size)
    192 {
    193   static char buf[21];
    194   size_t len;
    195 
    196   snprintf (buf, sizeof (buf), "%-10" BFD_VMA_FMT "u", size);
    197   len = strlen (buf);
    198   if (len > n)
    199     {
    200       bfd_set_error (bfd_error_file_too_big);
    201       return FALSE;
    202     }
    203   if (len < n)
    204     {
    205       memcpy (p, buf, len);
    206       memset (p + len, ' ', n - len);
    207     }
    208   else
    209     memcpy (p, buf, n);
    210   return TRUE;
    211 }
    212 
    213 bfd_boolean
    215 _bfd_generic_mkarchive (bfd *abfd)
    216 {
    217   bfd_size_type amt = sizeof (struct artdata);
    218 
    219   abfd->tdata.aout_ar_data = (struct artdata *) bfd_zalloc (abfd, amt);
    220   if (bfd_ardata (abfd) == NULL)
    221     return FALSE;
    222 
    223   /* Already cleared by bfd_zalloc above.
    224      bfd_ardata (abfd)->cache = NULL;
    225      bfd_ardata (abfd)->archive_head = NULL;
    226      bfd_ardata (abfd)->symdefs = NULL;
    227      bfd_ardata (abfd)->extended_names = NULL;
    228      bfd_ardata (abfd)->extended_names_size = 0;
    229      bfd_ardata (abfd)->tdata = NULL;  */
    230 
    231   return TRUE;
    232 }
    233 
    234 /*
    235 FUNCTION
    236 	bfd_get_next_mapent
    237 
    238 SYNOPSIS
    239 	symindex bfd_get_next_mapent
    240 	  (bfd *abfd, symindex previous, carsym **sym);
    241 
    242 DESCRIPTION
    243 	Step through archive @var{abfd}'s symbol table (if it
    244 	has one).  Successively update @var{sym} with the next symbol's
    245 	information, returning that symbol's (internal) index into the
    246 	symbol table.
    247 
    248 	Supply <<BFD_NO_MORE_SYMBOLS>> as the @var{previous} entry to get
    249 	the first one; returns <<BFD_NO_MORE_SYMBOLS>> when you've already
    250 	got the last one.
    251 
    252 	A <<carsym>> is a canonical archive symbol.  The only
    253 	user-visible element is its name, a null-terminated string.
    254 */
    255 
    256 symindex
    257 bfd_get_next_mapent (bfd *abfd, symindex prev, carsym **entry)
    258 {
    259   if (!bfd_has_map (abfd))
    260     {
    261       bfd_set_error (bfd_error_invalid_operation);
    262       return BFD_NO_MORE_SYMBOLS;
    263     }
    264 
    265   if (prev == BFD_NO_MORE_SYMBOLS)
    266     prev = 0;
    267   else
    268     ++prev;
    269   if (prev >= bfd_ardata (abfd)->symdef_count)
    270     return BFD_NO_MORE_SYMBOLS;
    271 
    272   *entry = (bfd_ardata (abfd)->symdefs + prev);
    273   return prev;
    274 }
    275 
    276 /* To be called by backends only.  */
    277 
    278 bfd *
    279 _bfd_create_empty_archive_element_shell (bfd *obfd)
    280 {
    281   return _bfd_new_bfd_contained_in (obfd);
    282 }
    283 
    284 /*
    285 FUNCTION
    286 	bfd_set_archive_head
    287 
    288 SYNOPSIS
    289 	bfd_boolean bfd_set_archive_head (bfd *output, bfd *new_head);
    290 
    291 DESCRIPTION
    292 	Set the head of the chain of
    293 	BFDs contained in the archive @var{output} to @var{new_head}.
    294 */
    295 
    296 bfd_boolean
    297 bfd_set_archive_head (bfd *output_archive, bfd *new_head)
    298 {
    299   output_archive->archive_head = new_head;
    300   return TRUE;
    301 }
    302 
    303 bfd *
    304 _bfd_look_for_bfd_in_cache (bfd *arch_bfd, file_ptr filepos)
    305 {
    306   htab_t hash_table = bfd_ardata (arch_bfd)->cache;
    307   struct ar_cache m;
    308 
    309   m.ptr = filepos;
    310 
    311   if (hash_table)
    312     {
    313       struct ar_cache *entry = (struct ar_cache *) htab_find (hash_table, &m);
    314       if (!entry)
    315 	return NULL;
    316 
    317       /* Unfortunately this flag is set after checking that we have
    318 	 an archive, and checking for an archive means one element has
    319 	 sneaked into the cache.  */
    320       entry->arbfd->no_export = arch_bfd->no_export;
    321       return entry->arbfd;
    322     }
    323   else
    324     return NULL;
    325 }
    326 
    327 static hashval_t
    328 hash_file_ptr (const void * p)
    329 {
    330   return (hashval_t) (((struct ar_cache *) p)->ptr);
    331 }
    332 
    333 /* Returns non-zero if P1 and P2 are equal.  */
    334 
    335 static int
    336 eq_file_ptr (const void * p1, const void * p2)
    337 {
    338   struct ar_cache *arc1 = (struct ar_cache *) p1;
    339   struct ar_cache *arc2 = (struct ar_cache *) p2;
    340   return arc1->ptr == arc2->ptr;
    341 }
    342 
    343 /* The calloc function doesn't always take size_t (e.g. on VMS)
    344    so wrap it to avoid a compile time warning.   */
    345 
    346 static void *
    347 _bfd_calloc_wrapper (size_t a, size_t b)
    348 {
    349   return calloc (a, b);
    350 }
    351 
    352 /* Kind of stupid to call cons for each one, but we don't do too many.  */
    353 
    354 bfd_boolean
    355 _bfd_add_bfd_to_archive_cache (bfd *arch_bfd, file_ptr filepos, bfd *new_elt)
    356 {
    357   struct ar_cache *cache;
    358   htab_t hash_table = bfd_ardata (arch_bfd)->cache;
    359 
    360   /* If the hash table hasn't been created, create it.  */
    361   if (hash_table == NULL)
    362     {
    363       hash_table = htab_create_alloc (16, hash_file_ptr, eq_file_ptr,
    364 				      NULL, _bfd_calloc_wrapper, free);
    365       if (hash_table == NULL)
    366 	return FALSE;
    367       bfd_ardata (arch_bfd)->cache = hash_table;
    368     }
    369 
    370   /* Insert new_elt into the hash table by filepos.  */
    371   cache = (struct ar_cache *) bfd_zalloc (arch_bfd, sizeof (struct ar_cache));
    372   cache->ptr = filepos;
    373   cache->arbfd = new_elt;
    374   *htab_find_slot (hash_table, (const void *) cache, INSERT) = cache;
    375 
    376   /* Provide a means of accessing this from child.  */
    377   arch_eltdata (new_elt)->parent_cache = hash_table;
    378   arch_eltdata (new_elt)->key = filepos;
    379 
    380   return TRUE;
    381 }
    382 
    383 static bfd *
    385 open_nested_file (const char *filename, bfd *archive)
    386 {
    387   const char *target;
    388   bfd *n_bfd;
    389 
    390   target = NULL;
    391   if (!archive->target_defaulted)
    392     target = archive->xvec->name;
    393   n_bfd = bfd_openr (filename, target);
    394   if (n_bfd != NULL)
    395     {
    396       n_bfd->lto_output = archive->lto_output;
    397       n_bfd->no_export = archive->no_export;
    398       n_bfd->my_archive = archive;
    399     }
    400   return n_bfd;
    401 }
    402 
    403 static bfd *
    404 find_nested_archive (const char *filename, bfd *arch_bfd)
    405 {
    406   bfd *abfd;
    407 
    408   /* PR 15140: Don't allow a nested archive pointing to itself.  */
    409   if (filename_cmp (filename, arch_bfd->filename) == 0)
    410     {
    411       bfd_set_error (bfd_error_malformed_archive);
    412       return NULL;
    413     }
    414 
    415   for (abfd = arch_bfd->nested_archives;
    416        abfd != NULL;
    417        abfd = abfd->archive_next)
    418     {
    419       if (filename_cmp (filename, abfd->filename) == 0)
    420 	return abfd;
    421     }
    422   abfd = open_nested_file (filename, arch_bfd);
    423   if (abfd)
    424     {
    425       abfd->archive_next = arch_bfd->nested_archives;
    426       arch_bfd->nested_archives = abfd;
    427     }
    428   return abfd;
    429 }
    430 
    431 /* The name begins with space.  Hence the rest of the name is an index into
    432    the string table.  */
    433 
    434 static char *
    435 get_extended_arelt_filename (bfd *arch, const char *name, file_ptr *originp)
    436 {
    437   unsigned long table_index = 0;
    438   const char *endp;
    439 
    440   /* Should extract string so that I can guarantee not to overflow into
    441      the next region, but I'm too lazy.  */
    442   errno = 0;
    443   /* Skip first char, which is '/' in SVR4 or ' ' in some other variants.  */
    444   table_index = strtol (name + 1, (char **) &endp, 10);
    445   if (errno != 0 || table_index >= bfd_ardata (arch)->extended_names_size)
    446     {
    447       bfd_set_error (bfd_error_malformed_archive);
    448       return NULL;
    449     }
    450   /* In a thin archive, a member of an archive-within-an-archive
    451      will have the offset in the inner archive encoded here.  */
    452   if (bfd_is_thin_archive (arch) && endp != NULL && *endp == ':')
    453     {
    454       file_ptr origin = strtol (endp + 1, NULL, 10);
    455 
    456       if (errno != 0)
    457 	{
    458 	  bfd_set_error (bfd_error_malformed_archive);
    459 	  return NULL;
    460 	}
    461       *originp = origin;
    462     }
    463   else
    464     *originp = 0;
    465 
    466   return bfd_ardata (arch)->extended_names + table_index;
    467 }
    468 
    469 /* This functions reads an arch header and returns an areltdata pointer, or
    470    NULL on error.
    471 
    472    Presumes the file pointer is already in the right place (ie pointing
    473    to the ar_hdr in the file).   Moves the file pointer; on success it
    474    should be pointing to the front of the file contents; on failure it
    475    could have been moved arbitrarily.  */
    476 
    477 void *
    478 _bfd_generic_read_ar_hdr (bfd *abfd)
    479 {
    480   return _bfd_generic_read_ar_hdr_mag (abfd, NULL);
    481 }
    482 
    483 /* Alpha ECOFF uses an optional different ARFMAG value, so we have a
    484    variant of _bfd_generic_read_ar_hdr which accepts a magic string.  */
    485 
    486 void *
    487 _bfd_generic_read_ar_hdr_mag (bfd *abfd, const char *mag)
    488 {
    489   struct ar_hdr hdr;
    490   char *hdrp = (char *) &hdr;
    491   bfd_size_type parsed_size;
    492   struct areltdata *ared;
    493   char *filename = NULL;
    494   bfd_size_type namelen = 0;
    495   bfd_size_type allocsize = sizeof (struct areltdata) + sizeof (struct ar_hdr);
    496   char *allocptr = 0;
    497   file_ptr origin = 0;
    498   unsigned int extra_size = 0;
    499   char fmag_save;
    500   int scan;
    501 
    502   if (bfd_bread (hdrp, sizeof (struct ar_hdr), abfd) != sizeof (struct ar_hdr))
    503     {
    504       if (bfd_get_error () != bfd_error_system_call)
    505 	bfd_set_error (bfd_error_no_more_archived_files);
    506       return NULL;
    507     }
    508   if (strncmp (hdr.ar_fmag, ARFMAG, 2) != 0
    509       && (mag == NULL
    510 	  || strncmp (hdr.ar_fmag, mag, 2) != 0))
    511     {
    512       bfd_set_error (bfd_error_malformed_archive);
    513       return NULL;
    514     }
    515 
    516   errno = 0;
    517   fmag_save = hdr.ar_fmag[0];
    518   hdr.ar_fmag[0] = 0;
    519   scan = sscanf (hdr.ar_size, "%" BFD_VMA_FMT "u", &parsed_size);
    520   hdr.ar_fmag[0] = fmag_save;
    521   if (scan != 1)
    522     {
    523       bfd_set_error (bfd_error_malformed_archive);
    524       return NULL;
    525     }
    526 
    527   /* Extract the filename from the archive - there are two ways to
    528      specify an extended name table, either the first char of the
    529      name is a space, or it's a slash.  */
    530   if ((hdr.ar_name[0] == '/'
    531        || (hdr.ar_name[0] == ' '
    532 	   && memchr (hdr.ar_name, '/', ar_maxnamelen (abfd)) == NULL))
    533       && bfd_ardata (abfd)->extended_names != NULL)
    534     {
    535       filename = get_extended_arelt_filename (abfd, hdr.ar_name, &origin);
    536       if (filename == NULL)
    537 	return NULL;
    538     }
    539   /* BSD4.4-style long filename.  */
    540   else if (is_bsd44_extended_name (hdr.ar_name))
    541     {
    542       /* BSD-4.4 extended name */
    543       namelen = atoi (&hdr.ar_name[3]);
    544       allocsize += namelen + 1;
    545       parsed_size -= namelen;
    546       extra_size = namelen;
    547 
    548       allocptr = (char *) bfd_zmalloc (allocsize);
    549       if (allocptr == NULL)
    550 	return NULL;
    551       filename = (allocptr
    552 		  + sizeof (struct areltdata)
    553 		  + sizeof (struct ar_hdr));
    554       if (bfd_bread (filename, namelen, abfd) != namelen)
    555 	{
    556 	  free (allocptr);
    557 	  if (bfd_get_error () != bfd_error_system_call)
    558 	    bfd_set_error (bfd_error_no_more_archived_files);
    559 	  return NULL;
    560 	}
    561       filename[namelen] = '\0';
    562     }
    563   else
    564     {
    565       /* We judge the end of the name by looking for '/' or ' '.
    566 	 Note:  The SYSV format (terminated by '/') allows embedded
    567 	 spaces, so only look for ' ' if we don't find '/'.  */
    568 
    569       char *e;
    570       e = (char *) memchr (hdr.ar_name, '\0', ar_maxnamelen (abfd));
    571       if (e == NULL)
    572 	{
    573 	  e = (char *) memchr (hdr.ar_name, '/', ar_maxnamelen (abfd));
    574 	  if (e == NULL)
    575 	    e = (char *) memchr (hdr.ar_name, ' ', ar_maxnamelen (abfd));
    576 	}
    577 
    578       if (e != NULL)
    579 	namelen = e - hdr.ar_name;
    580       else
    581 	{
    582 	  /* If we didn't find a termination character, then the name
    583 	     must be the entire field.  */
    584 	  namelen = ar_maxnamelen (abfd);
    585 	}
    586 
    587       allocsize += namelen + 1;
    588     }
    589 
    590   if (!allocptr)
    591     {
    592       allocptr = (char *) bfd_zmalloc (allocsize);
    593       if (allocptr == NULL)
    594 	return NULL;
    595     }
    596 
    597   ared = (struct areltdata *) allocptr;
    598 
    599   ared->arch_header = allocptr + sizeof (struct areltdata);
    600   memcpy (ared->arch_header, &hdr, sizeof (struct ar_hdr));
    601   ared->parsed_size = parsed_size;
    602   ared->extra_size = extra_size;
    603   ared->origin = origin;
    604 
    605   if (filename != NULL)
    606     ared->filename = filename;
    607   else
    608     {
    609       ared->filename = allocptr + (sizeof (struct areltdata) +
    610 				   sizeof (struct ar_hdr));
    611       if (namelen)
    612 	memcpy (ared->filename, hdr.ar_name, namelen);
    613       ared->filename[namelen] = '\0';
    614     }
    615 
    616   return ared;
    617 }
    618 
    619 /* Append the relative pathname for a member of the thin archive
    621    to the pathname of the directory containing the archive.  */
    622 
    623 char *
    624 _bfd_append_relative_path (bfd *arch, char *elt_name)
    625 {
    626   const char *arch_name = arch->filename;
    627   const char *base_name = lbasename (arch_name);
    628   size_t prefix_len;
    629   char *filename;
    630 
    631   if (base_name == arch_name)
    632     return elt_name;
    633 
    634   prefix_len = base_name - arch_name;
    635   filename = (char *) bfd_alloc (arch, prefix_len + strlen (elt_name) + 1);
    636   if (filename == NULL)
    637     return NULL;
    638 
    639   strncpy (filename, arch_name, prefix_len);
    640   strcpy (filename + prefix_len, elt_name);
    641   return filename;
    642 }
    643 
    644 /* This is an internal function; it's mainly used when indexing
    645    through the archive symbol table, but also used to get the next
    646    element, since it handles the bookkeeping so nicely for us.  */
    647 
    648 bfd *
    649 _bfd_get_elt_at_filepos (bfd *archive, file_ptr filepos)
    650 {
    651   struct areltdata *new_areldata;
    652   bfd *n_bfd;
    653   char *filename;
    654 
    655   n_bfd = _bfd_look_for_bfd_in_cache (archive, filepos);
    656   if (n_bfd)
    657     return n_bfd;
    658 
    659   if (0 > bfd_seek (archive, filepos, SEEK_SET))
    660     return NULL;
    661 
    662   if ((new_areldata = (struct areltdata *) _bfd_read_ar_hdr (archive)) == NULL)
    663     return NULL;
    664 
    665   filename = new_areldata->filename;
    666 
    667   if (bfd_is_thin_archive (archive))
    668     {
    669       /* This is a proxy entry for an external file.  */
    670       if (! IS_ABSOLUTE_PATH (filename))
    671 	{
    672 	  filename = _bfd_append_relative_path (archive, filename);
    673 	  if (filename == NULL)
    674 	    {
    675 	      free (new_areldata);
    676 	      return NULL;
    677 	    }
    678 	}
    679 
    680       if (new_areldata->origin > 0)
    681 	{
    682 	  /* This proxy entry refers to an element of a nested archive.
    683 	     Locate the member of that archive and return a bfd for it.  */
    684 	  bfd *ext_arch = find_nested_archive (filename, archive);
    685 
    686 	  if (ext_arch == NULL
    687 	      || ! bfd_check_format (ext_arch, bfd_archive))
    688 	    {
    689 	      free (new_areldata);
    690 	      return NULL;
    691 	    }
    692 	  n_bfd = _bfd_get_elt_at_filepos (ext_arch, new_areldata->origin);
    693 	  if (n_bfd == NULL)
    694 	    {
    695 	      free (new_areldata);
    696 	      return NULL;
    697 	    }
    698 	  n_bfd->proxy_origin = bfd_tell (archive);
    699 	  return n_bfd;
    700 	}
    701 
    702       /* It's not an element of a nested archive;
    703 	 open the external file as a bfd.  */
    704       n_bfd = open_nested_file (filename, archive);
    705       if (n_bfd == NULL)
    706 	bfd_set_error (bfd_error_malformed_archive);
    707     }
    708   else
    709     {
    710       n_bfd = _bfd_create_empty_archive_element_shell (archive);
    711     }
    712 
    713   if (n_bfd == NULL)
    714     {
    715       free (new_areldata);
    716       return NULL;
    717     }
    718 
    719   n_bfd->proxy_origin = bfd_tell (archive);
    720 
    721   if (bfd_is_thin_archive (archive))
    722     {
    723       n_bfd->origin = 0;
    724     }
    725   else
    726     {
    727       n_bfd->origin = n_bfd->proxy_origin;
    728       n_bfd->filename = xstrdup (filename);
    729     }
    730 
    731   n_bfd->arelt_data = new_areldata;
    732 
    733   /* Copy BFD_COMPRESS, BFD_DECOMPRESS and BFD_COMPRESS_GABI flags.  */
    734   n_bfd->flags |= archive->flags & (BFD_COMPRESS
    735 				    | BFD_DECOMPRESS
    736 				    | BFD_COMPRESS_GABI);
    737 
    738   /* Copy is_linker_input.  */
    739   n_bfd->is_linker_input = archive->is_linker_input;
    740 
    741   if (_bfd_add_bfd_to_archive_cache (archive, filepos, n_bfd))
    742     return n_bfd;
    743 
    744   free (new_areldata);
    745   n_bfd->arelt_data = NULL;
    746   return NULL;
    747 }
    748 
    749 /* Return the BFD which is referenced by the symbol in ABFD indexed by
    750    SYM_INDEX.  SYM_INDEX should have been returned by bfd_get_next_mapent.  */
    751 
    752 bfd *
    753 _bfd_generic_get_elt_at_index (bfd *abfd, symindex sym_index)
    754 {
    755   carsym *entry;
    756 
    757   entry = bfd_ardata (abfd)->symdefs + sym_index;
    758   return _bfd_get_elt_at_filepos (abfd, entry->file_offset);
    759 }
    760 
    761 /*
    762 FUNCTION
    763 	bfd_openr_next_archived_file
    764 
    765 SYNOPSIS
    766 	bfd *bfd_openr_next_archived_file (bfd *archive, bfd *previous);
    767 
    768 DESCRIPTION
    769 	Provided a BFD, @var{archive}, containing an archive and NULL, open
    770 	an input BFD on the first contained element and returns that.
    771 	Subsequent calls should pass
    772 	the archive and the previous return value to return a created
    773 	BFD to the next contained element. NULL is returned when there
    774 	are no more.
    775 */
    776 
    777 bfd *
    778 bfd_openr_next_archived_file (bfd *archive, bfd *last_file)
    779 {
    780   if ((bfd_get_format (archive) != bfd_archive)
    781       || (archive->direction == write_direction))
    782     {
    783       bfd_set_error (bfd_error_invalid_operation);
    784       return NULL;
    785     }
    786 
    787   return BFD_SEND (archive,
    788 		   openr_next_archived_file, (archive, last_file));
    789 }
    790 
    791 bfd *
    792 bfd_generic_openr_next_archived_file (bfd *archive, bfd *last_file)
    793 {
    794   ufile_ptr filestart;
    795 
    796   if (!last_file)
    797     filestart = bfd_ardata (archive)->first_file_filepos;
    798   else
    799     {
    800       filestart = last_file->proxy_origin;
    801       if (! bfd_is_thin_archive (archive))
    802 	{
    803 	  bfd_size_type size = arelt_size (last_file);
    804 
    805 	  filestart += size;
    806 	  /* Pad to an even boundary...
    807 	     Note that last_file->origin can be odd in the case of
    808 	     BSD-4.4-style element with a long odd size.  */
    809 	  filestart += filestart % 2;
    810 	  if (filestart < last_file->proxy_origin)
    811 	    {
    812 	      /* Prevent looping.  See PR19256.  */
    813 	      bfd_set_error (bfd_error_malformed_archive);
    814 	      return NULL;
    815 	    }
    816 	}
    817     }
    818 
    819   return _bfd_get_elt_at_filepos (archive, filestart);
    820 }
    821 
    822 const bfd_target *
    823 bfd_generic_archive_p (bfd *abfd)
    824 {
    825   struct artdata *tdata_hold;
    826   char armag[SARMAG + 1];
    827   bfd_size_type amt;
    828 
    829   if (bfd_bread (armag, SARMAG, abfd) != SARMAG)
    830     {
    831       if (bfd_get_error () != bfd_error_system_call)
    832 	bfd_set_error (bfd_error_wrong_format);
    833       return NULL;
    834     }
    835 
    836   bfd_is_thin_archive (abfd) = (strncmp (armag, ARMAGT, SARMAG) == 0);
    837 
    838   if (strncmp (armag, ARMAG, SARMAG) != 0
    839       && strncmp (armag, ARMAGB, SARMAG) != 0
    840       && ! bfd_is_thin_archive (abfd))
    841     return NULL;
    842 
    843   tdata_hold = bfd_ardata (abfd);
    844 
    845   amt = sizeof (struct artdata);
    846   bfd_ardata (abfd) = (struct artdata *) bfd_zalloc (abfd, amt);
    847   if (bfd_ardata (abfd) == NULL)
    848     {
    849       bfd_ardata (abfd) = tdata_hold;
    850       return NULL;
    851     }
    852 
    853   bfd_ardata (abfd)->first_file_filepos = SARMAG;
    854   /* Cleared by bfd_zalloc above.
    855      bfd_ardata (abfd)->cache = NULL;
    856      bfd_ardata (abfd)->archive_head = NULL;
    857      bfd_ardata (abfd)->symdefs = NULL;
    858      bfd_ardata (abfd)->extended_names = NULL;
    859      bfd_ardata (abfd)->extended_names_size = 0;
    860      bfd_ardata (abfd)->tdata = NULL;  */
    861 
    862   if (!BFD_SEND (abfd, _bfd_slurp_armap, (abfd))
    863       || !BFD_SEND (abfd, _bfd_slurp_extended_name_table, (abfd)))
    864     {
    865       if (bfd_get_error () != bfd_error_system_call)
    866 	bfd_set_error (bfd_error_wrong_format);
    867       bfd_release (abfd, bfd_ardata (abfd));
    868       bfd_ardata (abfd) = tdata_hold;
    869       return NULL;
    870     }
    871 
    872   if (abfd->target_defaulted && bfd_has_map (abfd))
    873     {
    874       bfd *first;
    875 
    876       /* This archive has a map, so we may presume that the contents
    877 	 are object files.  Make sure that if the first file in the
    878 	 archive can be recognized as an object file, it is for this
    879 	 target.  If not, assume that this is the wrong format.  If
    880 	 the first file is not an object file, somebody is doing
    881 	 something weird, and we permit it so that ar -t will work.
    882 
    883 	 This is done because any normal format will recognize any
    884 	 normal archive, regardless of the format of the object files.
    885 	 We do accept an empty archive.  */
    886 
    887       first = bfd_openr_next_archived_file (abfd, NULL);
    888       if (first != NULL)
    889 	{
    890 	  first->target_defaulted = FALSE;
    891 	  if (bfd_check_format (first, bfd_object)
    892 	      && first->xvec != abfd->xvec)
    893 	    bfd_set_error (bfd_error_wrong_object_format);
    894 	  /* And we ought to close `first' here too.  */
    895 	}
    896     }
    897 
    898   return abfd->xvec;
    899 }
    900 
    901 /* Some constants for a 32 bit BSD archive structure.  We do not
    902    support 64 bit archives presently; so far as I know, none actually
    903    exist.  Supporting them would require changing these constants, and
    904    changing some H_GET_32 to H_GET_64.  */
    905 
    906 /* The size of an external symdef structure.  */
    907 #define BSD_SYMDEF_SIZE 8
    908 
    909 /* The offset from the start of a symdef structure to the file offset.  */
    910 #define BSD_SYMDEF_OFFSET_SIZE 4
    911 
    912 /* The size of the symdef count.  */
    913 #define BSD_SYMDEF_COUNT_SIZE 4
    914 
    915 /* The size of the string count.  */
    916 #define BSD_STRING_COUNT_SIZE 4
    917 
    918 /* Read a BSD-style archive symbol table.  Returns FALSE on error,
    919    TRUE otherwise.  */
    920 
    921 static bfd_boolean
    922 do_slurp_bsd_armap (bfd *abfd)
    923 {
    924   struct areltdata *mapdata;
    925   unsigned int counter;
    926   bfd_byte *raw_armap, *rbase;
    927   struct artdata *ardata = bfd_ardata (abfd);
    928   char *stringbase;
    929   bfd_size_type parsed_size, amt;
    930   carsym *set;
    931 
    932   mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
    933   if (mapdata == NULL)
    934     return FALSE;
    935   parsed_size = mapdata->parsed_size;
    936   free (mapdata);
    937   /* PR 17512: file: 883ff754.  */
    938   /* PR 17512: file: 0458885f.  */
    939   if (parsed_size < 4)
    940     return FALSE;
    941 
    942   raw_armap = (bfd_byte *) bfd_zalloc (abfd, parsed_size);
    943   if (raw_armap == NULL)
    944     return FALSE;
    945 
    946   if (bfd_bread (raw_armap, parsed_size, abfd) != parsed_size)
    947     {
    948       if (bfd_get_error () != bfd_error_system_call)
    949 	bfd_set_error (bfd_error_malformed_archive);
    950     byebye:
    951       bfd_release (abfd, raw_armap);
    952       return FALSE;
    953     }
    954 
    955   ardata->symdef_count = H_GET_32 (abfd, raw_armap) / BSD_SYMDEF_SIZE;
    956   if (ardata->symdef_count * BSD_SYMDEF_SIZE >
    957       parsed_size - BSD_SYMDEF_COUNT_SIZE)
    958     {
    959       /* Probably we're using the wrong byte ordering.  */
    960       bfd_set_error (bfd_error_wrong_format);
    961       goto byebye;
    962     }
    963 
    964   ardata->cache = 0;
    965   rbase = raw_armap + BSD_SYMDEF_COUNT_SIZE;
    966   stringbase = ((char *) rbase
    967 		+ ardata->symdef_count * BSD_SYMDEF_SIZE
    968 		+ BSD_STRING_COUNT_SIZE);
    969   amt = ardata->symdef_count * sizeof (carsym);
    970   ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
    971   if (!ardata->symdefs)
    972     return FALSE;
    973 
    974   for (counter = 0, set = ardata->symdefs;
    975        counter < ardata->symdef_count;
    976        counter++, set++, rbase += BSD_SYMDEF_SIZE)
    977     {
    978       set->name = H_GET_32 (abfd, rbase) + stringbase;
    979       set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
    980     }
    981 
    982   ardata->first_file_filepos = bfd_tell (abfd);
    983   /* Pad to an even boundary if you have to.  */
    984   ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
    985   /* FIXME, we should provide some way to free raw_ardata when
    986      we are done using the strings from it.  For now, it seems
    987      to be allocated on an objalloc anyway...  */
    988   bfd_has_map (abfd) = TRUE;
    989   return TRUE;
    990 }
    991 
    992 /* Read a COFF archive symbol table.  Returns FALSE on error, TRUE
    993    otherwise.  */
    994 
    995 static bfd_boolean
    996 do_slurp_coff_armap (bfd *abfd)
    997 {
    998   struct areltdata *mapdata;
    999   int *raw_armap, *rawptr;
   1000   struct artdata *ardata = bfd_ardata (abfd);
   1001   char *stringbase;
   1002   bfd_size_type stringsize;
   1003   bfd_size_type parsed_size;
   1004   carsym *carsyms;
   1005   bfd_size_type nsymz;		/* Number of symbols in armap.  */
   1006   bfd_vma (*swap) (const void *);
   1007   char int_buf[sizeof (long)];
   1008   bfd_size_type carsym_size, ptrsize;
   1009   unsigned int i;
   1010 
   1011   mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
   1012   if (mapdata == NULL)
   1013     return FALSE;
   1014   parsed_size = mapdata->parsed_size;
   1015   free (mapdata);
   1016 
   1017   if (bfd_bread (int_buf, 4, abfd) != 4)
   1018     {
   1019       if (bfd_get_error () != bfd_error_system_call)
   1020 	bfd_set_error (bfd_error_malformed_archive);
   1021       return FALSE;
   1022     }
   1023   /* It seems that all numeric information in a coff archive is always
   1024      in big endian format, nomatter the host or target.  */
   1025   swap = bfd_getb32;
   1026   nsymz = bfd_getb32 (int_buf);
   1027   stringsize = parsed_size - (4 * nsymz) - 4;
   1028 
   1029   /* ... except that some archive formats are broken, and it may be our
   1030      fault - the i960 little endian coff sometimes has big and sometimes
   1031      little, because our tools changed.  Here's a horrible hack to clean
   1032      up the crap.  */
   1033 
   1034   if (stringsize > 0xfffff
   1035       && bfd_get_arch (abfd) == bfd_arch_i960
   1036       && bfd_get_flavour (abfd) == bfd_target_coff_flavour)
   1037     {
   1038       /* This looks dangerous, let's do it the other way around.  */
   1039       nsymz = bfd_getl32 (int_buf);
   1040       stringsize = parsed_size - (4 * nsymz) - 4;
   1041       swap = bfd_getl32;
   1042     }
   1043 
   1044   /* The coff armap must be read sequentially.  So we construct a
   1045      bsd-style one in core all at once, for simplicity.  */
   1046 
   1047   if (nsymz > ~ (bfd_size_type) 0 / sizeof (carsym))
   1048     return FALSE;
   1049 
   1050   carsym_size = (nsymz * sizeof (carsym));
   1051   ptrsize = (4 * nsymz);
   1052 
   1053   if (carsym_size + stringsize + 1 <= carsym_size)
   1054     return FALSE;
   1055 
   1056   ardata->symdefs = (struct carsym *) bfd_zalloc (abfd,
   1057 						  carsym_size + stringsize + 1);
   1058   if (ardata->symdefs == NULL)
   1059     return FALSE;
   1060   carsyms = ardata->symdefs;
   1061   stringbase = ((char *) ardata->symdefs) + carsym_size;
   1062 
   1063   /* Allocate and read in the raw offsets.  */
   1064   raw_armap = (int *) bfd_alloc (abfd, ptrsize);
   1065   if (raw_armap == NULL)
   1066     goto release_symdefs;
   1067   if (bfd_bread (raw_armap, ptrsize, abfd) != ptrsize
   1068       || (bfd_bread (stringbase, stringsize, abfd) != stringsize))
   1069     {
   1070       if (bfd_get_error () != bfd_error_system_call)
   1071 	bfd_set_error (bfd_error_malformed_archive);
   1072       goto release_raw_armap;
   1073     }
   1074 
   1075   /* OK, build the carsyms.  */
   1076   for (i = 0; i < nsymz && stringsize > 0; i++)
   1077     {
   1078       bfd_size_type len;
   1079 
   1080       rawptr = raw_armap + i;
   1081       carsyms->file_offset = swap ((bfd_byte *) rawptr);
   1082       carsyms->name = stringbase;
   1083       /* PR 17512: file: 4a1d50c1.  */
   1084       len = strnlen (stringbase, stringsize);
   1085       if (len < stringsize)
   1086 	len ++;
   1087       stringbase += len;
   1088       stringsize -= len;
   1089       carsyms++;
   1090     }
   1091   *stringbase = 0;
   1092 
   1093   ardata->symdef_count = nsymz;
   1094   ardata->first_file_filepos = bfd_tell (abfd);
   1095   /* Pad to an even boundary if you have to.  */
   1096   ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
   1097 
   1098   bfd_has_map (abfd) = TRUE;
   1099   bfd_release (abfd, raw_armap);
   1100 
   1101   /* Check for a second archive header (as used by PE).  */
   1102   {
   1103     struct areltdata *tmp;
   1104 
   1105     bfd_seek (abfd, ardata->first_file_filepos, SEEK_SET);
   1106     tmp = (struct areltdata *) _bfd_read_ar_hdr (abfd);
   1107     if (tmp != NULL)
   1108       {
   1109 	if (tmp->arch_header[0] == '/'
   1110 	    && tmp->arch_header[1] == ' ')
   1111 	  {
   1112 	    ardata->first_file_filepos +=
   1113 	      (tmp->parsed_size + sizeof (struct ar_hdr) + 1) & ~(unsigned) 1;
   1114 	  }
   1115 	free (tmp);
   1116       }
   1117   }
   1118 
   1119   return TRUE;
   1120 
   1121 release_raw_armap:
   1122   bfd_release (abfd, raw_armap);
   1123 release_symdefs:
   1124   bfd_release (abfd, (ardata)->symdefs);
   1125   return FALSE;
   1126 }
   1127 
   1128 /* This routine can handle either coff-style or bsd-style armaps
   1129    (archive symbol table).  Returns FALSE on error, TRUE otherwise */
   1130 
   1131 bfd_boolean
   1132 bfd_slurp_armap (bfd *abfd)
   1133 {
   1134   char nextname[17];
   1135   int i = bfd_bread (nextname, 16, abfd);
   1136 
   1137   if (i == 0)
   1138     return TRUE;
   1139   if (i != 16)
   1140     return FALSE;
   1141 
   1142   if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
   1143     return FALSE;
   1144 
   1145   if (CONST_STRNEQ (nextname, "__.SYMDEF       ")
   1146       || CONST_STRNEQ (nextname, "__.SYMDEF/      ")) /* Old Linux archives.  */
   1147     return do_slurp_bsd_armap (abfd);
   1148   else if (CONST_STRNEQ (nextname, "/               "))
   1149     return do_slurp_coff_armap (abfd);
   1150   else if (CONST_STRNEQ (nextname, "/SYM64/         "))
   1151     {
   1152       /* 64bit (Irix 6) archive.  */
   1153 #ifdef BFD64
   1154       return _bfd_archive_64_bit_slurp_armap (abfd);
   1155 #else
   1156       bfd_set_error (bfd_error_wrong_format);
   1157       return FALSE;
   1158 #endif
   1159     }
   1160   else if (CONST_STRNEQ (nextname, "#1/20           "))
   1161     {
   1162       /* Mach-O has a special name for armap when the map is sorted by name.
   1163 	 However because this name has a space it is slightly more difficult
   1164 	 to check it.  */
   1165       struct ar_hdr hdr;
   1166       char extname[21];
   1167 
   1168       if (bfd_bread (&hdr, sizeof (hdr), abfd) != sizeof (hdr))
   1169 	return FALSE;
   1170       /* Read the extended name.  We know its length.  */
   1171       if (bfd_bread (extname, 20, abfd) != 20)
   1172 	return FALSE;
   1173       if (bfd_seek (abfd, -(file_ptr) (sizeof (hdr) + 20), SEEK_CUR) != 0)
   1174 	return FALSE;
   1175       extname[20] = 0;
   1176       if (CONST_STRNEQ (extname, "__.SYMDEF SORTED")
   1177 	  || CONST_STRNEQ (extname, "__.SYMDEF"))
   1178 	return do_slurp_bsd_armap (abfd);
   1179     }
   1180 
   1181   bfd_has_map (abfd) = FALSE;
   1182   return TRUE;
   1183 }
   1184 
   1185 /* Returns FALSE on error, TRUE otherwise.  */
   1187 /* Flavor 2 of a bsd armap, similar to bfd_slurp_bsd_armap except the
   1188    header is in a slightly different order and the map name is '/'.
   1189    This flavour is used by hp300hpux.  */
   1190 
   1191 #define HPUX_SYMDEF_COUNT_SIZE 2
   1192 
   1193 bfd_boolean
   1194 bfd_slurp_bsd_armap_f2 (bfd *abfd)
   1195 {
   1196   struct areltdata *mapdata;
   1197   char nextname[17];
   1198   unsigned int counter;
   1199   bfd_byte *raw_armap, *rbase;
   1200   struct artdata *ardata = bfd_ardata (abfd);
   1201   char *stringbase;
   1202   unsigned int stringsize;
   1203   unsigned int left;
   1204   bfd_size_type amt;
   1205   carsym *set;
   1206   int i = bfd_bread (nextname, 16, abfd);
   1207 
   1208   if (i == 0)
   1209     return TRUE;
   1210   if (i != 16)
   1211     return FALSE;
   1212 
   1213   /* The archive has at least 16 bytes in it.  */
   1214   if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
   1215     return FALSE;
   1216 
   1217   if (CONST_STRNEQ (nextname, "__.SYMDEF       ")
   1218       || CONST_STRNEQ (nextname, "__.SYMDEF/      ")) /* Old Linux archives.  */
   1219     return do_slurp_bsd_armap (abfd);
   1220 
   1221   if (! CONST_STRNEQ (nextname, "/               "))
   1222     {
   1223       bfd_has_map (abfd) = FALSE;
   1224       return TRUE;
   1225     }
   1226 
   1227   mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
   1228   if (mapdata == NULL)
   1229     return FALSE;
   1230 
   1231   if (mapdata->parsed_size < HPUX_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE)
   1232     {
   1233       free (mapdata);
   1234     wrong_format:
   1235       bfd_set_error (bfd_error_wrong_format);
   1236     byebye:
   1237       return FALSE;
   1238     }
   1239   left = mapdata->parsed_size - HPUX_SYMDEF_COUNT_SIZE - BSD_STRING_COUNT_SIZE;
   1240 
   1241   amt = mapdata->parsed_size;
   1242   free (mapdata);
   1243 
   1244   raw_armap = (bfd_byte *) bfd_zalloc (abfd, amt);
   1245   if (raw_armap == NULL)
   1246     goto byebye;
   1247 
   1248   if (bfd_bread (raw_armap, amt, abfd) != amt)
   1249     {
   1250       if (bfd_get_error () != bfd_error_system_call)
   1251 	bfd_set_error (bfd_error_malformed_archive);
   1252       goto byebye;
   1253     }
   1254 
   1255   ardata->symdef_count = H_GET_16 (abfd, raw_armap);
   1256 
   1257   ardata->cache = 0;
   1258 
   1259   stringsize = H_GET_32 (abfd, raw_armap + HPUX_SYMDEF_COUNT_SIZE);
   1260   if (stringsize > left)
   1261     goto wrong_format;
   1262   left -= stringsize;
   1263 
   1264   /* Skip sym count and string sz.  */
   1265   stringbase = ((char *) raw_armap
   1266 		+ HPUX_SYMDEF_COUNT_SIZE
   1267 		+ BSD_STRING_COUNT_SIZE);
   1268   rbase = (bfd_byte *) stringbase + stringsize;
   1269   amt = ardata->symdef_count * BSD_SYMDEF_SIZE;
   1270   if (amt > left)
   1271     goto wrong_format;
   1272 
   1273   ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
   1274   if (!ardata->symdefs)
   1275     return FALSE;
   1276 
   1277   for (counter = 0, set = ardata->symdefs;
   1278        counter < ardata->symdef_count;
   1279        counter++, set++, rbase += BSD_SYMDEF_SIZE)
   1280     {
   1281       set->name = H_GET_32 (abfd, rbase) + stringbase;
   1282       set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
   1283     }
   1284 
   1285   ardata->first_file_filepos = bfd_tell (abfd);
   1286   /* Pad to an even boundary if you have to.  */
   1287   ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
   1288   /* FIXME, we should provide some way to free raw_ardata when
   1289      we are done using the strings from it.  For now, it seems
   1290      to be allocated on an objalloc anyway...  */
   1291   bfd_has_map (abfd) = TRUE;
   1292   return TRUE;
   1293 }
   1294 
   1295 /** Extended name table.
   1297 
   1298   Normally archives support only 14-character filenames.
   1299 
   1300   Intel has extended the format: longer names are stored in a special
   1301   element (the first in the archive, or second if there is an armap);
   1302   the name in the ar_hdr is replaced by <space><index into filename
   1303   element>.  Index is the P.R. of an int (decimal).  Data General have
   1304   extended the format by using the prefix // for the special element.  */
   1305 
   1306 /* Returns FALSE on error, TRUE otherwise.  */
   1307 
   1308 bfd_boolean
   1309 _bfd_slurp_extended_name_table (bfd *abfd)
   1310 {
   1311   char nextname[17];
   1312   struct areltdata *namedata;
   1313   bfd_size_type amt;
   1314 
   1315   /* FIXME:  Formatting sucks here, and in case of failure of BFD_READ,
   1316      we probably don't want to return TRUE.  */
   1317   if (bfd_seek (abfd, bfd_ardata (abfd)->first_file_filepos, SEEK_SET) != 0)
   1318     return FALSE;
   1319 
   1320   if (bfd_bread (nextname, 16, abfd) == 16)
   1321     {
   1322       if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
   1323 	return FALSE;
   1324 
   1325       if (! CONST_STRNEQ (nextname, "ARFILENAMES/    ")
   1326 	  && ! CONST_STRNEQ (nextname, "//              "))
   1327 	{
   1328 	  bfd_ardata (abfd)->extended_names = NULL;
   1329 	  bfd_ardata (abfd)->extended_names_size = 0;
   1330 	  return TRUE;
   1331 	}
   1332 
   1333       namedata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
   1334       if (namedata == NULL)
   1335 	return FALSE;
   1336 
   1337       amt = namedata->parsed_size;
   1338       if (amt + 1 == 0)
   1339 	goto byebye;
   1340 
   1341       bfd_ardata (abfd)->extended_names_size = amt;
   1342       bfd_ardata (abfd)->extended_names = (char *) bfd_zalloc (abfd, amt + 1);
   1343       if (bfd_ardata (abfd)->extended_names == NULL)
   1344 	{
   1345 	byebye:
   1346 	  free (namedata);
   1347 	  bfd_ardata (abfd)->extended_names = NULL;
   1348 	  bfd_ardata (abfd)->extended_names_size = 0;
   1349 	  return FALSE;
   1350 	}
   1351 
   1352       if (bfd_bread (bfd_ardata (abfd)->extended_names, amt, abfd) != amt)
   1353 	{
   1354 	  if (bfd_get_error () != bfd_error_system_call)
   1355 	    bfd_set_error (bfd_error_malformed_archive);
   1356 	  bfd_release (abfd, (bfd_ardata (abfd)->extended_names));
   1357 	  bfd_ardata (abfd)->extended_names = NULL;
   1358 	  goto byebye;
   1359 	}
   1360 
   1361       /* Since the archive is supposed to be printable if it contains
   1362 	 text, the entries in the list are newline-padded, not null
   1363 	 padded. In SVR4-style archives, the names also have a
   1364 	 trailing '/'.  DOS/NT created archive often have \ in them
   1365 	 We'll fix all problems here.  */
   1366       {
   1367 	char *ext_names = bfd_ardata (abfd)->extended_names;
   1368 	char *temp = ext_names;
   1369 	char *limit = temp + namedata->parsed_size;
   1370 
   1371 	for (; temp < limit; ++temp)
   1372 	  {
   1373 	    if (*temp == ARFMAG[1])
   1374 	      temp[temp > ext_names && temp[-1] == '/' ? -1 : 0] = '\0';
   1375 	    if (*temp == '\\')
   1376 	      *temp = '/';
   1377 	  }
   1378 	*limit = '\0';
   1379       }
   1380 
   1381       /* Pad to an even boundary if you have to.  */
   1382       bfd_ardata (abfd)->first_file_filepos = bfd_tell (abfd);
   1383       bfd_ardata (abfd)->first_file_filepos +=
   1384 	(bfd_ardata (abfd)->first_file_filepos) % 2;
   1385 
   1386       free (namedata);
   1387     }
   1388   return TRUE;
   1389 }
   1390 
   1391 #ifdef VMS
   1392 
   1393 /* Return a copy of the stuff in the filename between any :]> and a
   1394    semicolon.  */
   1395 
   1396 static const char *
   1397 normalize (bfd *abfd, const char *file)
   1398 {
   1399   const char *first;
   1400   const char *last;
   1401   char *copy;
   1402 
   1403   first = file + strlen (file) - 1;
   1404   last = first + 1;
   1405 
   1406   while (first != file)
   1407     {
   1408       if (*first == ';')
   1409 	last = first;
   1410       if (*first == ':' || *first == ']' || *first == '>')
   1411 	{
   1412 	  first++;
   1413 	  break;
   1414 	}
   1415       first--;
   1416     }
   1417 
   1418   copy = bfd_alloc (abfd, last - first + 1);
   1419   if (copy == NULL)
   1420     return NULL;
   1421 
   1422   memcpy (copy, first, last - first);
   1423   copy[last - first] = 0;
   1424 
   1425   return copy;
   1426 }
   1427 
   1428 #else
   1429 static const char *
   1430 normalize (bfd *abfd ATTRIBUTE_UNUSED, const char *file)
   1431 {
   1432   return lbasename (file);
   1433 }
   1434 #endif
   1435 
   1436 /* Adjust a relative path name based on the reference path.
   1437    For example:
   1438 
   1439      Relative path  Reference path  Result
   1440      -------------  --------------  ------
   1441      bar.o          lib.a           bar.o
   1442      foo/bar.o      lib.a           foo/bar.o
   1443      bar.o          foo/lib.a       ../bar.o
   1444      foo/bar.o      baz/lib.a       ../foo/bar.o
   1445      bar.o          ../lib.a        <parent of current dir>/bar.o
   1446    ; ../bar.o       ../lib.a        bar.o
   1447    ; ../bar.o       lib.a           ../bar.o
   1448      foo/bar.o      ../lib.a        <parent of current dir>/foo/bar.o
   1449      bar.o          ../../lib.a     <grandparent>/<parent>/bar.o
   1450      bar.o          foo/baz/lib.a   ../../bar.o
   1451 
   1452    Note - the semicolons above are there to prevent the BFD chew
   1453    utility from interpreting those lines as prototypes to put into
   1454    the autogenerated bfd.h header...
   1455 
   1456    Note - the string is returned in a static buffer.  */
   1457 
   1458 static const char *
   1459 adjust_relative_path (const char * path, const char * ref_path)
   1460 {
   1461   static char *pathbuf = NULL;
   1462   static unsigned int pathbuf_len = 0;
   1463   const char *pathp;
   1464   const char *refp;
   1465   char * lpath;
   1466   char * rpath;
   1467   unsigned int len;
   1468   unsigned int dir_up = 0;
   1469   unsigned int dir_down = 0;
   1470   char *newp;
   1471   char * pwd = getpwd ();
   1472   const char * down;
   1473 
   1474   /* Remove symlinks, '.' and '..' from the paths, if possible.  */
   1475   lpath = lrealpath (path);
   1476   pathp = lpath == NULL ? path : lpath;
   1477 
   1478   rpath = lrealpath (ref_path);
   1479   refp = rpath == NULL ? ref_path : rpath;
   1480 
   1481   /* Remove common leading path elements.  */
   1482   for (;;)
   1483     {
   1484       const char *e1 = pathp;
   1485       const char *e2 = refp;
   1486 
   1487       while (*e1 && ! IS_DIR_SEPARATOR (*e1))
   1488 	++e1;
   1489       while (*e2 && ! IS_DIR_SEPARATOR (*e2))
   1490 	++e2;
   1491       if (*e1 == '\0' || *e2 == '\0' || e1 - pathp != e2 - refp
   1492 	  || filename_ncmp (pathp, refp, e1 - pathp) != 0)
   1493 	break;
   1494       pathp = e1 + 1;
   1495       refp = e2 + 1;
   1496     }
   1497 
   1498   len = strlen (pathp) + 1;
   1499   /* For each leading path element in the reference path,
   1500      insert "../" into the path.  */
   1501   for (; *refp; ++refp)
   1502     if (IS_DIR_SEPARATOR (*refp))
   1503       {
   1504 	/* PR 12710:  If the path element is "../" then instead of
   1505 	   inserting "../" we need to insert the name of the directory
   1506 	   at the current level.  */
   1507 	if (refp > ref_path + 1
   1508 	    && refp[-1] == '.'
   1509 	    && refp[-2] == '.')
   1510 	  dir_down ++;
   1511 	else
   1512 	  dir_up ++;
   1513       }
   1514 
   1515   /* If the lrealpath calls above succeeded then we should never
   1516      see dir_up and dir_down both being non-zero.  */
   1517 
   1518   len += 3 * dir_up;
   1519 
   1520   if (dir_down)
   1521     {
   1522       down = pwd + strlen (pwd) - 1;
   1523 
   1524       while (dir_down && down > pwd)
   1525 	{
   1526 	  if (IS_DIR_SEPARATOR (*down))
   1527 	    --dir_down;
   1528 	}
   1529       BFD_ASSERT (dir_down == 0);
   1530       len += strlen (down) + 1;
   1531     }
   1532   else
   1533     down = NULL;
   1534 
   1535   if (len > pathbuf_len)
   1536     {
   1537       if (pathbuf != NULL)
   1538 	free (pathbuf);
   1539       pathbuf_len = 0;
   1540       pathbuf = (char *) bfd_malloc (len);
   1541       if (pathbuf == NULL)
   1542 	goto out;
   1543       pathbuf_len = len;
   1544     }
   1545 
   1546   newp = pathbuf;
   1547   while (dir_up-- > 0)
   1548     {
   1549       /* FIXME: Support Windows style path separators as well.  */
   1550       strcpy (newp, "../");
   1551       newp += 3;
   1552     }
   1553 
   1554   if (down)
   1555     sprintf (newp, "%s/%s", down, pathp);
   1556   else
   1557     strcpy (newp, pathp);
   1558 
   1559  out:
   1560   free (lpath);
   1561   free (rpath);
   1562   return pathbuf;
   1563 }
   1564 
   1565 /* Build a BFD style extended name table.  */
   1566 
   1567 bfd_boolean
   1568 _bfd_archive_bsd_construct_extended_name_table (bfd *abfd,
   1569 						char **tabloc,
   1570 						bfd_size_type *tablen,
   1571 						const char **name)
   1572 {
   1573   *name = "ARFILENAMES/";
   1574   return _bfd_construct_extended_name_table (abfd, FALSE, tabloc, tablen);
   1575 }
   1576 
   1577 /* Build an SVR4 style extended name table.  */
   1578 
   1579 bfd_boolean
   1580 _bfd_archive_coff_construct_extended_name_table (bfd *abfd,
   1581 						 char **tabloc,
   1582 						 bfd_size_type *tablen,
   1583 						 const char **name)
   1584 {
   1585   *name = "//";
   1586   return _bfd_construct_extended_name_table (abfd, TRUE, tabloc, tablen);
   1587 }
   1588 
   1589 /* Follows archive_head and produces an extended name table if
   1590    necessary.  Returns (in tabloc) a pointer to an extended name
   1591    table, and in tablen the length of the table.  If it makes an entry
   1592    it clobbers the filename so that the element may be written without
   1593    further massage.  Returns TRUE if it ran successfully, FALSE if
   1594    something went wrong.  A successful return may still involve a
   1595    zero-length tablen!  */
   1596 
   1597 bfd_boolean
   1598 _bfd_construct_extended_name_table (bfd *abfd,
   1599 				    bfd_boolean trailing_slash,
   1600 				    char **tabloc,
   1601 				    bfd_size_type *tablen)
   1602 {
   1603   unsigned int maxname = ar_maxnamelen (abfd);
   1604   bfd_size_type total_namelen = 0;
   1605   bfd *current;
   1606   char *strptr;
   1607   const char *last_filename;
   1608   long last_stroff;
   1609 
   1610   *tablen = 0;
   1611   last_filename = NULL;
   1612 
   1613   /* Figure out how long the table should be.  */
   1614   for (current = abfd->archive_head;
   1615        current != NULL;
   1616        current = current->archive_next)
   1617     {
   1618       const char *normal;
   1619       unsigned int thislen;
   1620 
   1621       if (bfd_is_thin_archive (abfd))
   1622 	{
   1623 	  const char *filename = current->filename;
   1624 
   1625 	  /* If the element being added is a member of another archive
   1626 	     (i.e., we are flattening), use the containing archive's name.  */
   1627 	  if (current->my_archive
   1628 	      && ! bfd_is_thin_archive (current->my_archive))
   1629 	    filename = current->my_archive->filename;
   1630 
   1631 	  /* If the path is the same as the previous path seen,
   1632 	     reuse it.  This can happen when flattening a thin
   1633 	     archive that contains other archives.  */
   1634 	  if (last_filename && filename_cmp (last_filename, filename) == 0)
   1635 	    continue;
   1636 
   1637 	  last_filename = filename;
   1638 
   1639 	  /* If the path is relative, adjust it relative to
   1640 	     the containing archive. */
   1641 	  if (! IS_ABSOLUTE_PATH (filename)
   1642 	      && ! IS_ABSOLUTE_PATH (abfd->filename))
   1643 	    normal = adjust_relative_path (filename, abfd->filename);
   1644 	  else
   1645 	    normal = filename;
   1646 
   1647 	  /* In a thin archive, always store the full pathname
   1648 	     in the extended name table.  */
   1649 	  total_namelen += strlen (normal) + 1;
   1650 	  if (trailing_slash)
   1651 	    /* Leave room for trailing slash.  */
   1652 	    ++total_namelen;
   1653 
   1654 	  continue;
   1655 	}
   1656 
   1657       normal = normalize (current, current->filename);
   1658       if (normal == NULL)
   1659 	return FALSE;
   1660 
   1661       thislen = strlen (normal);
   1662 
   1663       if (thislen > maxname
   1664 	  && (bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
   1665 	thislen = maxname;
   1666 
   1667       if (thislen > maxname)
   1668 	{
   1669 	  /* Add one to leave room for \n.  */
   1670 	  total_namelen += thislen + 1;
   1671 	  if (trailing_slash)
   1672 	    {
   1673 	      /* Leave room for trailing slash.  */
   1674 	      ++total_namelen;
   1675 	    }
   1676 	}
   1677       else
   1678 	{
   1679 	  struct ar_hdr *hdr = arch_hdr (current);
   1680 	  if (filename_ncmp (normal, hdr->ar_name, thislen) != 0
   1681 	      || (thislen < sizeof hdr->ar_name
   1682 		  && hdr->ar_name[thislen] != ar_padchar (current)))
   1683 	    {
   1684 	      /* Must have been using extended format even though it
   1685 		 didn't need to.  Fix it to use normal format.  */
   1686 	      memcpy (hdr->ar_name, normal, thislen);
   1687 	      if (thislen < maxname
   1688 		  || (thislen == maxname && thislen < sizeof hdr->ar_name))
   1689 		hdr->ar_name[thislen] = ar_padchar (current);
   1690 	    }
   1691 	}
   1692     }
   1693 
   1694   if (total_namelen == 0)
   1695     return TRUE;
   1696 
   1697   *tabloc = (char *) bfd_zalloc (abfd, total_namelen);
   1698   if (*tabloc == NULL)
   1699     return FALSE;
   1700 
   1701   *tablen = total_namelen;
   1702   strptr = *tabloc;
   1703 
   1704   last_filename = NULL;
   1705   last_stroff = 0;
   1706 
   1707   for (current = abfd->archive_head;
   1708        current != NULL;
   1709        current = current->archive_next)
   1710     {
   1711       const char *normal;
   1712       unsigned int thislen;
   1713       long stroff;
   1714       const char *filename = current->filename;
   1715 
   1716       if (bfd_is_thin_archive (abfd))
   1717 	{
   1718 	  /* If the element being added is a member of another archive
   1719 	     (i.e., we are flattening), use the containing archive's name.  */
   1720 	  if (current->my_archive
   1721 	      && ! bfd_is_thin_archive (current->my_archive))
   1722 	    filename = current->my_archive->filename;
   1723 	  /* If the path is the same as the previous path seen,
   1724 	     reuse it.  This can happen when flattening a thin
   1725 	     archive that contains other archives.
   1726 	     If the path is relative, adjust it relative to
   1727 	     the containing archive.  */
   1728 	  if (last_filename && filename_cmp (last_filename, filename) == 0)
   1729 	    normal = last_filename;
   1730 	  else if (! IS_ABSOLUTE_PATH (filename)
   1731 		   && ! IS_ABSOLUTE_PATH (abfd->filename))
   1732 	    normal = adjust_relative_path (filename, abfd->filename);
   1733 	  else
   1734 	    normal = filename;
   1735 	}
   1736       else
   1737 	{
   1738 	  normal = normalize (current, filename);
   1739 	  if (normal == NULL)
   1740 	    return FALSE;
   1741 	}
   1742 
   1743       thislen = strlen (normal);
   1744       if (thislen > maxname || bfd_is_thin_archive (abfd))
   1745 	{
   1746 	  /* Works for now; may need to be re-engineered if we
   1747 	     encounter an oddball archive format and want to
   1748 	     generalise this hack.  */
   1749 	  struct ar_hdr *hdr = arch_hdr (current);
   1750 	  if (normal == last_filename)
   1751 	    stroff = last_stroff;
   1752 	  else
   1753 	    {
   1754 	      strcpy (strptr, normal);
   1755 	      if (! trailing_slash)
   1756 		strptr[thislen] = ARFMAG[1];
   1757 	      else
   1758 		{
   1759 		  strptr[thislen] = '/';
   1760 		  strptr[thislen + 1] = ARFMAG[1];
   1761 		}
   1762 	      stroff = strptr - *tabloc;
   1763 	      last_stroff = stroff;
   1764 	    }
   1765 	  hdr->ar_name[0] = ar_padchar (current);
   1766 	  if (bfd_is_thin_archive (abfd) && current->origin > 0)
   1767 	    {
   1768 	      int len = snprintf (hdr->ar_name + 1, maxname - 1, "%-ld:",
   1769 				  stroff);
   1770 	      _bfd_ar_spacepad (hdr->ar_name + 1 + len, maxname - 1 - len,
   1771 				"%-ld",
   1772 				current->origin - sizeof (struct ar_hdr));
   1773 	    }
   1774 	  else
   1775 	    _bfd_ar_spacepad (hdr->ar_name + 1, maxname - 1, "%-ld", stroff);
   1776 	  if (normal != last_filename)
   1777 	    {
   1778 	      strptr += thislen + 1;
   1779 	      if (trailing_slash)
   1780 		++strptr;
   1781 	      last_filename = filename;
   1782 	    }
   1783 	}
   1784     }
   1785 
   1786   return TRUE;
   1787 }
   1788 
   1789 /* Do not construct an extended name table but transforms name field into
   1790    its extended form.  */
   1791 
   1792 bfd_boolean
   1793 _bfd_archive_bsd44_construct_extended_name_table (bfd *abfd,
   1794 						  char **tabloc,
   1795 						  bfd_size_type *tablen,
   1796 						  const char **name)
   1797 {
   1798   unsigned int maxname = ar_maxnamelen (abfd);
   1799   bfd *current;
   1800 
   1801   *tablen = 0;
   1802   *tabloc = NULL;
   1803   *name = NULL;
   1804 
   1805   for (current = abfd->archive_head;
   1806        current != NULL;
   1807        current = current->archive_next)
   1808     {
   1809       const char *normal = normalize (current, current->filename);
   1810       int has_space = 0;
   1811       unsigned int len;
   1812 
   1813       if (normal == NULL)
   1814 	return FALSE;
   1815 
   1816       for (len = 0; normal[len]; len++)
   1817 	if (normal[len] == ' ')
   1818 	  has_space = 1;
   1819 
   1820       if (len > maxname || has_space)
   1821 	{
   1822 	  struct ar_hdr *hdr = arch_hdr (current);
   1823 
   1824 	  len = (len + 3) & ~3;
   1825 	  arch_eltdata (current)->extra_size = len;
   1826 	  _bfd_ar_spacepad (hdr->ar_name, maxname, "#1/%lu", len);
   1827 	}
   1828     }
   1829 
   1830   return TRUE;
   1831 }
   1832 
   1833 /* Write an archive header.  */
   1835 
   1836 bfd_boolean
   1837 _bfd_generic_write_ar_hdr (bfd *archive, bfd *abfd)
   1838 {
   1839   struct ar_hdr *hdr = arch_hdr (abfd);
   1840 
   1841   if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
   1842     return FALSE;
   1843   return TRUE;
   1844 }
   1845 
   1846 /* Write an archive header using BSD4.4 convention.  */
   1847 
   1848 bfd_boolean
   1849 _bfd_bsd44_write_ar_hdr (bfd *archive, bfd *abfd)
   1850 {
   1851   struct ar_hdr *hdr = arch_hdr (abfd);
   1852 
   1853   if (is_bsd44_extended_name (hdr->ar_name))
   1854     {
   1855       /* This is a BSD 4.4 extended name.  */
   1856       const char *fullname = normalize (abfd, abfd->filename);
   1857       unsigned int len = strlen (fullname);
   1858       unsigned int padded_len = (len + 3) & ~3;
   1859 
   1860       BFD_ASSERT (padded_len == arch_eltdata (abfd)->extra_size);
   1861 
   1862       if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size),
   1863 			    arch_eltdata (abfd)->parsed_size + padded_len))
   1864 	return FALSE;
   1865 
   1866       if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
   1867 	return FALSE;
   1868 
   1869       if (bfd_bwrite (fullname, len, archive) != len)
   1870 	return FALSE;
   1871 
   1872       if (len & 3)
   1873 	{
   1874 	  static const char pad[3] = { 0, 0, 0 };
   1875 
   1876 	  len = 4 - (len & 3);
   1877 	  if (bfd_bwrite (pad, len, archive) != len)
   1878 	    return FALSE;
   1879 	}
   1880     }
   1881   else
   1882     {
   1883       if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
   1884 	return FALSE;
   1885     }
   1886   return TRUE;
   1887 }
   1888 
   1889 /* A couple of functions for creating ar_hdrs.  */
   1891 
   1892 #ifdef HPUX_LARGE_AR_IDS
   1893 /* Function to encode large UID/GID values according to HP.  */
   1894 
   1895 static void
   1896 hpux_uid_gid_encode (char str[6], long int id)
   1897 {
   1898   int cnt;
   1899 
   1900   str[5] = '@' + (id & 3);
   1901   id >>= 2;
   1902 
   1903   for (cnt = 4; cnt >= 0; --cnt, id >>= 6)
   1904     str[cnt] = ' ' + (id & 0x3f);
   1905 }
   1906 #endif	/* HPUX_LARGE_AR_IDS */
   1907 
   1908 #ifndef HAVE_GETUID
   1909 #define getuid() 0
   1910 #endif
   1911 
   1912 #ifndef HAVE_GETGID
   1913 #define getgid() 0
   1914 #endif
   1915 
   1916 /* Takes a filename, returns an arelt_data for it, or NULL if it can't
   1917    make one.  The filename must refer to a filename in the filesystem.
   1918    The filename field of the ar_hdr will NOT be initialized.  If member
   1919    is set, and it's an in-memory bfd, we fake it.  */
   1920 
   1921 static struct areltdata *
   1922 bfd_ar_hdr_from_filesystem (bfd *abfd, const char *filename, bfd *member)
   1923 {
   1924   struct stat status;
   1925   struct areltdata *ared;
   1926   struct ar_hdr *hdr;
   1927   bfd_size_type amt;
   1928 
   1929   if (member && (member->flags & BFD_IN_MEMORY) != 0)
   1930     {
   1931       /* Assume we just "made" the member, and fake it.  */
   1932       struct bfd_in_memory *bim = (struct bfd_in_memory *) member->iostream;
   1933       time (&status.st_mtime);
   1934       status.st_uid = getuid ();
   1935       status.st_gid = getgid ();
   1936       status.st_mode = 0644;
   1937       status.st_size = bim->size;
   1938     }
   1939   else if (stat (filename, &status) != 0)
   1940     {
   1941       bfd_set_error (bfd_error_system_call);
   1942       return NULL;
   1943     }
   1944 
   1945   /* If the caller requested that the BFD generate deterministic output,
   1946      fake values for modification time, UID, GID, and file mode.  */
   1947   if ((abfd->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
   1948     {
   1949       status.st_mtime = 0;
   1950       status.st_uid = 0;
   1951       status.st_gid = 0;
   1952       status.st_mode = 0644;
   1953     }
   1954 
   1955   amt = sizeof (struct ar_hdr) + sizeof (struct areltdata);
   1956   ared = (struct areltdata *) bfd_zmalloc (amt);
   1957   if (ared == NULL)
   1958     return NULL;
   1959   hdr = (struct ar_hdr *) (((char *) ared) + sizeof (struct areltdata));
   1960 
   1961   /* ar headers are space padded, not null padded!  */
   1962   memset (hdr, ' ', sizeof (struct ar_hdr));
   1963 
   1964   _bfd_ar_spacepad (hdr->ar_date, sizeof (hdr->ar_date), "%-12ld",
   1965 		    status.st_mtime);
   1966 #ifdef HPUX_LARGE_AR_IDS
   1967   /* HP has a very "special" way to handle UID/GID's with numeric values
   1968      > 99999.  */
   1969   if (status.st_uid > 99999)
   1970     hpux_uid_gid_encode (hdr->ar_uid, (long) status.st_uid);
   1971   else
   1972 #endif
   1973     _bfd_ar_spacepad (hdr->ar_uid, sizeof (hdr->ar_uid), "%ld",
   1974 		      status.st_uid);
   1975 #ifdef HPUX_LARGE_AR_IDS
   1976   /* HP has a very "special" way to handle UID/GID's with numeric values
   1977      > 99999.  */
   1978   if (status.st_gid > 99999)
   1979     hpux_uid_gid_encode (hdr->ar_gid, (long) status.st_gid);
   1980   else
   1981 #endif
   1982     _bfd_ar_spacepad (hdr->ar_gid, sizeof (hdr->ar_gid), "%ld",
   1983 		      status.st_gid);
   1984   _bfd_ar_spacepad (hdr->ar_mode, sizeof (hdr->ar_mode), "%-8lo",
   1985 		    status.st_mode);
   1986   if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size), status.st_size))
   1987     {
   1988       free (ared);
   1989       return NULL;
   1990     }
   1991   memcpy (hdr->ar_fmag, ARFMAG, 2);
   1992   ared->parsed_size = status.st_size;
   1993   ared->arch_header = (char *) hdr;
   1994 
   1995   return ared;
   1996 }
   1997 
   1998 /* Analogous to stat call.  */
   1999 
   2000 int
   2001 bfd_generic_stat_arch_elt (bfd *abfd, struct stat *buf)
   2002 {
   2003   struct ar_hdr *hdr;
   2004   char *aloser;
   2005 
   2006   if (abfd->arelt_data == NULL)
   2007     {
   2008       bfd_set_error (bfd_error_invalid_operation);
   2009       return -1;
   2010     }
   2011 
   2012   hdr = arch_hdr (abfd);
   2013   /* PR 17512: file: 3d9e9fe9.  */
   2014   if (hdr == NULL)
   2015     return -1;
   2016 #define foo(arelt, stelt, size)				\
   2017   buf->stelt = strtol (hdr->arelt, &aloser, size);	\
   2018   if (aloser == hdr->arelt)	      			\
   2019     return -1;
   2020 
   2021   /* Some platforms support special notations for large IDs.  */
   2022 #ifdef HPUX_LARGE_AR_IDS
   2023 # define foo2(arelt, stelt, size)					\
   2024   if (hdr->arelt[5] == ' ')						\
   2025     {									\
   2026       foo (arelt, stelt, size);						\
   2027     }									\
   2028   else									\
   2029     {									\
   2030       int cnt;								\
   2031       for (buf->stelt = cnt = 0; cnt < 5; ++cnt)			\
   2032 	{								\
   2033 	  if (hdr->arelt[cnt] < ' ' || hdr->arelt[cnt] > ' ' + 0x3f)	\
   2034 	    return -1;							\
   2035 	  buf->stelt <<= 6;						\
   2036 	  buf->stelt += hdr->arelt[cnt] - ' ';				\
   2037 	}								\
   2038       if (hdr->arelt[5] < '@' || hdr->arelt[5] > '@' + 3)		\
   2039 	return -1;							\
   2040       buf->stelt <<= 2;							\
   2041       buf->stelt += hdr->arelt[5] - '@';				\
   2042     }
   2043 #else
   2044 # define foo2(arelt, stelt, size) foo (arelt, stelt, size)
   2045 #endif
   2046 
   2047   foo (ar_date, st_mtime, 10);
   2048   foo2 (ar_uid, st_uid, 10);
   2049   foo2 (ar_gid, st_gid, 10);
   2050   foo (ar_mode, st_mode, 8);
   2051 
   2052   buf->st_size = arch_eltdata (abfd)->parsed_size;
   2053 
   2054   return 0;
   2055 }
   2056 
   2057 void
   2058 bfd_dont_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
   2059 {
   2060   /* FIXME: This interacts unpleasantly with ar's quick-append option.
   2061      Fortunately ic960 users will never use that option.  Fixing this
   2062      is very hard; fortunately I know how to do it and will do so once
   2063      intel's release is out the door.  */
   2064 
   2065   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
   2066   size_t length;
   2067   const char *filename;
   2068   size_t maxlen = ar_maxnamelen (abfd);
   2069 
   2070   if ((bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
   2071     {
   2072       bfd_bsd_truncate_arname (abfd, pathname, arhdr);
   2073       return;
   2074     }
   2075 
   2076   filename = normalize (abfd, pathname);
   2077   if (filename == NULL)
   2078     {
   2079       /* FIXME */
   2080       abort ();
   2081     }
   2082 
   2083   length = strlen (filename);
   2084 
   2085   if (length <= maxlen)
   2086     memcpy (hdr->ar_name, filename, length);
   2087 
   2088   /* Add the padding character if there is room for it.  */
   2089   if (length < maxlen
   2090       || (length == maxlen && length < sizeof hdr->ar_name))
   2091     (hdr->ar_name)[length] = ar_padchar (abfd);
   2092 }
   2093 
   2094 void
   2095 bfd_bsd_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
   2096 {
   2097   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
   2098   size_t length;
   2099   const char *filename = lbasename (pathname);
   2100   size_t maxlen = ar_maxnamelen (abfd);
   2101 
   2102   length = strlen (filename);
   2103 
   2104   if (length <= maxlen)
   2105     memcpy (hdr->ar_name, filename, length);
   2106   else
   2107     {
   2108       /* pathname: meet procrustes */
   2109       memcpy (hdr->ar_name, filename, maxlen);
   2110       length = maxlen;
   2111     }
   2112 
   2113   if (length < maxlen)
   2114     (hdr->ar_name)[length] = ar_padchar (abfd);
   2115 }
   2116 
   2117 /* Store name into ar header.  Truncates the name to fit.
   2118    1> strip pathname to be just the basename.
   2119    2> if it's short enuf to fit, stuff it in.
   2120    3> If it doesn't end with .o, truncate it to fit
   2121    4> truncate it before the .o, append .o, stuff THAT in.  */
   2122 
   2123 /* This is what gnu ar does.  It's better but incompatible with the
   2124    bsd ar.  */
   2125 
   2126 void
   2127 bfd_gnu_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
   2128 {
   2129   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
   2130   size_t length;
   2131   const char *filename = lbasename (pathname);
   2132   size_t maxlen = ar_maxnamelen (abfd);
   2133 
   2134   length = strlen (filename);
   2135 
   2136   if (length <= maxlen)
   2137     memcpy (hdr->ar_name, filename, length);
   2138   else
   2139     {
   2140       /* pathname: meet procrustes.  */
   2141       memcpy (hdr->ar_name, filename, maxlen);
   2142       if ((filename[length - 2] == '.') && (filename[length - 1] == 'o'))
   2143 	{
   2144 	  hdr->ar_name[maxlen - 2] = '.';
   2145 	  hdr->ar_name[maxlen - 1] = 'o';
   2146 	}
   2147       length = maxlen;
   2148     }
   2149 
   2150   if (length < 16)
   2151     (hdr->ar_name)[length] = ar_padchar (abfd);
   2152 }
   2153 
   2154 /* The BFD is open for write and has its format set to bfd_archive.  */
   2156 
   2157 bfd_boolean
   2158 _bfd_write_archive_contents (bfd *arch)
   2159 {
   2160   bfd *current;
   2161   char *etable = NULL;
   2162   bfd_size_type elength = 0;
   2163   const char *ename = NULL;
   2164   bfd_boolean makemap = bfd_has_map (arch);
   2165   /* If no .o's, don't bother to make a map.  */
   2166   bfd_boolean hasobjects = FALSE;
   2167   bfd_size_type wrote;
   2168   int tries;
   2169   char *armag;
   2170 
   2171   /* Verify the viability of all entries; if any of them live in the
   2172      filesystem (as opposed to living in an archive open for input)
   2173      then construct a fresh ar_hdr for them.  */
   2174   for (current = arch->archive_head;
   2175        current != NULL;
   2176        current = current->archive_next)
   2177     {
   2178       /* This check is checking the bfds for the objects we're reading
   2179 	 from (which are usually either an object file or archive on
   2180 	 disk), not the archive entries we're writing to.  We don't
   2181 	 actually create bfds for the archive members, we just copy
   2182 	 them byte-wise when we write out the archive.  */
   2183       if (bfd_write_p (current))
   2184 	{
   2185 	  bfd_set_error (bfd_error_invalid_operation);
   2186 	  goto input_err;
   2187 	}
   2188       if (!current->arelt_data)
   2189 	{
   2190 	  current->arelt_data =
   2191 	    bfd_ar_hdr_from_filesystem (arch, current->filename, current);
   2192 	  if (!current->arelt_data)
   2193 	    goto input_err;
   2194 
   2195 	  /* Put in the file name.  */
   2196 	  BFD_SEND (arch, _bfd_truncate_arname,
   2197 		    (arch, current->filename, (char *) arch_hdr (current)));
   2198 	}
   2199 
   2200       if (makemap && ! hasobjects)
   2201 	{			/* Don't bother if we won't make a map!  */
   2202 	  if ((bfd_check_format (current, bfd_object)))
   2203 	    hasobjects = TRUE;
   2204 	}
   2205     }
   2206 
   2207   if (!BFD_SEND (arch, _bfd_construct_extended_name_table,
   2208 		 (arch, &etable, &elength, &ename)))
   2209     return FALSE;
   2210 
   2211   if (bfd_seek (arch, (file_ptr) 0, SEEK_SET) != 0)
   2212     return FALSE;
   2213   armag = ARMAG;
   2214   if (bfd_is_thin_archive (arch))
   2215     armag = ARMAGT;
   2216   wrote = bfd_bwrite (armag, SARMAG, arch);
   2217   if (wrote != SARMAG)
   2218     return FALSE;
   2219 
   2220   if (makemap && hasobjects)
   2221     {
   2222       if (! _bfd_compute_and_write_armap (arch, (unsigned int) elength))
   2223 	return FALSE;
   2224     }
   2225 
   2226   if (elength != 0)
   2227     {
   2228       struct ar_hdr hdr;
   2229 
   2230       memset (&hdr, ' ', sizeof (struct ar_hdr));
   2231       memcpy (hdr.ar_name, ename, strlen (ename));
   2232       /* Round size up to even number in archive header.  */
   2233       if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size),
   2234 			    (elength + 1) & ~(bfd_size_type) 1))
   2235 	return FALSE;
   2236       memcpy (hdr.ar_fmag, ARFMAG, 2);
   2237       if ((bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
   2238 	   != sizeof (struct ar_hdr))
   2239 	  || bfd_bwrite (etable, elength, arch) != elength)
   2240 	return FALSE;
   2241       if ((elength % 2) == 1)
   2242 	{
   2243 	  if (bfd_bwrite (&ARFMAG[1], 1, arch) != 1)
   2244 	    return FALSE;
   2245 	}
   2246     }
   2247 
   2248   for (current = arch->archive_head;
   2249        current != NULL;
   2250        current = current->archive_next)
   2251     {
   2252       char buffer[DEFAULT_BUFFERSIZE];
   2253       bfd_size_type remaining = arelt_size (current);
   2254 
   2255       /* Write ar header.  */
   2256       if (!_bfd_write_ar_hdr (arch, current))
   2257 	return FALSE;
   2258       if (bfd_is_thin_archive (arch))
   2259 	continue;
   2260       if (bfd_seek (current, (file_ptr) 0, SEEK_SET) != 0)
   2261 	goto input_err;
   2262 
   2263       while (remaining)
   2264 	{
   2265 	  unsigned int amt = DEFAULT_BUFFERSIZE;
   2266 
   2267 	  if (amt > remaining)
   2268 	    amt = remaining;
   2269 	  errno = 0;
   2270 	  if (bfd_bread (buffer, amt, current) != amt)
   2271 	    {
   2272 	      if (bfd_get_error () != bfd_error_system_call)
   2273 		bfd_set_error (bfd_error_file_truncated);
   2274 	      goto input_err;
   2275 	    }
   2276 	  if (bfd_bwrite (buffer, amt, arch) != amt)
   2277 	    return FALSE;
   2278 	  remaining -= amt;
   2279 	}
   2280 
   2281       if ((arelt_size (current) % 2) == 1)
   2282 	{
   2283 	  if (bfd_bwrite (&ARFMAG[1], 1, arch) != 1)
   2284 	    return FALSE;
   2285 	}
   2286     }
   2287 
   2288   if (makemap && hasobjects)
   2289     {
   2290       /* Verify the timestamp in the archive file.  If it would not be
   2291 	 accepted by the linker, rewrite it until it would be.  If
   2292 	 anything odd happens, break out and just return.  (The
   2293 	 Berkeley linker checks the timestamp and refuses to read the
   2294 	 table-of-contents if it is >60 seconds less than the file's
   2295 	 modified-time.  That painful hack requires this painful hack.  */
   2296       tries = 1;
   2297       do
   2298 	{
   2299 	  if (bfd_update_armap_timestamp (arch))
   2300 	    break;
   2301 	  (*_bfd_error_handler)
   2302 	    (_("Warning: writing archive was slow: rewriting timestamp\n"));
   2303 	}
   2304       while (++tries < 6);
   2305     }
   2306 
   2307   return TRUE;
   2308 
   2309  input_err:
   2310   bfd_set_error (bfd_error_on_input, current, bfd_get_error ());
   2311   return FALSE;
   2312 }
   2313 
   2314 /* Note that the namidx for the first symbol is 0.  */
   2316 
   2317 bfd_boolean
   2318 _bfd_compute_and_write_armap (bfd *arch, unsigned int elength)
   2319 {
   2320   char *first_name = NULL;
   2321   bfd *current;
   2322   file_ptr elt_no = 0;
   2323   struct orl *map = NULL;
   2324   unsigned int orl_max = 1024;		/* Fine initial default.  */
   2325   unsigned int orl_count = 0;
   2326   int stridx = 0;
   2327   asymbol **syms = NULL;
   2328   long syms_max = 0;
   2329   bfd_boolean ret;
   2330   bfd_size_type amt;
   2331 
   2332   /* Dunno if this is the best place for this info...  */
   2333   if (elength != 0)
   2334     elength += sizeof (struct ar_hdr);
   2335   elength += elength % 2;
   2336 
   2337   amt = orl_max * sizeof (struct orl);
   2338   map = (struct orl *) bfd_malloc (amt);
   2339   if (map == NULL)
   2340     goto error_return;
   2341 
   2342   /* We put the symbol names on the arch objalloc, and then discard
   2343      them when done.  */
   2344   first_name = (char *) bfd_alloc (arch, 1);
   2345   if (first_name == NULL)
   2346     goto error_return;
   2347 
   2348   /* Drop all the files called __.SYMDEF, we're going to make our own.  */
   2349   while (arch->archive_head
   2350 	 && strcmp (arch->archive_head->filename, "__.SYMDEF") == 0)
   2351     arch->archive_head = arch->archive_head->archive_next;
   2352 
   2353   /* Map over each element.  */
   2354   for (current = arch->archive_head;
   2355        current != NULL;
   2356        current = current->archive_next, elt_no++)
   2357     {
   2358       if (bfd_check_format (current, bfd_object)
   2359 	  && (bfd_get_file_flags (current) & HAS_SYMS) != 0)
   2360 	{
   2361 	  long storage;
   2362 	  long symcount;
   2363 	  long src_count;
   2364 
   2365 	  storage = bfd_get_symtab_upper_bound (current);
   2366 	  if (storage < 0)
   2367 	    goto error_return;
   2368 
   2369 	  if (storage != 0)
   2370 	    {
   2371 	      if (storage > syms_max)
   2372 		{
   2373 		  if (syms_max > 0)
   2374 		    free (syms);
   2375 		  syms_max = storage;
   2376 		  syms = (asymbol **) bfd_malloc (syms_max);
   2377 		  if (syms == NULL)
   2378 		    goto error_return;
   2379 		}
   2380 	      symcount = bfd_canonicalize_symtab (current, syms);
   2381 	      if (symcount < 0)
   2382 		goto error_return;
   2383 
   2384 	      /* Now map over all the symbols, picking out the ones we
   2385 		 want.  */
   2386 	      for (src_count = 0; src_count < symcount; src_count++)
   2387 		{
   2388 		  flagword flags = (syms[src_count])->flags;
   2389 		  asection *sec = syms[src_count]->section;
   2390 
   2391 		  if (((flags & (BSF_GLOBAL
   2392 				 | BSF_WEAK
   2393 				 | BSF_INDIRECT
   2394 				 | BSF_GNU_UNIQUE)) != 0
   2395 		       || bfd_is_com_section (sec))
   2396 		      && ! bfd_is_und_section (sec))
   2397 		    {
   2398 		      bfd_size_type namelen;
   2399 		      struct orl *new_map;
   2400 
   2401 		      /* This symbol will go into the archive header.  */
   2402 		      if (orl_count == orl_max)
   2403 			{
   2404 			  orl_max *= 2;
   2405 			  amt = orl_max * sizeof (struct orl);
   2406 			  new_map = (struct orl *) bfd_realloc (map, amt);
   2407 			  if (new_map == NULL)
   2408 			    goto error_return;
   2409 
   2410 			  map = new_map;
   2411 			}
   2412 
   2413 		      if (strcmp (syms[src_count]->name, "__gnu_lto_slim") == 0)
   2414 			(*_bfd_error_handler)
   2415 			  (_("%s: plugin needed to handle lto object"),
   2416 			   bfd_get_filename (current));
   2417 		      namelen = strlen (syms[src_count]->name);
   2418 		      amt = sizeof (char *);
   2419 		      map[orl_count].name = (char **) bfd_alloc (arch, amt);
   2420 		      if (map[orl_count].name == NULL)
   2421 			goto error_return;
   2422 		      *(map[orl_count].name) = (char *) bfd_alloc (arch,
   2423 								   namelen + 1);
   2424 		      if (*(map[orl_count].name) == NULL)
   2425 			goto error_return;
   2426 		      strcpy (*(map[orl_count].name), syms[src_count]->name);
   2427 		      map[orl_count].u.abfd = current;
   2428 		      map[orl_count].namidx = stridx;
   2429 
   2430 		      stridx += namelen + 1;
   2431 		      ++orl_count;
   2432 		    }
   2433 		}
   2434 	    }
   2435 
   2436 	  /* Now ask the BFD to free up any cached information, so we
   2437 	     don't fill all of memory with symbol tables.  */
   2438 	  if (! bfd_free_cached_info (current))
   2439 	    goto error_return;
   2440 	}
   2441     }
   2442 
   2443   /* OK, now we have collected all the data, let's write them out.  */
   2444   ret = BFD_SEND (arch, write_armap,
   2445 		  (arch, elength, map, orl_count, stridx));
   2446 
   2447   if (syms_max > 0)
   2448     free (syms);
   2449   if (map != NULL)
   2450     free (map);
   2451   if (first_name != NULL)
   2452     bfd_release (arch, first_name);
   2453 
   2454   return ret;
   2455 
   2456  error_return:
   2457   if (syms_max > 0)
   2458     free (syms);
   2459   if (map != NULL)
   2460     free (map);
   2461   if (first_name != NULL)
   2462     bfd_release (arch, first_name);
   2463 
   2464   return FALSE;
   2465 }
   2466 
   2467 bfd_boolean
   2468 bsd_write_armap (bfd *arch,
   2469 		 unsigned int elength,
   2470 		 struct orl *map,
   2471 		 unsigned int orl_count,
   2472 		 int stridx)
   2473 {
   2474   int padit = stridx & 1;
   2475   unsigned int ranlibsize = orl_count * BSD_SYMDEF_SIZE;
   2476   unsigned int stringsize = stridx + padit;
   2477   /* Include 8 bytes to store ranlibsize and stringsize in output.  */
   2478   unsigned int mapsize = ranlibsize + stringsize + 8;
   2479   file_ptr firstreal, first;
   2480   bfd *current;
   2481   bfd *last_elt;
   2482   bfd_byte temp[4];
   2483   unsigned int count;
   2484   struct ar_hdr hdr;
   2485   long uid, gid;
   2486 
   2487   first = mapsize + elength + sizeof (struct ar_hdr) + SARMAG;
   2488 
   2489 #ifdef BFD64
   2490   firstreal = first;
   2491   current = arch->archive_head;
   2492   last_elt = current;	/* Last element arch seen.  */
   2493   for (count = 0; count < orl_count; count++)
   2494     {
   2495       unsigned int offset;
   2496 
   2497       if (map[count].u.abfd != last_elt)
   2498 	{
   2499 	  do
   2500 	    {
   2501 	      struct areltdata *ared = arch_eltdata (current);
   2502 
   2503 	      firstreal += (ared->parsed_size + ared->extra_size
   2504 			    + sizeof (struct ar_hdr));
   2505 	      firstreal += firstreal % 2;
   2506 	      current = current->archive_next;
   2507 	    }
   2508 	  while (current != map[count].u.abfd);
   2509 	}
   2510 
   2511       /* The archive file format only has 4 bytes to store the offset
   2512 	 of the member.  Generate 64-bit archive if an archive is past
   2513 	 its 4Gb limit.  */
   2514       offset = (unsigned int) firstreal;
   2515       if (firstreal != (file_ptr) offset)
   2516 	return _bfd_archive_64_bit_write_armap (arch, elength, map,
   2517 						orl_count, stridx);
   2518 
   2519       last_elt = current;
   2520     }
   2521 #endif
   2522 
   2523   /* If deterministic, we use 0 as the timestamp in the map.
   2524      Some linkers may require that the archive filesystem modification
   2525      time is less than (or near to) the archive map timestamp.  Those
   2526      linkers should not be used with deterministic mode.  (GNU ld and
   2527      Gold do not have this restriction.)  */
   2528   bfd_ardata (arch)->armap_timestamp = 0;
   2529   uid = 0;
   2530   gid = 0;
   2531   if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0)
   2532     {
   2533       struct stat statbuf;
   2534 
   2535       if (stat (arch->filename, &statbuf) == 0)
   2536 	bfd_ardata (arch)->armap_timestamp = (statbuf.st_mtime
   2537 					      + ARMAP_TIME_OFFSET);
   2538       uid = getuid();
   2539       gid = getgid();
   2540     }
   2541 
   2542   memset (&hdr, ' ', sizeof (struct ar_hdr));
   2543   memcpy (hdr.ar_name, RANLIBMAG, strlen (RANLIBMAG));
   2544   bfd_ardata (arch)->armap_datepos = (SARMAG
   2545 				      + offsetof (struct ar_hdr, ar_date[0]));
   2546   _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
   2547 		    bfd_ardata (arch)->armap_timestamp);
   2548   _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", uid);
   2549   _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", gid);
   2550   if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
   2551     return FALSE;
   2552   memcpy (hdr.ar_fmag, ARFMAG, 2);
   2553   if (bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
   2554       != sizeof (struct ar_hdr))
   2555     return FALSE;
   2556   H_PUT_32 (arch, ranlibsize, temp);
   2557   if (bfd_bwrite (temp, sizeof (temp), arch) != sizeof (temp))
   2558     return FALSE;
   2559 
   2560   firstreal = first;
   2561   current = arch->archive_head;
   2562   last_elt = current;	/* Last element arch seen.  */
   2563   for (count = 0; count < orl_count; count++)
   2564     {
   2565       unsigned int offset;
   2566       bfd_byte buf[BSD_SYMDEF_SIZE];
   2567 
   2568       if (map[count].u.abfd != last_elt)
   2569 	{
   2570 	  do
   2571 	    {
   2572 	      struct areltdata *ared = arch_eltdata (current);
   2573 
   2574 	      firstreal += (ared->parsed_size + ared->extra_size
   2575 			    + sizeof (struct ar_hdr));
   2576 	      firstreal += firstreal % 2;
   2577 	      current = current->archive_next;
   2578 	    }
   2579 	  while (current != map[count].u.abfd);
   2580 	}
   2581 
   2582       /* The archive file format only has 4 bytes to store the offset
   2583 	 of the member.  Check to make sure that firstreal has not grown
   2584 	 too big.  */
   2585       offset = (unsigned int) firstreal;
   2586       if (firstreal != (file_ptr) offset)
   2587 	{
   2588 	  bfd_set_error (bfd_error_file_truncated);
   2589 	  return FALSE;
   2590 	}
   2591 
   2592       last_elt = current;
   2593       H_PUT_32 (arch, map[count].namidx, buf);
   2594       H_PUT_32 (arch, firstreal, buf + BSD_SYMDEF_OFFSET_SIZE);
   2595       if (bfd_bwrite (buf, BSD_SYMDEF_SIZE, arch)
   2596 	  != BSD_SYMDEF_SIZE)
   2597 	return FALSE;
   2598     }
   2599 
   2600   /* Now write the strings themselves.  */
   2601   H_PUT_32 (arch, stringsize, temp);
   2602   if (bfd_bwrite (temp, sizeof (temp), arch) != sizeof (temp))
   2603     return FALSE;
   2604   for (count = 0; count < orl_count; count++)
   2605     {
   2606       size_t len = strlen (*map[count].name) + 1;
   2607 
   2608       if (bfd_bwrite (*map[count].name, len, arch) != len)
   2609 	return FALSE;
   2610     }
   2611 
   2612   /* The spec sez this should be a newline.  But in order to be
   2613      bug-compatible for sun's ar we use a null.  */
   2614   if (padit)
   2615     {
   2616       if (bfd_bwrite ("", 1, arch) != 1)
   2617 	return FALSE;
   2618     }
   2619 
   2620   return TRUE;
   2621 }
   2622 
   2623 /* At the end of archive file handling, update the timestamp in the
   2624    file, so the linker will accept it.
   2625 
   2626    Return TRUE if the timestamp was OK, or an unusual problem happened.
   2627    Return FALSE if we updated the timestamp.  */
   2628 
   2629 bfd_boolean
   2630 _bfd_archive_bsd_update_armap_timestamp (bfd *arch)
   2631 {
   2632   struct stat archstat;
   2633   struct ar_hdr hdr;
   2634 
   2635   /* If creating deterministic archives, just leave the timestamp as-is.  */
   2636   if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
   2637     return TRUE;
   2638 
   2639   /* Flush writes, get last-write timestamp from file, and compare it
   2640      to the timestamp IN the file.  */
   2641   bfd_flush (arch);
   2642   if (bfd_stat (arch, &archstat) == -1)
   2643     {
   2644       bfd_perror (_("Reading archive file mod timestamp"));
   2645 
   2646       /* Can't read mod time for some reason.  */
   2647       return TRUE;
   2648     }
   2649   if (((long) archstat.st_mtime) <= bfd_ardata (arch)->armap_timestamp)
   2650     /* OK by the linker's rules.  */
   2651     return TRUE;
   2652 
   2653   /* Update the timestamp.  */
   2654   bfd_ardata (arch)->armap_timestamp = archstat.st_mtime + ARMAP_TIME_OFFSET;
   2655 
   2656   /* Prepare an ASCII version suitable for writing.  */
   2657   memset (hdr.ar_date, ' ', sizeof (hdr.ar_date));
   2658   _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
   2659 		    bfd_ardata (arch)->armap_timestamp);
   2660 
   2661   /* Write it into the file.  */
   2662   bfd_ardata (arch)->armap_datepos = (SARMAG
   2663 				      + offsetof (struct ar_hdr, ar_date[0]));
   2664   if (bfd_seek (arch, bfd_ardata (arch)->armap_datepos, SEEK_SET) != 0
   2665       || (bfd_bwrite (hdr.ar_date, sizeof (hdr.ar_date), arch)
   2666 	  != sizeof (hdr.ar_date)))
   2667     {
   2668       bfd_perror (_("Writing updated armap timestamp"));
   2669 
   2670       /* Some error while writing.  */
   2671       return TRUE;
   2672     }
   2673 
   2674   /* We updated the timestamp successfully.  */
   2675   return FALSE;
   2676 }
   2677 
   2678 /* A coff armap looks like :
   2680    lARMAG
   2681    struct ar_hdr with name = '/'
   2682    number of symbols
   2683    offset of file for symbol 0
   2684    offset of file for symbol 1
   2685 
   2686    offset of file for symbol n-1
   2687    symbol name 0
   2688    symbol name 1
   2689 
   2690    symbol name n-1  */
   2691 
   2692 bfd_boolean
   2693 coff_write_armap (bfd *arch,
   2694 		  unsigned int elength,
   2695 		  struct orl *map,
   2696 		  unsigned int symbol_count,
   2697 		  int stridx)
   2698 {
   2699   /* The size of the ranlib is the number of exported symbols in the
   2700      archive * the number of bytes in an int, + an int for the count.  */
   2701   unsigned int ranlibsize = (symbol_count * 4) + 4;
   2702   unsigned int stringsize = stridx;
   2703   unsigned int mapsize = stringsize + ranlibsize;
   2704   file_ptr archive_member_file_ptr;
   2705   file_ptr first_archive_member_file_ptr;
   2706   bfd *current = arch->archive_head;
   2707   unsigned int count;
   2708   struct ar_hdr hdr;
   2709   int padit = mapsize & 1;
   2710 
   2711   if (padit)
   2712     mapsize++;
   2713 
   2714   /* Work out where the first object file will go in the archive.  */
   2715   first_archive_member_file_ptr = (mapsize
   2716 				   + elength
   2717 				   + sizeof (struct ar_hdr)
   2718 				   + SARMAG);
   2719 
   2720 #ifdef BFD64
   2721   current = arch->archive_head;
   2722   count = 0;
   2723   archive_member_file_ptr = first_archive_member_file_ptr;
   2724   while (current != NULL && count < symbol_count)
   2725     {
   2726       /* For each symbol which is used defined in this object, write
   2727 	 out the object file's address in the archive.  */
   2728 
   2729       while (count < symbol_count && map[count].u.abfd == current)
   2730 	{
   2731 	  unsigned int offset = (unsigned int) archive_member_file_ptr;
   2732 
   2733 	  /* Generate 64-bit archive if an archive is past its 4Gb
   2734 	     limit.  */
   2735 	  if (archive_member_file_ptr != (file_ptr) offset)
   2736 	    return _bfd_archive_64_bit_write_armap (arch, elength, map,
   2737 						    symbol_count, stridx);
   2738 	  count++;
   2739 	}
   2740       archive_member_file_ptr += sizeof (struct ar_hdr);
   2741       if (! bfd_is_thin_archive (arch))
   2742 	{
   2743 	  /* Add size of this archive entry.  */
   2744 	  archive_member_file_ptr += arelt_size (current);
   2745 	  /* Remember about the even alignment.  */
   2746 	  archive_member_file_ptr += archive_member_file_ptr % 2;
   2747 	}
   2748       current = current->archive_next;
   2749     }
   2750 #endif
   2751 
   2752   memset (&hdr, ' ', sizeof (struct ar_hdr));
   2753   hdr.ar_name[0] = '/';
   2754   if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
   2755     return FALSE;
   2756   _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
   2757 		    ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0
   2758 		     ? time (NULL) : 0));
   2759   /* This, at least, is what Intel coff sets the values to.  */
   2760   _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", 0);
   2761   _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", 0);
   2762   _bfd_ar_spacepad (hdr.ar_mode, sizeof (hdr.ar_mode), "%-7lo", 0);
   2763   memcpy (hdr.ar_fmag, ARFMAG, 2);
   2764 
   2765   /* Write the ar header for this item and the number of symbols.  */
   2766   if (bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
   2767       != sizeof (struct ar_hdr))
   2768     return FALSE;
   2769 
   2770   if (!bfd_write_bigendian_4byte_int (arch, symbol_count))
   2771     return FALSE;
   2772 
   2773   /* Two passes, first write the file offsets for each symbol -
   2774      remembering that each offset is on a two byte boundary.  */
   2775 
   2776   /* Write out the file offset for the file associated with each
   2777      symbol, and remember to keep the offsets padded out.  */
   2778 
   2779   current = arch->archive_head;
   2780   count = 0;
   2781   archive_member_file_ptr = first_archive_member_file_ptr;
   2782   while (current != NULL && count < symbol_count)
   2783     {
   2784       /* For each symbol which is used defined in this object, write
   2785 	 out the object file's address in the archive.  */
   2786 
   2787       while (count < symbol_count && map[count].u.abfd == current)
   2788 	{
   2789 	  unsigned int offset = (unsigned int) archive_member_file_ptr;
   2790 
   2791 	  /* Catch an attempt to grow an archive past its 4Gb limit.  */
   2792 	  if (archive_member_file_ptr != (file_ptr) offset)
   2793 	    {
   2794 	      bfd_set_error (bfd_error_file_truncated);
   2795 	      return FALSE;
   2796 	    }
   2797 	  if (!bfd_write_bigendian_4byte_int (arch, offset))
   2798 	    return FALSE;
   2799 	  count++;
   2800 	}
   2801       archive_member_file_ptr += sizeof (struct ar_hdr);
   2802       if (! bfd_is_thin_archive (arch))
   2803 	{
   2804 	  /* Add size of this archive entry.  */
   2805 	  archive_member_file_ptr += arelt_size (current);
   2806 	  /* Remember about the even alignment.  */
   2807 	  archive_member_file_ptr += archive_member_file_ptr % 2;
   2808 	}
   2809       current = current->archive_next;
   2810     }
   2811 
   2812   /* Now write the strings themselves.  */
   2813   for (count = 0; count < symbol_count; count++)
   2814     {
   2815       size_t len = strlen (*map[count].name) + 1;
   2816 
   2817       if (bfd_bwrite (*map[count].name, len, arch) != len)
   2818 	return FALSE;
   2819     }
   2820 
   2821   /* The spec sez this should be a newline.  But in order to be
   2822      bug-compatible for arc960 we use a null.  */
   2823   if (padit)
   2824     {
   2825       if (bfd_bwrite ("", 1, arch) != 1)
   2826 	return FALSE;
   2827     }
   2828 
   2829   return TRUE;
   2830 }
   2831 
   2832 static int
   2833 archive_close_worker (void **slot, void *inf ATTRIBUTE_UNUSED)
   2834 {
   2835   struct ar_cache *ent = (struct ar_cache *) *slot;
   2836 
   2837   bfd_close_all_done (ent->arbfd);
   2838   return 1;
   2839 }
   2840 
   2841 bfd_boolean
   2842 _bfd_archive_close_and_cleanup (bfd *abfd)
   2843 {
   2844   if (bfd_read_p (abfd) && abfd->format == bfd_archive)
   2845     {
   2846       bfd *nbfd;
   2847       bfd *next;
   2848       htab_t htab;
   2849 
   2850       /* Close nested archives (if this bfd is a thin archive).  */
   2851       for (nbfd = abfd->nested_archives; nbfd; nbfd = next)
   2852 	{
   2853 	  next = nbfd->archive_next;
   2854 	  bfd_close (nbfd);
   2855 	}
   2856 
   2857       htab = bfd_ardata (abfd)->cache;
   2858       if (htab)
   2859 	{
   2860 	  htab_traverse_noresize (htab, archive_close_worker, NULL);
   2861 	  htab_delete (htab);
   2862 	  bfd_ardata (abfd)->cache = NULL;
   2863 	}
   2864     }
   2865   if (arch_eltdata (abfd) != NULL)
   2866     {
   2867       struct areltdata *ared = arch_eltdata (abfd);
   2868       htab_t htab = (htab_t) ared->parent_cache;
   2869 
   2870       if (htab)
   2871 	{
   2872 	  struct ar_cache ent;
   2873 	  void **slot;
   2874 
   2875 	  ent.ptr = ared->key;
   2876 	  slot = htab_find_slot (htab, &ent, NO_INSERT);
   2877 	  if (slot != NULL)
   2878 	    {
   2879 	      BFD_ASSERT (((struct ar_cache *) *slot)->arbfd == abfd);
   2880 	      htab_clear_slot (htab, slot);
   2881 	    }
   2882 	}
   2883     }
   2884   if (abfd->is_linker_output)
   2885     (*abfd->link.hash->hash_table_free) (abfd);
   2886 
   2887   return TRUE;
   2888 }
   2889