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