2012-01-10 Tristan Gingold <gingold@adacore.com>
[external/binutils.git] / 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   n_nfd = _bfd_look_for_bfd_in_cache (archive, filepos);
585   if (n_nfd)
586     return n_nfd;
587
588   if (0 > bfd_seek (archive, filepos, SEEK_SET))
589     return NULL;
590
591   if ((new_areldata = (struct areltdata *) _bfd_read_ar_hdr (archive)) == NULL)
592     return NULL;
593
594   filename = new_areldata->filename;
595
596   if (bfd_is_thin_archive (archive))
597     {
598       const char *target;
599
600       /* This is a proxy entry for an external file.  */
601       if (! IS_ABSOLUTE_PATH (filename))
602         {
603           filename = _bfd_append_relative_path (archive, filename);
604           if (filename == NULL)
605             return NULL;
606         }
607
608       if (new_areldata->origin > 0)
609         {
610           /* This proxy entry refers to an element of a nested archive.
611              Locate the member of that archive and return a bfd for it.  */
612           bfd *ext_arch = _bfd_find_nested_archive (archive, filename);
613
614           if (ext_arch == NULL
615               || ! bfd_check_format (ext_arch, bfd_archive))
616             {
617               bfd_release (archive, new_areldata);
618               return NULL;
619             }
620           n_nfd = _bfd_get_elt_at_filepos (ext_arch, new_areldata->origin);
621           if (n_nfd == NULL)
622             {
623               bfd_release (archive, new_areldata);
624               return NULL;
625             }
626           n_nfd->proxy_origin = bfd_tell (archive);
627           return n_nfd;
628         }
629       /* It's not an element of a nested archive;
630          open the external file as a bfd.  */
631       target = NULL;
632       if (!archive->target_defaulted)
633         target = archive->xvec->name;
634       n_nfd = bfd_openr (filename, target);
635       if (n_nfd == NULL)
636         bfd_set_error (bfd_error_malformed_archive);
637     }
638   else
639     {
640       n_nfd = _bfd_create_empty_archive_element_shell (archive);
641     }
642
643   if (n_nfd == NULL)
644     {
645       bfd_release (archive, new_areldata);
646       return NULL;
647     }
648
649   n_nfd->proxy_origin = bfd_tell (archive);
650
651   if (bfd_is_thin_archive (archive))
652     {
653       n_nfd->origin = 0;
654     }
655   else
656     {
657       n_nfd->origin = n_nfd->proxy_origin;
658       n_nfd->filename = filename;
659     }
660
661   n_nfd->arelt_data = new_areldata;
662
663   /* Copy BFD_COMPRESS and BFD_DECOMPRESS flags.  */
664   n_nfd->flags |= archive->flags & (BFD_COMPRESS | BFD_DECOMPRESS);
665
666   if (_bfd_add_bfd_to_archive_cache (archive, filepos, n_nfd))
667     return n_nfd;
668
669   bfd_release (archive, new_areldata);
670   return NULL;
671 }
672
673 /* Return the BFD which is referenced by the symbol in ABFD indexed by
674    SYM_INDEX.  SYM_INDEX should have been returned by bfd_get_next_mapent.  */
675
676 bfd *
677 _bfd_generic_get_elt_at_index (bfd *abfd, symindex sym_index)
678 {
679   carsym *entry;
680
681   entry = bfd_ardata (abfd)->symdefs + sym_index;
682   return _bfd_get_elt_at_filepos (abfd, entry->file_offset);
683 }
684
685 /*
686 FUNCTION
687         bfd_openr_next_archived_file
688
689 SYNOPSIS
690         bfd *bfd_openr_next_archived_file (bfd *archive, bfd *previous);
691
692 DESCRIPTION
693         Provided a BFD, @var{archive}, containing an archive and NULL, open
694         an input BFD on the first contained element and returns that.
695         Subsequent calls should pass
696         the archive and the previous return value to return a created
697         BFD to the next contained element. NULL is returned when there
698         are no more.
699 */
700
701 bfd *
702 bfd_openr_next_archived_file (bfd *archive, bfd *last_file)
703 {
704   if ((bfd_get_format (archive) != bfd_archive)
705       || (archive->direction == write_direction))
706     {
707       bfd_set_error (bfd_error_invalid_operation);
708       return NULL;
709     }
710
711   return BFD_SEND (archive,
712                    openr_next_archived_file, (archive, last_file));
713 }
714
715 bfd *
716 bfd_generic_openr_next_archived_file (bfd *archive, bfd *last_file)
717 {
718   file_ptr filestart;
719
720   if (!last_file)
721     filestart = bfd_ardata (archive)->first_file_filepos;
722   else
723     {
724       unsigned int size = arelt_size (last_file);
725
726       filestart = last_file->proxy_origin;
727       if (! bfd_is_thin_archive (archive))
728         filestart += size;
729       /* Pad to an even boundary...
730          Note that last_file->origin can be odd in the case of
731          BSD-4.4-style element with a long odd size.  */
732       filestart += filestart % 2;
733     }
734
735   return _bfd_get_elt_at_filepos (archive, filestart);
736 }
737
738 const bfd_target *
739 bfd_generic_archive_p (bfd *abfd)
740 {
741   struct artdata *tdata_hold;
742   char armag[SARMAG + 1];
743   bfd_size_type amt;
744
745   if (bfd_bread (armag, SARMAG, abfd) != SARMAG)
746     {
747       if (bfd_get_error () != bfd_error_system_call)
748         bfd_set_error (bfd_error_wrong_format);
749       return NULL;
750     }
751
752   bfd_is_thin_archive (abfd) = (strncmp (armag, ARMAGT, SARMAG) == 0);
753
754   if (strncmp (armag, ARMAG, SARMAG) != 0
755       && strncmp (armag, ARMAGB, SARMAG) != 0
756       && ! bfd_is_thin_archive (abfd))
757     return NULL;
758
759   tdata_hold = bfd_ardata (abfd);
760
761   amt = sizeof (struct artdata);
762   bfd_ardata (abfd) = (struct artdata *) bfd_zalloc (abfd, amt);
763   if (bfd_ardata (abfd) == NULL)
764     {
765       bfd_ardata (abfd) = tdata_hold;
766       return NULL;
767     }
768
769   bfd_ardata (abfd)->first_file_filepos = SARMAG;
770   /* Cleared by bfd_zalloc above.
771      bfd_ardata (abfd)->cache = NULL;
772      bfd_ardata (abfd)->archive_head = NULL;
773      bfd_ardata (abfd)->symdefs = NULL;
774      bfd_ardata (abfd)->extended_names = NULL;
775      bfd_ardata (abfd)->extended_names_size = 0;
776      bfd_ardata (abfd)->tdata = NULL;  */
777
778   if (!BFD_SEND (abfd, _bfd_slurp_armap, (abfd))
779       || !BFD_SEND (abfd, _bfd_slurp_extended_name_table, (abfd)))
780     {
781       if (bfd_get_error () != bfd_error_system_call)
782         bfd_set_error (bfd_error_wrong_format);
783       bfd_release (abfd, bfd_ardata (abfd));
784       bfd_ardata (abfd) = tdata_hold;
785       return NULL;
786     }
787
788   if (abfd->target_defaulted && bfd_has_map (abfd))
789     {
790       bfd *first;
791
792       /* This archive has a map, so we may presume that the contents
793          are object files.  Make sure that if the first file in the
794          archive can be recognized as an object file, it is for this
795          target.  If not, assume that this is the wrong format.  If
796          the first file is not an object file, somebody is doing
797          something weird, and we permit it so that ar -t will work.
798
799          This is done because any normal format will recognize any
800          normal archive, regardless of the format of the object files.
801          We do accept an empty archive.  */
802
803       first = bfd_openr_next_archived_file (abfd, NULL);
804       if (first != NULL)
805         {
806           first->target_defaulted = FALSE;
807           if (bfd_check_format (first, bfd_object)
808               && first->xvec != abfd->xvec)
809             {
810               bfd_set_error (bfd_error_wrong_object_format);
811               bfd_ardata (abfd) = tdata_hold;
812               return NULL;
813             }
814           /* And we ought to close `first' here too.  */
815         }
816     }
817
818   return abfd->xvec;
819 }
820
821 /* Some constants for a 32 bit BSD archive structure.  We do not
822    support 64 bit archives presently; so far as I know, none actually
823    exist.  Supporting them would require changing these constants, and
824    changing some H_GET_32 to H_GET_64.  */
825
826 /* The size of an external symdef structure.  */
827 #define BSD_SYMDEF_SIZE 8
828
829 /* The offset from the start of a symdef structure to the file offset.  */
830 #define BSD_SYMDEF_OFFSET_SIZE 4
831
832 /* The size of the symdef count.  */
833 #define BSD_SYMDEF_COUNT_SIZE 4
834
835 /* The size of the string count.  */
836 #define BSD_STRING_COUNT_SIZE 4
837
838 /* Read a BSD-style archive symbol table.  Returns FALSE on error,
839    TRUE otherwise.  */
840
841 static bfd_boolean
842 do_slurp_bsd_armap (bfd *abfd)
843 {
844   struct areltdata *mapdata;
845   unsigned int counter;
846   bfd_byte *raw_armap, *rbase;
847   struct artdata *ardata = bfd_ardata (abfd);
848   char *stringbase;
849   bfd_size_type parsed_size, amt;
850   carsym *set;
851
852   mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
853   if (mapdata == NULL)
854     return FALSE;
855   parsed_size = mapdata->parsed_size;
856   bfd_release (abfd, mapdata);  /* Don't need it any more.  */
857
858   raw_armap = (bfd_byte *) bfd_zalloc (abfd, parsed_size);
859   if (raw_armap == NULL)
860     return FALSE;
861
862   if (bfd_bread (raw_armap, parsed_size, abfd) != parsed_size)
863     {
864       if (bfd_get_error () != bfd_error_system_call)
865         bfd_set_error (bfd_error_malformed_archive);
866     byebye:
867       bfd_release (abfd, raw_armap);
868       return FALSE;
869     }
870
871   ardata->symdef_count = H_GET_32 (abfd, raw_armap) / BSD_SYMDEF_SIZE;
872
873   if (ardata->symdef_count * BSD_SYMDEF_SIZE >
874       parsed_size - BSD_SYMDEF_COUNT_SIZE)
875     {
876       /* Probably we're using the wrong byte ordering.  */
877       bfd_set_error (bfd_error_wrong_format);
878       goto byebye;
879     }
880
881   ardata->cache = 0;
882   rbase = raw_armap + BSD_SYMDEF_COUNT_SIZE;
883   stringbase = ((char *) rbase
884                 + ardata->symdef_count * BSD_SYMDEF_SIZE
885                 + BSD_STRING_COUNT_SIZE);
886   amt = ardata->symdef_count * sizeof (carsym);
887   ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
888   if (!ardata->symdefs)
889     return FALSE;
890
891   for (counter = 0, set = ardata->symdefs;
892        counter < ardata->symdef_count;
893        counter++, set++, rbase += BSD_SYMDEF_SIZE)
894     {
895       set->name = H_GET_32 (abfd, rbase) + stringbase;
896       set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
897     }
898
899   ardata->first_file_filepos = bfd_tell (abfd);
900   /* Pad to an even boundary if you have to.  */
901   ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
902   /* FIXME, we should provide some way to free raw_ardata when
903      we are done using the strings from it.  For now, it seems
904      to be allocated on an objalloc anyway...  */
905   bfd_has_map (abfd) = TRUE;
906   return TRUE;
907 }
908
909 /* Read a COFF archive symbol table.  Returns FALSE on error, TRUE
910    otherwise.  */
911
912 static bfd_boolean
913 do_slurp_coff_armap (bfd *abfd)
914 {
915   struct areltdata *mapdata;
916   int *raw_armap, *rawptr;
917   struct artdata *ardata = bfd_ardata (abfd);
918   char *stringbase;
919   bfd_size_type stringsize;
920   unsigned int parsed_size;
921   carsym *carsyms;
922   bfd_size_type nsymz;          /* Number of symbols in armap.  */
923   bfd_vma (*swap) (const void *);
924   char int_buf[sizeof (long)];
925   bfd_size_type carsym_size, ptrsize;
926   unsigned int i;
927
928   mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
929   if (mapdata == NULL)
930     return FALSE;
931   parsed_size = mapdata->parsed_size;
932   bfd_release (abfd, mapdata);  /* Don't need it any more.  */
933
934   if (bfd_bread (int_buf, 4, abfd) != 4)
935     {
936       if (bfd_get_error () != bfd_error_system_call)
937         bfd_set_error (bfd_error_malformed_archive);
938       return FALSE;
939     }
940   /* It seems that all numeric information in a coff archive is always
941      in big endian format, nomatter the host or target.  */
942   swap = bfd_getb32;
943   nsymz = bfd_getb32 (int_buf);
944   stringsize = parsed_size - (4 * nsymz) - 4;
945
946   /* ... except that some archive formats are broken, and it may be our
947      fault - the i960 little endian coff sometimes has big and sometimes
948      little, because our tools changed.  Here's a horrible hack to clean
949      up the crap.  */
950
951   if (stringsize > 0xfffff
952       && bfd_get_arch (abfd) == bfd_arch_i960
953       && bfd_get_flavour (abfd) == bfd_target_coff_flavour)
954     {
955       /* This looks dangerous, let's do it the other way around.  */
956       nsymz = bfd_getl32 (int_buf);
957       stringsize = parsed_size - (4 * nsymz) - 4;
958       swap = bfd_getl32;
959     }
960
961   /* The coff armap must be read sequentially.  So we construct a
962      bsd-style one in core all at once, for simplicity.  */
963
964   if (nsymz > ~ (bfd_size_type) 0 / sizeof (carsym))
965     return FALSE;
966
967   carsym_size = (nsymz * sizeof (carsym));
968   ptrsize = (4 * nsymz);
969
970   if (carsym_size + stringsize + 1 <= carsym_size)
971     return FALSE;
972
973   ardata->symdefs = (struct carsym *) bfd_zalloc (abfd,
974                                                   carsym_size + stringsize + 1);
975   if (ardata->symdefs == NULL)
976     return FALSE;
977   carsyms = ardata->symdefs;
978   stringbase = ((char *) ardata->symdefs) + carsym_size;
979
980   /* Allocate and read in the raw offsets.  */
981   raw_armap = (int *) bfd_alloc (abfd, ptrsize);
982   if (raw_armap == NULL)
983     goto release_symdefs;
984   if (bfd_bread (raw_armap, ptrsize, abfd) != ptrsize
985       || (bfd_bread (stringbase, stringsize, abfd) != stringsize))
986     {
987       if (bfd_get_error () != bfd_error_system_call)
988         bfd_set_error (bfd_error_malformed_archive);
989       goto release_raw_armap;
990     }
991
992   /* OK, build the carsyms.  */
993   for (i = 0; i < nsymz; i++)
994     {
995       rawptr = raw_armap + i;
996       carsyms->file_offset = swap ((bfd_byte *) rawptr);
997       carsyms->name = stringbase;
998       stringbase += strlen (stringbase) + 1;
999       carsyms++;
1000     }
1001   *stringbase = 0;
1002
1003   ardata->symdef_count = nsymz;
1004   ardata->first_file_filepos = bfd_tell (abfd);
1005   /* Pad to an even boundary if you have to.  */
1006   ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1007
1008   bfd_has_map (abfd) = TRUE;
1009   bfd_release (abfd, raw_armap);
1010
1011   /* Check for a second archive header (as used by PE).  */
1012   {
1013     struct areltdata *tmp;
1014
1015     bfd_seek (abfd, ardata->first_file_filepos, SEEK_SET);
1016     tmp = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1017     if (tmp != NULL)
1018       {
1019         if (tmp->arch_header[0] == '/'
1020             && tmp->arch_header[1] == ' ')
1021           {
1022             ardata->first_file_filepos +=
1023               (tmp->parsed_size + sizeof (struct ar_hdr) + 1) & ~(unsigned) 1;
1024           }
1025         bfd_release (abfd, tmp);
1026       }
1027   }
1028
1029   return TRUE;
1030
1031 release_raw_armap:
1032   bfd_release (abfd, raw_armap);
1033 release_symdefs:
1034   bfd_release (abfd, (ardata)->symdefs);
1035   return FALSE;
1036 }
1037
1038 /* This routine can handle either coff-style or bsd-style armaps
1039    (archive symbol table).  Returns FALSE on error, TRUE otherwise */
1040
1041 bfd_boolean
1042 bfd_slurp_armap (bfd *abfd)
1043 {
1044   char nextname[17];
1045   int i = bfd_bread (nextname, 16, abfd);
1046
1047   if (i == 0)
1048     return TRUE;
1049   if (i != 16)
1050     return FALSE;
1051
1052   if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
1053     return FALSE;
1054
1055   if (CONST_STRNEQ (nextname, "__.SYMDEF       ")
1056       || CONST_STRNEQ (nextname, "__.SYMDEF/      ")) /* Old Linux archives.  */
1057     return do_slurp_bsd_armap (abfd);
1058   else if (CONST_STRNEQ (nextname, "/               "))
1059     return do_slurp_coff_armap (abfd);
1060   else if (CONST_STRNEQ (nextname, "/SYM64/         "))
1061     {
1062       /* 64bit ELF (Irix 6) archive.  */
1063 #ifdef BFD64
1064       extern bfd_boolean bfd_elf64_archive_slurp_armap (bfd *);
1065       return bfd_elf64_archive_slurp_armap (abfd);
1066 #else
1067       bfd_set_error (bfd_error_wrong_format);
1068       return FALSE;
1069 #endif
1070     }
1071   else if (CONST_STRNEQ (nextname, "#1/20           "))
1072     {
1073       /* Mach-O has a special name for armap when the map is sorted by name.
1074          However because this name has a space it is slightly more difficult
1075          to check it.  */
1076       struct ar_hdr hdr;
1077       char extname[21];
1078
1079       if (bfd_bread (&hdr, sizeof (hdr), abfd) != sizeof (hdr))
1080         return FALSE;
1081       /* Read the extended name.  We know its length.  */
1082       if (bfd_bread (extname, 20, abfd) != 20)
1083         return FALSE;
1084       if (bfd_seek (abfd, (file_ptr) -(sizeof (hdr) + 20), SEEK_CUR) != 0)
1085         return FALSE;
1086       if (CONST_STRNEQ (extname, "__.SYMDEF SORTED")
1087           || CONST_STRNEQ (extname, "__.SYMDEF"))
1088         return do_slurp_bsd_armap (abfd);
1089     }
1090
1091   bfd_has_map (abfd) = FALSE;
1092   return TRUE;
1093 }
1094 \f
1095 /* Returns FALSE on error, TRUE otherwise.  */
1096 /* Flavor 2 of a bsd armap, similar to bfd_slurp_bsd_armap except the
1097    header is in a slightly different order and the map name is '/'.
1098    This flavour is used by hp300hpux.  */
1099
1100 #define HPUX_SYMDEF_COUNT_SIZE 2
1101
1102 bfd_boolean
1103 bfd_slurp_bsd_armap_f2 (bfd *abfd)
1104 {
1105   struct areltdata *mapdata;
1106   char nextname[17];
1107   unsigned int counter;
1108   bfd_byte *raw_armap, *rbase;
1109   struct artdata *ardata = bfd_ardata (abfd);
1110   char *stringbase;
1111   unsigned int stringsize;
1112   unsigned int left;
1113   bfd_size_type amt;
1114   carsym *set;
1115   int i = bfd_bread (nextname, 16, abfd);
1116
1117   if (i == 0)
1118     return TRUE;
1119   if (i != 16)
1120     return FALSE;
1121
1122   /* The archive has at least 16 bytes in it.  */
1123   if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
1124     return FALSE;
1125
1126   if (CONST_STRNEQ (nextname, "__.SYMDEF       ")
1127       || CONST_STRNEQ (nextname, "__.SYMDEF/      ")) /* Old Linux archives.  */
1128     return do_slurp_bsd_armap (abfd);
1129
1130   if (! CONST_STRNEQ (nextname, "/               "))
1131     {
1132       bfd_has_map (abfd) = FALSE;
1133       return TRUE;
1134     }
1135
1136   mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1137   if (mapdata == NULL)
1138     return FALSE;
1139
1140   if (mapdata->parsed_size < HPUX_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE)
1141     {
1142     wrong_format:
1143       bfd_set_error (bfd_error_wrong_format);
1144     byebye:
1145       bfd_release (abfd, mapdata);
1146       return FALSE;
1147     }
1148   left = mapdata->parsed_size - HPUX_SYMDEF_COUNT_SIZE - BSD_STRING_COUNT_SIZE;
1149
1150   amt = mapdata->parsed_size;
1151   raw_armap = (bfd_byte *) bfd_zalloc (abfd, amt);
1152   if (raw_armap == NULL)
1153     goto byebye;
1154
1155   if (bfd_bread (raw_armap, amt, abfd) != amt)
1156     {
1157       if (bfd_get_error () != bfd_error_system_call)
1158         bfd_set_error (bfd_error_malformed_archive);
1159       goto byebye;
1160     }
1161
1162   ardata->symdef_count = H_GET_16 (abfd, raw_armap);
1163
1164   ardata->cache = 0;
1165
1166   stringsize = H_GET_32 (abfd, raw_armap + HPUX_SYMDEF_COUNT_SIZE);
1167   if (stringsize > left)
1168     goto wrong_format;
1169   left -= stringsize;
1170
1171   /* Skip sym count and string sz.  */
1172   stringbase = ((char *) raw_armap
1173                 + HPUX_SYMDEF_COUNT_SIZE
1174                 + BSD_STRING_COUNT_SIZE);
1175   rbase = (bfd_byte *) stringbase + stringsize;
1176   amt = ardata->symdef_count * BSD_SYMDEF_SIZE;
1177   if (amt > left)
1178     goto wrong_format;
1179
1180   ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
1181   if (!ardata->symdefs)
1182     return FALSE;
1183
1184   for (counter = 0, set = ardata->symdefs;
1185        counter < ardata->symdef_count;
1186        counter++, set++, rbase += BSD_SYMDEF_SIZE)
1187     {
1188       set->name = H_GET_32 (abfd, rbase) + stringbase;
1189       set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
1190     }
1191
1192   ardata->first_file_filepos = bfd_tell (abfd);
1193   /* Pad to an even boundary if you have to.  */
1194   ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1195   /* FIXME, we should provide some way to free raw_ardata when
1196      we are done using the strings from it.  For now, it seems
1197      to be allocated on an objalloc anyway...  */
1198   bfd_has_map (abfd) = TRUE;
1199   return TRUE;
1200 }
1201 \f
1202 /** Extended name table.
1203
1204   Normally archives support only 14-character filenames.
1205
1206   Intel has extended the format: longer names are stored in a special
1207   element (the first in the archive, or second if there is an armap);
1208   the name in the ar_hdr is replaced by <space><index into filename
1209   element>.  Index is the P.R. of an int (decimal).  Data General have
1210   extended the format by using the prefix // for the special element.  */
1211
1212 /* Returns FALSE on error, TRUE otherwise.  */
1213
1214 bfd_boolean
1215 _bfd_slurp_extended_name_table (bfd *abfd)
1216 {
1217   char nextname[17];
1218   struct areltdata *namedata;
1219   bfd_size_type amt;
1220
1221   /* FIXME:  Formatting sucks here, and in case of failure of BFD_READ,
1222      we probably don't want to return TRUE.  */
1223   if (bfd_seek (abfd, bfd_ardata (abfd)->first_file_filepos, SEEK_SET) != 0)
1224     return FALSE;
1225
1226   if (bfd_bread (nextname, 16, abfd) == 16)
1227     {
1228       if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
1229         return FALSE;
1230
1231       if (! CONST_STRNEQ (nextname, "ARFILENAMES/    ")
1232           && ! CONST_STRNEQ (nextname, "//              "))
1233         {
1234           bfd_ardata (abfd)->extended_names = NULL;
1235           bfd_ardata (abfd)->extended_names_size = 0;
1236           return TRUE;
1237         }
1238
1239       namedata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1240       if (namedata == NULL)
1241         return FALSE;
1242
1243       amt = namedata->parsed_size;
1244       if (amt + 1 == 0)
1245         goto byebye;
1246
1247       bfd_ardata (abfd)->extended_names_size = amt;
1248       bfd_ardata (abfd)->extended_names = (char *) bfd_zalloc (abfd, amt + 1);
1249       if (bfd_ardata (abfd)->extended_names == NULL)
1250         {
1251         byebye:
1252           bfd_release (abfd, namedata);
1253           return FALSE;
1254         }
1255
1256       if (bfd_bread (bfd_ardata (abfd)->extended_names, amt, abfd) != amt)
1257         {
1258           if (bfd_get_error () != bfd_error_system_call)
1259             bfd_set_error (bfd_error_malformed_archive);
1260           bfd_release (abfd, (bfd_ardata (abfd)->extended_names));
1261           bfd_ardata (abfd)->extended_names = NULL;
1262           goto byebye;
1263         }
1264
1265       /* Since the archive is supposed to be printable if it contains
1266          text, the entries in the list are newline-padded, not null
1267          padded. In SVR4-style archives, the names also have a
1268          trailing '/'.  DOS/NT created archive often have \ in them
1269          We'll fix all problems here..  */
1270       {
1271         char *ext_names = bfd_ardata (abfd)->extended_names;
1272         char *temp = ext_names;
1273         char *limit = temp + namedata->parsed_size;
1274         for (; temp < limit; ++temp)
1275           {
1276             if (*temp == ARFMAG[1])
1277               temp[temp > ext_names && temp[-1] == '/' ? -1 : 0] = '\0';
1278             if (*temp == '\\')
1279               *temp = '/';
1280           }
1281         *limit = '\0';
1282       }
1283
1284       /* Pad to an even boundary if you have to.  */
1285       bfd_ardata (abfd)->first_file_filepos = bfd_tell (abfd);
1286       bfd_ardata (abfd)->first_file_filepos +=
1287         (bfd_ardata (abfd)->first_file_filepos) % 2;
1288
1289       /* FIXME, we can't release namedata here because it was allocated
1290          below extended_names on the objalloc...  */
1291     }
1292   return TRUE;
1293 }
1294
1295 #ifdef VMS
1296
1297 /* Return a copy of the stuff in the filename between any :]> and a
1298    semicolon.  */
1299
1300 static const char *
1301 normalize (bfd *abfd, const char *file)
1302 {
1303   const char *first;
1304   const char *last;
1305   char *copy;
1306
1307   first = file + strlen (file) - 1;
1308   last = first + 1;
1309
1310   while (first != file)
1311     {
1312       if (*first == ';')
1313         last = first;
1314       if (*first == ':' || *first == ']' || *first == '>')
1315         {
1316           first++;
1317           break;
1318         }
1319       first--;
1320     }
1321
1322   copy = bfd_alloc (abfd, last - first + 1);
1323   if (copy == NULL)
1324     return NULL;
1325
1326   memcpy (copy, first, last - first);
1327   copy[last - first] = 0;
1328
1329   return copy;
1330 }
1331
1332 #else
1333 static const char *
1334 normalize (bfd *abfd ATTRIBUTE_UNUSED, const char *file)
1335 {
1336   return lbasename (file);
1337 }
1338 #endif
1339
1340 /* Adjust a relative path name based on the reference path.
1341    For example:
1342
1343      Relative path  Reference path  Result
1344      -------------  --------------  ------
1345      bar.o          lib.a           bar.o
1346      foo/bar.o      lib.a           foo/bar.o
1347      bar.o          foo/lib.a       ../bar.o
1348      foo/bar.o      baz/lib.a       ../foo/bar.o
1349      bar.o          ../lib.a        <parent of current dir>/bar.o
1350    ; ../bar.o       ../lib.a        bar.o
1351    ; ../bar.o       lib.a           ../bar.o
1352      foo/bar.o      ../lib.a        <parent of current dir>/foo/bar.o
1353      bar.o          ../../lib.a     <grandparent>/<parent>/bar.o
1354      bar.o          foo/baz/lib.a   ../../bar.o
1355
1356    Note - the semicolons above are there to prevent the BFD chew
1357    utility from interpreting those lines as prototypes to put into
1358    the autogenerated bfd.h header...
1359
1360    Note - the string is returned in a static buffer.  */
1361    
1362 static const char *
1363 adjust_relative_path (const char * path, const char * ref_path)
1364 {
1365   static char *pathbuf = NULL;
1366   static unsigned int pathbuf_len = 0;
1367   const char *pathp;
1368   const char *refp;
1369   char * lpath;
1370   char * rpath;
1371   unsigned int len;
1372   unsigned int dir_up = 0;
1373   unsigned int dir_down = 0;
1374   char *newp;
1375   char * pwd = getpwd ();
1376   const char * down;
1377
1378   /* Remove symlinks, '.' and '..' from the paths, if possible.  */
1379   lpath = lrealpath (path);
1380   pathp = lpath == NULL ? path : lpath;
1381
1382   rpath = lrealpath (ref_path);
1383   refp = rpath == NULL ? ref_path : rpath;
1384  
1385   /* Remove common leading path elements.  */
1386   for (;;)
1387     {
1388       const char *e1 = pathp;
1389       const char *e2 = refp;
1390
1391       while (*e1 && ! IS_DIR_SEPARATOR (*e1))
1392         ++e1;
1393       while (*e2 && ! IS_DIR_SEPARATOR (*e2))
1394         ++e2;
1395       if (*e1 == '\0' || *e2 == '\0' || e1 - pathp != e2 - refp
1396           || filename_ncmp (pathp, refp, e1 - pathp) != 0)
1397         break;
1398       pathp = e1 + 1;
1399       refp = e2 + 1;
1400     }
1401
1402   len = strlen (pathp) + 1;
1403   /* For each leading path element in the reference path,
1404      insert "../" into the path.  */
1405   for (; *refp; ++refp)
1406     if (IS_DIR_SEPARATOR (*refp))
1407       {
1408         /* PR 12710:  If the path element is "../" then instead of
1409            inserting "../" we need to insert the name of the directory
1410            at the current level.  */    
1411         if (refp > ref_path + 1
1412             && refp[-1] == '.'
1413             && refp[-2] == '.')
1414           dir_down ++;
1415         else
1416           dir_up ++;
1417       }
1418
1419   /* If the lrealpath calls above succeeded then we should never
1420      see dir_up and dir_down both being non-zero.  */
1421   
1422   len += 3 * dir_up;
1423
1424   if (dir_down)
1425     {
1426       down = pwd + strlen (pwd) - 1;
1427
1428       while (dir_down && down > pwd)
1429         {
1430           if (IS_DIR_SEPARATOR (*down))
1431             --dir_down;
1432         }
1433       BFD_ASSERT (dir_down == 0);
1434       len += strlen (down) + 1;
1435     }
1436   else
1437     down = NULL;
1438
1439   if (len > pathbuf_len)
1440     {
1441       if (pathbuf != NULL)
1442         free (pathbuf);
1443       pathbuf_len = 0;
1444       pathbuf = (char *) bfd_malloc (len);
1445       if (pathbuf == NULL)
1446         goto out;
1447       pathbuf_len = len;
1448     }
1449
1450   newp = pathbuf;
1451   while (dir_up-- > 0)
1452     {
1453       /* FIXME: Support Windows style path separators as well.  */
1454       strcpy (newp, "../");
1455       newp += 3;
1456     }
1457
1458   if (down)
1459     sprintf (newp, "%s/%s", down, pathp);
1460   else
1461     strcpy (newp, pathp);
1462
1463  out:
1464   free (lpath);
1465   free (rpath);
1466   return pathbuf;
1467 }
1468
1469 /* Build a BFD style extended name table.  */
1470
1471 bfd_boolean
1472 _bfd_archive_bsd_construct_extended_name_table (bfd *abfd,
1473                                                 char **tabloc,
1474                                                 bfd_size_type *tablen,
1475                                                 const char **name)
1476 {
1477   *name = "ARFILENAMES/";
1478   return _bfd_construct_extended_name_table (abfd, FALSE, tabloc, tablen);
1479 }
1480
1481 /* Build an SVR4 style extended name table.  */
1482
1483 bfd_boolean
1484 _bfd_archive_coff_construct_extended_name_table (bfd *abfd,
1485                                                  char **tabloc,
1486                                                  bfd_size_type *tablen,
1487                                                  const char **name)
1488 {
1489   *name = "//";
1490   return _bfd_construct_extended_name_table (abfd, TRUE, tabloc, tablen);
1491 }
1492
1493 /* Follows archive_head and produces an extended name table if
1494    necessary.  Returns (in tabloc) a pointer to an extended name
1495    table, and in tablen the length of the table.  If it makes an entry
1496    it clobbers the filename so that the element may be written without
1497    further massage.  Returns TRUE if it ran successfully, FALSE if
1498    something went wrong.  A successful return may still involve a
1499    zero-length tablen!  */
1500
1501 bfd_boolean
1502 _bfd_construct_extended_name_table (bfd *abfd,
1503                                     bfd_boolean trailing_slash,
1504                                     char **tabloc,
1505                                     bfd_size_type *tablen)
1506 {
1507   unsigned int maxname = ar_maxnamelen (abfd);
1508   bfd_size_type total_namelen = 0;
1509   bfd *current;
1510   char *strptr;
1511   const char *last_filename;
1512   long last_stroff;
1513
1514   *tablen = 0;
1515   last_filename = NULL;
1516
1517   /* Figure out how long the table should be.  */
1518   for (current = abfd->archive_head;
1519        current != NULL;
1520        current = current->archive_next)
1521     {
1522       const char *normal;
1523       unsigned int thislen;
1524
1525       if (bfd_is_thin_archive (abfd))
1526         {
1527           const char *filename = current->filename;
1528
1529           /* If the element being added is a member of another archive
1530              (i.e., we are flattening), use the containing archive's name.  */
1531           if (current->my_archive
1532               && ! bfd_is_thin_archive (current->my_archive))
1533             filename = current->my_archive->filename;
1534
1535           /* If the path is the same as the previous path seen,
1536              reuse it.  This can happen when flattening a thin
1537              archive that contains other archives.  */
1538           if (last_filename && filename_cmp (last_filename, filename) == 0)
1539             continue;
1540
1541           last_filename = filename;
1542
1543           /* If the path is relative, adjust it relative to
1544              the containing archive. */
1545           if (! IS_ABSOLUTE_PATH (filename)
1546               && ! IS_ABSOLUTE_PATH (abfd->filename))
1547             normal = adjust_relative_path (filename, abfd->filename);
1548           else
1549             normal = filename;
1550
1551           /* In a thin archive, always store the full pathname
1552              in the extended name table.  */
1553           total_namelen += strlen (normal) + 1;
1554           if (trailing_slash)
1555             /* Leave room for trailing slash.  */
1556             ++total_namelen;
1557
1558           continue;
1559         }
1560
1561       normal = normalize (current, current->filename);
1562       if (normal == NULL)
1563         return FALSE;
1564
1565       thislen = strlen (normal);
1566
1567       if (thislen > maxname
1568           && (bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
1569         thislen = maxname;
1570
1571       if (thislen > maxname)
1572         {
1573           /* Add one to leave room for \n.  */
1574           total_namelen += thislen + 1;
1575           if (trailing_slash)
1576             {
1577               /* Leave room for trailing slash.  */
1578               ++total_namelen;
1579             }
1580         }
1581       else
1582         {
1583           struct ar_hdr *hdr = arch_hdr (current);
1584           if (filename_ncmp (normal, hdr->ar_name, thislen) != 0
1585               || (thislen < sizeof hdr->ar_name
1586                   && hdr->ar_name[thislen] != ar_padchar (current)))
1587             {
1588               /* Must have been using extended format even though it
1589                  didn't need to.  Fix it to use normal format.  */
1590               memcpy (hdr->ar_name, normal, thislen);
1591               if (thislen < maxname
1592                   || (thislen == maxname && thislen < sizeof hdr->ar_name))
1593                 hdr->ar_name[thislen] = ar_padchar (current);
1594             }
1595         }
1596     }
1597
1598   if (total_namelen == 0)
1599     return TRUE;
1600
1601   *tabloc = (char *) bfd_zalloc (abfd, total_namelen);
1602   if (*tabloc == NULL)
1603     return FALSE;
1604
1605   *tablen = total_namelen;
1606   strptr = *tabloc;
1607
1608   last_filename = NULL;
1609   last_stroff = 0;
1610
1611   for (current = abfd->archive_head;
1612        current != NULL;
1613        current = current->archive_next)
1614     {
1615       const char *normal;
1616       unsigned int thislen;
1617       long stroff;
1618       const char *filename = current->filename;
1619
1620       if (bfd_is_thin_archive (abfd))
1621         {
1622           /* If the element being added is a member of another archive
1623              (i.e., we are flattening), use the containing archive's name.  */
1624           if (current->my_archive
1625               && ! bfd_is_thin_archive (current->my_archive))
1626             filename = current->my_archive->filename;
1627           /* If the path is the same as the previous path seen,
1628              reuse it.  This can happen when flattening a thin
1629              archive that contains other archives.
1630              If the path is relative, adjust it relative to
1631              the containing archive.  */
1632           if (last_filename && filename_cmp (last_filename, filename) == 0)
1633             normal = last_filename;
1634           else if (! IS_ABSOLUTE_PATH (filename)
1635                    && ! IS_ABSOLUTE_PATH (abfd->filename))
1636             normal = adjust_relative_path (filename, abfd->filename);
1637           else
1638             normal = filename;
1639         }
1640       else
1641         {
1642           normal = normalize (current, filename);
1643           if (normal == NULL)
1644             return FALSE;
1645         }
1646
1647       thislen = strlen (normal);
1648       if (thislen > maxname || bfd_is_thin_archive (abfd))
1649         {
1650           /* Works for now; may need to be re-engineered if we
1651              encounter an oddball archive format and want to
1652              generalise this hack.  */
1653           struct ar_hdr *hdr = arch_hdr (current);
1654           if (normal == last_filename)
1655             stroff = last_stroff;
1656           else
1657             {
1658               strcpy (strptr, normal);
1659               if (! trailing_slash)
1660                 strptr[thislen] = ARFMAG[1];
1661               else
1662                 {
1663                   strptr[thislen] = '/';
1664                   strptr[thislen + 1] = ARFMAG[1];
1665                 }
1666               stroff = strptr - *tabloc;
1667               last_stroff = stroff;
1668             }
1669           hdr->ar_name[0] = ar_padchar (current);
1670           if (bfd_is_thin_archive (abfd) && current->origin > 0)
1671             {
1672               int len = snprintf (hdr->ar_name + 1, maxname - 1, "%-ld:",
1673                                   stroff);
1674               _bfd_ar_spacepad (hdr->ar_name + 1 + len, maxname - 1 - len,
1675                                 "%-ld",
1676                                 current->origin - sizeof (struct ar_hdr));
1677             }
1678           else
1679             _bfd_ar_spacepad (hdr->ar_name + 1, maxname - 1, "%-ld", stroff);
1680           if (normal != last_filename)
1681             {
1682               strptr += thislen + 1;
1683               if (trailing_slash)
1684                 ++strptr;
1685               last_filename = filename;
1686             }
1687         }
1688     }
1689
1690   return TRUE;
1691 }
1692
1693 /* Do not construct an extended name table but transforms name field into
1694    its extended form.  */
1695
1696 bfd_boolean
1697 _bfd_archive_bsd44_construct_extended_name_table (bfd *abfd,
1698                                                   char **tabloc,
1699                                                   bfd_size_type *tablen,
1700                                                   const char **name)
1701 {
1702   unsigned int maxname = ar_maxnamelen (abfd);
1703   bfd *current;
1704
1705   *tablen = 0;
1706   *tabloc = NULL;
1707   *name = NULL;
1708
1709   for (current = abfd->archive_head;
1710        current != NULL;
1711        current = current->archive_next)
1712     {
1713       const char *normal = normalize (current, current->filename);
1714       int has_space = 0;
1715       unsigned int len;
1716
1717       if (normal == NULL)
1718         return FALSE;
1719
1720       for (len = 0; normal[len]; len++)
1721         if (normal[len] == ' ')
1722           has_space = 1;
1723
1724       if (len > maxname || has_space)
1725         {
1726           struct ar_hdr *hdr = arch_hdr (current);
1727
1728           len = (len + 3) & ~3;
1729           arch_eltdata (current)->extra_size = len;
1730           _bfd_ar_spacepad (hdr->ar_name, maxname, "#1/%lu", len);
1731         }
1732     }
1733
1734   return TRUE;
1735 }
1736 \f
1737 /* Write an archive header.  */
1738
1739 bfd_boolean
1740 _bfd_generic_write_ar_hdr (bfd *archive, bfd *abfd)
1741 {
1742   struct ar_hdr *hdr = arch_hdr (abfd);
1743
1744   if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1745     return FALSE;
1746   return TRUE;
1747 }
1748
1749 /* Write an archive header using BSD4.4 convention.  */
1750
1751 bfd_boolean
1752 _bfd_bsd44_write_ar_hdr (bfd *archive, bfd *abfd)
1753 {
1754   struct ar_hdr *hdr = arch_hdr (abfd);
1755
1756   if (is_bsd44_extended_name (hdr->ar_name))
1757     {
1758       /* This is a BSD 4.4 extended name.  */
1759       const char *fullname = normalize (abfd, abfd->filename);
1760       unsigned int len = strlen (fullname);
1761       unsigned int padded_len = (len + 3) & ~3;
1762
1763       BFD_ASSERT (padded_len == arch_eltdata (abfd)->extra_size);
1764
1765       _bfd_ar_spacepad (hdr->ar_size, sizeof (hdr->ar_size), "%-10ld",
1766                         arch_eltdata (abfd)->parsed_size + padded_len);
1767
1768       if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1769         return FALSE;
1770
1771       if (bfd_bwrite (fullname, len, archive) != len)
1772         return FALSE;
1773       if (len & 3)
1774         {
1775           static const char pad[3] = { 0, 0, 0 };
1776
1777           len = 4 - (len & 3);
1778           if (bfd_bwrite (pad, len, archive) != len)
1779             return FALSE;
1780         }
1781     }
1782   else
1783     {
1784       if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1785         return FALSE;
1786     }
1787   return TRUE;
1788 }
1789 \f
1790 /* A couple of functions for creating ar_hdrs.  */
1791
1792 #ifdef HPUX_LARGE_AR_IDS
1793 /* Function to encode large UID/GID values according to HP.  */
1794
1795 static void
1796 hpux_uid_gid_encode (char str[6], long int id)
1797 {
1798   int cnt;
1799
1800   str[5] = '@' + (id & 3);
1801   id >>= 2;
1802
1803   for (cnt = 4; cnt >= 0; --cnt, id >>= 6)
1804     str[cnt] = ' ' + (id & 0x3f);
1805 }
1806 #endif  /* HPUX_LARGE_AR_IDS */
1807
1808 #ifndef HAVE_GETUID
1809 #define getuid() 0
1810 #endif
1811
1812 #ifndef HAVE_GETGID
1813 #define getgid() 0
1814 #endif
1815
1816 /* Takes a filename, returns an arelt_data for it, or NULL if it can't
1817    make one.  The filename must refer to a filename in the filesystem.
1818    The filename field of the ar_hdr will NOT be initialized.  If member
1819    is set, and it's an in-memory bfd, we fake it.  */
1820
1821 static struct areltdata *
1822 bfd_ar_hdr_from_filesystem (bfd *abfd, const char *filename, bfd *member)
1823 {
1824   struct stat status;
1825   struct areltdata *ared;
1826   struct ar_hdr *hdr;
1827   bfd_size_type amt;
1828
1829   if (member && (member->flags & BFD_IN_MEMORY) != 0)
1830     {
1831       /* Assume we just "made" the member, and fake it.  */
1832       struct bfd_in_memory *bim = (struct bfd_in_memory *) member->iostream;
1833       time (&status.st_mtime);
1834       status.st_uid = getuid ();
1835       status.st_gid = getgid ();
1836       status.st_mode = 0644;
1837       status.st_size = bim->size;
1838     }
1839   else if (stat (filename, &status) != 0)
1840     {
1841       bfd_set_error (bfd_error_system_call);
1842       return NULL;
1843     }
1844
1845   /* If the caller requested that the BFD generate deterministic output,
1846      fake values for modification time, UID, GID, and file mode.  */
1847   if ((abfd->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
1848     {
1849       status.st_mtime = 0;
1850       status.st_uid = 0;
1851       status.st_gid = 0;
1852       status.st_mode = 0644;
1853     }
1854
1855   amt = sizeof (struct ar_hdr) + sizeof (struct areltdata);
1856   ared = (struct areltdata *) bfd_zalloc (abfd, amt);
1857   if (ared == NULL)
1858     return NULL;
1859   hdr = (struct ar_hdr *) (((char *) ared) + sizeof (struct areltdata));
1860
1861   /* ar headers are space padded, not null padded!  */
1862   memset (hdr, ' ', sizeof (struct ar_hdr));
1863
1864   _bfd_ar_spacepad (hdr->ar_date, sizeof (hdr->ar_date), "%-12ld",
1865                     status.st_mtime);
1866 #ifdef HPUX_LARGE_AR_IDS
1867   /* HP has a very "special" way to handle UID/GID's with numeric values
1868      > 99999.  */
1869   if (status.st_uid > 99999)
1870     hpux_uid_gid_encode (hdr->ar_uid, (long) status.st_uid);
1871   else
1872 #endif
1873     _bfd_ar_spacepad (hdr->ar_uid, sizeof (hdr->ar_uid), "%ld",
1874                       status.st_uid);
1875 #ifdef HPUX_LARGE_AR_IDS
1876   /* HP has a very "special" way to handle UID/GID's with numeric values
1877      > 99999.  */
1878   if (status.st_gid > 99999)
1879     hpux_uid_gid_encode (hdr->ar_gid, (long) status.st_gid);
1880   else
1881 #endif
1882     _bfd_ar_spacepad (hdr->ar_gid, sizeof (hdr->ar_gid), "%ld",
1883                       status.st_gid);
1884   _bfd_ar_spacepad (hdr->ar_mode, sizeof (hdr->ar_mode), "%-8lo",
1885                     status.st_mode);
1886   _bfd_ar_spacepad (hdr->ar_size, sizeof (hdr->ar_size), "%-10ld",
1887                     status.st_size);
1888   memcpy (hdr->ar_fmag, ARFMAG, 2);
1889   ared->parsed_size = status.st_size;
1890   ared->arch_header = (char *) hdr;
1891
1892   return ared;
1893 }
1894
1895 /* Analogous to stat call.  */
1896
1897 int
1898 bfd_generic_stat_arch_elt (bfd *abfd, struct stat *buf)
1899 {
1900   struct ar_hdr *hdr;
1901   char *aloser;
1902
1903   if (abfd->arelt_data == NULL)
1904     {
1905       bfd_set_error (bfd_error_invalid_operation);
1906       return -1;
1907     }
1908
1909   hdr = arch_hdr (abfd);
1910
1911 #define foo(arelt, stelt, size)                         \
1912   buf->stelt = strtol (hdr->arelt, &aloser, size);      \
1913   if (aloser == hdr->arelt)                             \
1914     return -1;
1915
1916   /* Some platforms support special notations for large IDs.  */
1917 #ifdef HPUX_LARGE_AR_IDS
1918 # define foo2(arelt, stelt, size)                                       \
1919   if (hdr->arelt[5] == ' ')                                             \
1920     {                                                                   \
1921       foo (arelt, stelt, size);                                         \
1922     }                                                                   \
1923   else                                                                  \
1924     {                                                                   \
1925       int cnt;                                                          \
1926       for (buf->stelt = cnt = 0; cnt < 5; ++cnt)                        \
1927         {                                                               \
1928           if (hdr->arelt[cnt] < ' ' || hdr->arelt[cnt] > ' ' + 0x3f)    \
1929             return -1;                                                  \
1930           buf->stelt <<= 6;                                             \
1931           buf->stelt += hdr->arelt[cnt] - ' ';                          \
1932         }                                                               \
1933       if (hdr->arelt[5] < '@' || hdr->arelt[5] > '@' + 3)               \
1934         return -1;                                                      \
1935       buf->stelt <<= 2;                                                 \
1936       buf->stelt += hdr->arelt[5] - '@';                                \
1937     }
1938 #else
1939 # define foo2(arelt, stelt, size) foo (arelt, stelt, size)
1940 #endif
1941
1942   foo (ar_date, st_mtime, 10);
1943   foo2 (ar_uid, st_uid, 10);
1944   foo2 (ar_gid, st_gid, 10);
1945   foo (ar_mode, st_mode, 8);
1946
1947   buf->st_size = arch_eltdata (abfd)->parsed_size;
1948
1949   return 0;
1950 }
1951
1952 void
1953 bfd_dont_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
1954 {
1955   /* FIXME: This interacts unpleasantly with ar's quick-append option.
1956      Fortunately ic960 users will never use that option.  Fixing this
1957      is very hard; fortunately I know how to do it and will do so once
1958      intel's release is out the door.  */
1959
1960   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
1961   size_t length;
1962   const char *filename;
1963   size_t maxlen = ar_maxnamelen (abfd);
1964
1965   if ((bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
1966     {
1967       bfd_bsd_truncate_arname (abfd, pathname, arhdr);
1968       return;
1969     }
1970
1971   filename = normalize (abfd, pathname);
1972   if (filename == NULL)
1973     {
1974       /* FIXME */
1975       abort ();
1976     }
1977
1978   length = strlen (filename);
1979
1980   if (length <= maxlen)
1981     memcpy (hdr->ar_name, filename, length);
1982
1983   /* Add the padding character if there is room for it.  */
1984   if (length < maxlen
1985       || (length == maxlen && length < sizeof hdr->ar_name))
1986     (hdr->ar_name)[length] = ar_padchar (abfd);
1987 }
1988
1989 void
1990 bfd_bsd_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
1991 {
1992   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
1993   size_t length;
1994   const char *filename = lbasename (pathname);
1995   size_t maxlen = ar_maxnamelen (abfd);
1996
1997   length = strlen (filename);
1998
1999   if (length <= maxlen)
2000     memcpy (hdr->ar_name, filename, length);
2001   else
2002     {
2003       /* pathname: meet procrustes */
2004       memcpy (hdr->ar_name, filename, maxlen);
2005       length = maxlen;
2006     }
2007
2008   if (length < maxlen)
2009     (hdr->ar_name)[length] = ar_padchar (abfd);
2010 }
2011
2012 /* Store name into ar header.  Truncates the name to fit.
2013    1> strip pathname to be just the basename.
2014    2> if it's short enuf to fit, stuff it in.
2015    3> If it doesn't end with .o, truncate it to fit
2016    4> truncate it before the .o, append .o, stuff THAT in.  */
2017
2018 /* This is what gnu ar does.  It's better but incompatible with the
2019    bsd ar.  */
2020
2021 void
2022 bfd_gnu_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2023 {
2024   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2025   size_t length;
2026   const char *filename = lbasename (pathname);
2027   size_t maxlen = ar_maxnamelen (abfd);
2028
2029   length = strlen (filename);
2030
2031   if (length <= maxlen)
2032     memcpy (hdr->ar_name, filename, length);
2033   else
2034     {
2035       /* pathname: meet procrustes.  */
2036       memcpy (hdr->ar_name, filename, maxlen);
2037       if ((filename[length - 2] == '.') && (filename[length - 1] == 'o'))
2038         {
2039           hdr->ar_name[maxlen - 2] = '.';
2040           hdr->ar_name[maxlen - 1] = 'o';
2041         }
2042       length = maxlen;
2043     }
2044
2045   if (length < 16)
2046     (hdr->ar_name)[length] = ar_padchar (abfd);
2047 }
2048 \f
2049 /* The BFD is open for write and has its format set to bfd_archive.  */
2050
2051 bfd_boolean
2052 _bfd_write_archive_contents (bfd *arch)
2053 {
2054   bfd *current;
2055   char *etable = NULL;
2056   bfd_size_type elength = 0;
2057   const char *ename = NULL;
2058   bfd_boolean makemap = bfd_has_map (arch);
2059   /* If no .o's, don't bother to make a map.  */
2060   bfd_boolean hasobjects = FALSE;
2061   bfd_size_type wrote;
2062   int tries;
2063   char *armag;
2064
2065   /* Verify the viability of all entries; if any of them live in the
2066      filesystem (as opposed to living in an archive open for input)
2067      then construct a fresh ar_hdr for them.  */
2068   for (current = arch->archive_head;
2069        current != NULL;
2070        current = current->archive_next)
2071     {
2072       /* This check is checking the bfds for the objects we're reading
2073          from (which are usually either an object file or archive on
2074          disk), not the archive entries we're writing to.  We don't
2075          actually create bfds for the archive members, we just copy
2076          them byte-wise when we write out the archive.  */
2077       if (bfd_write_p (current))
2078         {
2079           bfd_set_error (bfd_error_invalid_operation);
2080           goto input_err;
2081         }
2082       if (!current->arelt_data)
2083         {
2084           current->arelt_data =
2085             bfd_ar_hdr_from_filesystem (arch, current->filename, current);
2086           if (!current->arelt_data)
2087             goto input_err;
2088
2089           /* Put in the file name.  */
2090           BFD_SEND (arch, _bfd_truncate_arname,
2091                     (arch, current->filename, (char *) arch_hdr (current)));
2092         }
2093
2094       if (makemap && ! hasobjects)
2095         {                       /* Don't bother if we won't make a map!  */
2096           if ((bfd_check_format (current, bfd_object)))
2097             hasobjects = TRUE;
2098         }
2099     }
2100
2101   if (!BFD_SEND (arch, _bfd_construct_extended_name_table,
2102                  (arch, &etable, &elength, &ename)))
2103     return FALSE;
2104
2105   if (bfd_seek (arch, (file_ptr) 0, SEEK_SET) != 0)
2106     return FALSE;
2107   armag = ARMAG;
2108   if (bfd_is_thin_archive (arch))
2109     armag = ARMAGT;
2110   wrote = bfd_bwrite (armag, SARMAG, arch);
2111   if (wrote != SARMAG)
2112     return FALSE;
2113
2114   if (makemap && hasobjects)
2115     {
2116       if (! _bfd_compute_and_write_armap (arch, (unsigned int) elength))
2117         return FALSE;
2118     }
2119
2120   if (elength != 0)
2121     {
2122       struct ar_hdr hdr;
2123
2124       memset (&hdr, ' ', sizeof (struct ar_hdr));
2125       memcpy (hdr.ar_name, ename, strlen (ename));
2126       /* Round size up to even number in archive header.  */
2127       _bfd_ar_spacepad (hdr.ar_size, sizeof (hdr.ar_size), "%-10ld",
2128                         (elength + 1) & ~(bfd_size_type) 1);
2129       memcpy (hdr.ar_fmag, ARFMAG, 2);
2130       if ((bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
2131            != sizeof (struct ar_hdr))
2132           || bfd_bwrite (etable, elength, arch) != elength)
2133         return FALSE;
2134       if ((elength % 2) == 1)
2135         {
2136           if (bfd_bwrite (&ARFMAG[1], 1, arch) != 1)
2137             return FALSE;
2138         }
2139     }
2140
2141   for (current = arch->archive_head;
2142        current != NULL;
2143        current = current->archive_next)
2144     {
2145       char buffer[DEFAULT_BUFFERSIZE];
2146       unsigned int remaining = arelt_size (current);
2147
2148       /* Write ar header.  */
2149       if (!_bfd_write_ar_hdr (arch, current))
2150         return FALSE;
2151       if (bfd_is_thin_archive (arch))
2152         continue;
2153       if (bfd_seek (current, (file_ptr) 0, SEEK_SET) != 0)
2154         goto input_err;
2155
2156       while (remaining)
2157         {
2158           unsigned int amt = DEFAULT_BUFFERSIZE;
2159
2160           if (amt > remaining)
2161             amt = remaining;
2162           errno = 0;
2163           if (bfd_bread (buffer, amt, current) != amt)
2164             {
2165               if (bfd_get_error () != bfd_error_system_call)
2166                 bfd_set_error (bfd_error_file_truncated);
2167               goto input_err;
2168             }
2169           if (bfd_bwrite (buffer, amt, arch) != amt)
2170             return FALSE;
2171           remaining -= amt;
2172         }
2173
2174       if ((arelt_size (current) % 2) == 1)
2175         {
2176           if (bfd_bwrite (&ARFMAG[1], 1, arch) != 1)
2177             return FALSE;
2178         }
2179     }
2180
2181   if (makemap && hasobjects)
2182     {
2183       /* Verify the timestamp in the archive file.  If it would not be
2184          accepted by the linker, rewrite it until it would be.  If
2185          anything odd happens, break out and just return.  (The
2186          Berkeley linker checks the timestamp and refuses to read the
2187          table-of-contents if it is >60 seconds less than the file's
2188          modified-time.  That painful hack requires this painful hack.  */
2189       tries = 1;
2190       do
2191         {
2192           if (bfd_update_armap_timestamp (arch))
2193             break;
2194           (*_bfd_error_handler)
2195             (_("Warning: writing archive was slow: rewriting timestamp\n"));
2196         }
2197       while (++tries < 6);
2198     }
2199
2200   return TRUE;
2201
2202  input_err:
2203   bfd_set_error (bfd_error_on_input, current, bfd_get_error ());
2204   return FALSE;
2205 }
2206 \f
2207 /* Note that the namidx for the first symbol is 0.  */
2208
2209 bfd_boolean
2210 _bfd_compute_and_write_armap (bfd *arch, unsigned int elength)
2211 {
2212   char *first_name = NULL;
2213   bfd *current;
2214   file_ptr elt_no = 0;
2215   struct orl *map = NULL;
2216   unsigned int orl_max = 1024;          /* Fine initial default.  */
2217   unsigned int orl_count = 0;
2218   int stridx = 0;
2219   asymbol **syms = NULL;
2220   long syms_max = 0;
2221   bfd_boolean ret;
2222   bfd_size_type amt;
2223
2224   /* Dunno if this is the best place for this info...  */
2225   if (elength != 0)
2226     elength += sizeof (struct ar_hdr);
2227   elength += elength % 2;
2228
2229   amt = orl_max * sizeof (struct orl);
2230   map = (struct orl *) bfd_malloc (amt);
2231   if (map == NULL)
2232     goto error_return;
2233
2234   /* We put the symbol names on the arch objalloc, and then discard
2235      them when done.  */
2236   first_name = (char *) bfd_alloc (arch, 1);
2237   if (first_name == NULL)
2238     goto error_return;
2239
2240   /* Drop all the files called __.SYMDEF, we're going to make our own.  */
2241   while (arch->archive_head
2242          && strcmp (arch->archive_head->filename, "__.SYMDEF") == 0)
2243     arch->archive_head = arch->archive_head->archive_next;
2244
2245   /* Map over each element.  */
2246   for (current = arch->archive_head;
2247        current != NULL;
2248        current = current->archive_next, elt_no++)
2249     {
2250       if (bfd_check_format (current, bfd_object)
2251           && (bfd_get_file_flags (current) & HAS_SYMS) != 0)
2252         {
2253           long storage;
2254           long symcount;
2255           long src_count;
2256
2257           storage = bfd_get_symtab_upper_bound (current);
2258           if (storage < 0)
2259             goto error_return;
2260
2261           if (storage != 0)
2262             {
2263               if (storage > syms_max)
2264                 {
2265                   if (syms_max > 0)
2266                     free (syms);
2267                   syms_max = storage;
2268                   syms = (asymbol **) bfd_malloc (syms_max);
2269                   if (syms == NULL)
2270                     goto error_return;
2271                 }
2272               symcount = bfd_canonicalize_symtab (current, syms);
2273               if (symcount < 0)
2274                 goto error_return;
2275
2276               /* Now map over all the symbols, picking out the ones we
2277                  want.  */
2278               for (src_count = 0; src_count < symcount; src_count++)
2279                 {
2280                   flagword flags = (syms[src_count])->flags;
2281                   asection *sec = syms[src_count]->section;
2282
2283                   if ((flags & BSF_GLOBAL
2284                        || flags & BSF_WEAK
2285                        || flags & BSF_INDIRECT
2286                        || flags & BSF_GNU_UNIQUE
2287                        || bfd_is_com_section (sec))
2288                       && ! bfd_is_und_section (sec))
2289                     {
2290                       bfd_size_type namelen;
2291                       struct orl *new_map;
2292
2293                       /* This symbol will go into the archive header.  */
2294                       if (orl_count == orl_max)
2295                         {
2296                           orl_max *= 2;
2297                           amt = orl_max * sizeof (struct orl);
2298                           new_map = (struct orl *) bfd_realloc (map, amt);
2299                           if (new_map == NULL)
2300                             goto error_return;
2301
2302                           map = new_map;
2303                         }
2304
2305                       namelen = strlen (syms[src_count]->name);
2306                       amt = sizeof (char *);
2307                       map[orl_count].name = (char **) bfd_alloc (arch, amt);
2308                       if (map[orl_count].name == NULL)
2309                         goto error_return;
2310                       *(map[orl_count].name) = (char *) bfd_alloc (arch,
2311                                                                    namelen + 1);
2312                       if (*(map[orl_count].name) == NULL)
2313                         goto error_return;
2314                       strcpy (*(map[orl_count].name), syms[src_count]->name);
2315                       map[orl_count].u.abfd = current;
2316                       map[orl_count].namidx = stridx;
2317
2318                       stridx += namelen + 1;
2319                       ++orl_count;
2320                     }
2321                 }
2322             }
2323
2324           /* Now ask the BFD to free up any cached information, so we
2325              don't fill all of memory with symbol tables.  */
2326           if (! bfd_free_cached_info (current))
2327             goto error_return;
2328         }
2329     }
2330
2331   /* OK, now we have collected all the data, let's write them out.  */
2332   ret = BFD_SEND (arch, write_armap,
2333                   (arch, elength, map, orl_count, stridx));
2334
2335   if (syms_max > 0)
2336     free (syms);
2337   if (map != NULL)
2338     free (map);
2339   if (first_name != NULL)
2340     bfd_release (arch, first_name);
2341
2342   return ret;
2343
2344  error_return:
2345   if (syms_max > 0)
2346     free (syms);
2347   if (map != NULL)
2348     free (map);
2349   if (first_name != NULL)
2350     bfd_release (arch, first_name);
2351
2352   return FALSE;
2353 }
2354
2355 bfd_boolean
2356 bsd_write_armap (bfd *arch,
2357                  unsigned int elength,
2358                  struct orl *map,
2359                  unsigned int orl_count,
2360                  int stridx)
2361 {
2362   int padit = stridx & 1;
2363   unsigned int ranlibsize = orl_count * BSD_SYMDEF_SIZE;
2364   unsigned int stringsize = stridx + padit;
2365   /* Include 8 bytes to store ranlibsize and stringsize in output.  */
2366   unsigned int mapsize = ranlibsize + stringsize + 8;
2367   file_ptr firstreal;
2368   bfd *current = arch->archive_head;
2369   bfd *last_elt = current;      /* Last element arch seen.  */
2370   bfd_byte temp[4];
2371   unsigned int count;
2372   struct ar_hdr hdr;
2373   long uid, gid;
2374
2375   firstreal = mapsize + elength + sizeof (struct ar_hdr) + SARMAG;
2376
2377   /* If deterministic, we use 0 as the timestamp in the map.
2378      Some linkers may require that the archive filesystem modification
2379      time is less than (or near to) the archive map timestamp.  Those
2380      linkers should not be used with deterministic mode.  (GNU ld and
2381      Gold do not have this restriction.)  */
2382   bfd_ardata (arch)->armap_timestamp = 0;
2383   uid = 0;
2384   gid = 0;
2385   if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0)
2386     {
2387       struct stat statbuf;
2388
2389       if (stat (arch->filename, &statbuf) == 0)
2390         bfd_ardata (arch)->armap_timestamp = (statbuf.st_mtime
2391                                               + ARMAP_TIME_OFFSET);
2392       uid = getuid();
2393       gid = getgid();
2394     }
2395
2396   memset (&hdr, ' ', sizeof (struct ar_hdr));
2397   memcpy (hdr.ar_name, RANLIBMAG, strlen (RANLIBMAG));
2398   bfd_ardata (arch)->armap_datepos = (SARMAG
2399                                       + offsetof (struct ar_hdr, ar_date[0]));
2400   _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2401                     bfd_ardata (arch)->armap_timestamp);
2402   _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", uid);
2403   _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", gid);
2404   _bfd_ar_spacepad (hdr.ar_size, sizeof (hdr.ar_size), "%-10ld", mapsize);
2405   memcpy (hdr.ar_fmag, ARFMAG, 2);
2406   if (bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
2407       != sizeof (struct ar_hdr))
2408     return FALSE;
2409   H_PUT_32 (arch, ranlibsize, temp);
2410   if (bfd_bwrite (temp, sizeof (temp), arch) != sizeof (temp))
2411     return FALSE;
2412
2413   for (count = 0; count < orl_count; count++)
2414     {
2415       bfd_byte buf[BSD_SYMDEF_SIZE];
2416
2417       if (map[count].u.abfd != last_elt)
2418         {
2419           do
2420             {
2421               struct areltdata *ared = arch_eltdata (current);
2422
2423               firstreal += (ared->parsed_size + ared->extra_size
2424                             + sizeof (struct ar_hdr));
2425               firstreal += firstreal % 2;
2426               current = current->archive_next;
2427             }
2428           while (current != map[count].u.abfd);
2429         }
2430
2431       last_elt = current;
2432       H_PUT_32 (arch, map[count].namidx, buf);
2433       H_PUT_32 (arch, firstreal, buf + BSD_SYMDEF_OFFSET_SIZE);
2434       if (bfd_bwrite (buf, BSD_SYMDEF_SIZE, arch)
2435           != BSD_SYMDEF_SIZE)
2436         return FALSE;
2437     }
2438
2439   /* Now write the strings themselves.  */
2440   H_PUT_32 (arch, stringsize, temp);
2441   if (bfd_bwrite (temp, sizeof (temp), arch) != sizeof (temp))
2442     return FALSE;
2443   for (count = 0; count < orl_count; count++)
2444     {
2445       size_t len = strlen (*map[count].name) + 1;
2446
2447       if (bfd_bwrite (*map[count].name, len, arch) != len)
2448         return FALSE;
2449     }
2450
2451   /* The spec sez this should be a newline.  But in order to be
2452      bug-compatible for sun's ar we use a null.  */
2453   if (padit)
2454     {
2455       if (bfd_bwrite ("", 1, arch) != 1)
2456         return FALSE;
2457     }
2458
2459   return TRUE;
2460 }
2461
2462 /* At the end of archive file handling, update the timestamp in the
2463    file, so the linker will accept it.
2464
2465    Return TRUE if the timestamp was OK, or an unusual problem happened.
2466    Return FALSE if we updated the timestamp.  */
2467
2468 bfd_boolean
2469 _bfd_archive_bsd_update_armap_timestamp (bfd *arch)
2470 {
2471   struct stat archstat;
2472   struct ar_hdr hdr;
2473
2474   /* If creating deterministic archives, just leave the timestamp as-is.  */
2475   if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
2476     return TRUE;
2477
2478   /* Flush writes, get last-write timestamp from file, and compare it
2479      to the timestamp IN the file.  */
2480   bfd_flush (arch);
2481   if (bfd_stat (arch, &archstat) == -1)
2482     {
2483       bfd_perror (_("Reading archive file mod timestamp"));
2484
2485       /* Can't read mod time for some reason.  */
2486       return TRUE;
2487     }
2488   if (((long) archstat.st_mtime) <= bfd_ardata (arch)->armap_timestamp)
2489     /* OK by the linker's rules.  */
2490     return TRUE;
2491
2492   /* Update the timestamp.  */
2493   bfd_ardata (arch)->armap_timestamp = archstat.st_mtime + ARMAP_TIME_OFFSET;
2494
2495   /* Prepare an ASCII version suitable for writing.  */
2496   memset (hdr.ar_date, ' ', sizeof (hdr.ar_date));
2497   _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2498                     bfd_ardata (arch)->armap_timestamp);
2499
2500   /* Write it into the file.  */
2501   bfd_ardata (arch)->armap_datepos = (SARMAG
2502                                       + offsetof (struct ar_hdr, ar_date[0]));
2503   if (bfd_seek (arch, bfd_ardata (arch)->armap_datepos, SEEK_SET) != 0
2504       || (bfd_bwrite (hdr.ar_date, sizeof (hdr.ar_date), arch)
2505           != sizeof (hdr.ar_date)))
2506     {
2507       bfd_perror (_("Writing updated armap timestamp"));
2508
2509       /* Some error while writing.  */
2510       return TRUE;
2511     }
2512
2513   /* We updated the timestamp successfully.  */
2514   return FALSE;
2515 }
2516 \f
2517 /* A coff armap looks like :
2518    lARMAG
2519    struct ar_hdr with name = '/'
2520    number of symbols
2521    offset of file for symbol 0
2522    offset of file for symbol 1
2523
2524    offset of file for symbol n-1
2525    symbol name 0
2526    symbol name 1
2527
2528    symbol name n-1  */
2529
2530 bfd_boolean
2531 coff_write_armap (bfd *arch,
2532                   unsigned int elength,
2533                   struct orl *map,
2534                   unsigned int symbol_count,
2535                   int stridx)
2536 {
2537   /* The size of the ranlib is the number of exported symbols in the
2538      archive * the number of bytes in an int, + an int for the count.  */
2539   unsigned int ranlibsize = (symbol_count * 4) + 4;
2540   unsigned int stringsize = stridx;
2541   unsigned int mapsize = stringsize + ranlibsize;
2542   unsigned int archive_member_file_ptr;
2543   bfd *current = arch->archive_head;
2544   unsigned int count;
2545   struct ar_hdr hdr;
2546   int padit = mapsize & 1;
2547
2548   if (padit)
2549     mapsize++;
2550
2551   /* Work out where the first object file will go in the archive.  */
2552   archive_member_file_ptr = (mapsize
2553                              + elength
2554                              + sizeof (struct ar_hdr)
2555                              + SARMAG);
2556
2557   memset (&hdr, ' ', sizeof (struct ar_hdr));
2558   hdr.ar_name[0] = '/';
2559   _bfd_ar_spacepad (hdr.ar_size, sizeof (hdr.ar_size), "%-10ld",
2560                     mapsize);
2561   _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2562                     ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0
2563                      ? time (NULL) : 0));
2564   /* This, at least, is what Intel coff sets the values to.  */
2565   _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", 0);
2566   _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", 0);
2567   _bfd_ar_spacepad (hdr.ar_mode, sizeof (hdr.ar_mode), "%-7lo", 0);
2568   memcpy (hdr.ar_fmag, ARFMAG, 2);
2569
2570   /* Write the ar header for this item and the number of symbols.  */
2571   if (bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
2572       != sizeof (struct ar_hdr))
2573     return FALSE;
2574
2575   if (!bfd_write_bigendian_4byte_int (arch, symbol_count))
2576     return FALSE;
2577
2578   /* Two passes, first write the file offsets for each symbol -
2579      remembering that each offset is on a two byte boundary.  */
2580
2581   /* Write out the file offset for the file associated with each
2582      symbol, and remember to keep the offsets padded out.  */
2583
2584   current = arch->archive_head;
2585   count = 0;
2586   while (current != NULL && count < symbol_count)
2587     {
2588       /* For each symbol which is used defined in this object, write
2589          out the object file's address in the archive.  */
2590
2591       while (count < symbol_count && map[count].u.abfd == current)
2592         {
2593           if (!bfd_write_bigendian_4byte_int (arch, archive_member_file_ptr))
2594             return FALSE;
2595           count++;
2596         }
2597       archive_member_file_ptr += sizeof (struct ar_hdr);
2598       if (! bfd_is_thin_archive (arch))
2599         {
2600           /* Add size of this archive entry.  */
2601           archive_member_file_ptr += arelt_size (current);
2602           /* Remember about the even alignment.  */
2603           archive_member_file_ptr += archive_member_file_ptr % 2;
2604         }
2605       current = current->archive_next;
2606     }
2607
2608   /* Now write the strings themselves.  */
2609   for (count = 0; count < symbol_count; count++)
2610     {
2611       size_t len = strlen (*map[count].name) + 1;
2612
2613       if (bfd_bwrite (*map[count].name, len, arch) != len)
2614         return FALSE;
2615     }
2616
2617   /* The spec sez this should be a newline.  But in order to be
2618      bug-compatible for arc960 we use a null.  */
2619   if (padit)
2620     {
2621       if (bfd_bwrite ("", 1, arch) != 1)
2622         return FALSE;
2623     }
2624
2625   return TRUE;
2626 }