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