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