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