OSDN Git Service

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