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