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