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