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