Wed Dec 30 12:46:30 1992 Ian Lance Taylor (ian@cygnus.com)
[external/binutils.git] / bfd / archive.c
1 /* BFD back-end for archive files (libraries).
2    Copyright 1990, 1991, 1992 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         Archives are supported in BFD in <<archive.c>>.
28
29         An archive (or library) is just another BFD.  It has a symbol
30         table, although there's not much a user program will do with it.
31
32         The big difference between an archive BFD and an ordinary BFD
33         is that the archive doesn't have sections.  Instead it has a
34         chain of BFDs considered its contents.  These BFDs can be
35         manipulated just like any other.  The BFDs contained in an
36         archive opened for reading will all be opened for reading; you
37         may put either input or output BFDs into an archive opened for
38         output; it will be handled correctly when the archive is closed.
39
40         Use <<bfd_openr_next_archived_file>> to step through all
41         the contents of an archive opened for input.  It's not
42         required that you read the entire archive if you don't want
43         to!  Read it until you find what you want.
44
45         Archive contents of output BFDs are chained through the
46         <<next>> pointer in a BFD.  The first one is findable through
47         the <<archive_head>> slot of the archive.  Set it with
48         <<set_archive_head>> (q.v.).  A given BFD may be in only one
49         open output archive at a time.
50
51         As expected, the BFD archive code is more general than the
52         archive code of any given environment.  BFD archives may
53         contain files of different formats (e.g., a.out and coff) and
54         even different architectures.  You may even place archives
55         recursively into archives!
56
57         This can cause unexpected confusion, since some archive
58         formats are more expressive than others.  For instance, Intel
59         COFF archives can preserve long filenames; Sun a.out archives
60         cannot.  If you move a file from the first to the second
61         format and back again, the filename may be truncated.
62         Likewise, different a.out environments have different
63         conventions as to how they truncate filenames, whether they
64         preserve directory names in filenames, etc.  When
65         interoperating with native tools, be sure your files are
66         homogeneous.
67
68         Beware: most of these formats do not react well to the
69         presence of spaces in filenames.  We do the best we can, but
70         can't always handle this due to restrctions in the format of
71         archives.  Many unix utilities are braindead in regards to
72         spaces and such in filenames anyway, so this shouldn't be much
73         of a restriction.
74 */
75
76 /* Assumes:
77    o - all archive elements start on an even boundary, newline padded;
78    o - all arch headers are char *;
79    o - all arch headers are the same size (across architectures).
80 */
81
82 /* Some formats provide a way to cram a long filename into the short
83    (16 chars) space provided by a bsd archive.  The trick is: make a
84    special "file" in the front of the archive, sort of like the SYMDEF
85    entry.  If the filename is too long to fit, put it in the extended
86    name table, and use its index as the filename.  To prevent
87    confusion prepend the index with a space.  This means you can't
88    have filenames that start with a space, but then again, many unix
89    utilities can't handle that anyway.
90
91    This scheme unfortunately requires that you stand on your head in
92    order to write an archive since you need to put a magic file at the
93    front, and need to touch every entry to do so.  C'est la vie.
94 */
95
96 #include "bfd.h"
97 #include "sysdep.h"
98 #include "libbfd.h"
99 #include "aout/ar.h"
100 #include "aout/ranlib.h"
101 #include <errno.h>
102
103 #ifndef errno
104 extern int errno;
105 #endif
106
107 #ifdef GNU960
108 #define BFD_GNU960_ARMAG(abfd)  (BFD_COFF_FILE_P((abfd)) ? ARMAG : ARMAGB)
109 #endif
110
111 /* We keep a cache of archive filepointers to archive elements to
112    speed up searching the archive by filepos.  We only add an entry to
113    the cache when we actually read one.  We also don't sort the cache;
114    it's generally short enough to search linearly.
115    Note that the pointers here point to the front of the ar_hdr, not
116    to the front of the contents!
117 */
118 struct ar_cache {
119   file_ptr ptr;
120   bfd* arelt;
121   struct ar_cache *next;
122 };
123
124 #define ar_padchar(abfd) ((abfd)->xvec->ar_pad_char)
125 #define ar_maxnamelen(abfd) ((abfd)->xvec->ar_max_namelen)
126
127 #define arch_hdr(bfd) ((struct ar_hdr *)   \
128                        (((struct areltdata *)((bfd)->arelt_data))->arch_header))
129 \f
130 boolean
131 _bfd_generic_mkarchive (abfd)
132      bfd *abfd;
133 {
134   abfd->tdata.aout_ar_data = (struct artdata *)bfd_zalloc(abfd, sizeof (struct artdata));
135
136   if (bfd_ardata (abfd) == NULL) {
137       bfd_error = no_memory;
138       return false;
139     }
140   bfd_ardata(abfd)->cache = 0;
141   return true;
142 }
143
144 /*
145 FUNCTION
146         bfd_get_next_mapent
147
148 SYNOPSIS
149         symindex bfd_get_next_mapent(bfd *, symindex previous, carsym ** sym);
150
151 DESCRIPTION
152         This function steps through an archive's symbol table (if it
153         has one).  Successively updates <<sym>> with the next symbol's
154         information, returning that symbol's (internal) index into the
155         symbol table.
156
157         Supply BFD_NO_MORE_SYMBOLS as the <<previous>> entry to get
158         the first one; returns BFD_NO_MORE_SYMBOLS when you're already
159         got the last one.
160
161         A <<carsym>> is a canonical archive symbol.  The only
162         user-visible element is its name, a null-terminated string.
163 */
164
165 symindex
166 DEFUN(bfd_get_next_mapent,(abfd, prev, entry),
167      bfd *abfd AND
168      symindex prev AND
169      carsym **entry)
170 {
171   if (!bfd_has_map (abfd)) {
172     bfd_error = invalid_operation;
173     return BFD_NO_MORE_SYMBOLS;
174   }
175   
176   if (prev == BFD_NO_MORE_SYMBOLS) prev = 0;
177   else if (++prev >= bfd_ardata (abfd)->symdef_count)
178     return BFD_NO_MORE_SYMBOLS;
179
180   *entry = (bfd_ardata (abfd)->symdefs + prev);
181   return prev;
182 }
183
184 /* To be called by backends only */
185 bfd *
186 _bfd_create_empty_archive_element_shell (obfd)
187      bfd *obfd;
188 {
189   bfd *nbfd;
190
191   nbfd = new_bfd_contained_in(obfd);
192   if (nbfd == NULL) {
193     bfd_error = no_memory;
194     return NULL;
195   }
196   return nbfd;
197 }
198
199 /*
200 FUNCTION
201         bfd_set_archive_head
202
203 SYNOPSIS
204         boolean bfd_set_archive_head(bfd *output, bfd *new_head);
205
206 DESCRIPTION
207         Used whilst processing archives. Sets the head of the chain of
208         BFDs contained in an archive to @var{new_head}. 
209 */
210
211 boolean
212 DEFUN(bfd_set_archive_head,(output_archive, new_head),
213      bfd *output_archive AND 
214      bfd *new_head)
215 {
216
217   output_archive->archive_head = new_head;
218   return true;
219 }
220
221 bfd *
222 look_for_bfd_in_cache (arch_bfd, filepos)
223      bfd *arch_bfd;
224      file_ptr filepos;
225 {
226   struct ar_cache *current;
227
228   for (current = bfd_ardata (arch_bfd)->cache; current != NULL;
229        current = current->next)
230     if (current->ptr == filepos) return current->arelt;
231
232   return NULL;
233 }
234
235 /* Kind of stupid to call cons for each one, but we don't do too many */
236 boolean
237 add_bfd_to_cache (arch_bfd, filepos, new_elt)
238      bfd *arch_bfd, *new_elt;
239      file_ptr filepos;
240 {
241   struct ar_cache *new_cache = (struct ar_cache *)
242                                 bfd_zalloc(arch_bfd, sizeof (struct ar_cache));
243
244   if (new_cache == NULL) {
245     bfd_error = no_memory;
246     return false;
247   }
248
249   new_cache->ptr = filepos;
250   new_cache->arelt = new_elt;
251   new_cache->next = (struct ar_cache *)NULL;
252   if (bfd_ardata (arch_bfd)->cache == NULL)
253     bfd_ardata (arch_bfd)->cache = new_cache;
254   else {
255     struct ar_cache *current = bfd_ardata (arch_bfd)->cache;
256
257     for (; current->next != NULL; current = current->next);
258     current->next = new_cache;
259   }
260     
261   return true;
262 }
263
264 \f
265
266 /* The name begins with space.  Hence the rest of the name is an index into
267    the string table. */
268 char *
269 get_extended_arelt_filename (arch, name)
270      bfd *arch;
271      char *name;
272 {
273   unsigned long index = 0;
274
275   /* Should extract string so that I can guarantee not to overflow into
276      the next region, but I'm too lazy. */
277   errno = 0;
278   /* Skip first char, which is '/' in SVR4 or ' ' in some other variants. */
279   index = strtol (name+1, NULL, 10);
280   if (errno != 0) {
281       bfd_error = malformed_archive;
282       return NULL;
283     }
284
285   return bfd_ardata (arch)->extended_names + index;
286 }  
287
288 /* This functions reads an arch header and returns an areltdata pointer, or
289    NULL on error.
290
291    Presumes the file pointer is already in the right place (ie pointing
292    to the ar_hdr in the file).   Moves the file pointer; on success it
293    should be pointing to the front of the file contents; on failure it
294    could have been moved arbitrarily.
295 */
296
297 struct areltdata *
298 snarf_ar_hdr (abfd)
299      bfd *abfd;
300 {
301 #ifndef errno
302   extern int errno;
303 #endif
304
305     struct ar_hdr hdr;
306     char *hdrp = (char *) &hdr;
307     unsigned int parsed_size;
308     struct areltdata *ared;
309     char *filename = NULL;
310     unsigned int namelen = 0;
311     unsigned int allocsize = sizeof (struct areltdata) + sizeof (struct ar_hdr);
312     char *allocptr;
313
314     if (bfd_read ((PTR)hdrp, 1, sizeof (struct ar_hdr), abfd)
315         != sizeof (struct ar_hdr)) {
316         bfd_error = no_more_archived_files;
317         return NULL;
318     }
319     if (strncmp ((hdr.ar_fmag), ARFMAG, 2)) {
320         bfd_error = malformed_archive;
321         return NULL;
322     }
323
324     errno = 0;
325     parsed_size = strtol (hdr.ar_size, NULL, 10);
326     if (errno != 0) {
327         bfd_error = malformed_archive;
328         return NULL;
329     }
330
331     /* extract the filename from the archive - there are two ways to
332        specify an extendend name table, either the first char of the
333        name is a space, or it's a slash.  */
334     if ((hdr.ar_name[0] == '/'
335          || (hdr.ar_name[0] == ' '
336              && memchr (hdr.ar_name, '/', ar_maxnamelen(abfd)) == NULL))
337         && bfd_ardata (abfd)->extended_names != NULL) {
338         filename = get_extended_arelt_filename (abfd, hdr.ar_name);
339         if (filename == NULL) {
340             bfd_error = malformed_archive;
341             return NULL;
342         }
343     } 
344     else 
345         {
346             /* We judge the end of the name by looking for '/' or ' '.
347                Note:  The SYSV format (terminated by '/') allows embedded
348                spaces, so only look for ' ' if we don't find '/'. */
349
350             namelen = 0;
351             while (hdr.ar_name[namelen] != '\0' &&
352                    hdr.ar_name[namelen] != '/') {
353                 namelen++;
354                 if (namelen == (unsigned)ar_maxnamelen(abfd)) {
355                     namelen = 0;
356                     while (hdr.ar_name[namelen] != ' '
357                            && namelen < (unsigned)ar_maxnamelen(abfd)) {
358                         namelen++;
359                     }
360                     break;
361                 }
362             }
363
364             allocsize += namelen + 1;
365         }
366
367     allocptr = bfd_zalloc(abfd, allocsize);
368     if (allocptr == NULL) {
369         bfd_error = no_memory;
370         return NULL;
371     }
372
373     ared = (struct areltdata *) allocptr;
374
375     ared->arch_header = allocptr + sizeof (struct areltdata);
376     memcpy ((char *) ared->arch_header, (char *) &hdr, sizeof (struct ar_hdr));
377     ared->parsed_size = parsed_size;
378
379     if (filename != NULL) ared->filename = filename;
380     else {
381         ared->filename = allocptr + (sizeof (struct areltdata) +
382                                      sizeof (struct ar_hdr));
383         if (namelen)
384             memcpy (ared->filename, hdr.ar_name, namelen);
385         ared->filename[namelen] = '\0';
386     }
387   
388     return ared;
389 }
390 \f
391 /* This is an internal function; it's mainly used when indexing
392    through the archive symbol table, but also used to get the next
393    element, since it handles the bookkeeping so nicely for us.
394 */
395
396 bfd *
397 get_elt_at_filepos (archive, filepos)
398      bfd *archive;
399      file_ptr filepos;
400 {
401   struct areltdata *new_areldata;
402   bfd *n_nfd;
403
404   n_nfd = look_for_bfd_in_cache (archive, filepos);
405   if (n_nfd) return n_nfd;
406
407   if (0 > bfd_seek (archive, filepos, SEEK_SET)) {
408     bfd_error = system_call_error;
409     return NULL;
410   }
411
412   if ((new_areldata = snarf_ar_hdr (archive)) == NULL) return NULL;
413   
414   n_nfd = _bfd_create_empty_archive_element_shell (archive);
415   if (n_nfd == NULL) {
416     bfd_release (archive, (PTR)new_areldata);
417     return NULL;
418   }
419   n_nfd->origin = bfd_tell (archive);
420   n_nfd->arelt_data = (PTR) new_areldata;
421   n_nfd->filename = new_areldata->filename;
422
423   if (add_bfd_to_cache (archive, filepos, n_nfd))
424     return n_nfd;
425
426   /* huh? */
427   bfd_release (archive, (PTR)n_nfd);
428   bfd_release (archive, (PTR)new_areldata);
429   return NULL;
430 }
431
432 /*
433 FUNCTION
434         bfd_get_elt_at_index
435
436 SYNOPSIS
437         bfd *bfd_get_elt_at_index(bfd * archive, int index);
438
439 DESCRIPTION
440         Return the bfd which is referenced by the symbol indexed by <<index>>.
441         <<index>> should have been returned by <<bfd_get_next_mapent>> (q.v.).
442
443 */
444 bfd *
445 DEFUN(bfd_get_elt_at_index,(abfd, index),
446      bfd *abfd AND
447      int index)
448 {
449   bfd *result =
450     get_elt_at_filepos
451       (abfd, (bfd_ardata (abfd)->symdefs + index)->file_offset);
452   return result;
453 }
454
455 /*
456 FUNCTION
457         bfd_openr_next_archived_file
458
459 SYNOPSIS
460         bfd* bfd_openr_next_archived_file(bfd *archive, bfd *previous);
461
462 DESCRIPTION
463         Initially provided a BFD containing an archive and NULL, opens
464         an inpout BFD on the first contained element and returns that.
465         Subsequent calls to bfd_openr_next_archived_file should pass
466         the archive and the previous return value to return a created
467         BFD to the next contained element. NULL is returned when there
468         are no more.
469
470 */
471
472 bfd *
473 DEFUN(bfd_openr_next_archived_file,(archive, last_file),
474      bfd *archive AND  
475       bfd*last_file)
476 {
477
478     if ((bfd_get_format (archive) != bfd_archive) ||
479         (archive->direction == write_direction)) {
480             bfd_error = invalid_operation;
481             return NULL;
482         }
483
484
485     return BFD_SEND (archive,
486                      openr_next_archived_file,
487                      (archive,
488                       last_file));
489
490 }
491
492 bfd *bfd_generic_openr_next_archived_file(archive, last_file)
493      bfd *archive;
494      bfd *last_file;
495 {
496   file_ptr filestart;
497
498   if (!last_file)
499     filestart = bfd_ardata (archive)->first_file_filepos;
500   else {
501     unsigned int size = arelt_size(last_file);
502     /* Pad to an even boundary... */
503     filestart = last_file->origin + size + size%2;
504   }
505
506   return get_elt_at_filepos (archive, filestart);
507 }
508
509
510 bfd_target *
511 bfd_generic_archive_p (abfd)
512      bfd *abfd;
513 {
514   char armag[SARMAG+1];
515
516   if (bfd_read ((PTR)armag, 1, SARMAG, abfd) != SARMAG) {
517     bfd_error = wrong_format;
518     return 0;
519   }
520
521 #ifdef GNU960
522   if (strncmp (armag, BFD_GNU960_ARMAG(abfd), SARMAG)) return 0;
523 #else
524   if (strncmp (armag, ARMAG, SARMAG) &&
525       strncmp (armag, ARMAGB, SARMAG)) return 0;
526 #endif
527
528
529
530   /* We are setting bfd_ardata(abfd) here, but since bfd_ardata
531      involves a cast, we can't do it as the left operand of assignment. */
532   abfd->tdata.aout_ar_data = (struct artdata *) bfd_zalloc(abfd,sizeof (struct artdata));
533
534   if (bfd_ardata (abfd)  == NULL) {
535     bfd_error = no_memory;
536     return 0;
537   }
538
539   bfd_ardata (abfd)->first_file_filepos = SARMAG;
540   
541   if (!bfd_slurp_armap (abfd)) {
542     bfd_release(abfd, bfd_ardata (abfd));
543     abfd->tdata.aout_ar_data = NULL;
544     return 0;
545   }
546
547   if (!BFD_SEND (abfd, _bfd_slurp_extended_name_table, (abfd))) {
548     bfd_release(abfd, bfd_ardata (abfd));
549     abfd->tdata.aout_ar_data = NULL;
550     return 0;
551   }
552   
553   return abfd->xvec;
554 }
555
556 /* Returns false on error, true otherwise */
557 static boolean
558 do_slurp_bsd_armap (abfd)
559      bfd *abfd;
560 {
561
562   struct areltdata *mapdata;
563   char nextname[17];
564   unsigned int counter = 0;
565   int *raw_armap, *rbase;
566   struct artdata *ardata = bfd_ardata (abfd);
567   char *stringbase;
568   unsigned int parsed_size;
569
570   mapdata = snarf_ar_hdr (abfd);
571   if (mapdata == NULL) return false;
572   parsed_size = mapdata->parsed_size;
573   bfd_release (abfd, (PTR)mapdata); /* Don't need it any more. */
574     
575   raw_armap = (int *) bfd_zalloc(abfd, parsed_size);
576   if (raw_armap == NULL) {
577       bfd_error = no_memory;
578       return false;
579   }
580     
581   if (bfd_read ((PTR)raw_armap, 1, parsed_size, abfd) != parsed_size) {
582       bfd_error = malformed_archive;
583     byebye:
584       bfd_release (abfd, (PTR)raw_armap);
585       return false;
586   }
587     
588   ardata->symdef_count =
589       bfd_h_get_32(abfd, (PTR)raw_armap) / sizeof (struct symdef);
590     
591   if (ardata->symdef_count * sizeof (struct symdef)
592       > parsed_size - sizeof (*raw_armap)) {
593       /* Probably we're using the wrong byte ordering.  */
594       bfd_error = wrong_format;
595       goto byebye;
596   }
597   
598   ardata->cache = 0;
599   rbase = raw_armap+1;
600   ardata->symdefs = (carsym *) rbase;
601   stringbase = ((char *) (ardata->symdefs + ardata->symdef_count)) + 4;
602   
603   for (;counter < ardata->symdef_count; counter++) {
604       struct symdef *sym = ((struct symdef *) rbase) + counter;
605       sym->s.name = bfd_h_get_32(abfd, (PTR)(&(sym->s.string_offset))) + stringbase;
606       sym->file_offset = bfd_h_get_32(abfd, (PTR)( &(sym->file_offset)));
607   }
608   
609   ardata->first_file_filepos = bfd_tell (abfd);
610   /* Pad to an even boundary if you have to */
611   ardata->first_file_filepos += (ardata-> first_file_filepos) %2;
612   /* FIXME, we should provide some way to free raw_ardata when
613      we are done using the strings from it.  For now, it seems
614      to be allocated on an obstack anyway... */
615   bfd_has_map (abfd) = true;
616   return true;
617 }
618
619 /* Returns false on error, true otherwise */
620 static boolean
621 do_slurp_coff_armap (abfd)
622      bfd *abfd;
623 {
624   struct areltdata *mapdata;
625   char nextname;
626   int *raw_armap, *rawptr;
627   struct artdata *ardata = bfd_ardata (abfd);
628   char *stringbase;
629   unsigned int stringsize;
630   unsigned int parsed_size;
631   carsym *carsyms;
632   int result;
633   unsigned int nsymz; /* Number of symbols in armap. */
634
635   bfd_vma (*swap)();
636   char int_buf[sizeof(long)];
637   unsigned int carsym_size, ptrsize, i;
638   
639   mapdata = snarf_ar_hdr (abfd);
640   if (mapdata == NULL) return false;
641   parsed_size = mapdata->parsed_size;
642   bfd_release (abfd, (PTR)mapdata); /* Don't need it any more. */
643
644   if (bfd_read ((PTR)int_buf, 1, 4, abfd) != 4) {
645     bfd_error = malformed_archive;
646     return false;
647   }
648   /* It seems that all numeric information in a coff archive is always
649      in big endian format, nomatter the host or target. */
650   swap = _do_getb32;
651   nsymz = _do_getb32((PTR)int_buf);
652   stringsize = parsed_size - (4 * nsymz) - 4;
653
654 #if 1
655   /* ... except that some archive formats are broken, and it may be our
656      fault - the i960 little endian coff sometimes has big and sometimes
657      little, because our tools changed.  Here's a horrible hack to clean
658      up the crap.  */
659   
660   if (stringsize > 0xfffff) {
661       /* This looks dangerous, let's do it the other way around */
662       nsymz = _do_getl32((PTR)int_buf);
663       stringsize = parsed_size - (4 * nsymz) - 4;
664       swap = _do_getl32;
665   }
666 #endif
667
668   /* The coff armap must be read sequentially.  So we construct a bsd-style
669      one in core all at once, for simplicity. */  
670   
671   carsym_size = (nsymz * sizeof (carsym));
672   ptrsize = (4 * nsymz);
673
674   ardata->symdefs = (carsym *) bfd_zalloc(abfd, carsym_size + stringsize + 1);
675   if (ardata->symdefs == NULL) {
676       bfd_error = no_memory;
677       return false;
678   }
679   carsyms = ardata->symdefs;
680   stringbase = ((char *) ardata->symdefs) + carsym_size;
681
682   /* Allocate and read in the raw offsets. */
683   raw_armap = (int *) bfd_alloc(abfd, ptrsize);
684   if (raw_armap == NULL) {
685       bfd_error = no_memory;
686       goto release_symdefs;
687   }
688   if (bfd_read ((PTR)raw_armap, 1, ptrsize, abfd) != ptrsize
689       || bfd_read ((PTR)stringbase, 1, stringsize, abfd) != stringsize) {
690     bfd_error = malformed_archive;
691     goto release_raw_armap;
692   }
693
694   /* OK, build the carsyms */
695   for (i = 0; i < nsymz; i++) {
696       rawptr = raw_armap + i;
697       carsyms->file_offset = swap((PTR)rawptr);
698       carsyms->name = stringbase;
699       while (*stringbase++) ;
700       carsyms++;
701   }
702   *stringbase = 0;
703
704   ardata->symdef_count = nsymz;
705   ardata->first_file_filepos = bfd_tell (abfd);
706   /* Pad to an even boundary if you have to */
707   ardata->first_file_filepos += (ardata->first_file_filepos) %2;
708
709   bfd_has_map (abfd) = true;
710   bfd_release (abfd, (PTR)raw_armap);
711   return true;
712
713  release_raw_armap:
714   bfd_release (abfd, (PTR)raw_armap);
715  release_symdefs:
716   bfd_release (abfd, (PTR)(ardata)->symdefs);
717   return false;
718 }
719
720 /* This routine can handle either coff-style or bsd-style armaps.
721    Returns false on error, true otherwise */
722
723 boolean
724 bfd_slurp_armap (abfd)
725      bfd *abfd;
726 {
727   char nextname[17];
728   int i = bfd_read ((PTR)nextname, 1, 16, abfd);
729   
730   if (i == 0)
731       return true;
732   if (i != 16)
733       return false;
734
735   bfd_seek (abfd, (file_ptr) -16, SEEK_CUR);
736
737   if (!strncmp (nextname, "__.SYMDEF       ", 16))
738     return do_slurp_bsd_armap (abfd);
739   else if (!strncmp (nextname, "/               ", 16))
740     return do_slurp_coff_armap (abfd);
741
742   bfd_has_map (abfd) = false;
743   return true;
744 }
745 \f
746 /** Extended name table.
747
748   Normally archives support only 14-character filenames.
749
750   Intel has extended the format: longer names are stored in a special
751   element (the first in the archive, or second if there is an armap);
752   the name in the ar_hdr is replaced by <space><index into filename
753   element>.  Index is the P.R. of an int (decimal).  Data General have
754   extended the format by using the prefix // for the special element */
755
756 /* Returns false on error, true otherwise */
757 boolean
758 _bfd_slurp_extended_name_table (abfd)
759      bfd *abfd;
760 {
761   char nextname[17];
762   struct areltdata *namedata;
763
764   /* FIXME:  Formatting sucks here, and in case of failure of BFD_READ,
765      we probably don't want to return true.  */
766   if (bfd_read ((PTR)nextname, 1, 16, abfd) == 16) {
767
768     bfd_seek (abfd, (file_ptr) -16, SEEK_CUR);
769
770     if (strncmp (nextname, "ARFILENAMES/    ", 16) != 0 &&
771         strncmp (nextname, "//              ", 16) != 0) 
772         {
773       bfd_ardata (abfd)->extended_names = NULL;
774       return true;
775     }
776
777     namedata = snarf_ar_hdr (abfd);
778     if (namedata == NULL) return false;
779   
780     bfd_ardata (abfd)->extended_names = bfd_zalloc(abfd,namedata->parsed_size);
781     if (bfd_ardata (abfd)->extended_names == NULL) {
782       bfd_error = no_memory;
783     byebye:
784       bfd_release (abfd, (PTR)namedata);
785       return false;
786     }
787
788     if (bfd_read ((PTR)bfd_ardata (abfd)->extended_names, 1,
789                   namedata->parsed_size, abfd) != namedata->parsed_size) {
790       bfd_error = malformed_archive;
791       bfd_release (abfd, (PTR)(bfd_ardata (abfd)->extended_names));
792       bfd_ardata (abfd)->extended_names = NULL;
793       goto byebye;
794     }
795
796     /* Since the archive is supposed to be printable if it contains
797        text, the entries in the list are newline-padded, not null
798        padded. In SVR4-style archives, the names also have a
799        trailing '/'.  We'll fix both problems here..  */
800       {
801         char *temp = bfd_ardata (abfd)->extended_names;
802         char *limit = temp + namedata->parsed_size;
803         for (; temp < limit; ++temp)
804           if (*temp == '\n')
805             temp[temp[-1] == '/' ? -1 : 0] = '\0';
806       }
807   
808     /* Pad to an even boundary if you have to */
809     bfd_ardata (abfd)->first_file_filepos = bfd_tell (abfd);
810     bfd_ardata (abfd)->first_file_filepos +=
811       (bfd_ardata (abfd)->first_file_filepos) %2;
812
813     /* FIXME, we can't release namedata here because it was allocated
814        below extended_names on the obstack... */
815     /* bfd_release (abfd, namedata); */
816   }
817   return true;
818 }
819
820 #ifdef VMS
821
822 /* Return a copy of the stuff in the filename between any :]> and a
823    semicolon */
824 static CONST char *
825 DEFUN(normalize,(file),
826       CONST char *file)
827 {
828   CONST char *first;
829   CONST char *last;
830   char *copy;
831
832   first = file + strlen(file)-1;
833   last = first+1;
834
835   while (first != file) 
836   {
837     if (*first == ';') 
838      last = first;
839     if (*first == ':' || *first == ']' ||*first == '>') 
840     { 
841       first++;
842       break;
843     }
844     first --;
845   }
846   
847
848   copy = malloc(last - first + 1);
849   memcpy(copy, first, last-first);
850   copy[last-first] = 0;
851
852   return copy;
853 }
854
855 #else
856 static
857 CONST char *normalize(file)
858 CONST char *file;
859 {
860   CONST char *    filename = strrchr(file, '/');
861
862   if (filename != (char *)NULL) {
863       filename ++;
864     }
865   else {
866       filename = file;
867     }
868   return filename;
869 }
870 #endif
871 /* Follows archive_head and produces an extended name table if necessary.
872    Returns (in tabloc) a pointer to an extended name table, and in tablen
873    the length of the table.  If it makes an entry it clobbers the filename
874    so that the element may be written without further massage.
875    Returns true if it ran successfully, false if something went wrong.
876    A successful return may still involve a zero-length tablen!
877    */
878 boolean
879 bfd_construct_extended_name_table (abfd, tabloc, tablen)
880      bfd *abfd;
881      char **tabloc;
882      unsigned int *tablen;
883 {
884   unsigned int maxname = abfd->xvec->ar_max_namelen;
885   unsigned int total_namelen = 0;
886   bfd *current;
887   char *strptr;
888
889   *tablen = 0;
890   
891   /* Figure out how long the table should be */
892   for (current = abfd->archive_head; current != NULL; current = current->next){
893     unsigned int thislen = strlen (normalize(current->filename));
894     if (thislen > maxname) total_namelen += thislen + 1; /* leave room for \n */
895   }
896
897   if (total_namelen == 0) return true;
898
899   *tabloc = bfd_zalloc (abfd,total_namelen);
900   if (*tabloc == NULL) {
901     bfd_error = no_memory;
902     return false;
903   }
904
905   *tablen = total_namelen;
906   strptr = *tabloc;
907
908   for (current = abfd->archive_head; current != NULL; current =
909        current->next) {
910     CONST char *normal =normalize( current->filename);
911     unsigned int thislen = strlen (normal);
912     if (thislen > maxname) {
913       /* Works for now; may need to be re-engineered if we encounter an oddball
914          archive format and want to generalise this hack. */
915       struct ar_hdr *hdr = arch_hdr(current);
916       strcpy (strptr, normal);
917       strptr[thislen] = '\n';
918       hdr->ar_name[0] = ' ';
919       /* We know there will always be enough room (one of the few cases
920          where you may safely use sprintf). */
921       sprintf ((hdr->ar_name) + 1, "%-d", (unsigned) (strptr - *tabloc));
922       /* Kinda Kludgy.   We should just use the returned value of sprintf
923          but not all implementations get this right */
924         {
925           char *temp = hdr->ar_name +2; 
926           for (; temp < hdr->ar_name + maxname; temp++)
927             if (*temp == '\0') *temp = ' ';
928         }
929       strptr += thislen + 1;
930     }
931   }
932
933   return true;
934 }
935 \f
936 /** A couple of functions for creating ar_hdrs */
937
938 /* Takes a filename, returns an arelt_data for it, or NULL if it can't make one.
939    The filename must refer to a filename in the filesystem.
940    The filename field of the ar_hdr will NOT be initialized
941 */
942
943 struct areltdata *
944 DEFUN(bfd_ar_hdr_from_filesystem, (abfd,filename),
945       bfd* abfd AND
946       CONST char *filename)
947 {
948   struct stat status;
949   struct areltdata *ared;
950   struct ar_hdr *hdr;
951   char *temp, *temp1;
952
953
954   if (stat (filename, &status) != 0) {
955     bfd_error = system_call_error;
956     return NULL;
957   }
958
959   ared = (struct areltdata *) bfd_zalloc(abfd, sizeof (struct ar_hdr) +
960                                       sizeof (struct areltdata));
961   if (ared == NULL) {
962     bfd_error = no_memory;
963     return NULL;
964   }
965   hdr = (struct ar_hdr *) (((char *) ared) + sizeof (struct areltdata));
966
967   /* ar headers are space padded, not null padded! */
968   temp = (char *) hdr;
969   temp1 = temp + sizeof (struct ar_hdr) - 2;
970   for (; temp < temp1; *(temp++) = ' ');
971   strncpy (hdr->ar_fmag, ARFMAG, 2);
972   
973   /* Goddamned sprintf doesn't permit MAXIMUM field lengths */
974   sprintf ((hdr->ar_date), "%-12ld", status.st_mtime);
975   sprintf ((hdr->ar_uid), "%d", status.st_uid);
976   sprintf ((hdr->ar_gid), "%d", status.st_gid);
977   sprintf ((hdr->ar_mode), "%-8o", (unsigned) status.st_mode);
978   sprintf ((hdr->ar_size), "%-10ld", status.st_size);
979   /* Correct for a lossage in sprintf whereby it null-terminates.  I cannot
980      understand how these C losers could design such a ramshackle bunch of
981      IO operations */
982   temp = (char *) hdr;
983   temp1 = temp + sizeof (struct ar_hdr) - 2;
984   for (; temp < temp1; temp++) {
985     if (*temp == '\0') *temp = ' ';
986   }
987   strncpy (hdr->ar_fmag, ARFMAG, 2);
988   ared->parsed_size = status.st_size;
989   ared->arch_header = (char *) hdr;
990
991   return ared;
992 }
993
994 /* This is magic required by the "ar" program.  Since it's
995     undocumented, it's undocumented.   You may think that it would
996     take a strong stomach to write this, and it does, but it takes
997     even a stronger stomach to try to code around such a thing!
998 */
999
1000 struct ar_hdr *
1001 DEFUN(bfd_special_undocumented_glue, (abfd, filename),
1002       bfd *abfd AND
1003       char *filename)
1004 {
1005   struct areltdata *ar_elt = bfd_ar_hdr_from_filesystem (abfd, filename);
1006   if (ar_elt == NULL)
1007       return NULL;
1008   return (struct ar_hdr *) ar_elt->arch_header;
1009 }
1010
1011
1012 /* Analogous to stat call */
1013 int
1014 bfd_generic_stat_arch_elt (abfd, buf)
1015      bfd *abfd;
1016      struct stat *buf;
1017 {
1018   struct ar_hdr *hdr;
1019   char *aloser;
1020   
1021   if (abfd->arelt_data == NULL) {
1022     bfd_error = invalid_operation;
1023     return -1;
1024   }
1025     
1026   hdr = arch_hdr (abfd);
1027
1028 #define foo(arelt, stelt, size)  \
1029   buf->stelt = strtol (hdr->arelt, &aloser, size); \
1030   if (aloser == hdr->arelt) return -1;
1031   
1032   foo (ar_date, st_mtime, 10);
1033   foo (ar_uid, st_uid, 10);
1034   foo (ar_gid, st_gid, 10);
1035   foo (ar_mode, st_mode, 8);
1036   foo (ar_size, st_size, 10);
1037
1038   return 0;
1039 }
1040
1041 void
1042 bfd_dont_truncate_arname (abfd, pathname, arhdr)
1043      bfd *abfd;
1044      CONST char *pathname;
1045      char *arhdr;
1046 {
1047   /* FIXME: This interacts unpleasantly with ar's quick-append option.
1048      Fortunately ic960 users will never use that option.  Fixing this
1049      is very hard; fortunately I know how to do it and will do so once
1050      intel's release is out the door. */
1051    
1052   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
1053   int length;
1054   CONST char *filename = normalize(pathname);
1055   int maxlen = ar_maxnamelen (abfd);
1056
1057   length = strlen (filename);
1058
1059   if (length <= maxlen)
1060     memcpy (hdr->ar_name, filename, length);
1061
1062   if (length < maxlen) (hdr->ar_name)[length] = ar_padchar (abfd);
1063   return;
1064
1065 }
1066
1067 void
1068 bfd_bsd_truncate_arname (abfd, pathname, arhdr)
1069      bfd *abfd;
1070      CONST char *pathname;
1071      char *arhdr;
1072 {
1073   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
1074   int length;
1075   CONST char *filename = strrchr (pathname, '/');
1076   int maxlen = ar_maxnamelen (abfd);
1077
1078
1079   if (filename == NULL)
1080     filename = pathname;
1081   else
1082     ++filename;
1083
1084   length = strlen (filename);
1085
1086   if (length <= maxlen)
1087     memcpy (hdr->ar_name, filename, length);
1088   else {
1089     /* pathname: meet procrustes */
1090     memcpy (hdr->ar_name, filename, maxlen);
1091     length = maxlen;
1092   }
1093
1094   if (length < maxlen) (hdr->ar_name)[length] = ar_padchar (abfd);
1095 }
1096
1097 /* Store name into ar header.  Truncates the name to fit.
1098    1> strip pathname to be just the basename.
1099    2> if it's short enuf to fit, stuff it in.
1100    3> If it doesn't end with .o, truncate it to fit
1101    4> truncate it before the .o, append .o, stuff THAT in.
1102 */
1103
1104 /* This is what gnu ar does.  It's better but incompatible with the bsd ar. */
1105 void
1106 bfd_gnu_truncate_arname (abfd, pathname, arhdr)
1107      bfd *abfd;
1108      CONST char *pathname;
1109      char *arhdr;
1110 {
1111   struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
1112   int length;
1113   CONST char *filename = strrchr (pathname, '/');
1114   int maxlen = ar_maxnamelen (abfd);
1115         
1116   if (filename == NULL)
1117     filename = pathname;
1118   else
1119     ++filename;
1120
1121   length = strlen (filename);
1122
1123   if (length <= maxlen)
1124     memcpy (hdr->ar_name, filename, length);
1125   else {                        /* pathname: meet procrustes */
1126     memcpy (hdr->ar_name, filename, maxlen);
1127     if ((filename[length - 2] == '.') && (filename[length - 1] == 'o')) {
1128       hdr->ar_name[maxlen - 2] = '.';
1129       hdr->ar_name[maxlen - 1] = 'o';
1130     }
1131     length = maxlen;
1132   }
1133
1134   if (length < 16) (hdr->ar_name)[length] = ar_padchar (abfd);
1135 }
1136 \f
1137
1138 PROTO (boolean, compute_and_write_armap, (bfd *arch, unsigned int elength));
1139
1140 /* The BFD is open for write and has its format set to bfd_archive */
1141 boolean
1142 _bfd_write_archive_contents (arch)
1143      bfd *arch;
1144 {
1145   bfd *current;
1146   char *etable = NULL;
1147   unsigned int elength = 0;
1148
1149   boolean makemap = bfd_has_map (arch);
1150   boolean hasobjects = false;   /* if no .o's, don't bother to make a map */
1151   unsigned int i;
1152
1153   /* Verify the viability of all entries; if any of them live in the
1154      filesystem (as opposed to living in an archive open for input)
1155      then construct a fresh ar_hdr for them.
1156      */
1157   for (current = arch->archive_head; current; current = current->next) {
1158     if (bfd_write_p (current)) {
1159       bfd_error = invalid_operation;
1160       return false;
1161     }
1162     if (!current->arelt_data) {
1163       current->arelt_data =
1164           (PTR) bfd_ar_hdr_from_filesystem (arch, current->filename);
1165       if (!current->arelt_data) return false;
1166
1167       /* Put in the file name */
1168     
1169     BFD_SEND (arch, _bfd_truncate_arname,(arch, 
1170                                           current->filename,
1171                                          (char *) arch_hdr(current)));
1172
1173       
1174     }
1175
1176     if (makemap) {              /* don't bother if we won't make a map! */
1177       if ((bfd_check_format (current, bfd_object))
1178 #if 0                           /* FIXME -- these are not set correctly */
1179           && ((bfd_get_file_flags (current) & HAS_SYMS))
1180 #endif
1181           )
1182         hasobjects = true;
1183     }
1184   }
1185
1186   if (!bfd_construct_extended_name_table (arch, &etable, &elength))
1187     return false;
1188
1189   bfd_seek (arch, (file_ptr) 0, SEEK_SET);
1190 #ifdef GNU960
1191   bfd_write (BFD_GNU960_ARMAG(arch), 1, SARMAG, arch);
1192 #else
1193   bfd_write (ARMAG, 1, SARMAG, arch);
1194 #endif
1195
1196   if (makemap && hasobjects) {
1197
1198     if (compute_and_write_armap (arch, elength) != true) {
1199       return false;
1200     }
1201   }
1202
1203   if (elength != 0) {
1204     struct ar_hdr hdr;
1205
1206     memset ((char *)(&hdr), 0, sizeof (struct ar_hdr));
1207     sprintf (&(hdr.ar_name[0]), "ARFILENAMES/");
1208     sprintf (&(hdr.ar_size[0]), "%-10d", (int) elength);
1209     hdr.ar_fmag[0] = '`'; hdr.ar_fmag[1] = '\n';
1210     for (i = 0; i < sizeof (struct ar_hdr); i++)
1211       if (((char *)(&hdr))[i] == '\0') (((char *)(&hdr))[i]) = ' ';
1212     bfd_write ((char *)&hdr, 1, sizeof (struct ar_hdr), arch);
1213     bfd_write (etable, 1, elength, arch);
1214     if ((elength % 2) == 1) bfd_write ("\n", 1, 1, arch);
1215
1216   }
1217
1218   for (current = arch->archive_head; current; current = current->next) {
1219     char buffer[DEFAULT_BUFFERSIZE];
1220     unsigned int remaining = arelt_size (current);
1221     struct ar_hdr *hdr = arch_hdr(current);
1222     /* write ar header */
1223
1224     if (bfd_write ((char *)hdr, 1, sizeof(*hdr), arch) != sizeof(*hdr)) {
1225     syserr:
1226         bfd_error = system_call_error;
1227         return false;
1228       }
1229     if (bfd_seek (current, (file_ptr) 0, SEEK_SET) != 0) goto syserr;
1230     while (remaining) 
1231         {
1232           unsigned int amt = DEFAULT_BUFFERSIZE;
1233           if (amt > remaining) {
1234             amt = remaining;
1235           }
1236           errno = 0;
1237           if (bfd_read (buffer, amt, 1, current) != amt) {
1238               if (errno) goto syserr;
1239               /* Looks like a truncated archive. */
1240               bfd_error = malformed_archive;
1241               return false;
1242           }
1243           if (bfd_write (buffer, amt, 1, arch)   != amt) goto syserr;
1244           remaining -= amt;
1245         }
1246     if ((arelt_size (current) % 2) == 1) bfd_write ("\n", 1, 1, arch);
1247   }
1248 return true;
1249 }
1250 \f
1251 /* Note that the namidx for the first symbol is 0 */
1252
1253 boolean
1254 compute_and_write_armap (arch, elength)
1255      bfd *arch;
1256      unsigned int elength;
1257 {
1258     bfd *current;
1259     file_ptr elt_no = 0;
1260     struct orl *map;
1261     int orl_max = 15000;        /* fine initial default */
1262     int orl_count = 0;
1263     int stridx = 0;             /* string index */
1264
1265     /* Dunno if this is the best place for this info... */
1266     if (elength != 0) elength += sizeof (struct ar_hdr);
1267     elength += elength %2 ;
1268
1269     map = (struct orl *) bfd_zalloc (arch,orl_max * sizeof (struct orl));
1270     if (map == NULL) {
1271             bfd_error = no_memory;
1272             return false;
1273         }
1274
1275     /* Drop all the files called __.SYMDEF, we're going to make our
1276        own */
1277     while (arch->archive_head   &&
1278            strcmp(arch->archive_head->filename,"__.SYMDEF") == 0) 
1279     {
1280         arch->archive_head = arch->archive_head->next;
1281     }
1282     /* Map over each element */
1283     for (current = arch->archive_head;
1284          current != (bfd *)NULL;
1285          current = current->next, elt_no++) 
1286     {
1287         if ((bfd_check_format (current, bfd_object) == true)
1288             && ((bfd_get_file_flags (current) & HAS_SYMS))) {
1289                 asymbol **syms;
1290                 unsigned int storage;
1291                 unsigned int symcount;
1292                 unsigned int src_count;
1293
1294                 storage = get_symtab_upper_bound (current);
1295                 if (storage != 0) {
1296
1297                         syms = (asymbol **) bfd_zalloc (arch,storage);
1298                         if (syms == NULL) {
1299                                 bfd_error = no_memory; /* FIXME -- memory leak */
1300                                 return false;
1301                             }
1302                         symcount = bfd_canonicalize_symtab (current, syms);
1303
1304
1305                         /* Now map over all the symbols, picking out the ones we want */
1306                         for (src_count = 0; src_count <symcount; src_count++) {
1307                                 flagword flags =
1308                                  (syms[src_count])->flags;
1309                                 asection  *sec =
1310                                  syms[src_count]->section;
1311                                 
1312                                 if ((flags & BSF_GLOBAL ||
1313                                     flags & BSF_INDIRECT ||
1314                                     sec == &bfd_com_section)
1315                                     && (sec != &bfd_und_section)) {
1316
1317                                         /* This symbol will go into the archive header */
1318                                         if (orl_count == orl_max) 
1319                                         {
1320                                             orl_max *= 2;
1321                                             map = (struct orl *) bfd_realloc (arch, (char *) map,
1322                                                                               orl_max * sizeof (struct orl));
1323                                         }
1324
1325                                         (map[orl_count]).name = (char **) &((syms[src_count])->name);
1326                                         (map[orl_count]).pos = (file_ptr) current;
1327                                         (map[orl_count]).namidx = stridx;
1328
1329                                         stridx += strlen ((syms[src_count])->name) + 1;
1330                                         ++orl_count;
1331                                     }
1332                             }
1333                     }
1334             }
1335     }
1336     /* OK, now we have collected all the data, let's write them out */
1337     if (!BFD_SEND (arch, write_armap,
1338                    (arch, elength, map, orl_count, stridx))) {
1339
1340             return false;
1341         }
1342
1343
1344     return true;
1345 }
1346
1347 boolean
1348 bsd_write_armap (arch, elength, map, orl_count, stridx)
1349      bfd *arch;
1350      unsigned int elength;
1351      struct orl *map;
1352      unsigned int orl_count;
1353      int stridx;
1354 {
1355   int padit = stridx & 1;
1356   unsigned int ranlibsize = orl_count * sizeof (struct ranlib);
1357   unsigned int stringsize = stridx + padit;
1358   /* Include 8 bytes to store ranlibsize and stringsize in output. */
1359   unsigned int mapsize = ranlibsize + stringsize + 8;
1360   file_ptr firstreal;
1361   bfd *current = arch->archive_head;
1362   bfd *last_elt = current;      /* last element arch seen */
1363   int temp;
1364   int count;
1365   struct ar_hdr hdr;
1366   struct stat statbuf;
1367   unsigned int i;
1368
1369   firstreal = mapsize + elength + sizeof (struct ar_hdr) + SARMAG;
1370
1371   stat (arch->filename, &statbuf);
1372   memset ((char *)(&hdr), 0, sizeof (struct ar_hdr));
1373   sprintf (hdr.ar_name, RANLIBMAG);
1374
1375   /* write the timestamp of the archive header to be just a little bit
1376      later than the timestamp of the file, otherwise the linker will
1377      complain that the index is out of date.
1378      */
1379
1380   sprintf (hdr.ar_date, "%ld", statbuf.st_mtime + 60);  
1381   sprintf (hdr.ar_uid, "%d", getuid());
1382   sprintf (hdr.ar_gid, "%d", getgid());
1383   sprintf (hdr.ar_size, "%-10d", (int) mapsize);
1384   hdr.ar_fmag[0] = '`'; hdr.ar_fmag[1] = '\n';
1385   for (i = 0; i < sizeof (struct ar_hdr); i++)
1386    if (((char *)(&hdr))[i] == '\0') (((char *)(&hdr))[i]) = ' ';
1387   bfd_write ((char *)&hdr, 1, sizeof (struct ar_hdr), arch);
1388   bfd_h_put_32(arch, ranlibsize, (PTR)&temp);
1389   bfd_write (&temp, 1, sizeof (temp), arch);
1390   
1391   for (count = 0; count < orl_count; count++) {
1392     struct symdef outs;
1393     struct symdef *outp = &outs;
1394     
1395     if (((bfd *)(map[count]).pos) != last_elt) {
1396       do {
1397         firstreal += arelt_size (current) + sizeof (struct ar_hdr);
1398         firstreal += firstreal % 2;
1399         current = current->next;
1400       } while (current != (bfd *)(map[count]).pos);
1401     }                           /* if new archive element */
1402
1403     last_elt = current;
1404     bfd_h_put_32(arch, ((map[count]).namidx),(PTR) &outs.s.string_offset);
1405     bfd_h_put_32(arch, firstreal,(PTR) &outs.file_offset);
1406     bfd_write ((char *)outp, 1, sizeof (outs), arch);
1407   }
1408
1409   /* now write the strings themselves */
1410   bfd_h_put_32(arch, stringsize, (PTR)&temp);
1411   bfd_write ((PTR)&temp, 1, sizeof (temp), arch);
1412   for (count = 0; count < orl_count; count++)
1413    bfd_write (*((map[count]).name), 1, strlen (*((map[count]).name))+1, arch);
1414
1415   /* The spec sez this should be a newline.  But in order to be
1416      bug-compatible for sun's ar we use a null. */
1417   if (padit)
1418    bfd_write("\0",1,1,arch);
1419
1420   return true;
1421 }
1422 \f
1423
1424 /* A coff armap looks like :
1425  lARMAG
1426  struct ar_hdr with name = '/' 
1427  number of symbols
1428  offset of file for symbol 0
1429  offset of file for symbol 1
1430
1431  offset of file for symbol n-1
1432  symbol name 0
1433  symbol name 1  
1434  
1435  symbol name n-1
1436
1437 */
1438
1439 boolean
1440 coff_write_armap (arch, elength, map, symbol_count, stridx)
1441      bfd *arch;
1442      unsigned int elength;
1443      struct orl *map;
1444      unsigned int symbol_count;
1445      int stridx;
1446 {
1447     /* The size of the ranlib is the number of exported symbols in the
1448        archive * the number of bytes in a int, + an int for the count */
1449
1450     unsigned int ranlibsize = (symbol_count * 4) + 4;
1451     unsigned int stringsize = stridx;
1452     unsigned int mapsize = stringsize + ranlibsize;
1453     file_ptr archive_member_file_ptr;
1454     bfd *current = arch->archive_head;
1455     int count;
1456     struct ar_hdr hdr;
1457     unsigned int i;
1458     int padit = mapsize & 1;
1459   
1460     if (padit) mapsize ++;
1461
1462     /* work out where the first object file will go in the archive */
1463     archive_member_file_ptr =   mapsize + elength + sizeof (struct ar_hdr) + SARMAG;
1464
1465     memset ((char *)(&hdr), 0, sizeof (struct ar_hdr));
1466     hdr.ar_name[0] = '/';
1467     sprintf (hdr.ar_size, "%-10d", (int) mapsize);
1468     sprintf (hdr.ar_date, "%ld", (long)time (NULL));
1469     /* This, at least, is what Intel coff sets the values to.: */
1470     sprintf ((hdr.ar_uid), "%d", 0);
1471     sprintf ((hdr.ar_gid), "%d", 0);
1472     sprintf ((hdr.ar_mode), "%-7o",(unsigned ) 0);
1473     hdr.ar_fmag[0] = '`'; hdr.ar_fmag[1] = '\n';
1474
1475     for (i = 0; i < sizeof (struct ar_hdr); i++)
1476      if (((char *)(&hdr))[i] == '\0') (((char *)(&hdr))[i]) = ' ';
1477
1478     /* Write the ar header for this item and the number of symbols */
1479
1480   
1481     bfd_write ((PTR)&hdr, 1, sizeof (struct ar_hdr), arch);
1482
1483     bfd_write_bigendian_4byte_int(arch, symbol_count);
1484
1485     /* Two passes, first write the file offsets for each symbol -
1486        remembering that each offset is on a two byte boundary.  */
1487
1488     /* Write out the file offset for the file associated with each
1489        symbol, and remember to keep the offsets padded out.  */
1490
1491     current = arch->archive_head;
1492     count = 0;
1493     while (current != (bfd *)NULL && count < symbol_count) {
1494         /* For each symbol which is used defined in this object, write out
1495            the object file's address in the archive */
1496     
1497         while (((bfd *)(map[count]).pos) == current) {
1498             bfd_write_bigendian_4byte_int(arch, archive_member_file_ptr);
1499             count++;
1500         }
1501         /* Add size of this archive entry */
1502         archive_member_file_ptr += arelt_size (current) + sizeof (struct
1503                                                                   ar_hdr);
1504         /* remember aboout the even alignment */
1505         archive_member_file_ptr += archive_member_file_ptr % 2;
1506         current = current->next;
1507     }  
1508
1509
1510
1511     /* now write the strings themselves */
1512     for (count = 0; count < symbol_count; count++) {
1513         bfd_write ((PTR)*((map[count]).name),
1514                    1,
1515                    strlen (*((map[count]).name))+1, arch);
1516
1517     }
1518     /* The spec sez this should be a newline.  But in order to be
1519        bug-compatible for arc960 we use a null. */
1520     if (padit)
1521      bfd_write("\0",1,1,arch);
1522
1523     return true;
1524 }