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