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