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