OSDN Git Service

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