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