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