merge from gcc
[gdb/gnu.git] / bfd / archive.c
blob32b07a718a2b9825c41885572dbd544d6803c16f
1 /* BFD back-end for archive files (libraries).
2 Copyright 1990-2013 Free Software Foundation, Inc.
3 Written by Cygnus Support. Mostly Gumby Henkel-Wallace's fault.
5 This file is part of BFD, the Binary File Descriptor library.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */
22 @setfilename archive-info
23 SECTION
24 Archives
26 DESCRIPTION
27 An archive (or library) is just another BFD. It has a symbol
28 table, although there's not much a user program will do with it.
30 The big difference between an archive BFD and an ordinary BFD
31 is that the archive doesn't have sections. Instead it has a
32 chain of BFDs that are considered its contents. These BFDs can
33 be manipulated like any other. The BFDs contained in an
34 archive opened for reading will all be opened for reading. You
35 may put either input or output BFDs into an archive opened for
36 output; they will be handled correctly when the archive is closed.
38 Use <<bfd_openr_next_archived_file>> to step through
39 the contents of an archive opened for input. You don't
40 have to read the entire archive if you don't want
41 to! Read it until you find what you want.
43 A BFD returned by <<bfd_openr_next_archived_file>> can be
44 closed manually with <<bfd_close>>. If you do not close it,
45 then a second iteration through the members of an archive may
46 return the same BFD. If you close the archive BFD, then all
47 the member BFDs will automatically be closed as well.
49 Archive contents of output BFDs are chained through the
50 <<archive_next>> pointer in a BFD. The first one is findable
51 through the <<archive_head>> slot of the archive. Set it with
52 <<bfd_set_archive_head>> (q.v.). A given BFD may be in only
53 one open output archive at a time.
55 As expected, the BFD archive code is more general than the
56 archive code of any given environment. BFD archives may
57 contain files of different formats (e.g., a.out and coff) and
58 even different architectures. You may even place archives
59 recursively into archives!
61 This can cause unexpected confusion, since some archive
62 formats are more expressive than others. For instance, Intel
63 COFF archives can preserve long filenames; SunOS a.out archives
64 cannot. If you move a file from the first to the second
65 format and back again, the filename may be truncated.
66 Likewise, different a.out environments have different
67 conventions as to how they truncate filenames, whether they
68 preserve directory names in filenames, etc. When
69 interoperating with native tools, be sure your files are
70 homogeneous.
72 Beware: most of these formats do not react well to the
73 presence of spaces in filenames. We do the best we can, but
74 can't always handle this case due to restrictions in the format of
75 archives. Many Unix utilities are braindead in regards to
76 spaces and such in filenames anyway, so this shouldn't be much
77 of a restriction.
79 Archives are supported in BFD in <<archive.c>>.
81 SUBSECTION
82 Archive functions
85 /* Assumes:
86 o - all archive elements start on an even boundary, newline padded;
87 o - all arch headers are char *;
88 o - all arch headers are the same size (across architectures).
91 /* Some formats provide a way to cram a long filename into the short
92 (16 chars) space provided by a BSD archive. The trick is: make a
93 special "file" in the front of the archive, sort of like the SYMDEF
94 entry. If the filename is too long to fit, put it in the extended
95 name table, and use its index as the filename. To prevent
96 confusion prepend the index with a space. This means you can't
97 have filenames that start with a space, but then again, many Unix
98 utilities can't handle that anyway.
100 This scheme unfortunately requires that you stand on your head in
101 order to write an archive since you need to put a magic file at the
102 front, and need to touch every entry to do so. C'est la vie.
104 We support two variants of this idea:
105 The SVR4 format (extended name table is named "//"),
106 and an extended pseudo-BSD variant (extended name table is named
107 "ARFILENAMES/"). The origin of the latter format is uncertain.
109 BSD 4.4 uses a third scheme: It writes a long filename
110 directly after the header. This allows 'ar q' to work.
113 /* Summary of archive member names:
115 Symbol table (must be first):
116 "__.SYMDEF " - Symbol table, Berkeley style, produced by ranlib.
117 "/ " - Symbol table, system 5 style.
119 Long name table (must be before regular file members):
120 "// " - Long name table, System 5 R4 style.
121 "ARFILENAMES/ " - Long name table, non-standard extended BSD (not BSD 4.4).
123 Regular file members with short names:
124 "filename.o/ " - Regular file, System 5 style (embedded spaces ok).
125 "filename.o " - Regular file, Berkeley style (no embedded spaces).
127 Regular files with long names (or embedded spaces, for BSD variants):
128 "/18 " - SVR4 style, name at offset 18 in name table.
129 "#1/23 " - Long name (or embedded spaces) 23 characters long,
130 BSD 4.4 style, full name follows header.
131 " 18 " - Long name 18 characters long, extended pseudo-BSD.
134 #include "sysdep.h"
135 #include "bfd.h"
136 #include "libiberty.h"
137 #include "libbfd.h"
138 #include "aout/ar.h"
139 #include "aout/ranlib.h"
140 #include "safe-ctype.h"
141 #include "hashtab.h"
142 #include "filenames.h"
144 #ifndef errno
145 extern int errno;
146 #endif
148 /* We keep a cache of archive filepointers to archive elements to
149 speed up searching the archive by filepos. We only add an entry to
150 the cache when we actually read one. We also don't sort the cache;
151 it's generally short enough to search linearly.
152 Note that the pointers here point to the front of the ar_hdr, not
153 to the front of the contents! */
154 struct ar_cache
156 file_ptr ptr;
157 bfd *arbfd;
160 #define ar_padchar(abfd) ((abfd)->xvec->ar_pad_char)
161 #define ar_maxnamelen(abfd) ((abfd)->xvec->ar_max_namelen)
163 #define arch_eltdata(bfd) ((struct areltdata *) ((bfd)->arelt_data))
164 #define arch_hdr(bfd) ((struct ar_hdr *) arch_eltdata (bfd)->arch_header)
166 /* True iff NAME designated a BSD 4.4 extended name. */
168 #define is_bsd44_extended_name(NAME) \
169 (NAME[0] == '#' && NAME[1] == '1' && NAME[2] == '/' && ISDIGIT (NAME[3]))
171 void
172 _bfd_ar_spacepad (char *p, size_t n, const char *fmt, long val)
174 static char buf[20];
175 size_t len;
177 snprintf (buf, sizeof (buf), fmt, val);
178 len = strlen (buf);
179 if (len < n)
181 memcpy (p, buf, len);
182 memset (p + len, ' ', n - len);
184 else
185 memcpy (p, buf, n);
188 bfd_boolean
189 _bfd_ar_sizepad (char *p, size_t n, bfd_size_type size)
191 static char buf[21];
192 size_t len;
194 snprintf (buf, sizeof (buf), "%-10" BFD_VMA_FMT "u", size);
195 len = strlen (buf);
196 if (len > n)
198 bfd_set_error (bfd_error_file_too_big);
199 return FALSE;
201 if (len < n)
203 memcpy (p, buf, len);
204 memset (p + len, ' ', n - len);
206 else
207 memcpy (p, buf, n);
208 return TRUE;
211 bfd_boolean
212 _bfd_generic_mkarchive (bfd *abfd)
214 bfd_size_type amt = sizeof (struct artdata);
216 abfd->tdata.aout_ar_data = (struct artdata *) bfd_zalloc (abfd, amt);
217 if (bfd_ardata (abfd) == NULL)
218 return FALSE;
220 /* Already cleared by bfd_zalloc above.
221 bfd_ardata (abfd)->cache = NULL;
222 bfd_ardata (abfd)->archive_head = NULL;
223 bfd_ardata (abfd)->symdefs = NULL;
224 bfd_ardata (abfd)->extended_names = NULL;
225 bfd_ardata (abfd)->extended_names_size = 0;
226 bfd_ardata (abfd)->tdata = NULL; */
228 return TRUE;
232 FUNCTION
233 bfd_get_next_mapent
235 SYNOPSIS
236 symindex bfd_get_next_mapent
237 (bfd *abfd, symindex previous, carsym **sym);
239 DESCRIPTION
240 Step through archive @var{abfd}'s symbol table (if it
241 has one). Successively update @var{sym} with the next symbol's
242 information, returning that symbol's (internal) index into the
243 symbol table.
245 Supply <<BFD_NO_MORE_SYMBOLS>> as the @var{previous} entry to get
246 the first one; returns <<BFD_NO_MORE_SYMBOLS>> when you've already
247 got the last one.
249 A <<carsym>> is a canonical archive symbol. The only
250 user-visible element is its name, a null-terminated string.
253 symindex
254 bfd_get_next_mapent (bfd *abfd, symindex prev, carsym **entry)
256 if (!bfd_has_map (abfd))
258 bfd_set_error (bfd_error_invalid_operation);
259 return BFD_NO_MORE_SYMBOLS;
262 if (prev == BFD_NO_MORE_SYMBOLS)
263 prev = 0;
264 else
265 ++prev;
266 if (prev >= bfd_ardata (abfd)->symdef_count)
267 return BFD_NO_MORE_SYMBOLS;
269 *entry = (bfd_ardata (abfd)->symdefs + prev);
270 return prev;
273 /* To be called by backends only. */
275 bfd *
276 _bfd_create_empty_archive_element_shell (bfd *obfd)
278 return _bfd_new_bfd_contained_in (obfd);
282 FUNCTION
283 bfd_set_archive_head
285 SYNOPSIS
286 bfd_boolean bfd_set_archive_head (bfd *output, bfd *new_head);
288 DESCRIPTION
289 Set the head of the chain of
290 BFDs contained in the archive @var{output} to @var{new_head}.
293 bfd_boolean
294 bfd_set_archive_head (bfd *output_archive, bfd *new_head)
296 output_archive->archive_head = new_head;
297 return TRUE;
300 bfd *
301 _bfd_look_for_bfd_in_cache (bfd *arch_bfd, file_ptr filepos)
303 htab_t hash_table = bfd_ardata (arch_bfd)->cache;
304 struct ar_cache m;
306 m.ptr = filepos;
308 if (hash_table)
310 struct ar_cache *entry = (struct ar_cache *) htab_find (hash_table, &m);
311 if (!entry)
312 return NULL;
313 else
314 return entry->arbfd;
316 else
317 return NULL;
320 static hashval_t
321 hash_file_ptr (const void * p)
323 return (hashval_t) (((struct ar_cache *) p)->ptr);
326 /* Returns non-zero if P1 and P2 are equal. */
328 static int
329 eq_file_ptr (const void * p1, const void * p2)
331 struct ar_cache *arc1 = (struct ar_cache *) p1;
332 struct ar_cache *arc2 = (struct ar_cache *) p2;
333 return arc1->ptr == arc2->ptr;
336 /* The calloc function doesn't always take size_t (e.g. on VMS)
337 so wrap it to avoid a compile time warning. */
339 static void *
340 _bfd_calloc_wrapper (size_t a, size_t b)
342 return calloc (a, b);
345 /* Kind of stupid to call cons for each one, but we don't do too many. */
347 bfd_boolean
348 _bfd_add_bfd_to_archive_cache (bfd *arch_bfd, file_ptr filepos, bfd *new_elt)
350 struct ar_cache *cache;
351 htab_t hash_table = bfd_ardata (arch_bfd)->cache;
353 /* If the hash table hasn't been created, create it. */
354 if (hash_table == NULL)
356 hash_table = htab_create_alloc (16, hash_file_ptr, eq_file_ptr,
357 NULL, _bfd_calloc_wrapper, free);
358 if (hash_table == NULL)
359 return FALSE;
360 bfd_ardata (arch_bfd)->cache = hash_table;
363 /* Insert new_elt into the hash table by filepos. */
364 cache = (struct ar_cache *) bfd_zalloc (arch_bfd, sizeof (struct ar_cache));
365 cache->ptr = filepos;
366 cache->arbfd = new_elt;
367 *htab_find_slot (hash_table, (const void *) cache, INSERT) = cache;
369 /* Provide a means of accessing this from child. */
370 arch_eltdata (new_elt)->parent_cache = hash_table;
371 arch_eltdata (new_elt)->key = filepos;
373 return TRUE;
376 static bfd *
377 _bfd_find_nested_archive (bfd *arch_bfd, const char *filename)
379 bfd *abfd;
380 const char *target;
382 /* PR 15140: Don't allow a nested archive pointing to itself. */
383 if (filename_cmp (filename, arch_bfd->filename) == 0)
385 bfd_set_error (bfd_error_malformed_archive);
386 return NULL;
389 for (abfd = arch_bfd->nested_archives;
390 abfd != NULL;
391 abfd = abfd->archive_next)
393 if (filename_cmp (filename, abfd->filename) == 0)
394 return abfd;
396 target = NULL;
397 if (!arch_bfd->target_defaulted)
398 target = arch_bfd->xvec->name;
399 abfd = bfd_openr (filename, target);
400 if (abfd)
402 abfd->archive_next = arch_bfd->nested_archives;
403 arch_bfd->nested_archives = abfd;
405 return abfd;
408 /* The name begins with space. Hence the rest of the name is an index into
409 the string table. */
411 static char *
412 get_extended_arelt_filename (bfd *arch, const char *name, file_ptr *originp)
414 unsigned long table_index = 0;
415 const char *endp;
417 /* Should extract string so that I can guarantee not to overflow into
418 the next region, but I'm too lazy. */
419 errno = 0;
420 /* Skip first char, which is '/' in SVR4 or ' ' in some other variants. */
421 table_index = strtol (name + 1, (char **) &endp, 10);
422 if (errno != 0 || table_index >= bfd_ardata (arch)->extended_names_size)
424 bfd_set_error (bfd_error_malformed_archive);
425 return NULL;
427 /* In a thin archive, a member of an archive-within-an-archive
428 will have the offset in the inner archive encoded here. */
429 if (bfd_is_thin_archive (arch) && endp != NULL && *endp == ':')
431 file_ptr origin = strtol (endp + 1, NULL, 10);
433 if (errno != 0)
435 bfd_set_error (bfd_error_malformed_archive);
436 return NULL;
438 *originp = origin;
440 else
441 *originp = 0;
443 return bfd_ardata (arch)->extended_names + table_index;
446 /* This functions reads an arch header and returns an areltdata pointer, or
447 NULL on error.
449 Presumes the file pointer is already in the right place (ie pointing
450 to the ar_hdr in the file). Moves the file pointer; on success it
451 should be pointing to the front of the file contents; on failure it
452 could have been moved arbitrarily. */
454 void *
455 _bfd_generic_read_ar_hdr (bfd *abfd)
457 return _bfd_generic_read_ar_hdr_mag (abfd, NULL);
460 /* Alpha ECOFF uses an optional different ARFMAG value, so we have a
461 variant of _bfd_generic_read_ar_hdr which accepts a magic string. */
463 void *
464 _bfd_generic_read_ar_hdr_mag (bfd *abfd, const char *mag)
466 struct ar_hdr hdr;
467 char *hdrp = (char *) &hdr;
468 bfd_size_type parsed_size;
469 struct areltdata *ared;
470 char *filename = NULL;
471 bfd_size_type namelen = 0;
472 bfd_size_type allocsize = sizeof (struct areltdata) + sizeof (struct ar_hdr);
473 char *allocptr = 0;
474 file_ptr origin = 0;
475 unsigned int extra_size = 0;
476 char fmag_save;
477 int scan;
479 if (bfd_bread (hdrp, sizeof (struct ar_hdr), abfd) != sizeof (struct ar_hdr))
481 if (bfd_get_error () != bfd_error_system_call)
482 bfd_set_error (bfd_error_no_more_archived_files);
483 return NULL;
485 if (strncmp (hdr.ar_fmag, ARFMAG, 2) != 0
486 && (mag == NULL
487 || strncmp (hdr.ar_fmag, mag, 2) != 0))
489 bfd_set_error (bfd_error_malformed_archive);
490 return NULL;
493 errno = 0;
494 fmag_save = hdr.ar_fmag[0];
495 hdr.ar_fmag[0] = 0;
496 scan = sscanf (hdr.ar_size, "%" BFD_VMA_FMT "u", &parsed_size);
497 hdr.ar_fmag[0] = fmag_save;
498 if (scan != 1)
500 bfd_set_error (bfd_error_malformed_archive);
501 return NULL;
504 /* Extract the filename from the archive - there are two ways to
505 specify an extended name table, either the first char of the
506 name is a space, or it's a slash. */
507 if ((hdr.ar_name[0] == '/'
508 || (hdr.ar_name[0] == ' '
509 && memchr (hdr.ar_name, '/', ar_maxnamelen (abfd)) == NULL))
510 && bfd_ardata (abfd)->extended_names != NULL)
512 filename = get_extended_arelt_filename (abfd, hdr.ar_name, &origin);
513 if (filename == NULL)
514 return NULL;
516 /* BSD4.4-style long filename. */
517 else if (is_bsd44_extended_name (hdr.ar_name))
519 /* BSD-4.4 extended name */
520 namelen = atoi (&hdr.ar_name[3]);
521 allocsize += namelen + 1;
522 parsed_size -= namelen;
523 extra_size = namelen;
525 allocptr = (char *) bfd_zmalloc (allocsize);
526 if (allocptr == NULL)
527 return NULL;
528 filename = (allocptr
529 + sizeof (struct areltdata)
530 + sizeof (struct ar_hdr));
531 if (bfd_bread (filename, namelen, abfd) != namelen)
533 free (allocptr);
534 if (bfd_get_error () != bfd_error_system_call)
535 bfd_set_error (bfd_error_no_more_archived_files);
536 return NULL;
538 filename[namelen] = '\0';
540 else
542 /* We judge the end of the name by looking for '/' or ' '.
543 Note: The SYSV format (terminated by '/') allows embedded
544 spaces, so only look for ' ' if we don't find '/'. */
546 char *e;
547 e = (char *) memchr (hdr.ar_name, '\0', ar_maxnamelen (abfd));
548 if (e == NULL)
550 e = (char *) memchr (hdr.ar_name, '/', ar_maxnamelen (abfd));
551 if (e == NULL)
552 e = (char *) memchr (hdr.ar_name, ' ', ar_maxnamelen (abfd));
555 if (e != NULL)
556 namelen = e - hdr.ar_name;
557 else
559 /* If we didn't find a termination character, then the name
560 must be the entire field. */
561 namelen = ar_maxnamelen (abfd);
564 allocsize += namelen + 1;
567 if (!allocptr)
569 allocptr = (char *) bfd_zmalloc (allocsize);
570 if (allocptr == NULL)
571 return NULL;
574 ared = (struct areltdata *) allocptr;
576 ared->arch_header = allocptr + sizeof (struct areltdata);
577 memcpy (ared->arch_header, &hdr, sizeof (struct ar_hdr));
578 ared->parsed_size = parsed_size;
579 ared->extra_size = extra_size;
580 ared->origin = origin;
582 if (filename != NULL)
583 ared->filename = filename;
584 else
586 ared->filename = allocptr + (sizeof (struct areltdata) +
587 sizeof (struct ar_hdr));
588 if (namelen)
589 memcpy (ared->filename, hdr.ar_name, namelen);
590 ared->filename[namelen] = '\0';
593 return ared;
596 /* Append the relative pathname for a member of the thin archive
597 to the pathname of the directory containing the archive. */
599 char *
600 _bfd_append_relative_path (bfd *arch, char *elt_name)
602 const char *arch_name = arch->filename;
603 const char *base_name = lbasename (arch_name);
604 size_t prefix_len;
605 char *filename;
607 if (base_name == arch_name)
608 return elt_name;
610 prefix_len = base_name - arch_name;
611 filename = (char *) bfd_alloc (arch, prefix_len + strlen (elt_name) + 1);
612 if (filename == NULL)
613 return NULL;
615 strncpy (filename, arch_name, prefix_len);
616 strcpy (filename + prefix_len, elt_name);
617 return filename;
620 /* This is an internal function; it's mainly used when indexing
621 through the archive symbol table, but also used to get the next
622 element, since it handles the bookkeeping so nicely for us. */
624 bfd *
625 _bfd_get_elt_at_filepos (bfd *archive, file_ptr filepos)
627 struct areltdata *new_areldata;
628 bfd *n_nfd;
629 char *filename;
631 n_nfd = _bfd_look_for_bfd_in_cache (archive, filepos);
632 if (n_nfd)
633 return n_nfd;
635 if (0 > bfd_seek (archive, filepos, SEEK_SET))
636 return NULL;
638 if ((new_areldata = (struct areltdata *) _bfd_read_ar_hdr (archive)) == NULL)
639 return NULL;
641 filename = new_areldata->filename;
643 if (bfd_is_thin_archive (archive))
645 const char *target;
647 /* This is a proxy entry for an external file. */
648 if (! IS_ABSOLUTE_PATH (filename))
650 filename = _bfd_append_relative_path (archive, filename);
651 if (filename == NULL)
653 free (new_areldata);
654 return NULL;
658 if (new_areldata->origin > 0)
660 /* This proxy entry refers to an element of a nested archive.
661 Locate the member of that archive and return a bfd for it. */
662 bfd *ext_arch = _bfd_find_nested_archive (archive, filename);
664 if (ext_arch == NULL
665 || ! bfd_check_format (ext_arch, bfd_archive))
667 free (new_areldata);
668 return NULL;
670 n_nfd = _bfd_get_elt_at_filepos (ext_arch, new_areldata->origin);
671 if (n_nfd == NULL)
673 free (new_areldata);
674 return NULL;
676 n_nfd->proxy_origin = bfd_tell (archive);
677 return n_nfd;
679 /* It's not an element of a nested archive;
680 open the external file as a bfd. */
681 target = NULL;
682 if (!archive->target_defaulted)
683 target = archive->xvec->name;
684 n_nfd = bfd_openr (filename, target);
685 if (n_nfd == NULL)
686 bfd_set_error (bfd_error_malformed_archive);
688 else
690 n_nfd = _bfd_create_empty_archive_element_shell (archive);
693 if (n_nfd == NULL)
695 free (new_areldata);
696 return NULL;
699 n_nfd->proxy_origin = bfd_tell (archive);
701 if (bfd_is_thin_archive (archive))
703 n_nfd->origin = 0;
705 else
707 n_nfd->origin = n_nfd->proxy_origin;
708 n_nfd->filename = filename;
711 n_nfd->arelt_data = new_areldata;
713 /* Copy BFD_COMPRESS and BFD_DECOMPRESS flags. */
714 n_nfd->flags |= archive->flags & (BFD_COMPRESS | BFD_DECOMPRESS);
716 if (_bfd_add_bfd_to_archive_cache (archive, filepos, n_nfd))
717 return n_nfd;
719 free (new_areldata);
720 n_nfd->arelt_data = NULL;
721 return NULL;
724 /* Return the BFD which is referenced by the symbol in ABFD indexed by
725 SYM_INDEX. SYM_INDEX should have been returned by bfd_get_next_mapent. */
727 bfd *
728 _bfd_generic_get_elt_at_index (bfd *abfd, symindex sym_index)
730 carsym *entry;
732 entry = bfd_ardata (abfd)->symdefs + sym_index;
733 return _bfd_get_elt_at_filepos (abfd, entry->file_offset);
737 FUNCTION
738 bfd_openr_next_archived_file
740 SYNOPSIS
741 bfd *bfd_openr_next_archived_file (bfd *archive, bfd *previous);
743 DESCRIPTION
744 Provided a BFD, @var{archive}, containing an archive and NULL, open
745 an input BFD on the first contained element and returns that.
746 Subsequent calls should pass
747 the archive and the previous return value to return a created
748 BFD to the next contained element. NULL is returned when there
749 are no more.
752 bfd *
753 bfd_openr_next_archived_file (bfd *archive, bfd *last_file)
755 if ((bfd_get_format (archive) != bfd_archive)
756 || (archive->direction == write_direction))
758 bfd_set_error (bfd_error_invalid_operation);
759 return NULL;
762 return BFD_SEND (archive,
763 openr_next_archived_file, (archive, last_file));
766 bfd *
767 bfd_generic_openr_next_archived_file (bfd *archive, bfd *last_file)
769 file_ptr filestart;
771 if (!last_file)
772 filestart = bfd_ardata (archive)->first_file_filepos;
773 else
775 bfd_size_type size = arelt_size (last_file);
777 filestart = last_file->proxy_origin;
778 if (! bfd_is_thin_archive (archive))
779 filestart += size;
780 /* Pad to an even boundary...
781 Note that last_file->origin can be odd in the case of
782 BSD-4.4-style element with a long odd size. */
783 filestart += filestart % 2;
786 return _bfd_get_elt_at_filepos (archive, filestart);
789 const bfd_target *
790 bfd_generic_archive_p (bfd *abfd)
792 struct artdata *tdata_hold;
793 char armag[SARMAG + 1];
794 bfd_size_type amt;
796 if (bfd_bread (armag, SARMAG, abfd) != SARMAG)
798 if (bfd_get_error () != bfd_error_system_call)
799 bfd_set_error (bfd_error_wrong_format);
800 return NULL;
803 bfd_is_thin_archive (abfd) = (strncmp (armag, ARMAGT, SARMAG) == 0);
805 if (strncmp (armag, ARMAG, SARMAG) != 0
806 && strncmp (armag, ARMAGB, SARMAG) != 0
807 && ! bfd_is_thin_archive (abfd))
808 return NULL;
810 tdata_hold = bfd_ardata (abfd);
812 amt = sizeof (struct artdata);
813 bfd_ardata (abfd) = (struct artdata *) bfd_zalloc (abfd, amt);
814 if (bfd_ardata (abfd) == NULL)
816 bfd_ardata (abfd) = tdata_hold;
817 return NULL;
820 bfd_ardata (abfd)->first_file_filepos = SARMAG;
821 /* Cleared by bfd_zalloc above.
822 bfd_ardata (abfd)->cache = NULL;
823 bfd_ardata (abfd)->archive_head = NULL;
824 bfd_ardata (abfd)->symdefs = NULL;
825 bfd_ardata (abfd)->extended_names = NULL;
826 bfd_ardata (abfd)->extended_names_size = 0;
827 bfd_ardata (abfd)->tdata = NULL; */
829 if (!BFD_SEND (abfd, _bfd_slurp_armap, (abfd))
830 || !BFD_SEND (abfd, _bfd_slurp_extended_name_table, (abfd)))
832 if (bfd_get_error () != bfd_error_system_call)
833 bfd_set_error (bfd_error_wrong_format);
834 bfd_release (abfd, bfd_ardata (abfd));
835 bfd_ardata (abfd) = tdata_hold;
836 return NULL;
839 if (abfd->target_defaulted && bfd_has_map (abfd))
841 bfd *first;
843 /* This archive has a map, so we may presume that the contents
844 are object files. Make sure that if the first file in the
845 archive can be recognized as an object file, it is for this
846 target. If not, assume that this is the wrong format. If
847 the first file is not an object file, somebody is doing
848 something weird, and we permit it so that ar -t will work.
850 This is done because any normal format will recognize any
851 normal archive, regardless of the format of the object files.
852 We do accept an empty archive. */
854 first = bfd_openr_next_archived_file (abfd, NULL);
855 if (first != NULL)
857 first->target_defaulted = FALSE;
858 if (bfd_check_format (first, bfd_object)
859 && first->xvec != abfd->xvec)
860 bfd_set_error (bfd_error_wrong_object_format);
861 /* And we ought to close `first' here too. */
865 return abfd->xvec;
868 /* Some constants for a 32 bit BSD archive structure. We do not
869 support 64 bit archives presently; so far as I know, none actually
870 exist. Supporting them would require changing these constants, and
871 changing some H_GET_32 to H_GET_64. */
873 /* The size of an external symdef structure. */
874 #define BSD_SYMDEF_SIZE 8
876 /* The offset from the start of a symdef structure to the file offset. */
877 #define BSD_SYMDEF_OFFSET_SIZE 4
879 /* The size of the symdef count. */
880 #define BSD_SYMDEF_COUNT_SIZE 4
882 /* The size of the string count. */
883 #define BSD_STRING_COUNT_SIZE 4
885 /* Read a BSD-style archive symbol table. Returns FALSE on error,
886 TRUE otherwise. */
888 static bfd_boolean
889 do_slurp_bsd_armap (bfd *abfd)
891 struct areltdata *mapdata;
892 unsigned int counter;
893 bfd_byte *raw_armap, *rbase;
894 struct artdata *ardata = bfd_ardata (abfd);
895 char *stringbase;
896 bfd_size_type parsed_size, amt;
897 carsym *set;
899 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
900 if (mapdata == NULL)
901 return FALSE;
902 parsed_size = mapdata->parsed_size;
903 free (mapdata);
905 raw_armap = (bfd_byte *) bfd_zalloc (abfd, parsed_size);
906 if (raw_armap == NULL)
907 return FALSE;
909 if (bfd_bread (raw_armap, parsed_size, abfd) != parsed_size)
911 if (bfd_get_error () != bfd_error_system_call)
912 bfd_set_error (bfd_error_malformed_archive);
913 byebye:
914 bfd_release (abfd, raw_armap);
915 return FALSE;
918 ardata->symdef_count = H_GET_32 (abfd, raw_armap) / BSD_SYMDEF_SIZE;
920 if (ardata->symdef_count * BSD_SYMDEF_SIZE >
921 parsed_size - BSD_SYMDEF_COUNT_SIZE)
923 /* Probably we're using the wrong byte ordering. */
924 bfd_set_error (bfd_error_wrong_format);
925 goto byebye;
928 ardata->cache = 0;
929 rbase = raw_armap + BSD_SYMDEF_COUNT_SIZE;
930 stringbase = ((char *) rbase
931 + ardata->symdef_count * BSD_SYMDEF_SIZE
932 + BSD_STRING_COUNT_SIZE);
933 amt = ardata->symdef_count * sizeof (carsym);
934 ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
935 if (!ardata->symdefs)
936 return FALSE;
938 for (counter = 0, set = ardata->symdefs;
939 counter < ardata->symdef_count;
940 counter++, set++, rbase += BSD_SYMDEF_SIZE)
942 set->name = H_GET_32 (abfd, rbase) + stringbase;
943 set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
946 ardata->first_file_filepos = bfd_tell (abfd);
947 /* Pad to an even boundary if you have to. */
948 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
949 /* FIXME, we should provide some way to free raw_ardata when
950 we are done using the strings from it. For now, it seems
951 to be allocated on an objalloc anyway... */
952 bfd_has_map (abfd) = TRUE;
953 return TRUE;
956 /* Read a COFF archive symbol table. Returns FALSE on error, TRUE
957 otherwise. */
959 static bfd_boolean
960 do_slurp_coff_armap (bfd *abfd)
962 struct areltdata *mapdata;
963 int *raw_armap, *rawptr;
964 struct artdata *ardata = bfd_ardata (abfd);
965 char *stringbase;
966 bfd_size_type stringsize;
967 bfd_size_type parsed_size;
968 carsym *carsyms;
969 bfd_size_type nsymz; /* Number of symbols in armap. */
970 bfd_vma (*swap) (const void *);
971 char int_buf[sizeof (long)];
972 bfd_size_type carsym_size, ptrsize;
973 unsigned int i;
975 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
976 if (mapdata == NULL)
977 return FALSE;
978 parsed_size = mapdata->parsed_size;
979 free (mapdata);
981 if (bfd_bread (int_buf, 4, abfd) != 4)
983 if (bfd_get_error () != bfd_error_system_call)
984 bfd_set_error (bfd_error_malformed_archive);
985 return FALSE;
987 /* It seems that all numeric information in a coff archive is always
988 in big endian format, nomatter the host or target. */
989 swap = bfd_getb32;
990 nsymz = bfd_getb32 (int_buf);
991 stringsize = parsed_size - (4 * nsymz) - 4;
993 /* ... except that some archive formats are broken, and it may be our
994 fault - the i960 little endian coff sometimes has big and sometimes
995 little, because our tools changed. Here's a horrible hack to clean
996 up the crap. */
998 if (stringsize > 0xfffff
999 && bfd_get_arch (abfd) == bfd_arch_i960
1000 && bfd_get_flavour (abfd) == bfd_target_coff_flavour)
1002 /* This looks dangerous, let's do it the other way around. */
1003 nsymz = bfd_getl32 (int_buf);
1004 stringsize = parsed_size - (4 * nsymz) - 4;
1005 swap = bfd_getl32;
1008 /* The coff armap must be read sequentially. So we construct a
1009 bsd-style one in core all at once, for simplicity. */
1011 if (nsymz > ~ (bfd_size_type) 0 / sizeof (carsym))
1012 return FALSE;
1014 carsym_size = (nsymz * sizeof (carsym));
1015 ptrsize = (4 * nsymz);
1017 if (carsym_size + stringsize + 1 <= carsym_size)
1018 return FALSE;
1020 ardata->symdefs = (struct carsym *) bfd_zalloc (abfd,
1021 carsym_size + stringsize + 1);
1022 if (ardata->symdefs == NULL)
1023 return FALSE;
1024 carsyms = ardata->symdefs;
1025 stringbase = ((char *) ardata->symdefs) + carsym_size;
1027 /* Allocate and read in the raw offsets. */
1028 raw_armap = (int *) bfd_alloc (abfd, ptrsize);
1029 if (raw_armap == NULL)
1030 goto release_symdefs;
1031 if (bfd_bread (raw_armap, ptrsize, abfd) != ptrsize
1032 || (bfd_bread (stringbase, stringsize, abfd) != stringsize))
1034 if (bfd_get_error () != bfd_error_system_call)
1035 bfd_set_error (bfd_error_malformed_archive);
1036 goto release_raw_armap;
1039 /* OK, build the carsyms. */
1040 for (i = 0; i < nsymz; i++)
1042 rawptr = raw_armap + i;
1043 carsyms->file_offset = swap ((bfd_byte *) rawptr);
1044 carsyms->name = stringbase;
1045 stringbase += strlen (stringbase) + 1;
1046 carsyms++;
1048 *stringbase = 0;
1050 ardata->symdef_count = nsymz;
1051 ardata->first_file_filepos = bfd_tell (abfd);
1052 /* Pad to an even boundary if you have to. */
1053 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1055 bfd_has_map (abfd) = TRUE;
1056 bfd_release (abfd, raw_armap);
1058 /* Check for a second archive header (as used by PE). */
1060 struct areltdata *tmp;
1062 bfd_seek (abfd, ardata->first_file_filepos, SEEK_SET);
1063 tmp = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1064 if (tmp != NULL)
1066 if (tmp->arch_header[0] == '/'
1067 && tmp->arch_header[1] == ' ')
1069 ardata->first_file_filepos +=
1070 (tmp->parsed_size + sizeof (struct ar_hdr) + 1) & ~(unsigned) 1;
1072 free (tmp);
1076 return TRUE;
1078 release_raw_armap:
1079 bfd_release (abfd, raw_armap);
1080 release_symdefs:
1081 bfd_release (abfd, (ardata)->symdefs);
1082 return FALSE;
1085 /* This routine can handle either coff-style or bsd-style armaps
1086 (archive symbol table). Returns FALSE on error, TRUE otherwise */
1088 bfd_boolean
1089 bfd_slurp_armap (bfd *abfd)
1091 char nextname[17];
1092 int i = bfd_bread (nextname, 16, abfd);
1094 if (i == 0)
1095 return TRUE;
1096 if (i != 16)
1097 return FALSE;
1099 if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
1100 return FALSE;
1102 if (CONST_STRNEQ (nextname, "__.SYMDEF ")
1103 || CONST_STRNEQ (nextname, "__.SYMDEF/ ")) /* Old Linux archives. */
1104 return do_slurp_bsd_armap (abfd);
1105 else if (CONST_STRNEQ (nextname, "/ "))
1106 return do_slurp_coff_armap (abfd);
1107 else if (CONST_STRNEQ (nextname, "/SYM64/ "))
1109 /* 64bit ELF (Irix 6) archive. */
1110 #ifdef BFD64
1111 extern bfd_boolean bfd_elf64_archive_slurp_armap (bfd *);
1112 return bfd_elf64_archive_slurp_armap (abfd);
1113 #else
1114 bfd_set_error (bfd_error_wrong_format);
1115 return FALSE;
1116 #endif
1118 else if (CONST_STRNEQ (nextname, "#1/20 "))
1120 /* Mach-O has a special name for armap when the map is sorted by name.
1121 However because this name has a space it is slightly more difficult
1122 to check it. */
1123 struct ar_hdr hdr;
1124 char extname[21];
1126 if (bfd_bread (&hdr, sizeof (hdr), abfd) != sizeof (hdr))
1127 return FALSE;
1128 /* Read the extended name. We know its length. */
1129 if (bfd_bread (extname, 20, abfd) != 20)
1130 return FALSE;
1131 if (bfd_seek (abfd, -(file_ptr) (sizeof (hdr) + 20), SEEK_CUR) != 0)
1132 return FALSE;
1133 if (CONST_STRNEQ (extname, "__.SYMDEF SORTED")
1134 || CONST_STRNEQ (extname, "__.SYMDEF"))
1135 return do_slurp_bsd_armap (abfd);
1138 bfd_has_map (abfd) = FALSE;
1139 return TRUE;
1142 /* Returns FALSE on error, TRUE otherwise. */
1143 /* Flavor 2 of a bsd armap, similar to bfd_slurp_bsd_armap except the
1144 header is in a slightly different order and the map name is '/'.
1145 This flavour is used by hp300hpux. */
1147 #define HPUX_SYMDEF_COUNT_SIZE 2
1149 bfd_boolean
1150 bfd_slurp_bsd_armap_f2 (bfd *abfd)
1152 struct areltdata *mapdata;
1153 char nextname[17];
1154 unsigned int counter;
1155 bfd_byte *raw_armap, *rbase;
1156 struct artdata *ardata = bfd_ardata (abfd);
1157 char *stringbase;
1158 unsigned int stringsize;
1159 unsigned int left;
1160 bfd_size_type amt;
1161 carsym *set;
1162 int i = bfd_bread (nextname, 16, abfd);
1164 if (i == 0)
1165 return TRUE;
1166 if (i != 16)
1167 return FALSE;
1169 /* The archive has at least 16 bytes in it. */
1170 if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
1171 return FALSE;
1173 if (CONST_STRNEQ (nextname, "__.SYMDEF ")
1174 || CONST_STRNEQ (nextname, "__.SYMDEF/ ")) /* Old Linux archives. */
1175 return do_slurp_bsd_armap (abfd);
1177 if (! CONST_STRNEQ (nextname, "/ "))
1179 bfd_has_map (abfd) = FALSE;
1180 return TRUE;
1183 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1184 if (mapdata == NULL)
1185 return FALSE;
1187 if (mapdata->parsed_size < HPUX_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE)
1189 free (mapdata);
1190 wrong_format:
1191 bfd_set_error (bfd_error_wrong_format);
1192 byebye:
1193 return FALSE;
1195 left = mapdata->parsed_size - HPUX_SYMDEF_COUNT_SIZE - BSD_STRING_COUNT_SIZE;
1197 amt = mapdata->parsed_size;
1198 free (mapdata);
1200 raw_armap = (bfd_byte *) bfd_zalloc (abfd, amt);
1201 if (raw_armap == NULL)
1202 goto byebye;
1204 if (bfd_bread (raw_armap, amt, abfd) != amt)
1206 if (bfd_get_error () != bfd_error_system_call)
1207 bfd_set_error (bfd_error_malformed_archive);
1208 goto byebye;
1211 ardata->symdef_count = H_GET_16 (abfd, raw_armap);
1213 ardata->cache = 0;
1215 stringsize = H_GET_32 (abfd, raw_armap + HPUX_SYMDEF_COUNT_SIZE);
1216 if (stringsize > left)
1217 goto wrong_format;
1218 left -= stringsize;
1220 /* Skip sym count and string sz. */
1221 stringbase = ((char *) raw_armap
1222 + HPUX_SYMDEF_COUNT_SIZE
1223 + BSD_STRING_COUNT_SIZE);
1224 rbase = (bfd_byte *) stringbase + stringsize;
1225 amt = ardata->symdef_count * BSD_SYMDEF_SIZE;
1226 if (amt > left)
1227 goto wrong_format;
1229 ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
1230 if (!ardata->symdefs)
1231 return FALSE;
1233 for (counter = 0, set = ardata->symdefs;
1234 counter < ardata->symdef_count;
1235 counter++, set++, rbase += BSD_SYMDEF_SIZE)
1237 set->name = H_GET_32 (abfd, rbase) + stringbase;
1238 set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
1241 ardata->first_file_filepos = bfd_tell (abfd);
1242 /* Pad to an even boundary if you have to. */
1243 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1244 /* FIXME, we should provide some way to free raw_ardata when
1245 we are done using the strings from it. For now, it seems
1246 to be allocated on an objalloc anyway... */
1247 bfd_has_map (abfd) = TRUE;
1248 return TRUE;
1251 /** Extended name table.
1253 Normally archives support only 14-character filenames.
1255 Intel has extended the format: longer names are stored in a special
1256 element (the first in the archive, or second if there is an armap);
1257 the name in the ar_hdr is replaced by <space><index into filename
1258 element>. Index is the P.R. of an int (decimal). Data General have
1259 extended the format by using the prefix // for the special element. */
1261 /* Returns FALSE on error, TRUE otherwise. */
1263 bfd_boolean
1264 _bfd_slurp_extended_name_table (bfd *abfd)
1266 char nextname[17];
1267 struct areltdata *namedata;
1268 bfd_size_type amt;
1270 /* FIXME: Formatting sucks here, and in case of failure of BFD_READ,
1271 we probably don't want to return TRUE. */
1272 if (bfd_seek (abfd, bfd_ardata (abfd)->first_file_filepos, SEEK_SET) != 0)
1273 return FALSE;
1275 if (bfd_bread (nextname, 16, abfd) == 16)
1277 if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
1278 return FALSE;
1280 if (! CONST_STRNEQ (nextname, "ARFILENAMES/ ")
1281 && ! CONST_STRNEQ (nextname, "// "))
1283 bfd_ardata (abfd)->extended_names = NULL;
1284 bfd_ardata (abfd)->extended_names_size = 0;
1285 return TRUE;
1288 namedata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1289 if (namedata == NULL)
1290 return FALSE;
1292 amt = namedata->parsed_size;
1293 if (amt + 1 == 0)
1294 goto byebye;
1296 bfd_ardata (abfd)->extended_names_size = amt;
1297 bfd_ardata (abfd)->extended_names = (char *) bfd_zalloc (abfd, amt + 1);
1298 if (bfd_ardata (abfd)->extended_names == NULL)
1300 byebye:
1301 free (namedata);
1302 return FALSE;
1305 if (bfd_bread (bfd_ardata (abfd)->extended_names, amt, abfd) != amt)
1307 if (bfd_get_error () != bfd_error_system_call)
1308 bfd_set_error (bfd_error_malformed_archive);
1309 bfd_release (abfd, (bfd_ardata (abfd)->extended_names));
1310 bfd_ardata (abfd)->extended_names = NULL;
1311 goto byebye;
1314 /* Since the archive is supposed to be printable if it contains
1315 text, the entries in the list are newline-padded, not null
1316 padded. In SVR4-style archives, the names also have a
1317 trailing '/'. DOS/NT created archive often have \ in them
1318 We'll fix all problems here.. */
1320 char *ext_names = bfd_ardata (abfd)->extended_names;
1321 char *temp = ext_names;
1322 char *limit = temp + namedata->parsed_size;
1323 for (; temp < limit; ++temp)
1325 if (*temp == ARFMAG[1])
1326 temp[temp > ext_names && temp[-1] == '/' ? -1 : 0] = '\0';
1327 if (*temp == '\\')
1328 *temp = '/';
1330 *limit = '\0';
1333 /* Pad to an even boundary if you have to. */
1334 bfd_ardata (abfd)->first_file_filepos = bfd_tell (abfd);
1335 bfd_ardata (abfd)->first_file_filepos +=
1336 (bfd_ardata (abfd)->first_file_filepos) % 2;
1338 free (namedata);
1340 return TRUE;
1343 #ifdef VMS
1345 /* Return a copy of the stuff in the filename between any :]> and a
1346 semicolon. */
1348 static const char *
1349 normalize (bfd *abfd, const char *file)
1351 const char *first;
1352 const char *last;
1353 char *copy;
1355 first = file + strlen (file) - 1;
1356 last = first + 1;
1358 while (first != file)
1360 if (*first == ';')
1361 last = first;
1362 if (*first == ':' || *first == ']' || *first == '>')
1364 first++;
1365 break;
1367 first--;
1370 copy = bfd_alloc (abfd, last - first + 1);
1371 if (copy == NULL)
1372 return NULL;
1374 memcpy (copy, first, last - first);
1375 copy[last - first] = 0;
1377 return copy;
1380 #else
1381 static const char *
1382 normalize (bfd *abfd ATTRIBUTE_UNUSED, const char *file)
1384 return lbasename (file);
1386 #endif
1388 /* Adjust a relative path name based on the reference path.
1389 For example:
1391 Relative path Reference path Result
1392 ------------- -------------- ------
1393 bar.o lib.a bar.o
1394 foo/bar.o lib.a foo/bar.o
1395 bar.o foo/lib.a ../bar.o
1396 foo/bar.o baz/lib.a ../foo/bar.o
1397 bar.o ../lib.a <parent of current dir>/bar.o
1398 ; ../bar.o ../lib.a bar.o
1399 ; ../bar.o lib.a ../bar.o
1400 foo/bar.o ../lib.a <parent of current dir>/foo/bar.o
1401 bar.o ../../lib.a <grandparent>/<parent>/bar.o
1402 bar.o foo/baz/lib.a ../../bar.o
1404 Note - the semicolons above are there to prevent the BFD chew
1405 utility from interpreting those lines as prototypes to put into
1406 the autogenerated bfd.h header...
1408 Note - the string is returned in a static buffer. */
1410 static const char *
1411 adjust_relative_path (const char * path, const char * ref_path)
1413 static char *pathbuf = NULL;
1414 static unsigned int pathbuf_len = 0;
1415 const char *pathp;
1416 const char *refp;
1417 char * lpath;
1418 char * rpath;
1419 unsigned int len;
1420 unsigned int dir_up = 0;
1421 unsigned int dir_down = 0;
1422 char *newp;
1423 char * pwd = getpwd ();
1424 const char * down;
1426 /* Remove symlinks, '.' and '..' from the paths, if possible. */
1427 lpath = lrealpath (path);
1428 pathp = lpath == NULL ? path : lpath;
1430 rpath = lrealpath (ref_path);
1431 refp = rpath == NULL ? ref_path : rpath;
1433 /* Remove common leading path elements. */
1434 for (;;)
1436 const char *e1 = pathp;
1437 const char *e2 = refp;
1439 while (*e1 && ! IS_DIR_SEPARATOR (*e1))
1440 ++e1;
1441 while (*e2 && ! IS_DIR_SEPARATOR (*e2))
1442 ++e2;
1443 if (*e1 == '\0' || *e2 == '\0' || e1 - pathp != e2 - refp
1444 || filename_ncmp (pathp, refp, e1 - pathp) != 0)
1445 break;
1446 pathp = e1 + 1;
1447 refp = e2 + 1;
1450 len = strlen (pathp) + 1;
1451 /* For each leading path element in the reference path,
1452 insert "../" into the path. */
1453 for (; *refp; ++refp)
1454 if (IS_DIR_SEPARATOR (*refp))
1456 /* PR 12710: If the path element is "../" then instead of
1457 inserting "../" we need to insert the name of the directory
1458 at the current level. */
1459 if (refp > ref_path + 1
1460 && refp[-1] == '.'
1461 && refp[-2] == '.')
1462 dir_down ++;
1463 else
1464 dir_up ++;
1467 /* If the lrealpath calls above succeeded then we should never
1468 see dir_up and dir_down both being non-zero. */
1470 len += 3 * dir_up;
1472 if (dir_down)
1474 down = pwd + strlen (pwd) - 1;
1476 while (dir_down && down > pwd)
1478 if (IS_DIR_SEPARATOR (*down))
1479 --dir_down;
1481 BFD_ASSERT (dir_down == 0);
1482 len += strlen (down) + 1;
1484 else
1485 down = NULL;
1487 if (len > pathbuf_len)
1489 if (pathbuf != NULL)
1490 free (pathbuf);
1491 pathbuf_len = 0;
1492 pathbuf = (char *) bfd_malloc (len);
1493 if (pathbuf == NULL)
1494 goto out;
1495 pathbuf_len = len;
1498 newp = pathbuf;
1499 while (dir_up-- > 0)
1501 /* FIXME: Support Windows style path separators as well. */
1502 strcpy (newp, "../");
1503 newp += 3;
1506 if (down)
1507 sprintf (newp, "%s/%s", down, pathp);
1508 else
1509 strcpy (newp, pathp);
1511 out:
1512 free (lpath);
1513 free (rpath);
1514 return pathbuf;
1517 /* Build a BFD style extended name table. */
1519 bfd_boolean
1520 _bfd_archive_bsd_construct_extended_name_table (bfd *abfd,
1521 char **tabloc,
1522 bfd_size_type *tablen,
1523 const char **name)
1525 *name = "ARFILENAMES/";
1526 return _bfd_construct_extended_name_table (abfd, FALSE, tabloc, tablen);
1529 /* Build an SVR4 style extended name table. */
1531 bfd_boolean
1532 _bfd_archive_coff_construct_extended_name_table (bfd *abfd,
1533 char **tabloc,
1534 bfd_size_type *tablen,
1535 const char **name)
1537 *name = "//";
1538 return _bfd_construct_extended_name_table (abfd, TRUE, tabloc, tablen);
1541 /* Follows archive_head and produces an extended name table if
1542 necessary. Returns (in tabloc) a pointer to an extended name
1543 table, and in tablen the length of the table. If it makes an entry
1544 it clobbers the filename so that the element may be written without
1545 further massage. Returns TRUE if it ran successfully, FALSE if
1546 something went wrong. A successful return may still involve a
1547 zero-length tablen! */
1549 bfd_boolean
1550 _bfd_construct_extended_name_table (bfd *abfd,
1551 bfd_boolean trailing_slash,
1552 char **tabloc,
1553 bfd_size_type *tablen)
1555 unsigned int maxname = ar_maxnamelen (abfd);
1556 bfd_size_type total_namelen = 0;
1557 bfd *current;
1558 char *strptr;
1559 const char *last_filename;
1560 long last_stroff;
1562 *tablen = 0;
1563 last_filename = NULL;
1565 /* Figure out how long the table should be. */
1566 for (current = abfd->archive_head;
1567 current != NULL;
1568 current = current->archive_next)
1570 const char *normal;
1571 unsigned int thislen;
1573 if (bfd_is_thin_archive (abfd))
1575 const char *filename = current->filename;
1577 /* If the element being added is a member of another archive
1578 (i.e., we are flattening), use the containing archive's name. */
1579 if (current->my_archive
1580 && ! bfd_is_thin_archive (current->my_archive))
1581 filename = current->my_archive->filename;
1583 /* If the path is the same as the previous path seen,
1584 reuse it. This can happen when flattening a thin
1585 archive that contains other archives. */
1586 if (last_filename && filename_cmp (last_filename, filename) == 0)
1587 continue;
1589 last_filename = filename;
1591 /* If the path is relative, adjust it relative to
1592 the containing archive. */
1593 if (! IS_ABSOLUTE_PATH (filename)
1594 && ! IS_ABSOLUTE_PATH (abfd->filename))
1595 normal = adjust_relative_path (filename, abfd->filename);
1596 else
1597 normal = filename;
1599 /* In a thin archive, always store the full pathname
1600 in the extended name table. */
1601 total_namelen += strlen (normal) + 1;
1602 if (trailing_slash)
1603 /* Leave room for trailing slash. */
1604 ++total_namelen;
1606 continue;
1609 normal = normalize (current, current->filename);
1610 if (normal == NULL)
1611 return FALSE;
1613 thislen = strlen (normal);
1615 if (thislen > maxname
1616 && (bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
1617 thislen = maxname;
1619 if (thislen > maxname)
1621 /* Add one to leave room for \n. */
1622 total_namelen += thislen + 1;
1623 if (trailing_slash)
1625 /* Leave room for trailing slash. */
1626 ++total_namelen;
1629 else
1631 struct ar_hdr *hdr = arch_hdr (current);
1632 if (filename_ncmp (normal, hdr->ar_name, thislen) != 0
1633 || (thislen < sizeof hdr->ar_name
1634 && hdr->ar_name[thislen] != ar_padchar (current)))
1636 /* Must have been using extended format even though it
1637 didn't need to. Fix it to use normal format. */
1638 memcpy (hdr->ar_name, normal, thislen);
1639 if (thislen < maxname
1640 || (thislen == maxname && thislen < sizeof hdr->ar_name))
1641 hdr->ar_name[thislen] = ar_padchar (current);
1646 if (total_namelen == 0)
1647 return TRUE;
1649 *tabloc = (char *) bfd_zalloc (abfd, total_namelen);
1650 if (*tabloc == NULL)
1651 return FALSE;
1653 *tablen = total_namelen;
1654 strptr = *tabloc;
1656 last_filename = NULL;
1657 last_stroff = 0;
1659 for (current = abfd->archive_head;
1660 current != NULL;
1661 current = current->archive_next)
1663 const char *normal;
1664 unsigned int thislen;
1665 long stroff;
1666 const char *filename = current->filename;
1668 if (bfd_is_thin_archive (abfd))
1670 /* If the element being added is a member of another archive
1671 (i.e., we are flattening), use the containing archive's name. */
1672 if (current->my_archive
1673 && ! bfd_is_thin_archive (current->my_archive))
1674 filename = current->my_archive->filename;
1675 /* If the path is the same as the previous path seen,
1676 reuse it. This can happen when flattening a thin
1677 archive that contains other archives.
1678 If the path is relative, adjust it relative to
1679 the containing archive. */
1680 if (last_filename && filename_cmp (last_filename, filename) == 0)
1681 normal = last_filename;
1682 else if (! IS_ABSOLUTE_PATH (filename)
1683 && ! IS_ABSOLUTE_PATH (abfd->filename))
1684 normal = adjust_relative_path (filename, abfd->filename);
1685 else
1686 normal = filename;
1688 else
1690 normal = normalize (current, filename);
1691 if (normal == NULL)
1692 return FALSE;
1695 thislen = strlen (normal);
1696 if (thislen > maxname || bfd_is_thin_archive (abfd))
1698 /* Works for now; may need to be re-engineered if we
1699 encounter an oddball archive format and want to
1700 generalise this hack. */
1701 struct ar_hdr *hdr = arch_hdr (current);
1702 if (normal == last_filename)
1703 stroff = last_stroff;
1704 else
1706 strcpy (strptr, normal);
1707 if (! trailing_slash)
1708 strptr[thislen] = ARFMAG[1];
1709 else
1711 strptr[thislen] = '/';
1712 strptr[thislen + 1] = ARFMAG[1];
1714 stroff = strptr - *tabloc;
1715 last_stroff = stroff;
1717 hdr->ar_name[0] = ar_padchar (current);
1718 if (bfd_is_thin_archive (abfd) && current->origin > 0)
1720 int len = snprintf (hdr->ar_name + 1, maxname - 1, "%-ld:",
1721 stroff);
1722 _bfd_ar_spacepad (hdr->ar_name + 1 + len, maxname - 1 - len,
1723 "%-ld",
1724 current->origin - sizeof (struct ar_hdr));
1726 else
1727 _bfd_ar_spacepad (hdr->ar_name + 1, maxname - 1, "%-ld", stroff);
1728 if (normal != last_filename)
1730 strptr += thislen + 1;
1731 if (trailing_slash)
1732 ++strptr;
1733 last_filename = filename;
1738 return TRUE;
1741 /* Do not construct an extended name table but transforms name field into
1742 its extended form. */
1744 bfd_boolean
1745 _bfd_archive_bsd44_construct_extended_name_table (bfd *abfd,
1746 char **tabloc,
1747 bfd_size_type *tablen,
1748 const char **name)
1750 unsigned int maxname = ar_maxnamelen (abfd);
1751 bfd *current;
1753 *tablen = 0;
1754 *tabloc = NULL;
1755 *name = NULL;
1757 for (current = abfd->archive_head;
1758 current != NULL;
1759 current = current->archive_next)
1761 const char *normal = normalize (current, current->filename);
1762 int has_space = 0;
1763 unsigned int len;
1765 if (normal == NULL)
1766 return FALSE;
1768 for (len = 0; normal[len]; len++)
1769 if (normal[len] == ' ')
1770 has_space = 1;
1772 if (len > maxname || has_space)
1774 struct ar_hdr *hdr = arch_hdr (current);
1776 len = (len + 3) & ~3;
1777 arch_eltdata (current)->extra_size = len;
1778 _bfd_ar_spacepad (hdr->ar_name, maxname, "#1/%lu", len);
1782 return TRUE;
1785 /* Write an archive header. */
1787 bfd_boolean
1788 _bfd_generic_write_ar_hdr (bfd *archive, bfd *abfd)
1790 struct ar_hdr *hdr = arch_hdr (abfd);
1792 if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1793 return FALSE;
1794 return TRUE;
1797 /* Write an archive header using BSD4.4 convention. */
1799 bfd_boolean
1800 _bfd_bsd44_write_ar_hdr (bfd *archive, bfd *abfd)
1802 struct ar_hdr *hdr = arch_hdr (abfd);
1804 if (is_bsd44_extended_name (hdr->ar_name))
1806 /* This is a BSD 4.4 extended name. */
1807 const char *fullname = normalize (abfd, abfd->filename);
1808 unsigned int len = strlen (fullname);
1809 unsigned int padded_len = (len + 3) & ~3;
1811 BFD_ASSERT (padded_len == arch_eltdata (abfd)->extra_size);
1813 if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size),
1814 arch_eltdata (abfd)->parsed_size + padded_len))
1815 return FALSE;
1817 if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1818 return FALSE;
1820 if (bfd_bwrite (fullname, len, archive) != len)
1821 return FALSE;
1823 if (len & 3)
1825 static const char pad[3] = { 0, 0, 0 };
1827 len = 4 - (len & 3);
1828 if (bfd_bwrite (pad, len, archive) != len)
1829 return FALSE;
1832 else
1834 if (bfd_bwrite (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1835 return FALSE;
1837 return TRUE;
1840 /* A couple of functions for creating ar_hdrs. */
1842 #ifdef HPUX_LARGE_AR_IDS
1843 /* Function to encode large UID/GID values according to HP. */
1845 static void
1846 hpux_uid_gid_encode (char str[6], long int id)
1848 int cnt;
1850 str[5] = '@' + (id & 3);
1851 id >>= 2;
1853 for (cnt = 4; cnt >= 0; --cnt, id >>= 6)
1854 str[cnt] = ' ' + (id & 0x3f);
1856 #endif /* HPUX_LARGE_AR_IDS */
1858 #ifndef HAVE_GETUID
1859 #define getuid() 0
1860 #endif
1862 #ifndef HAVE_GETGID
1863 #define getgid() 0
1864 #endif
1866 /* Takes a filename, returns an arelt_data for it, or NULL if it can't
1867 make one. The filename must refer to a filename in the filesystem.
1868 The filename field of the ar_hdr will NOT be initialized. If member
1869 is set, and it's an in-memory bfd, we fake it. */
1871 static struct areltdata *
1872 bfd_ar_hdr_from_filesystem (bfd *abfd, const char *filename, bfd *member)
1874 struct stat status;
1875 struct areltdata *ared;
1876 struct ar_hdr *hdr;
1877 bfd_size_type amt;
1879 if (member && (member->flags & BFD_IN_MEMORY) != 0)
1881 /* Assume we just "made" the member, and fake it. */
1882 struct bfd_in_memory *bim = (struct bfd_in_memory *) member->iostream;
1883 time (&status.st_mtime);
1884 status.st_uid = getuid ();
1885 status.st_gid = getgid ();
1886 status.st_mode = 0644;
1887 status.st_size = bim->size;
1889 else if (stat (filename, &status) != 0)
1891 bfd_set_error (bfd_error_system_call);
1892 return NULL;
1895 /* If the caller requested that the BFD generate deterministic output,
1896 fake values for modification time, UID, GID, and file mode. */
1897 if ((abfd->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
1899 status.st_mtime = 0;
1900 status.st_uid = 0;
1901 status.st_gid = 0;
1902 status.st_mode = 0644;
1905 amt = sizeof (struct ar_hdr) + sizeof (struct areltdata);
1906 ared = (struct areltdata *) bfd_zmalloc (amt);
1907 if (ared == NULL)
1908 return NULL;
1909 hdr = (struct ar_hdr *) (((char *) ared) + sizeof (struct areltdata));
1911 /* ar headers are space padded, not null padded! */
1912 memset (hdr, ' ', sizeof (struct ar_hdr));
1914 _bfd_ar_spacepad (hdr->ar_date, sizeof (hdr->ar_date), "%-12ld",
1915 status.st_mtime);
1916 #ifdef HPUX_LARGE_AR_IDS
1917 /* HP has a very "special" way to handle UID/GID's with numeric values
1918 > 99999. */
1919 if (status.st_uid > 99999)
1920 hpux_uid_gid_encode (hdr->ar_uid, (long) status.st_uid);
1921 else
1922 #endif
1923 _bfd_ar_spacepad (hdr->ar_uid, sizeof (hdr->ar_uid), "%ld",
1924 status.st_uid);
1925 #ifdef HPUX_LARGE_AR_IDS
1926 /* HP has a very "special" way to handle UID/GID's with numeric values
1927 > 99999. */
1928 if (status.st_gid > 99999)
1929 hpux_uid_gid_encode (hdr->ar_gid, (long) status.st_gid);
1930 else
1931 #endif
1932 _bfd_ar_spacepad (hdr->ar_gid, sizeof (hdr->ar_gid), "%ld",
1933 status.st_gid);
1934 _bfd_ar_spacepad (hdr->ar_mode, sizeof (hdr->ar_mode), "%-8lo",
1935 status.st_mode);
1936 if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size), status.st_size))
1938 free (ared);
1939 return NULL;
1941 memcpy (hdr->ar_fmag, ARFMAG, 2);
1942 ared->parsed_size = status.st_size;
1943 ared->arch_header = (char *) hdr;
1945 return ared;
1948 /* Analogous to stat call. */
1951 bfd_generic_stat_arch_elt (bfd *abfd, struct stat *buf)
1953 struct ar_hdr *hdr;
1954 char *aloser;
1956 if (abfd->arelt_data == NULL)
1958 bfd_set_error (bfd_error_invalid_operation);
1959 return -1;
1962 hdr = arch_hdr (abfd);
1964 #define foo(arelt, stelt, size) \
1965 buf->stelt = strtol (hdr->arelt, &aloser, size); \
1966 if (aloser == hdr->arelt) \
1967 return -1;
1969 /* Some platforms support special notations for large IDs. */
1970 #ifdef HPUX_LARGE_AR_IDS
1971 # define foo2(arelt, stelt, size) \
1972 if (hdr->arelt[5] == ' ') \
1974 foo (arelt, stelt, size); \
1976 else \
1978 int cnt; \
1979 for (buf->stelt = cnt = 0; cnt < 5; ++cnt) \
1981 if (hdr->arelt[cnt] < ' ' || hdr->arelt[cnt] > ' ' + 0x3f) \
1982 return -1; \
1983 buf->stelt <<= 6; \
1984 buf->stelt += hdr->arelt[cnt] - ' '; \
1986 if (hdr->arelt[5] < '@' || hdr->arelt[5] > '@' + 3) \
1987 return -1; \
1988 buf->stelt <<= 2; \
1989 buf->stelt += hdr->arelt[5] - '@'; \
1991 #else
1992 # define foo2(arelt, stelt, size) foo (arelt, stelt, size)
1993 #endif
1995 foo (ar_date, st_mtime, 10);
1996 foo2 (ar_uid, st_uid, 10);
1997 foo2 (ar_gid, st_gid, 10);
1998 foo (ar_mode, st_mode, 8);
2000 buf->st_size = arch_eltdata (abfd)->parsed_size;
2002 return 0;
2005 void
2006 bfd_dont_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2008 /* FIXME: This interacts unpleasantly with ar's quick-append option.
2009 Fortunately ic960 users will never use that option. Fixing this
2010 is very hard; fortunately I know how to do it and will do so once
2011 intel's release is out the door. */
2013 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2014 size_t length;
2015 const char *filename;
2016 size_t maxlen = ar_maxnamelen (abfd);
2018 if ((bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
2020 bfd_bsd_truncate_arname (abfd, pathname, arhdr);
2021 return;
2024 filename = normalize (abfd, pathname);
2025 if (filename == NULL)
2027 /* FIXME */
2028 abort ();
2031 length = strlen (filename);
2033 if (length <= maxlen)
2034 memcpy (hdr->ar_name, filename, length);
2036 /* Add the padding character if there is room for it. */
2037 if (length < maxlen
2038 || (length == maxlen && length < sizeof hdr->ar_name))
2039 (hdr->ar_name)[length] = ar_padchar (abfd);
2042 void
2043 bfd_bsd_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2045 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2046 size_t length;
2047 const char *filename = lbasename (pathname);
2048 size_t maxlen = ar_maxnamelen (abfd);
2050 length = strlen (filename);
2052 if (length <= maxlen)
2053 memcpy (hdr->ar_name, filename, length);
2054 else
2056 /* pathname: meet procrustes */
2057 memcpy (hdr->ar_name, filename, maxlen);
2058 length = maxlen;
2061 if (length < maxlen)
2062 (hdr->ar_name)[length] = ar_padchar (abfd);
2065 /* Store name into ar header. Truncates the name to fit.
2066 1> strip pathname to be just the basename.
2067 2> if it's short enuf to fit, stuff it in.
2068 3> If it doesn't end with .o, truncate it to fit
2069 4> truncate it before the .o, append .o, stuff THAT in. */
2071 /* This is what gnu ar does. It's better but incompatible with the
2072 bsd ar. */
2074 void
2075 bfd_gnu_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2077 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2078 size_t length;
2079 const char *filename = lbasename (pathname);
2080 size_t maxlen = ar_maxnamelen (abfd);
2082 length = strlen (filename);
2084 if (length <= maxlen)
2085 memcpy (hdr->ar_name, filename, length);
2086 else
2088 /* pathname: meet procrustes. */
2089 memcpy (hdr->ar_name, filename, maxlen);
2090 if ((filename[length - 2] == '.') && (filename[length - 1] == 'o'))
2092 hdr->ar_name[maxlen - 2] = '.';
2093 hdr->ar_name[maxlen - 1] = 'o';
2095 length = maxlen;
2098 if (length < 16)
2099 (hdr->ar_name)[length] = ar_padchar (abfd);
2102 /* The BFD is open for write and has its format set to bfd_archive. */
2104 bfd_boolean
2105 _bfd_write_archive_contents (bfd *arch)
2107 bfd *current;
2108 char *etable = NULL;
2109 bfd_size_type elength = 0;
2110 const char *ename = NULL;
2111 bfd_boolean makemap = bfd_has_map (arch);
2112 /* If no .o's, don't bother to make a map. */
2113 bfd_boolean hasobjects = FALSE;
2114 bfd_size_type wrote;
2115 int tries;
2116 char *armag;
2118 /* Verify the viability of all entries; if any of them live in the
2119 filesystem (as opposed to living in an archive open for input)
2120 then construct a fresh ar_hdr for them. */
2121 for (current = arch->archive_head;
2122 current != NULL;
2123 current = current->archive_next)
2125 /* This check is checking the bfds for the objects we're reading
2126 from (which are usually either an object file or archive on
2127 disk), not the archive entries we're writing to. We don't
2128 actually create bfds for the archive members, we just copy
2129 them byte-wise when we write out the archive. */
2130 if (bfd_write_p (current))
2132 bfd_set_error (bfd_error_invalid_operation);
2133 goto input_err;
2135 if (!current->arelt_data)
2137 current->arelt_data =
2138 bfd_ar_hdr_from_filesystem (arch, current->filename, current);
2139 if (!current->arelt_data)
2140 goto input_err;
2142 /* Put in the file name. */
2143 BFD_SEND (arch, _bfd_truncate_arname,
2144 (arch, current->filename, (char *) arch_hdr (current)));
2147 if (makemap && ! hasobjects)
2148 { /* Don't bother if we won't make a map! */
2149 if ((bfd_check_format (current, bfd_object)))
2150 hasobjects = TRUE;
2154 if (!BFD_SEND (arch, _bfd_construct_extended_name_table,
2155 (arch, &etable, &elength, &ename)))
2156 return FALSE;
2158 if (bfd_seek (arch, (file_ptr) 0, SEEK_SET) != 0)
2159 return FALSE;
2160 armag = ARMAG;
2161 if (bfd_is_thin_archive (arch))
2162 armag = ARMAGT;
2163 wrote = bfd_bwrite (armag, SARMAG, arch);
2164 if (wrote != SARMAG)
2165 return FALSE;
2167 if (makemap && hasobjects)
2169 if (! _bfd_compute_and_write_armap (arch, (unsigned int) elength))
2170 return FALSE;
2173 if (elength != 0)
2175 struct ar_hdr hdr;
2177 memset (&hdr, ' ', sizeof (struct ar_hdr));
2178 memcpy (hdr.ar_name, ename, strlen (ename));
2179 /* Round size up to even number in archive header. */
2180 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size),
2181 (elength + 1) & ~(bfd_size_type) 1))
2182 return FALSE;
2183 memcpy (hdr.ar_fmag, ARFMAG, 2);
2184 if ((bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
2185 != sizeof (struct ar_hdr))
2186 || bfd_bwrite (etable, elength, arch) != elength)
2187 return FALSE;
2188 if ((elength % 2) == 1)
2190 if (bfd_bwrite (&ARFMAG[1], 1, arch) != 1)
2191 return FALSE;
2195 for (current = arch->archive_head;
2196 current != NULL;
2197 current = current->archive_next)
2199 char buffer[DEFAULT_BUFFERSIZE];
2200 bfd_size_type remaining = arelt_size (current);
2202 /* Write ar header. */
2203 if (!_bfd_write_ar_hdr (arch, current))
2204 return FALSE;
2205 if (bfd_is_thin_archive (arch))
2206 continue;
2207 if (bfd_seek (current, (file_ptr) 0, SEEK_SET) != 0)
2208 goto input_err;
2210 while (remaining)
2212 unsigned int amt = DEFAULT_BUFFERSIZE;
2214 if (amt > remaining)
2215 amt = remaining;
2216 errno = 0;
2217 if (bfd_bread (buffer, amt, current) != amt)
2219 if (bfd_get_error () != bfd_error_system_call)
2220 bfd_set_error (bfd_error_file_truncated);
2221 goto input_err;
2223 if (bfd_bwrite (buffer, amt, arch) != amt)
2224 return FALSE;
2225 remaining -= amt;
2228 if ((arelt_size (current) % 2) == 1)
2230 if (bfd_bwrite (&ARFMAG[1], 1, arch) != 1)
2231 return FALSE;
2235 if (makemap && hasobjects)
2237 /* Verify the timestamp in the archive file. If it would not be
2238 accepted by the linker, rewrite it until it would be. If
2239 anything odd happens, break out and just return. (The
2240 Berkeley linker checks the timestamp and refuses to read the
2241 table-of-contents if it is >60 seconds less than the file's
2242 modified-time. That painful hack requires this painful hack. */
2243 tries = 1;
2246 if (bfd_update_armap_timestamp (arch))
2247 break;
2248 (*_bfd_error_handler)
2249 (_("Warning: writing archive was slow: rewriting timestamp\n"));
2251 while (++tries < 6);
2254 return TRUE;
2256 input_err:
2257 bfd_set_error (bfd_error_on_input, current, bfd_get_error ());
2258 return FALSE;
2261 /* Note that the namidx for the first symbol is 0. */
2263 bfd_boolean
2264 _bfd_compute_and_write_armap (bfd *arch, unsigned int elength)
2266 char *first_name = NULL;
2267 bfd *current;
2268 file_ptr elt_no = 0;
2269 struct orl *map = NULL;
2270 unsigned int orl_max = 1024; /* Fine initial default. */
2271 unsigned int orl_count = 0;
2272 int stridx = 0;
2273 asymbol **syms = NULL;
2274 long syms_max = 0;
2275 bfd_boolean ret;
2276 bfd_size_type amt;
2278 /* Dunno if this is the best place for this info... */
2279 if (elength != 0)
2280 elength += sizeof (struct ar_hdr);
2281 elength += elength % 2;
2283 amt = orl_max * sizeof (struct orl);
2284 map = (struct orl *) bfd_malloc (amt);
2285 if (map == NULL)
2286 goto error_return;
2288 /* We put the symbol names on the arch objalloc, and then discard
2289 them when done. */
2290 first_name = (char *) bfd_alloc (arch, 1);
2291 if (first_name == NULL)
2292 goto error_return;
2294 /* Drop all the files called __.SYMDEF, we're going to make our own. */
2295 while (arch->archive_head
2296 && strcmp (arch->archive_head->filename, "__.SYMDEF") == 0)
2297 arch->archive_head = arch->archive_head->archive_next;
2299 /* Map over each element. */
2300 for (current = arch->archive_head;
2301 current != NULL;
2302 current = current->archive_next, elt_no++)
2304 if (bfd_check_format (current, bfd_object)
2305 && (bfd_get_file_flags (current) & HAS_SYMS) != 0)
2307 long storage;
2308 long symcount;
2309 long src_count;
2311 storage = bfd_get_symtab_upper_bound (current);
2312 if (storage < 0)
2313 goto error_return;
2315 if (storage != 0)
2317 if (storage > syms_max)
2319 if (syms_max > 0)
2320 free (syms);
2321 syms_max = storage;
2322 syms = (asymbol **) bfd_malloc (syms_max);
2323 if (syms == NULL)
2324 goto error_return;
2326 symcount = bfd_canonicalize_symtab (current, syms);
2327 if (symcount < 0)
2328 goto error_return;
2330 /* Now map over all the symbols, picking out the ones we
2331 want. */
2332 for (src_count = 0; src_count < symcount; src_count++)
2334 flagword flags = (syms[src_count])->flags;
2335 asection *sec = syms[src_count]->section;
2337 if (((flags & (BSF_GLOBAL
2338 | BSF_WEAK
2339 | BSF_INDIRECT
2340 | BSF_GNU_UNIQUE)) != 0
2341 || bfd_is_com_section (sec))
2342 && ! bfd_is_und_section (sec))
2344 bfd_size_type namelen;
2345 struct orl *new_map;
2347 /* This symbol will go into the archive header. */
2348 if (orl_count == orl_max)
2350 orl_max *= 2;
2351 amt = orl_max * sizeof (struct orl);
2352 new_map = (struct orl *) bfd_realloc (map, amt);
2353 if (new_map == NULL)
2354 goto error_return;
2356 map = new_map;
2359 namelen = strlen (syms[src_count]->name);
2360 amt = sizeof (char *);
2361 map[orl_count].name = (char **) bfd_alloc (arch, amt);
2362 if (map[orl_count].name == NULL)
2363 goto error_return;
2364 *(map[orl_count].name) = (char *) bfd_alloc (arch,
2365 namelen + 1);
2366 if (*(map[orl_count].name) == NULL)
2367 goto error_return;
2368 strcpy (*(map[orl_count].name), syms[src_count]->name);
2369 map[orl_count].u.abfd = current;
2370 map[orl_count].namidx = stridx;
2372 stridx += namelen + 1;
2373 ++orl_count;
2378 /* Now ask the BFD to free up any cached information, so we
2379 don't fill all of memory with symbol tables. */
2380 if (! bfd_free_cached_info (current))
2381 goto error_return;
2385 /* OK, now we have collected all the data, let's write them out. */
2386 ret = BFD_SEND (arch, write_armap,
2387 (arch, elength, map, orl_count, stridx));
2389 if (syms_max > 0)
2390 free (syms);
2391 if (map != NULL)
2392 free (map);
2393 if (first_name != NULL)
2394 bfd_release (arch, first_name);
2396 return ret;
2398 error_return:
2399 if (syms_max > 0)
2400 free (syms);
2401 if (map != NULL)
2402 free (map);
2403 if (first_name != NULL)
2404 bfd_release (arch, first_name);
2406 return FALSE;
2409 bfd_boolean
2410 bsd_write_armap (bfd *arch,
2411 unsigned int elength,
2412 struct orl *map,
2413 unsigned int orl_count,
2414 int stridx)
2416 int padit = stridx & 1;
2417 unsigned int ranlibsize = orl_count * BSD_SYMDEF_SIZE;
2418 unsigned int stringsize = stridx + padit;
2419 /* Include 8 bytes to store ranlibsize and stringsize in output. */
2420 unsigned int mapsize = ranlibsize + stringsize + 8;
2421 file_ptr firstreal;
2422 bfd *current = arch->archive_head;
2423 bfd *last_elt = current; /* Last element arch seen. */
2424 bfd_byte temp[4];
2425 unsigned int count;
2426 struct ar_hdr hdr;
2427 long uid, gid;
2429 firstreal = mapsize + elength + sizeof (struct ar_hdr) + SARMAG;
2431 /* If deterministic, we use 0 as the timestamp in the map.
2432 Some linkers may require that the archive filesystem modification
2433 time is less than (or near to) the archive map timestamp. Those
2434 linkers should not be used with deterministic mode. (GNU ld and
2435 Gold do not have this restriction.) */
2436 bfd_ardata (arch)->armap_timestamp = 0;
2437 uid = 0;
2438 gid = 0;
2439 if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0)
2441 struct stat statbuf;
2443 if (stat (arch->filename, &statbuf) == 0)
2444 bfd_ardata (arch)->armap_timestamp = (statbuf.st_mtime
2445 + ARMAP_TIME_OFFSET);
2446 uid = getuid();
2447 gid = getgid();
2450 memset (&hdr, ' ', sizeof (struct ar_hdr));
2451 memcpy (hdr.ar_name, RANLIBMAG, strlen (RANLIBMAG));
2452 bfd_ardata (arch)->armap_datepos = (SARMAG
2453 + offsetof (struct ar_hdr, ar_date[0]));
2454 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2455 bfd_ardata (arch)->armap_timestamp);
2456 _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", uid);
2457 _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", gid);
2458 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
2459 return FALSE;
2460 memcpy (hdr.ar_fmag, ARFMAG, 2);
2461 if (bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
2462 != sizeof (struct ar_hdr))
2463 return FALSE;
2464 H_PUT_32 (arch, ranlibsize, temp);
2465 if (bfd_bwrite (temp, sizeof (temp), arch) != sizeof (temp))
2466 return FALSE;
2468 for (count = 0; count < orl_count; count++)
2470 unsigned int offset;
2471 bfd_byte buf[BSD_SYMDEF_SIZE];
2473 if (map[count].u.abfd != last_elt)
2477 struct areltdata *ared = arch_eltdata (current);
2479 firstreal += (ared->parsed_size + ared->extra_size
2480 + sizeof (struct ar_hdr));
2481 firstreal += firstreal % 2;
2482 current = current->archive_next;
2484 while (current != map[count].u.abfd);
2487 /* The archive file format only has 4 bytes to store the offset
2488 of the member. Check to make sure that firstreal has not grown
2489 too big. */
2490 offset = (unsigned int) firstreal;
2491 if (firstreal != (file_ptr) offset)
2493 bfd_set_error (bfd_error_file_truncated);
2494 return FALSE;
2497 last_elt = current;
2498 H_PUT_32 (arch, map[count].namidx, buf);
2499 H_PUT_32 (arch, firstreal, buf + BSD_SYMDEF_OFFSET_SIZE);
2500 if (bfd_bwrite (buf, BSD_SYMDEF_SIZE, arch)
2501 != BSD_SYMDEF_SIZE)
2502 return FALSE;
2505 /* Now write the strings themselves. */
2506 H_PUT_32 (arch, stringsize, temp);
2507 if (bfd_bwrite (temp, sizeof (temp), arch) != sizeof (temp))
2508 return FALSE;
2509 for (count = 0; count < orl_count; count++)
2511 size_t len = strlen (*map[count].name) + 1;
2513 if (bfd_bwrite (*map[count].name, len, arch) != len)
2514 return FALSE;
2517 /* The spec sez this should be a newline. But in order to be
2518 bug-compatible for sun's ar we use a null. */
2519 if (padit)
2521 if (bfd_bwrite ("", 1, arch) != 1)
2522 return FALSE;
2525 return TRUE;
2528 /* At the end of archive file handling, update the timestamp in the
2529 file, so the linker will accept it.
2531 Return TRUE if the timestamp was OK, or an unusual problem happened.
2532 Return FALSE if we updated the timestamp. */
2534 bfd_boolean
2535 _bfd_archive_bsd_update_armap_timestamp (bfd *arch)
2537 struct stat archstat;
2538 struct ar_hdr hdr;
2540 /* If creating deterministic archives, just leave the timestamp as-is. */
2541 if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
2542 return TRUE;
2544 /* Flush writes, get last-write timestamp from file, and compare it
2545 to the timestamp IN the file. */
2546 bfd_flush (arch);
2547 if (bfd_stat (arch, &archstat) == -1)
2549 bfd_perror (_("Reading archive file mod timestamp"));
2551 /* Can't read mod time for some reason. */
2552 return TRUE;
2554 if (((long) archstat.st_mtime) <= bfd_ardata (arch)->armap_timestamp)
2555 /* OK by the linker's rules. */
2556 return TRUE;
2558 /* Update the timestamp. */
2559 bfd_ardata (arch)->armap_timestamp = archstat.st_mtime + ARMAP_TIME_OFFSET;
2561 /* Prepare an ASCII version suitable for writing. */
2562 memset (hdr.ar_date, ' ', sizeof (hdr.ar_date));
2563 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2564 bfd_ardata (arch)->armap_timestamp);
2566 /* Write it into the file. */
2567 bfd_ardata (arch)->armap_datepos = (SARMAG
2568 + offsetof (struct ar_hdr, ar_date[0]));
2569 if (bfd_seek (arch, bfd_ardata (arch)->armap_datepos, SEEK_SET) != 0
2570 || (bfd_bwrite (hdr.ar_date, sizeof (hdr.ar_date), arch)
2571 != sizeof (hdr.ar_date)))
2573 bfd_perror (_("Writing updated armap timestamp"));
2575 /* Some error while writing. */
2576 return TRUE;
2579 /* We updated the timestamp successfully. */
2580 return FALSE;
2583 /* A coff armap looks like :
2584 lARMAG
2585 struct ar_hdr with name = '/'
2586 number of symbols
2587 offset of file for symbol 0
2588 offset of file for symbol 1
2590 offset of file for symbol n-1
2591 symbol name 0
2592 symbol name 1
2594 symbol name n-1 */
2596 bfd_boolean
2597 coff_write_armap (bfd *arch,
2598 unsigned int elength,
2599 struct orl *map,
2600 unsigned int symbol_count,
2601 int stridx)
2603 /* The size of the ranlib is the number of exported symbols in the
2604 archive * the number of bytes in an int, + an int for the count. */
2605 unsigned int ranlibsize = (symbol_count * 4) + 4;
2606 unsigned int stringsize = stridx;
2607 unsigned int mapsize = stringsize + ranlibsize;
2608 file_ptr archive_member_file_ptr;
2609 bfd *current = arch->archive_head;
2610 unsigned int count;
2611 struct ar_hdr hdr;
2612 int padit = mapsize & 1;
2614 if (padit)
2615 mapsize++;
2617 /* Work out where the first object file will go in the archive. */
2618 archive_member_file_ptr = (mapsize
2619 + elength
2620 + sizeof (struct ar_hdr)
2621 + SARMAG);
2623 memset (&hdr, ' ', sizeof (struct ar_hdr));
2624 hdr.ar_name[0] = '/';
2625 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
2626 return FALSE;
2627 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2628 ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0
2629 ? time (NULL) : 0));
2630 /* This, at least, is what Intel coff sets the values to. */
2631 _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", 0);
2632 _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", 0);
2633 _bfd_ar_spacepad (hdr.ar_mode, sizeof (hdr.ar_mode), "%-7lo", 0);
2634 memcpy (hdr.ar_fmag, ARFMAG, 2);
2636 /* Write the ar header for this item and the number of symbols. */
2637 if (bfd_bwrite (&hdr, sizeof (struct ar_hdr), arch)
2638 != sizeof (struct ar_hdr))
2639 return FALSE;
2641 if (!bfd_write_bigendian_4byte_int (arch, symbol_count))
2642 return FALSE;
2644 /* Two passes, first write the file offsets for each symbol -
2645 remembering that each offset is on a two byte boundary. */
2647 /* Write out the file offset for the file associated with each
2648 symbol, and remember to keep the offsets padded out. */
2650 current = arch->archive_head;
2651 count = 0;
2652 while (current != NULL && count < symbol_count)
2654 /* For each symbol which is used defined in this object, write
2655 out the object file's address in the archive. */
2657 while (count < symbol_count && map[count].u.abfd == current)
2659 unsigned int offset = (unsigned int) archive_member_file_ptr;
2661 /* Catch an attempt to grow an archive past its 4Gb limit. */
2662 if (archive_member_file_ptr != (file_ptr) offset)
2664 bfd_set_error (bfd_error_file_truncated);
2665 return FALSE;
2667 if (!bfd_write_bigendian_4byte_int (arch, offset))
2668 return FALSE;
2669 count++;
2671 archive_member_file_ptr += sizeof (struct ar_hdr);
2672 if (! bfd_is_thin_archive (arch))
2674 /* Add size of this archive entry. */
2675 archive_member_file_ptr += arelt_size (current);
2676 /* Remember about the even alignment. */
2677 archive_member_file_ptr += archive_member_file_ptr % 2;
2679 current = current->archive_next;
2682 /* Now write the strings themselves. */
2683 for (count = 0; count < symbol_count; count++)
2685 size_t len = strlen (*map[count].name) + 1;
2687 if (bfd_bwrite (*map[count].name, len, arch) != len)
2688 return FALSE;
2691 /* The spec sez this should be a newline. But in order to be
2692 bug-compatible for arc960 we use a null. */
2693 if (padit)
2695 if (bfd_bwrite ("", 1, arch) != 1)
2696 return FALSE;
2699 return TRUE;
2702 static int
2703 archive_close_worker (void **slot, void *inf ATTRIBUTE_UNUSED)
2705 struct ar_cache *ent = (struct ar_cache *) *slot;
2707 bfd_close_all_done (ent->arbfd);
2708 return 1;
2711 bfd_boolean
2712 _bfd_archive_close_and_cleanup (bfd *abfd)
2714 if (bfd_read_p (abfd) && abfd->format == bfd_archive)
2716 bfd *nbfd;
2717 bfd *next;
2718 htab_t htab;
2720 /* Close nested archives (if this bfd is a thin archive). */
2721 for (nbfd = abfd->nested_archives; nbfd; nbfd = next)
2723 next = nbfd->archive_next;
2724 bfd_close (nbfd);
2727 htab = bfd_ardata (abfd)->cache;
2728 if (htab)
2730 htab_traverse_noresize (htab, archive_close_worker, NULL);
2731 htab_delete (htab);
2732 bfd_ardata (abfd)->cache = NULL;
2735 if (arch_eltdata (abfd) != NULL)
2737 struct areltdata *ared = arch_eltdata (abfd);
2738 htab_t htab = (htab_t) ared->parent_cache;
2740 if (htab)
2742 struct ar_cache ent;
2743 void **slot;
2745 ent.ptr = ared->key;
2746 slot = htab_find_slot (htab, &ent, NO_INSERT);
2747 if (slot != NULL)
2749 BFD_ASSERT (((struct ar_cache *) *slot)->arbfd == abfd);
2750 htab_clear_slot (htab, slot);
2754 return TRUE;