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