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