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