Add translations for various sub-directories
[binutils-gdb.git] / bfd / archive.c
blobef0109599e15d5eaaae0d0ab81ad2f124b21f6e7
1 /* BFD back-end for archive files (libraries).
2 Copyright (C) 1990-2025 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"
143 #include "bfdlink.h"
145 #ifndef errno
146 extern int errno;
147 #endif
150 EXTERNAL
151 .{* A canonical archive symbol. *}
152 .{* This is a type pun with struct symdef/struct ranlib on purpose! *}
153 .typedef struct carsym
155 . const char *name;
156 . file_ptr file_offset; {* Look here to find the file. *}
158 .carsym;
160 .{* A count of carsyms (canonical archive symbols). *}
161 . typedef unsigned long symindex;
162 .#define BFD_NO_MORE_SYMBOLS ((symindex) ~0)
165 INTERNAL
166 .{* Used in generating armaps (archive tables of contents). *}
167 .struct orl {* Output ranlib. *}
169 . char **name; {* Symbol name. *}
170 . union
172 . file_ptr pos;
173 . bfd *abfd;
174 . } u; {* bfd* or file position. *}
175 . int namidx; {* Index into string table. *}
180 /* We keep a cache of archive filepointers to archive elements to
181 speed up searching the archive by filepos. We only add an entry to
182 the cache when we actually read one. We also don't sort the cache;
183 it's generally short enough to search linearly.
184 Note that the pointers here point to the front of the ar_hdr, not
185 to the front of the contents! */
186 struct ar_cache
188 file_ptr ptr;
189 bfd *arbfd;
192 #define ar_padchar(abfd) ((abfd)->xvec->ar_pad_char)
193 #define ar_maxnamelen(abfd) ((abfd)->xvec->ar_max_namelen)
195 #define arch_eltdata(bfd) ((struct areltdata *) ((bfd)->arelt_data))
196 #define arch_hdr(bfd) ((struct ar_hdr *) arch_eltdata (bfd)->arch_header)
198 /* True iff NAME designated a BSD 4.4 extended name. */
200 #define is_bsd44_extended_name(NAME) \
201 (NAME[0] == '#' && NAME[1] == '1' && NAME[2] == '/' && ISDIGIT (NAME[3]))
203 void
204 _bfd_ar_spacepad (char *p, size_t n, const char *fmt, long val)
206 char buf[20];
207 size_t len;
209 snprintf (buf, sizeof (buf), fmt, val);
210 len = strlen (buf);
211 if (len < n)
213 memcpy (p, buf, len);
214 memset (p + len, ' ', n - len);
216 else
217 memcpy (p, buf, n);
220 bool
221 _bfd_ar_sizepad (char *p, size_t n, bfd_size_type size)
223 char buf[21];
224 size_t len;
226 snprintf (buf, sizeof (buf), "%-10" PRIu64, (uint64_t) size);
227 len = strlen (buf);
228 if (len > n)
230 bfd_set_error (bfd_error_file_too_big);
231 return false;
233 if (len < n)
235 memcpy (p, buf, len);
236 memset (p + len, ' ', n - len);
238 else
239 memcpy (p, buf, n);
240 return true;
243 bool
244 _bfd_generic_mkarchive (bfd *abfd)
246 size_t amt = sizeof (struct artdata);
248 abfd->tdata.aout_ar_data = (struct artdata *) bfd_zalloc (abfd, amt);
249 return bfd_ardata (abfd) != NULL;
253 FUNCTION
254 bfd_get_next_mapent
256 SYNOPSIS
257 symindex bfd_get_next_mapent
258 (bfd *abfd, symindex previous, carsym **sym);
260 DESCRIPTION
261 Step through archive @var{abfd}'s symbol table (if it
262 has one). Successively update @var{sym} with the next symbol's
263 information, returning that symbol's (internal) index into the
264 symbol table.
266 Supply <<BFD_NO_MORE_SYMBOLS>> as the @var{previous} entry to get
267 the first one; returns <<BFD_NO_MORE_SYMBOLS>> when you've already
268 got the last one.
270 A <<carsym>> is a canonical archive symbol. The only
271 user-visible element is its name, a null-terminated string.
274 symindex
275 bfd_get_next_mapent (bfd *abfd, symindex prev, carsym **entry)
277 if (!bfd_has_map (abfd))
279 bfd_set_error (bfd_error_invalid_operation);
280 return BFD_NO_MORE_SYMBOLS;
283 if (prev == BFD_NO_MORE_SYMBOLS)
284 prev = 0;
285 else
286 ++prev;
287 if (prev >= bfd_ardata (abfd)->symdef_count)
288 return BFD_NO_MORE_SYMBOLS;
290 *entry = (bfd_ardata (abfd)->symdefs + prev);
291 return prev;
294 /* To be called by backends only. */
296 bfd *
297 _bfd_create_empty_archive_element_shell (bfd *obfd)
299 return _bfd_new_bfd_contained_in (obfd);
303 FUNCTION
304 bfd_set_archive_head
306 SYNOPSIS
307 bool bfd_set_archive_head (bfd *output, bfd *new_head);
309 DESCRIPTION
310 Set the head of the chain of
311 BFDs contained in the archive @var{output} to @var{new_head}.
314 bool
315 bfd_set_archive_head (bfd *output_archive, bfd *new_head)
317 output_archive->archive_head = new_head;
318 return true;
321 bfd *
322 _bfd_look_for_bfd_in_cache (bfd *arch_bfd, file_ptr filepos)
324 htab_t hash_table = bfd_ardata (arch_bfd)->cache;
325 struct ar_cache m;
327 m.ptr = filepos;
329 if (hash_table)
331 struct ar_cache *entry = (struct ar_cache *) htab_find (hash_table, &m);
332 if (!entry)
333 return NULL;
335 /* Unfortunately this flag is set after checking that we have
336 an archive, and checking for an archive means one element has
337 sneaked into the cache. */
338 entry->arbfd->no_export = arch_bfd->no_export;
339 return entry->arbfd;
341 else
342 return NULL;
345 static hashval_t
346 hash_file_ptr (const void * p)
348 return (hashval_t) (((struct ar_cache *) p)->ptr);
351 /* Returns non-zero if P1 and P2 are equal. */
353 static int
354 eq_file_ptr (const void * p1, const void * p2)
356 struct ar_cache *arc1 = (struct ar_cache *) p1;
357 struct ar_cache *arc2 = (struct ar_cache *) p2;
358 return arc1->ptr == arc2->ptr;
361 /* The calloc function doesn't always take size_t (e.g. on VMS)
362 so wrap it to avoid a compile time warning. */
364 static void *
365 _bfd_calloc_wrapper (size_t a, size_t b)
367 return calloc (a, b);
370 /* Kind of stupid to call cons for each one, but we don't do too many. */
372 bool
373 _bfd_add_bfd_to_archive_cache (bfd *arch_bfd, file_ptr filepos, bfd *new_elt)
375 struct ar_cache *cache;
376 htab_t hash_table = bfd_ardata (arch_bfd)->cache;
378 /* If the hash table hasn't been created, create it. */
379 if (hash_table == NULL)
381 hash_table = htab_create_alloc (16, hash_file_ptr, eq_file_ptr,
382 NULL, _bfd_calloc_wrapper, free);
383 if (hash_table == NULL)
384 return false;
385 bfd_ardata (arch_bfd)->cache = hash_table;
388 /* Insert new_elt into the hash table by filepos. */
389 cache = (struct ar_cache *) bfd_zalloc (arch_bfd, sizeof (struct ar_cache));
390 cache->ptr = filepos;
391 cache->arbfd = new_elt;
392 *htab_find_slot (hash_table, (const void *) cache, INSERT) = cache;
394 /* Provide a means of accessing this from child. */
395 arch_eltdata (new_elt)->parent_cache = hash_table;
396 arch_eltdata (new_elt)->key = filepos;
398 return true;
401 static bfd *
402 open_nested_file (const char *filename, bfd *archive)
404 const char *target;
405 bfd *n_bfd;
407 target = NULL;
408 if (!archive->target_defaulted)
409 target = archive->xvec->name;
410 n_bfd = bfd_openr (filename, target);
411 if (n_bfd != NULL)
413 n_bfd->lto_output = archive->lto_output;
414 n_bfd->no_export = archive->no_export;
415 n_bfd->my_archive = archive;
417 return n_bfd;
420 static bfd *
421 find_nested_archive (const char *filename, bfd *arch_bfd)
423 bfd *abfd;
425 /* PR 15140: Don't allow a nested archive pointing to itself. */
426 if (filename_cmp (filename, bfd_get_filename (arch_bfd)) == 0)
428 bfd_set_error (bfd_error_malformed_archive);
429 return NULL;
432 for (abfd = arch_bfd->nested_archives;
433 abfd != NULL;
434 abfd = abfd->archive_next)
436 if (filename_cmp (filename, bfd_get_filename (abfd)) == 0)
437 return abfd;
439 abfd = open_nested_file (filename, arch_bfd);
440 if (abfd)
442 abfd->archive_next = arch_bfd->nested_archives;
443 arch_bfd->nested_archives = abfd;
445 return abfd;
448 /* The name begins with space. Hence the rest of the name is an index into
449 the string table. */
451 static char *
452 get_extended_arelt_filename (bfd *arch, const char *name, file_ptr *originp)
454 unsigned long table_index = 0;
455 const char *endp;
457 /* Should extract string so that I can guarantee not to overflow into
458 the next region, but I'm too lazy. */
459 errno = 0;
460 /* Skip first char, which is '/' in SVR4 or ' ' in some other variants. */
461 table_index = strtol (name + 1, (char **) &endp, 10);
462 if (errno != 0 || table_index >= bfd_ardata (arch)->extended_names_size)
464 bfd_set_error (bfd_error_malformed_archive);
465 return NULL;
467 /* In a thin archive, a member of an archive-within-an-archive
468 will have the offset in the inner archive encoded here. */
469 if (bfd_is_thin_archive (arch) && endp != NULL && *endp == ':')
471 file_ptr origin = strtol (endp + 1, NULL, 10);
473 if (errno != 0)
475 bfd_set_error (bfd_error_malformed_archive);
476 return NULL;
478 *originp = origin;
480 else
481 *originp = 0;
483 return bfd_ardata (arch)->extended_names + table_index;
486 /* This functions reads an arch header and returns an areltdata pointer, or
487 NULL on error.
489 Presumes the file pointer is already in the right place (ie pointing
490 to the ar_hdr in the file). Moves the file pointer; on success it
491 should be pointing to the front of the file contents; on failure it
492 could have been moved arbitrarily. */
494 void *
495 _bfd_generic_read_ar_hdr (bfd *abfd)
497 return _bfd_generic_read_ar_hdr_mag (abfd, NULL);
500 /* Alpha ECOFF uses an optional different ARFMAG value, so we have a
501 variant of _bfd_generic_read_ar_hdr which accepts a magic string. */
503 void *
504 _bfd_generic_read_ar_hdr_mag (bfd *abfd, const char *mag)
506 struct ar_hdr hdr;
507 char *hdrp = (char *) &hdr;
508 uint64_t parsed_size;
509 struct areltdata *ared;
510 char *filename = NULL;
511 ufile_ptr filesize;
512 bfd_size_type namelen = 0;
513 bfd_size_type allocsize = sizeof (struct areltdata) + sizeof (struct ar_hdr);
514 char *allocptr = 0;
515 file_ptr origin = 0;
516 unsigned int extra_size = 0;
517 char fmag_save;
518 int scan;
520 if (bfd_read (hdrp, sizeof (struct ar_hdr), abfd) != sizeof (struct ar_hdr))
522 if (bfd_get_error () != bfd_error_system_call)
523 bfd_set_error (bfd_error_no_more_archived_files);
524 return NULL;
526 if (strncmp (hdr.ar_fmag, ARFMAG, 2) != 0
527 && (mag == NULL
528 || strncmp (hdr.ar_fmag, mag, 2) != 0))
530 bfd_set_error (bfd_error_malformed_archive);
531 return NULL;
534 errno = 0;
535 fmag_save = hdr.ar_fmag[0];
536 hdr.ar_fmag[0] = 0;
537 scan = sscanf (hdr.ar_size, "%" SCNu64, &parsed_size);
538 hdr.ar_fmag[0] = fmag_save;
539 if (scan != 1)
541 bfd_set_error (bfd_error_malformed_archive);
542 return NULL;
545 /* Extract the filename from the archive - there are two ways to
546 specify an extended name table, either the first char of the
547 name is a space, or it's a slash. */
548 if ((hdr.ar_name[0] == '/'
549 || (hdr.ar_name[0] == ' '
550 && memchr (hdr.ar_name, '/', ar_maxnamelen (abfd)) == NULL))
551 && bfd_ardata (abfd)->extended_names != NULL)
553 filename = get_extended_arelt_filename (abfd, hdr.ar_name, &origin);
554 if (filename == NULL)
555 return NULL;
557 /* BSD4.4-style long filename. */
558 else if (is_bsd44_extended_name (hdr.ar_name))
560 /* BSD-4.4 extended name */
561 namelen = atoi (&hdr.ar_name[3]);
562 filesize = bfd_get_file_size (abfd);
563 if (namelen > parsed_size
564 || namelen > -allocsize - 2
565 || (filesize != 0 && namelen > filesize))
567 bfd_set_error (bfd_error_malformed_archive);
568 return NULL;
570 allocsize += namelen + 1;
571 parsed_size -= namelen;
572 extra_size = namelen;
574 allocptr = (char *) bfd_malloc (allocsize);
575 if (allocptr == NULL)
576 return NULL;
577 filename = (allocptr
578 + sizeof (struct areltdata)
579 + sizeof (struct ar_hdr));
580 if (bfd_read (filename, namelen, abfd) != namelen)
582 free (allocptr);
583 if (bfd_get_error () != bfd_error_system_call)
584 bfd_set_error (bfd_error_no_more_archived_files);
585 return NULL;
587 filename[namelen] = '\0';
589 else
591 /* We judge the end of the name by looking for '/' or ' '.
592 Note: The SYSV format (terminated by '/') allows embedded
593 spaces, so only look for ' ' if we don't find '/'. */
595 char *e;
596 e = (char *) memchr (hdr.ar_name, '\0', ar_maxnamelen (abfd));
597 if (e == NULL)
599 e = (char *) memchr (hdr.ar_name, '/', ar_maxnamelen (abfd));
600 if (e == NULL)
601 e = (char *) memchr (hdr.ar_name, ' ', ar_maxnamelen (abfd));
604 if (e != NULL)
605 namelen = e - hdr.ar_name;
606 else
608 /* If we didn't find a termination character, then the name
609 must be the entire field. */
610 namelen = ar_maxnamelen (abfd);
613 allocsize += namelen + 1;
616 if (!allocptr)
618 allocptr = (char *) bfd_malloc (allocsize);
619 if (allocptr == NULL)
620 return NULL;
623 memset (allocptr, 0, sizeof (struct areltdata));
624 ared = (struct areltdata *) allocptr;
625 ared->arch_header = allocptr + sizeof (struct areltdata);
626 memcpy (ared->arch_header, &hdr, sizeof (struct ar_hdr));
627 ared->parsed_size = parsed_size;
628 ared->extra_size = extra_size;
629 ared->origin = origin;
631 if (filename != NULL)
632 ared->filename = filename;
633 else
635 ared->filename = allocptr + (sizeof (struct areltdata) +
636 sizeof (struct ar_hdr));
637 if (namelen)
638 memcpy (ared->filename, hdr.ar_name, namelen);
639 ared->filename[namelen] = '\0';
642 return ared;
645 /* Append the relative pathname for a member of the thin archive
646 to the pathname of the directory containing the archive. */
648 char *
649 _bfd_append_relative_path (bfd *arch, char *elt_name)
651 const char *arch_name = bfd_get_filename (arch);
652 const char *base_name = lbasename (arch_name);
653 size_t prefix_len;
654 char *filename;
656 if (base_name == arch_name)
657 return elt_name;
659 prefix_len = base_name - arch_name;
660 filename = (char *) bfd_alloc (arch, prefix_len + strlen (elt_name) + 1);
661 if (filename == NULL)
662 return NULL;
664 strncpy (filename, arch_name, prefix_len);
665 strcpy (filename + prefix_len, elt_name);
666 return filename;
669 /* This is an internal function; it's mainly used when indexing
670 through the archive symbol table, but also used to get the next
671 element, since it handles the bookkeeping so nicely for us. */
673 bfd *
674 _bfd_get_elt_at_filepos (bfd *archive, file_ptr filepos,
675 struct bfd_link_info *info)
677 struct areltdata *new_areldata;
678 bfd *n_bfd;
679 char *filename;
681 n_bfd = _bfd_look_for_bfd_in_cache (archive, filepos);
682 if (n_bfd)
683 return n_bfd;
685 if (0 > bfd_seek (archive, filepos, SEEK_SET))
686 return NULL;
688 if ((new_areldata = (struct areltdata *) _bfd_read_ar_hdr (archive)) == NULL)
689 return NULL;
691 filename = new_areldata->filename;
693 if (bfd_is_thin_archive (archive))
695 /* This is a proxy entry for an external file. */
696 if (! IS_ABSOLUTE_PATH (filename))
698 filename = _bfd_append_relative_path (archive, filename);
699 if (filename == NULL)
701 free (new_areldata);
702 return NULL;
706 if (new_areldata->origin > 0)
708 /* This proxy entry refers to an element of a nested archive.
709 Locate the member of that archive and return a bfd for it. */
710 bfd *ext_arch = find_nested_archive (filename, archive);
711 file_ptr origin = new_areldata->origin;
713 free (new_areldata);
714 if (ext_arch == NULL
715 || ! bfd_check_format (ext_arch, bfd_archive))
716 return NULL;
717 n_bfd = _bfd_get_elt_at_filepos (ext_arch, origin, info);
718 if (n_bfd == NULL)
719 return NULL;
720 n_bfd->proxy_origin = bfd_tell (archive);
722 /* Copy BFD_COMPRESS, BFD_DECOMPRESS and BFD_COMPRESS_GABI
723 flags. */
724 n_bfd->flags |= archive->flags & (BFD_COMPRESS
725 | BFD_DECOMPRESS
726 | BFD_COMPRESS_GABI);
728 return n_bfd;
731 /* It's not an element of a nested archive;
732 open the external file as a bfd. */
733 bfd_set_error (bfd_error_no_error);
734 n_bfd = open_nested_file (filename, archive);
735 if (n_bfd == NULL)
737 switch (bfd_get_error ())
739 default:
740 break;
741 case bfd_error_no_error:
742 bfd_set_error (bfd_error_malformed_archive);
743 break;
744 case bfd_error_system_call:
745 if (info != NULL)
747 info->callbacks->einfo
748 (_("%F%P: %pB(%s): error opening thin archive member: %E\n"),
749 archive, filename);
750 break;
752 break;
756 else
758 n_bfd = _bfd_create_empty_archive_element_shell (archive);
761 if (n_bfd == NULL)
763 free (new_areldata);
764 return NULL;
767 n_bfd->proxy_origin = bfd_tell (archive);
769 if (bfd_is_thin_archive (archive))
771 n_bfd->origin = 0;
773 else
775 n_bfd->origin = n_bfd->proxy_origin;
776 if (!bfd_set_filename (n_bfd, filename))
777 goto out;
780 n_bfd->arelt_data = new_areldata;
782 /* Copy BFD_COMPRESS, BFD_DECOMPRESS and BFD_COMPRESS_GABI flags. */
783 n_bfd->flags |= archive->flags & (BFD_COMPRESS
784 | BFD_DECOMPRESS
785 | BFD_COMPRESS_GABI);
787 /* Copy is_linker_input. */
788 n_bfd->is_linker_input = archive->is_linker_input;
790 if (archive->no_element_cache
791 || _bfd_add_bfd_to_archive_cache (archive, filepos, n_bfd))
792 return n_bfd;
794 out:
795 free (new_areldata);
796 n_bfd->arelt_data = NULL;
797 bfd_close (n_bfd);
798 return NULL;
801 /* Return the BFD which is referenced by the symbol in ABFD indexed by
802 SYM_INDEX. SYM_INDEX should have been returned by bfd_get_next_mapent. */
804 bfd *
805 _bfd_generic_get_elt_at_index (bfd *abfd, symindex sym_index)
807 carsym *entry;
809 entry = bfd_ardata (abfd)->symdefs + sym_index;
810 return _bfd_get_elt_at_filepos (abfd, entry->file_offset, NULL);
813 bfd *
814 _bfd_noarchive_get_elt_at_index (bfd *abfd,
815 symindex sym_index ATTRIBUTE_UNUSED)
817 return (bfd *) _bfd_ptr_bfd_null_error (abfd);
821 FUNCTION
822 bfd_openr_next_archived_file
824 SYNOPSIS
825 bfd *bfd_openr_next_archived_file (bfd *archive, bfd *previous);
827 DESCRIPTION
828 Provided a BFD, @var{archive}, containing an archive and NULL, open
829 an input BFD on the first contained element and returns that.
830 Subsequent calls should pass the archive and the previous return
831 value to return a created BFD to the next contained element. NULL
832 is returned when there are no more.
833 Note - if you want to process the bfd returned by this call be
834 sure to call bfd_check_format() on it first.
837 bfd *
838 bfd_openr_next_archived_file (bfd *archive, bfd *last_file)
840 if ((bfd_get_format (archive) != bfd_archive)
841 || (archive->direction == write_direction))
843 bfd_set_error (bfd_error_invalid_operation);
844 return NULL;
847 return BFD_SEND (archive,
848 openr_next_archived_file, (archive, last_file));
851 bfd *
852 bfd_generic_openr_next_archived_file (bfd *archive, bfd *last_file)
854 ufile_ptr filestart;
856 if (!last_file)
857 filestart = bfd_ardata (archive)->first_file_filepos;
858 else
860 filestart = last_file->proxy_origin;
861 if (! bfd_is_thin_archive (archive))
863 bfd_size_type size = arelt_size (last_file);
865 filestart += size;
866 /* Pad to an even boundary...
867 Note that last_file->origin can be odd in the case of
868 BSD-4.4-style element with a long odd size. */
869 filestart += filestart % 2;
870 if (filestart < last_file->proxy_origin)
872 /* Prevent looping. See PR19256. */
873 bfd_set_error (bfd_error_malformed_archive);
874 return NULL;
879 return _bfd_get_elt_at_filepos (archive, filestart, NULL);
882 bfd *
883 _bfd_noarchive_openr_next_archived_file (bfd *archive,
884 bfd *last_file ATTRIBUTE_UNUSED)
886 return (bfd *) _bfd_ptr_bfd_null_error (archive);
889 bfd_cleanup
890 bfd_generic_archive_p (bfd *abfd)
892 char armag[SARMAG + 1];
893 size_t amt;
895 if (bfd_read (armag, SARMAG, abfd) != SARMAG)
897 if (bfd_get_error () != bfd_error_system_call)
898 bfd_set_error (bfd_error_wrong_format);
899 return NULL;
902 bfd_set_thin_archive (abfd, strncmp (armag, ARMAGT, SARMAG) == 0);
904 if (strncmp (armag, ARMAG, SARMAG) != 0
905 && ! bfd_is_thin_archive (abfd))
907 bfd_set_error (bfd_error_wrong_format);
908 return NULL;
911 amt = sizeof (struct artdata);
912 bfd_ardata (abfd) = (struct artdata *) bfd_zalloc (abfd, amt);
913 if (bfd_ardata (abfd) == NULL)
914 return NULL;
916 bfd_ardata (abfd)->first_file_filepos = SARMAG;
918 if (!BFD_SEND (abfd, _bfd_slurp_armap, (abfd))
919 || !BFD_SEND (abfd, _bfd_slurp_extended_name_table, (abfd)))
921 if (bfd_get_error () != bfd_error_system_call)
922 bfd_set_error (bfd_error_wrong_format);
923 bfd_release (abfd, bfd_ardata (abfd));
924 return NULL;
927 if (abfd->target_defaulted && bfd_has_map (abfd))
929 bfd *first;
930 unsigned int save;
932 /* This archive has a map, so we may presume that the contents
933 are object files. Make sure that if the first file in the
934 archive can be recognized as an object file, it is for this
935 target. If not, assume that this is the wrong format. If
936 the first file is not an object file, somebody is doing
937 something weird, and we permit it so that ar -t will work.
939 This is done because any normal format will recognize any
940 normal archive, regardless of the format of the object files.
941 We do accept an empty archive. */
943 save = abfd->no_element_cache;
944 abfd->no_element_cache = 1;
945 first = bfd_openr_next_archived_file (abfd, NULL);
946 abfd->no_element_cache = save;
947 if (first != NULL)
949 first->target_defaulted = false;
950 if (bfd_check_format (first, bfd_object)
951 && first->xvec != abfd->xvec)
952 bfd_set_error (bfd_error_wrong_object_format);
953 bfd_close (first);
957 return _bfd_no_cleanup;
960 /* Some constants for a 32 bit BSD archive structure. We do not
961 support 64 bit archives presently; so far as I know, none actually
962 exist. Supporting them would require changing these constants, and
963 changing some H_GET_32 to H_GET_64. */
965 /* The size of an external symdef structure. */
966 #define BSD_SYMDEF_SIZE 8
968 /* The offset from the start of a symdef structure to the file offset. */
969 #define BSD_SYMDEF_OFFSET_SIZE 4
971 /* The size of the symdef count. */
972 #define BSD_SYMDEF_COUNT_SIZE 4
974 /* The size of the string count. */
975 #define BSD_STRING_COUNT_SIZE 4
977 /* Read a BSD-style archive symbol table. Returns FALSE on error,
978 TRUE otherwise. */
980 static bool
981 do_slurp_bsd_armap (bfd *abfd)
983 struct areltdata *mapdata;
984 size_t counter;
985 bfd_byte *raw_armap, *rbase;
986 struct artdata *ardata = bfd_ardata (abfd);
987 char *stringbase;
988 bfd_size_type parsed_size;
989 size_t amt, string_size;
990 carsym *set;
992 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
993 if (mapdata == NULL)
994 return false;
995 parsed_size = mapdata->parsed_size;
996 free (mapdata);
997 /* PR 17512: file: 883ff754. */
998 /* PR 17512: file: 0458885f. */
999 if (parsed_size < BSD_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE)
1001 bfd_set_error (bfd_error_malformed_archive);
1002 return false;
1005 raw_armap = (bfd_byte *) _bfd_alloc_and_read (abfd, parsed_size, parsed_size);
1006 if (raw_armap == NULL)
1007 return false;
1009 parsed_size -= BSD_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE;
1010 amt = H_GET_32 (abfd, raw_armap);
1011 if (amt > parsed_size
1012 || amt % BSD_SYMDEF_SIZE != 0)
1014 /* Probably we're using the wrong byte ordering. */
1015 bfd_set_error (bfd_error_wrong_format);
1016 goto release_armap;
1019 rbase = raw_armap + BSD_SYMDEF_COUNT_SIZE;
1020 stringbase = (char *) rbase + amt + BSD_STRING_COUNT_SIZE;
1021 string_size = parsed_size - amt;
1023 ardata->symdef_count = amt / BSD_SYMDEF_SIZE;
1024 if (_bfd_mul_overflow (ardata->symdef_count, sizeof (carsym), &amt))
1026 bfd_set_error (bfd_error_no_memory);
1027 goto release_armap;
1029 ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
1030 if (!ardata->symdefs)
1031 goto release_armap;
1033 for (counter = 0, set = ardata->symdefs;
1034 counter < ardata->symdef_count;
1035 counter++, set++, rbase += BSD_SYMDEF_SIZE)
1037 unsigned nameoff = H_GET_32 (abfd, rbase);
1038 if (nameoff >= string_size)
1040 bfd_set_error (bfd_error_malformed_archive);
1041 goto release_armap;
1043 set->name = stringbase + nameoff;
1044 set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
1047 ardata->first_file_filepos = bfd_tell (abfd);
1048 /* Pad to an even boundary if you have to. */
1049 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1050 /* FIXME, we should provide some way to free raw_ardata when
1051 we are done using the strings from it. For now, it seems
1052 to be allocated on an objalloc anyway... */
1053 abfd->has_armap = true;
1054 return true;
1056 release_armap:
1057 ardata->symdef_count = 0;
1058 ardata->symdefs = NULL;
1059 bfd_release (abfd, raw_armap);
1060 return false;
1063 /* Read a COFF archive symbol table. Returns FALSE on error, TRUE
1064 otherwise. */
1066 static bool
1067 do_slurp_coff_armap (bfd *abfd)
1069 struct areltdata *mapdata;
1070 int *raw_armap, *rawptr;
1071 struct artdata *ardata = bfd_ardata (abfd);
1072 char *stringbase;
1073 char *stringend;
1074 bfd_size_type stringsize;
1075 bfd_size_type parsed_size;
1076 ufile_ptr filesize;
1077 size_t nsymz, carsym_size, ptrsize, i;
1078 carsym *carsyms;
1079 bfd_vma (*swap) (const void *);
1080 char int_buf[4];
1081 struct areltdata *tmp;
1083 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1084 if (mapdata == NULL)
1085 return false;
1086 parsed_size = mapdata->parsed_size;
1087 free (mapdata);
1089 if (bfd_read (int_buf, 4, abfd) != 4)
1090 return false;
1092 /* It seems that all numeric information in a coff archive is always
1093 in big endian format, no matter the host or target. */
1094 swap = bfd_getb32;
1095 nsymz = bfd_getb32 (int_buf);
1097 /* The coff armap must be read sequentially. So we construct a
1098 bsd-style one in core all at once, for simplicity. */
1100 if (_bfd_mul_overflow (nsymz, sizeof (carsym), &carsym_size))
1102 bfd_set_error (bfd_error_no_memory);
1103 return false;
1106 filesize = bfd_get_file_size (abfd);
1107 ptrsize = 4 * nsymz;
1108 if ((filesize != 0 && parsed_size > filesize)
1109 || parsed_size < 4
1110 || parsed_size - 4 < ptrsize)
1112 bfd_set_error (bfd_error_malformed_archive);
1113 return false;
1116 stringsize = parsed_size - ptrsize - 4;
1118 if (carsym_size + stringsize + 1 <= carsym_size)
1120 bfd_set_error (bfd_error_no_memory);
1121 return false;
1124 /* Allocate and read in the raw offsets. */
1125 raw_armap = (int *) _bfd_malloc_and_read (abfd, ptrsize, ptrsize);
1126 if (raw_armap == NULL)
1127 return false;
1129 ardata->symdefs = (struct carsym *) bfd_alloc (abfd,
1130 carsym_size + stringsize + 1);
1131 if (ardata->symdefs == NULL)
1132 goto free_armap;
1133 carsyms = ardata->symdefs;
1134 stringbase = ((char *) ardata->symdefs) + carsym_size;
1136 if (bfd_read (stringbase, stringsize, abfd) != stringsize)
1137 goto release_symdefs;
1139 /* OK, build the carsyms. */
1140 stringend = stringbase + stringsize;
1141 *stringend = 0;
1142 for (i = 0; i < nsymz; i++)
1144 rawptr = raw_armap + i;
1145 carsyms->file_offset = swap ((bfd_byte *) rawptr);
1146 carsyms->name = stringbase;
1147 stringbase += strlen (stringbase);
1148 if (stringbase != stringend)
1149 ++stringbase;
1150 carsyms++;
1153 ardata->symdef_count = nsymz;
1154 ardata->first_file_filepos = bfd_tell (abfd);
1155 /* Pad to an even boundary if you have to. */
1156 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1157 if (bfd_seek (abfd, ardata->first_file_filepos, SEEK_SET) != 0)
1158 goto release_symdefs;
1160 abfd->has_armap = true;
1161 free (raw_armap);
1163 /* Check for a second archive header (as used by PE). */
1164 tmp = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1165 if (tmp != NULL)
1167 if (tmp->arch_header[0] == '/'
1168 && tmp->arch_header[1] == ' ')
1169 ardata->first_file_filepos
1170 += (tmp->parsed_size + sizeof (struct ar_hdr) + 1) & ~(unsigned) 1;
1171 free (tmp);
1174 return true;
1176 release_symdefs:
1177 bfd_release (abfd, (ardata)->symdefs);
1178 free_armap:
1179 free (raw_armap);
1180 return false;
1183 /* This routine can handle either coff-style or bsd-style armaps
1184 (archive symbol table). Returns FALSE on error, TRUE otherwise */
1186 bool
1187 bfd_slurp_armap (bfd *abfd)
1189 char nextname[17];
1190 int i = bfd_read (nextname, 16, abfd);
1192 if (i == 0)
1193 return true;
1194 if (i != 16)
1195 return false;
1197 if (bfd_seek (abfd, -16, SEEK_CUR) != 0)
1198 return false;
1200 if (startswith (nextname, "__.SYMDEF ")
1201 || startswith (nextname, "__.SYMDEF/ ")) /* Old Linux archives. */
1202 return do_slurp_bsd_armap (abfd);
1203 else if (startswith (nextname, "/ "))
1204 return do_slurp_coff_armap (abfd);
1205 else if (startswith (nextname, "/SYM64/ "))
1207 /* 64bit (Irix 6) archive. */
1208 #ifdef BFD64
1209 return _bfd_archive_64_bit_slurp_armap (abfd);
1210 #else
1211 bfd_set_error (bfd_error_wrong_format);
1212 return false;
1213 #endif
1215 else if (startswith (nextname, "#1/20 "))
1217 /* Mach-O has a special name for armap when the map is sorted by name.
1218 However because this name has a space it is slightly more difficult
1219 to check it. */
1220 struct ar_hdr hdr;
1221 char extname[21];
1223 if (bfd_read (&hdr, sizeof (hdr), abfd) != sizeof (hdr))
1224 return false;
1225 /* Read the extended name. We know its length. */
1226 if (bfd_read (extname, 20, abfd) != 20)
1227 return false;
1228 if (bfd_seek (abfd, -(file_ptr) (sizeof (hdr) + 20), SEEK_CUR) != 0)
1229 return false;
1230 extname[20] = 0;
1231 if (startswith (extname, "__.SYMDEF SORTED")
1232 || startswith (extname, "__.SYMDEF"))
1233 return do_slurp_bsd_armap (abfd);
1236 abfd->has_armap = false;
1237 return true;
1240 /** Extended name table.
1242 Normally archives support only 14-character filenames.
1244 Intel has extended the format: longer names are stored in a special
1245 element (the first in the archive, or second if there is an armap);
1246 the name in the ar_hdr is replaced by <space><index into filename
1247 element>. Index is the P.R. of an int (decimal). Data General have
1248 extended the format by using the prefix // for the special element. */
1250 /* Returns FALSE on error, TRUE otherwise. */
1252 bool
1253 _bfd_slurp_extended_name_table (bfd *abfd)
1255 char nextname[17];
1257 /* FIXME: Formatting sucks here, and in case of failure of BFD_READ,
1258 we probably don't want to return TRUE. */
1259 if (bfd_seek (abfd, bfd_ardata (abfd)->first_file_filepos, SEEK_SET) != 0)
1260 return false;
1262 if (bfd_read (nextname, 16, abfd) == 16)
1264 struct areltdata *namedata;
1265 bfd_size_type amt;
1266 ufile_ptr filesize;
1268 if (bfd_seek (abfd, -16, SEEK_CUR) != 0)
1269 return false;
1271 if (! startswith (nextname, "ARFILENAMES/ ")
1272 && ! startswith (nextname, "// "))
1274 bfd_ardata (abfd)->extended_names = NULL;
1275 bfd_ardata (abfd)->extended_names_size = 0;
1276 return true;
1279 namedata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1280 if (namedata == NULL)
1281 return false;
1283 filesize = bfd_get_file_size (abfd);
1284 amt = namedata->parsed_size;
1285 if (amt + 1 == 0 || (filesize != 0 && amt > filesize))
1287 bfd_set_error (bfd_error_malformed_archive);
1288 goto byebye;
1291 bfd_ardata (abfd)->extended_names_size = amt;
1292 bfd_ardata (abfd)->extended_names = (char *) bfd_alloc (abfd, amt + 1);
1293 if (bfd_ardata (abfd)->extended_names == NULL)
1295 byebye:
1296 free (namedata);
1297 bfd_ardata (abfd)->extended_names = NULL;
1298 bfd_ardata (abfd)->extended_names_size = 0;
1299 return false;
1302 if (bfd_read (bfd_ardata (abfd)->extended_names, amt, abfd) != amt)
1304 if (bfd_get_error () != bfd_error_system_call)
1305 bfd_set_error (bfd_error_malformed_archive);
1306 bfd_release (abfd, (bfd_ardata (abfd)->extended_names));
1307 bfd_ardata (abfd)->extended_names = NULL;
1308 goto byebye;
1310 bfd_ardata (abfd)->extended_names[amt] = 0;
1312 /* Since the archive is supposed to be printable if it contains
1313 text, the entries in the list are newline-padded, not null
1314 padded. In SVR4-style archives, the names also have a
1315 trailing '/'. DOS/NT created archive often have \ in them
1316 We'll fix all problems here. */
1318 char *ext_names = bfd_ardata (abfd)->extended_names;
1319 char *temp = ext_names;
1320 char *limit = temp + namedata->parsed_size;
1322 for (; temp < limit; ++temp)
1324 if (*temp == ARFMAG[1])
1325 temp[temp > ext_names && temp[-1] == '/' ? -1 : 0] = '\0';
1326 if (*temp == '\\')
1327 *temp = '/';
1329 *limit = '\0';
1332 /* Pad to an even boundary if you have to. */
1333 bfd_ardata (abfd)->first_file_filepos = bfd_tell (abfd);
1334 bfd_ardata (abfd)->first_file_filepos +=
1335 (bfd_ardata (abfd)->first_file_filepos) % 2;
1337 free (namedata);
1339 return true;
1342 #ifdef VMS
1344 /* Return a copy of the stuff in the filename between any :]> and a
1345 semicolon. */
1347 static const char *
1348 normalize (bfd *abfd, const char *file)
1350 const char *first;
1351 const char *last;
1352 char *copy;
1354 if (abfd->flags & BFD_ARCHIVE_FULL_PATH)
1355 return file;
1357 first = file + strlen (file) - 1;
1358 last = first + 1;
1360 while (first != file)
1362 if (*first == ';')
1363 last = first;
1364 if (*first == ':' || *first == ']' || *first == '>')
1366 first++;
1367 break;
1369 first--;
1372 copy = bfd_alloc (abfd, last - first + 1);
1373 if (copy == NULL)
1374 return NULL;
1376 memcpy (copy, first, last - first);
1377 copy[last - first] = 0;
1379 return copy;
1382 #else
1383 static const char *
1384 normalize (bfd *abfd, const char *file)
1386 if (abfd->flags & BFD_ARCHIVE_FULL_PATH)
1387 return file;
1388 return lbasename (file);
1390 #endif
1392 /* Adjust a relative path name based on the reference path.
1393 For example:
1395 Relative path Reference path Result
1396 ------------- -------------- ------
1397 bar.o lib.a bar.o
1398 foo/bar.o lib.a foo/bar.o
1399 bar.o foo/lib.a ../bar.o
1400 foo/bar.o baz/lib.a ../foo/bar.o
1401 bar.o ../lib.a <parent of current dir>/bar.o
1402 ; ../bar.o ../lib.a bar.o
1403 ; ../bar.o lib.a ../bar.o
1404 foo/bar.o ../lib.a <parent of current dir>/foo/bar.o
1405 bar.o ../../lib.a <grandparent>/<parent>/bar.o
1406 bar.o foo/baz/lib.a ../../bar.o
1408 Note - the semicolons above are there to prevent the BFD chew
1409 utility from interpreting those lines as prototypes to put into
1410 the autogenerated bfd.h header...
1412 Note - the string is returned in a static buffer. */
1414 static const char *
1415 adjust_relative_path (const char * path, const char * ref_path)
1417 static char *pathbuf = NULL;
1418 static unsigned int pathbuf_len = 0;
1419 const char *pathp;
1420 const char *refp;
1421 char * lpath;
1422 char * rpath;
1423 unsigned int len;
1424 unsigned int dir_up = 0;
1425 unsigned int dir_down = 0;
1426 char *newp;
1427 char * pwd = getpwd ();
1428 const char * down;
1430 /* Remove symlinks, '.' and '..' from the paths, if possible. */
1431 lpath = lrealpath (path);
1432 pathp = lpath == NULL ? path : lpath;
1434 rpath = lrealpath (ref_path);
1435 refp = rpath == NULL ? ref_path : rpath;
1437 /* Remove common leading path elements. */
1438 for (;;)
1440 const char *e1 = pathp;
1441 const char *e2 = refp;
1443 while (*e1 && ! IS_DIR_SEPARATOR (*e1))
1444 ++e1;
1445 while (*e2 && ! IS_DIR_SEPARATOR (*e2))
1446 ++e2;
1447 if (*e1 == '\0' || *e2 == '\0' || e1 - pathp != e2 - refp
1448 || filename_ncmp (pathp, refp, e1 - pathp) != 0)
1449 break;
1450 pathp = e1 + 1;
1451 refp = e2 + 1;
1454 len = strlen (pathp) + 1;
1455 /* For each leading path element in the reference path,
1456 insert "../" into the path. */
1457 for (; *refp; ++refp)
1458 if (IS_DIR_SEPARATOR (*refp))
1460 /* PR 12710: If the path element is "../" then instead of
1461 inserting "../" we need to insert the name of the directory
1462 at the current level. */
1463 if (refp > ref_path + 1
1464 && refp[-1] == '.'
1465 && refp[-2] == '.')
1466 dir_down ++;
1467 else
1468 dir_up ++;
1471 /* If the lrealpath calls above succeeded then we should never
1472 see dir_up and dir_down both being non-zero. */
1474 len += 3 * dir_up;
1476 if (dir_down)
1478 down = pwd + strlen (pwd) - 1;
1480 while (dir_down && down > pwd)
1482 if (IS_DIR_SEPARATOR (*down))
1483 --dir_down;
1485 BFD_ASSERT (dir_down == 0);
1486 len += strlen (down) + 1;
1488 else
1489 down = NULL;
1491 if (len > pathbuf_len)
1493 free (pathbuf);
1494 pathbuf_len = 0;
1495 pathbuf = (char *) bfd_malloc (len);
1496 if (pathbuf == NULL)
1497 goto out;
1498 pathbuf_len = len;
1501 newp = pathbuf;
1502 while (dir_up-- > 0)
1504 /* FIXME: Support Windows style path separators as well. */
1505 strcpy (newp, "../");
1506 newp += 3;
1509 if (down)
1510 sprintf (newp, "%s/%s", down, pathp);
1511 else
1512 strcpy (newp, pathp);
1514 out:
1515 free (lpath);
1516 free (rpath);
1517 return pathbuf;
1520 /* Build a BFD style extended name table. */
1522 bool
1523 _bfd_archive_bsd_construct_extended_name_table (bfd *abfd,
1524 char **tabloc,
1525 bfd_size_type *tablen,
1526 const char **name)
1528 *name = "ARFILENAMES/";
1529 return _bfd_construct_extended_name_table (abfd, false, tabloc, tablen);
1532 /* Build an SVR4 style extended name table. */
1534 bool
1535 _bfd_archive_coff_construct_extended_name_table (bfd *abfd,
1536 char **tabloc,
1537 bfd_size_type *tablen,
1538 const char **name)
1540 *name = "//";
1541 return _bfd_construct_extended_name_table (abfd, true, tabloc, tablen);
1544 bool
1545 _bfd_noarchive_construct_extended_name_table (bfd *abfd ATTRIBUTE_UNUSED,
1546 char **tabloc ATTRIBUTE_UNUSED,
1547 bfd_size_type *len ATTRIBUTE_UNUSED,
1548 const char **name ATTRIBUTE_UNUSED)
1550 return true;
1553 /* Follows archive_head and produces an extended name table if
1554 necessary. Returns (in tabloc) a pointer to an extended name
1555 table, and in tablen the length of the table. If it makes an entry
1556 it clobbers the filename so that the element may be written without
1557 further massage. Returns TRUE if it ran successfully, FALSE if
1558 something went wrong. A successful return may still involve a
1559 zero-length tablen! */
1561 bool
1562 _bfd_construct_extended_name_table (bfd *abfd,
1563 bool trailing_slash,
1564 char **tabloc,
1565 bfd_size_type *tablen)
1567 unsigned int maxname = ar_maxnamelen (abfd);
1568 bfd_size_type total_namelen = 0;
1569 bfd *current;
1570 char *strptr;
1571 const char *last_filename;
1572 long last_stroff;
1574 *tablen = 0;
1575 last_filename = NULL;
1577 /* Figure out how long the table should be. */
1578 for (current = abfd->archive_head;
1579 current != NULL;
1580 current = current->archive_next)
1582 const char *normal;
1583 unsigned int thislen;
1585 if (bfd_is_thin_archive (abfd))
1587 const char *filename = bfd_get_filename (current);
1589 /* If the element being added is a member of another archive
1590 (i.e., we are flattening), use the containing archive's name. */
1591 if (current->my_archive
1592 && ! bfd_is_thin_archive (current->my_archive))
1593 filename = bfd_get_filename (current->my_archive);
1595 /* If the path is the same as the previous path seen,
1596 reuse it. This can happen when flattening a thin
1597 archive that contains other archives. */
1598 if (last_filename && filename_cmp (last_filename, filename) == 0)
1599 continue;
1601 last_filename = filename;
1603 /* If the path is relative, adjust it relative to
1604 the containing archive. */
1605 if (! IS_ABSOLUTE_PATH (filename)
1606 && ! IS_ABSOLUTE_PATH (bfd_get_filename (abfd)))
1607 normal = adjust_relative_path (filename, bfd_get_filename (abfd));
1608 else
1609 normal = filename;
1611 /* In a thin archive, always store the full pathname
1612 in the extended name table. */
1613 total_namelen += strlen (normal) + 1;
1614 if (trailing_slash)
1615 /* Leave room for trailing slash. */
1616 ++total_namelen;
1618 continue;
1621 normal = normalize (abfd, bfd_get_filename (current));
1622 if (normal == NULL)
1623 return false;
1625 thislen = strlen (normal);
1627 if (thislen > maxname
1628 && (bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
1629 thislen = maxname;
1631 if (thislen > maxname)
1633 /* Add one to leave room for \n. */
1634 total_namelen += thislen + 1;
1635 if (trailing_slash)
1637 /* Leave room for trailing slash. */
1638 ++total_namelen;
1641 else
1643 struct ar_hdr *hdr = arch_hdr (current);
1644 if (filename_ncmp (normal, hdr->ar_name, thislen) != 0
1645 || (thislen < sizeof hdr->ar_name
1646 && hdr->ar_name[thislen] != ar_padchar (current)))
1648 /* Must have been using extended format even though it
1649 didn't need to. Fix it to use normal format. */
1650 memcpy (hdr->ar_name, normal, thislen);
1651 if (thislen < maxname
1652 || (thislen == maxname && thislen < sizeof hdr->ar_name))
1653 hdr->ar_name[thislen] = ar_padchar (current);
1658 if (total_namelen == 0)
1659 return true;
1661 *tabloc = (char *) bfd_alloc (abfd, total_namelen);
1662 if (*tabloc == NULL)
1663 return false;
1665 *tablen = total_namelen;
1666 strptr = *tabloc;
1668 last_filename = NULL;
1669 last_stroff = 0;
1671 for (current = abfd->archive_head;
1672 current != NULL;
1673 current = current->archive_next)
1675 const char *normal;
1676 unsigned int thislen;
1677 long stroff;
1678 const char *filename = bfd_get_filename (current);
1680 if (bfd_is_thin_archive (abfd))
1682 /* If the element being added is a member of another archive
1683 (i.e., we are flattening), use the containing archive's name. */
1684 if (current->my_archive
1685 && ! bfd_is_thin_archive (current->my_archive))
1686 filename = bfd_get_filename (current->my_archive);
1687 /* If the path is the same as the previous path seen,
1688 reuse it. This can happen when flattening a thin
1689 archive that contains other archives.
1690 If the path is relative, adjust it relative to
1691 the containing archive. */
1692 if (last_filename && filename_cmp (last_filename, filename) == 0)
1693 normal = last_filename;
1694 else if (! IS_ABSOLUTE_PATH (filename)
1695 && ! IS_ABSOLUTE_PATH (bfd_get_filename (abfd)))
1696 normal = adjust_relative_path (filename, bfd_get_filename (abfd));
1697 else
1698 normal = filename;
1700 else
1702 normal = normalize (abfd, filename);
1703 if (normal == NULL)
1704 return false;
1707 thislen = strlen (normal);
1708 if (thislen > maxname || bfd_is_thin_archive (abfd))
1710 /* Works for now; may need to be re-engineered if we
1711 encounter an oddball archive format and want to
1712 generalise this hack. */
1713 struct ar_hdr *hdr = arch_hdr (current);
1714 if (normal == last_filename)
1715 stroff = last_stroff;
1716 else
1718 last_filename = filename;
1719 stroff = strptr - *tabloc;
1720 last_stroff = stroff;
1721 memcpy (strptr, normal, thislen);
1722 strptr += thislen;
1723 if (trailing_slash)
1724 *strptr++ = '/';
1725 *strptr++ = ARFMAG[1];
1727 hdr->ar_name[0] = ar_padchar (current);
1728 if (bfd_is_thin_archive (abfd) && current->origin > 0)
1730 int len = snprintf (hdr->ar_name + 1, maxname - 1, "%-ld:",
1731 stroff);
1732 _bfd_ar_spacepad (hdr->ar_name + 1 + len, maxname - 1 - len,
1733 "%-ld",
1734 current->origin - sizeof (struct ar_hdr));
1736 else
1737 _bfd_ar_spacepad (hdr->ar_name + 1, maxname - 1, "%-ld", stroff);
1741 return true;
1744 /* Do not construct an extended name table but transforms name field into
1745 its extended form. */
1747 bool
1748 _bfd_archive_bsd44_construct_extended_name_table (bfd *abfd,
1749 char **tabloc,
1750 bfd_size_type *tablen,
1751 const char **name)
1753 unsigned int maxname = ar_maxnamelen (abfd);
1754 bfd *current;
1756 *tablen = 0;
1757 *tabloc = NULL;
1758 *name = NULL;
1760 for (current = abfd->archive_head;
1761 current != NULL;
1762 current = current->archive_next)
1764 const char *normal = normalize (abfd, bfd_get_filename (current));
1765 int has_space = 0;
1766 unsigned int len;
1768 if (normal == NULL)
1769 return false;
1771 for (len = 0; normal[len]; len++)
1772 if (normal[len] == ' ')
1773 has_space = 1;
1775 if (len > maxname || has_space)
1777 struct ar_hdr *hdr = arch_hdr (current);
1779 len = (len + 3) & ~3;
1780 arch_eltdata (current)->extra_size = len;
1781 _bfd_ar_spacepad (hdr->ar_name, maxname, "#1/%lu", len);
1785 return true;
1788 /* Write an archive header. */
1790 bool
1791 _bfd_generic_write_ar_hdr (bfd *archive, bfd *abfd)
1793 struct ar_hdr *hdr = arch_hdr (abfd);
1795 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1796 return false;
1797 return true;
1800 /* Write an archive header using BSD4.4 convention. */
1802 bool
1803 _bfd_bsd44_write_ar_hdr (bfd *archive, bfd *abfd)
1805 struct ar_hdr *hdr = arch_hdr (abfd);
1807 if (is_bsd44_extended_name (hdr->ar_name))
1809 /* This is a BSD 4.4 extended name. */
1810 const char *fullname = normalize (abfd, bfd_get_filename (abfd));
1811 unsigned int len = strlen (fullname);
1812 unsigned int padded_len = (len + 3) & ~3;
1814 BFD_ASSERT (padded_len == arch_eltdata (abfd)->extra_size);
1816 if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size),
1817 arch_eltdata (abfd)->parsed_size + padded_len))
1818 return false;
1820 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1821 return false;
1823 if (bfd_write (fullname, len, archive) != len)
1824 return false;
1826 if (len & 3)
1828 static const char pad[3] = { 0, 0, 0 };
1830 len = 4 - (len & 3);
1831 if (bfd_write (pad, len, archive) != len)
1832 return false;
1835 else
1837 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1838 return false;
1840 return true;
1843 bool
1844 _bfd_noarchive_write_ar_hdr (bfd *archive, bfd *abfd ATTRIBUTE_UNUSED)
1846 return _bfd_bool_bfd_false_error (archive);
1849 /* A couple of functions for creating ar_hdrs. */
1851 #ifdef HPUX_LARGE_AR_IDS
1852 /* Function to encode large UID/GID values according to HP. */
1854 static void
1855 hpux_uid_gid_encode (char str[6], long int id)
1857 int cnt;
1859 str[5] = '@' + (id & 3);
1860 id >>= 2;
1862 for (cnt = 4; cnt >= 0; --cnt, id >>= 6)
1863 str[cnt] = ' ' + (id & 0x3f);
1865 #endif /* HPUX_LARGE_AR_IDS */
1867 /* Takes a filename, returns an arelt_data for it, or NULL if it can't
1868 make one. The filename must refer to a filename in the filesystem.
1869 The filename field of the ar_hdr will NOT be initialized. If member
1870 is set, and it's an in-memory bfd, we fake it. */
1872 static struct areltdata *
1873 bfd_ar_hdr_from_filesystem (bfd *abfd, const char *filename, bfd *member)
1875 struct stat status;
1876 struct areltdata *ared;
1877 struct ar_hdr *hdr;
1878 size_t amt;
1880 if (member && (member->flags & BFD_IN_MEMORY) != 0)
1882 /* Assume we just "made" the member, and fake it. */
1883 struct bfd_in_memory *bim = (struct bfd_in_memory *) member->iostream;
1884 status.st_mtime = bfd_get_current_time (0);
1885 status.st_uid = getuid ();
1886 status.st_gid = getgid ();
1887 status.st_mode = 0644;
1888 status.st_size = bim->size;
1890 else if (stat (filename, &status) != 0)
1892 bfd_set_error (bfd_error_system_call);
1893 return NULL;
1895 else
1897 /* The call to stat() above has filled in the st_mtime field
1898 with the real time that the object was modified. But if
1899 we are trying to generate deterministic archives based upon
1900 the SOURCE_DATE_EPOCH environment variable then we want to
1901 override that. */
1902 status.st_mtime = bfd_get_current_time (status.st_mtime);
1905 /* If the caller requested that the BFD generate deterministic output,
1906 fake values for modification time, UID, GID, and file mode. */
1907 if ((abfd->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
1909 status.st_mtime = 0;
1910 status.st_uid = 0;
1911 status.st_gid = 0;
1912 status.st_mode = 0644;
1915 amt = sizeof (struct ar_hdr) + sizeof (struct areltdata);
1916 ared = (struct areltdata *) bfd_zmalloc (amt);
1917 if (ared == NULL)
1918 return NULL;
1919 hdr = (struct ar_hdr *) (((char *) ared) + sizeof (struct areltdata));
1921 /* ar headers are space padded, not null padded! */
1922 memset (hdr, ' ', sizeof (struct ar_hdr));
1924 _bfd_ar_spacepad (hdr->ar_date, sizeof (hdr->ar_date), "%-12ld",
1925 status.st_mtime);
1926 #ifdef HPUX_LARGE_AR_IDS
1927 /* HP has a very "special" way to handle UID/GID's with numeric values
1928 > 99999. */
1929 if (status.st_uid > 99999)
1930 hpux_uid_gid_encode (hdr->ar_uid, (long) status.st_uid);
1931 else
1932 #endif
1933 _bfd_ar_spacepad (hdr->ar_uid, sizeof (hdr->ar_uid), "%ld",
1934 status.st_uid);
1935 #ifdef HPUX_LARGE_AR_IDS
1936 /* HP has a very "special" way to handle UID/GID's with numeric values
1937 > 99999. */
1938 if (status.st_gid > 99999)
1939 hpux_uid_gid_encode (hdr->ar_gid, (long) status.st_gid);
1940 else
1941 #endif
1942 _bfd_ar_spacepad (hdr->ar_gid, sizeof (hdr->ar_gid), "%ld",
1943 status.st_gid);
1944 _bfd_ar_spacepad (hdr->ar_mode, sizeof (hdr->ar_mode), "%-8lo",
1945 status.st_mode);
1946 if (status.st_size - (bfd_size_type) status.st_size != 0)
1948 bfd_set_error (bfd_error_file_too_big);
1949 free (ared);
1950 return NULL;
1952 if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size), status.st_size))
1954 free (ared);
1955 return NULL;
1957 memcpy (hdr->ar_fmag, ARFMAG, 2);
1958 ared->parsed_size = status.st_size;
1959 ared->arch_header = (char *) hdr;
1961 return ared;
1964 /* Analogous to stat call. */
1967 bfd_generic_stat_arch_elt (bfd *abfd, struct stat *buf)
1969 struct ar_hdr *hdr;
1970 char *aloser;
1972 if (abfd->arelt_data == NULL)
1974 bfd_set_error (bfd_error_invalid_operation);
1975 return -1;
1978 hdr = arch_hdr (abfd);
1979 /* PR 17512: file: 3d9e9fe9. */
1980 if (hdr == NULL)
1981 return -1;
1982 #define foo(arelt, stelt, size) \
1983 buf->stelt = strtol (hdr->arelt, &aloser, size); \
1984 if (aloser == hdr->arelt) \
1985 return -1;
1987 /* Some platforms support special notations for large IDs. */
1988 #ifdef HPUX_LARGE_AR_IDS
1989 # define foo2(arelt, stelt, size) \
1990 if (hdr->arelt[5] == ' ') \
1992 foo (arelt, stelt, size); \
1994 else \
1996 int cnt; \
1997 for (buf->stelt = cnt = 0; cnt < 5; ++cnt) \
1999 if (hdr->arelt[cnt] < ' ' || hdr->arelt[cnt] > ' ' + 0x3f) \
2000 return -1; \
2001 buf->stelt <<= 6; \
2002 buf->stelt += hdr->arelt[cnt] - ' '; \
2004 if (hdr->arelt[5] < '@' || hdr->arelt[5] > '@' + 3) \
2005 return -1; \
2006 buf->stelt <<= 2; \
2007 buf->stelt += hdr->arelt[5] - '@'; \
2009 #else
2010 # define foo2(arelt, stelt, size) foo (arelt, stelt, size)
2011 #endif
2013 foo (ar_date, st_mtime, 10);
2014 foo2 (ar_uid, st_uid, 10);
2015 foo2 (ar_gid, st_gid, 10);
2016 foo (ar_mode, st_mode, 8);
2018 buf->st_size = arch_eltdata (abfd)->parsed_size;
2020 return 0;
2023 void
2024 bfd_dont_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2026 /* FIXME: This interacts unpleasantly with ar's quick-append option.
2027 Fortunately ic960 users will never use that option. Fixing this
2028 is very hard; fortunately I know how to do it and will do so once
2029 intel's release is out the door. */
2031 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2032 size_t length;
2033 const char *filename;
2034 size_t maxlen = ar_maxnamelen (abfd);
2036 if ((bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
2038 bfd_bsd_truncate_arname (abfd, pathname, arhdr);
2039 return;
2042 filename = normalize (abfd, pathname);
2043 if (filename == NULL)
2045 /* FIXME */
2046 abort ();
2049 length = strlen (filename);
2051 if (length <= maxlen)
2052 memcpy (hdr->ar_name, filename, length);
2054 /* Add the padding character if there is room for it. */
2055 if (length < maxlen
2056 || (length == maxlen && length < sizeof hdr->ar_name))
2057 (hdr->ar_name)[length] = ar_padchar (abfd);
2060 void
2061 bfd_bsd_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2063 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2064 size_t length;
2065 const char *filename = lbasename (pathname);
2066 size_t maxlen = ar_maxnamelen (abfd);
2068 length = strlen (filename);
2070 if (length <= maxlen)
2071 memcpy (hdr->ar_name, filename, length);
2072 else
2074 /* pathname: meet procrustes */
2075 memcpy (hdr->ar_name, filename, maxlen);
2076 length = maxlen;
2079 if (length < maxlen)
2080 (hdr->ar_name)[length] = ar_padchar (abfd);
2083 /* Store name into ar header. Truncates the name to fit.
2084 1> strip pathname to be just the basename.
2085 2> if it's short enuf to fit, stuff it in.
2086 3> If it doesn't end with .o, truncate it to fit
2087 4> truncate it before the .o, append .o, stuff THAT in. */
2089 /* This is what gnu ar does. It's better but incompatible with the
2090 bsd ar. */
2092 void
2093 bfd_gnu_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2095 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2096 size_t length;
2097 const char *filename = lbasename (pathname);
2098 size_t maxlen = ar_maxnamelen (abfd);
2100 length = strlen (filename);
2102 if (length <= maxlen)
2103 memcpy (hdr->ar_name, filename, length);
2104 else
2106 /* pathname: meet procrustes. */
2107 memcpy (hdr->ar_name, filename, maxlen);
2108 if ((filename[length - 2] == '.') && (filename[length - 1] == 'o'))
2110 hdr->ar_name[maxlen - 2] = '.';
2111 hdr->ar_name[maxlen - 1] = 'o';
2113 length = maxlen;
2116 if (length < 16)
2117 (hdr->ar_name)[length] = ar_padchar (abfd);
2120 void
2121 _bfd_noarchive_truncate_arname (bfd *abfd ATTRIBUTE_UNUSED,
2122 const char *pathname ATTRIBUTE_UNUSED,
2123 char *arhdr ATTRIBUTE_UNUSED)
2127 /* The BFD is open for write and has its format set to bfd_archive. */
2129 bool
2130 _bfd_write_archive_contents (bfd *arch)
2132 bfd *current;
2133 char *etable = NULL;
2134 bfd_size_type elength = 0;
2135 const char *ename = NULL;
2136 bool makemap = bfd_has_map (arch);
2137 /* If no .o's, don't bother to make a map. */
2138 bool hasobjects = false;
2139 bfd_size_type wrote;
2140 int tries;
2141 char *armag;
2142 char *buffer = NULL;
2144 /* Verify the viability of all entries; if any of them live in the
2145 filesystem (as opposed to living in an archive open for input)
2146 then construct a fresh ar_hdr for them. */
2147 for (current = arch->archive_head;
2148 current != NULL;
2149 current = current->archive_next)
2151 /* This check is checking the bfds for the objects we're reading
2152 from (which are usually either an object file or archive on
2153 disk), not the archive entries we're writing to. We don't
2154 actually create bfds for the archive members, we just copy
2155 them byte-wise when we write out the archive. */
2156 if (bfd_write_p (current))
2158 bfd_set_error (bfd_error_invalid_operation);
2159 goto input_err;
2161 if (!current->arelt_data)
2163 current->arelt_data =
2164 bfd_ar_hdr_from_filesystem (arch, bfd_get_filename (current),
2165 current);
2166 if (!current->arelt_data)
2167 goto input_err;
2169 /* Put in the file name. */
2170 BFD_SEND (arch, _bfd_truncate_arname,
2171 (arch, bfd_get_filename (current),
2172 (char *) arch_hdr (current)));
2175 if (makemap && ! hasobjects)
2176 { /* Don't bother if we won't make a map! */
2177 if ((bfd_check_format (current, bfd_object)))
2178 hasobjects = true;
2182 if (!BFD_SEND (arch, _bfd_construct_extended_name_table,
2183 (arch, &etable, &elength, &ename)))
2184 return false;
2186 if (bfd_seek (arch, 0, SEEK_SET) != 0)
2187 return false;
2188 armag = ARMAG;
2189 if (bfd_is_thin_archive (arch))
2190 armag = ARMAGT;
2191 wrote = bfd_write (armag, SARMAG, arch);
2192 if (wrote != SARMAG)
2193 return false;
2195 if (makemap && hasobjects)
2197 if (! _bfd_compute_and_write_armap (arch, (unsigned int) elength))
2198 return false;
2201 if (elength != 0)
2203 struct ar_hdr hdr;
2205 memset (&hdr, ' ', sizeof (struct ar_hdr));
2206 memcpy (hdr.ar_name, ename, strlen (ename));
2207 /* Round size up to even number in archive header. */
2208 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size),
2209 (elength + 1) & ~(bfd_size_type) 1))
2210 return false;
2211 memcpy (hdr.ar_fmag, ARFMAG, 2);
2212 if ((bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2213 != sizeof (struct ar_hdr))
2214 || bfd_write (etable, elength, arch) != elength)
2215 return false;
2216 if ((elength % 2) == 1)
2218 if (bfd_write (&ARFMAG[1], 1, arch) != 1)
2219 return false;
2223 #define AR_WRITE_BUFFERSIZE (8 * 1024 * 1024)
2225 /* FIXME: Find a way to test link_info.reduce_memory_overheads
2226 and change the buffer size. */
2227 buffer = bfd_malloc (AR_WRITE_BUFFERSIZE);
2228 if (buffer == NULL)
2229 goto input_err;
2231 for (current = arch->archive_head;
2232 current != NULL;
2233 current = current->archive_next)
2235 bfd_size_type remaining = arelt_size (current);
2237 /* Write ar header. */
2238 if (!_bfd_write_ar_hdr (arch, current))
2239 goto input_err;
2240 if (bfd_is_thin_archive (arch))
2241 continue;
2242 if (bfd_seek (current, 0, SEEK_SET) != 0)
2243 goto input_err;
2245 while (remaining)
2247 size_t amt = AR_WRITE_BUFFERSIZE;
2249 if (amt > remaining)
2250 amt = remaining;
2251 errno = 0;
2252 if (bfd_read (buffer, amt, current) != amt)
2253 goto input_err;
2254 if (bfd_write (buffer, amt, arch) != amt)
2255 goto input_err;
2256 remaining -= amt;
2259 if ((arelt_size (current) % 2) == 1)
2261 if (bfd_write (&ARFMAG[1], 1, arch) != 1)
2262 goto input_err;
2266 free (buffer);
2268 if (makemap && hasobjects)
2270 /* Verify the timestamp in the archive file. If it would not be
2271 accepted by the linker, rewrite it until it would be. If
2272 anything odd happens, break out and just return. (The
2273 Berkeley linker checks the timestamp and refuses to read the
2274 table-of-contents if it is >60 seconds less than the file's
2275 modified-time. That painful hack requires this painful hack. */
2276 tries = 1;
2279 if (bfd_update_armap_timestamp (arch))
2280 break;
2281 _bfd_error_handler
2282 (_("warning: writing archive was slow: rewriting timestamp"));
2284 while (++tries < 6);
2287 return true;
2289 input_err:
2290 bfd_set_input_error (current, bfd_get_error ());
2291 free (buffer);
2292 return false;
2295 /* Note that the namidx for the first symbol is 0. */
2297 bool
2298 _bfd_compute_and_write_armap (bfd *arch, unsigned int elength)
2300 char *first_name = NULL;
2301 bfd *current;
2302 file_ptr elt_no = 0;
2303 struct orl *map = NULL;
2304 unsigned int orl_max = 1024; /* Fine initial default. */
2305 unsigned int orl_count = 0;
2306 int stridx = 0;
2307 asymbol **syms = NULL;
2308 long syms_max = 0;
2309 bool ret;
2310 size_t amt;
2311 static bool report_plugin_err = true;
2313 /* Dunno if this is the best place for this info... */
2314 if (elength != 0)
2315 elength += sizeof (struct ar_hdr);
2316 elength += elength % 2;
2318 amt = orl_max * sizeof (struct orl);
2319 map = (struct orl *) bfd_malloc (amt);
2320 if (map == NULL)
2321 goto error_return;
2323 /* We put the symbol names on the arch objalloc, and then discard
2324 them when done. */
2325 first_name = (char *) bfd_alloc (arch, 1);
2326 if (first_name == NULL)
2327 goto error_return;
2329 /* Drop all the files called __.SYMDEF, we're going to make our own. */
2330 while (arch->archive_head
2331 && strcmp (bfd_get_filename (arch->archive_head), "__.SYMDEF") == 0)
2332 arch->archive_head = arch->archive_head->archive_next;
2334 /* Map over each element. */
2335 for (current = arch->archive_head;
2336 current != NULL;
2337 current = current->archive_next, elt_no++)
2339 if (bfd_check_format (current, bfd_object)
2340 && (bfd_get_file_flags (current) & HAS_SYMS) != 0)
2342 long storage;
2343 long symcount;
2344 long src_count;
2346 if (bfd_get_lto_type (current) == lto_slim_ir_object
2347 && report_plugin_err)
2349 report_plugin_err = false;
2350 _bfd_error_handler
2351 (_("%pB: plugin needed to handle lto object"),
2352 current);
2355 storage = bfd_get_symtab_upper_bound (current);
2356 if (storage < 0)
2357 goto error_return;
2359 if (storage != 0)
2361 if (storage > syms_max)
2363 free (syms);
2364 syms_max = storage;
2365 syms = (asymbol **) bfd_malloc (syms_max);
2366 if (syms == NULL)
2367 goto error_return;
2369 symcount = bfd_canonicalize_symtab (current, syms);
2370 if (symcount < 0)
2371 goto error_return;
2373 /* Now map over all the symbols, picking out the ones we
2374 want. */
2375 for (src_count = 0; src_count < symcount; src_count++)
2377 flagword flags = (syms[src_count])->flags;
2378 asection *sec = syms[src_count]->section;
2380 if (((flags & (BSF_GLOBAL
2381 | BSF_WEAK
2382 | BSF_INDIRECT
2383 | BSF_GNU_UNIQUE)) != 0
2384 || bfd_is_com_section (sec))
2385 && ! bfd_is_und_section (sec))
2387 bfd_size_type namelen;
2388 struct orl *new_map;
2390 /* This symbol will go into the archive header. */
2391 if (orl_count == orl_max)
2393 orl_max *= 2;
2394 amt = orl_max * sizeof (struct orl);
2395 new_map = (struct orl *) bfd_realloc (map, amt);
2396 if (new_map == NULL)
2397 goto error_return;
2399 map = new_map;
2402 if (syms[src_count]->name != NULL
2403 && syms[src_count]->name[0] == '_'
2404 && syms[src_count]->name[1] == '_'
2405 && strcmp (syms[src_count]->name
2406 + (syms[src_count]->name[2] == '_'),
2407 "__gnu_lto_slim") == 0
2408 && report_plugin_err)
2410 report_plugin_err = false;
2411 _bfd_error_handler
2412 (_("%pB: plugin needed to handle lto object"),
2413 current);
2415 namelen = strlen (syms[src_count]->name);
2416 amt = sizeof (char *);
2417 map[orl_count].name = (char **) bfd_alloc (arch, amt);
2418 if (map[orl_count].name == NULL)
2419 goto error_return;
2420 *(map[orl_count].name) = (char *) bfd_alloc (arch,
2421 namelen + 1);
2422 if (*(map[orl_count].name) == NULL)
2423 goto error_return;
2424 strcpy (*(map[orl_count].name), syms[src_count]->name);
2425 map[orl_count].u.abfd = current;
2426 map[orl_count].namidx = stridx;
2428 stridx += namelen + 1;
2429 ++orl_count;
2434 /* Now ask the BFD to free up any cached information, so we
2435 don't fill all of memory with symbol tables. */
2436 if (! bfd_free_cached_info (current))
2437 goto error_return;
2441 /* OK, now we have collected all the data, let's write them out. */
2442 ret = BFD_SEND (arch, write_armap,
2443 (arch, elength, map, orl_count, stridx));
2445 free (syms);
2446 free (map);
2447 if (first_name != NULL)
2448 bfd_release (arch, first_name);
2450 return ret;
2452 error_return:
2453 free (syms);
2454 free (map);
2455 if (first_name != NULL)
2456 bfd_release (arch, first_name);
2458 return false;
2461 bool
2462 _bfd_bsd_write_armap (bfd *arch,
2463 unsigned int elength,
2464 struct orl *map,
2465 unsigned int orl_count,
2466 int stridx)
2468 int padit = stridx & 1;
2469 unsigned int ranlibsize = orl_count * BSD_SYMDEF_SIZE;
2470 unsigned int stringsize = stridx + padit;
2471 /* Include 8 bytes to store ranlibsize and stringsize in output. */
2472 unsigned int mapsize = ranlibsize + stringsize + 8;
2473 file_ptr firstreal, first;
2474 bfd *current;
2475 bfd *last_elt;
2476 bfd_byte temp[4];
2477 unsigned int count;
2478 struct ar_hdr hdr;
2479 long uid, gid;
2481 first = mapsize + elength + sizeof (struct ar_hdr) + SARMAG;
2483 #ifdef BFD64
2484 firstreal = first;
2485 current = arch->archive_head;
2486 last_elt = current; /* Last element arch seen. */
2487 for (count = 0; count < orl_count; count++)
2489 unsigned int offset;
2491 if (map[count].u.abfd != last_elt)
2495 struct areltdata *ared = arch_eltdata (current);
2497 firstreal += (ared->parsed_size + ared->extra_size
2498 + sizeof (struct ar_hdr));
2499 firstreal += firstreal % 2;
2500 current = current->archive_next;
2502 while (current != map[count].u.abfd);
2505 /* The archive file format only has 4 bytes to store the offset
2506 of the member. Generate 64-bit archive if an archive is past
2507 its 4Gb limit. */
2508 offset = (unsigned int) firstreal;
2509 if (firstreal != (file_ptr) offset)
2510 return _bfd_archive_64_bit_write_armap (arch, elength, map,
2511 orl_count, stridx);
2513 last_elt = current;
2515 #endif
2517 /* If deterministic, we use 0 as the timestamp in the map.
2518 Some linkers may require that the archive filesystem modification
2519 time is less than (or near to) the archive map timestamp. Those
2520 linkers should not be used with deterministic mode. (GNU ld and
2521 Gold do not have this restriction.) */
2522 bfd_ardata (arch)->armap_timestamp = 0;
2523 uid = 0;
2524 gid = 0;
2525 if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0)
2527 struct stat statbuf;
2529 if (stat (bfd_get_filename (arch), &statbuf) == 0)
2531 /* If asked, replace the time with a deterministic value. */
2532 statbuf.st_mtime = bfd_get_current_time (statbuf.st_mtime);
2534 bfd_ardata (arch)->armap_timestamp = (statbuf.st_mtime
2535 + ARMAP_TIME_OFFSET);
2537 uid = getuid();
2538 gid = getgid();
2541 memset (&hdr, ' ', sizeof (struct ar_hdr));
2542 memcpy (hdr.ar_name, RANLIBMAG, strlen (RANLIBMAG));
2543 bfd_ardata (arch)->armap_datepos = (SARMAG
2544 + offsetof (struct ar_hdr, ar_date[0]));
2545 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2546 bfd_ardata (arch)->armap_timestamp);
2547 _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", uid);
2548 _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", gid);
2549 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
2550 return false;
2551 memcpy (hdr.ar_fmag, ARFMAG, 2);
2552 if (bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2553 != sizeof (struct ar_hdr))
2554 return false;
2555 H_PUT_32 (arch, ranlibsize, temp);
2556 if (bfd_write (temp, sizeof (temp), arch) != sizeof (temp))
2557 return false;
2559 firstreal = first;
2560 current = arch->archive_head;
2561 last_elt = current; /* Last element arch seen. */
2562 for (count = 0; count < orl_count; count++)
2564 unsigned int offset;
2565 bfd_byte buf[BSD_SYMDEF_SIZE];
2567 if (map[count].u.abfd != last_elt)
2571 struct areltdata *ared = arch_eltdata (current);
2573 firstreal += (ared->parsed_size + ared->extra_size
2574 + sizeof (struct ar_hdr));
2575 firstreal += firstreal % 2;
2576 current = current->archive_next;
2578 while (current != map[count].u.abfd);
2581 /* The archive file format only has 4 bytes to store the offset
2582 of the member. Check to make sure that firstreal has not grown
2583 too big. */
2584 offset = (unsigned int) firstreal;
2585 if (firstreal != (file_ptr) offset)
2587 bfd_set_error (bfd_error_file_truncated);
2588 return false;
2591 last_elt = current;
2592 H_PUT_32 (arch, map[count].namidx, buf);
2593 H_PUT_32 (arch, firstreal, buf + BSD_SYMDEF_OFFSET_SIZE);
2594 if (bfd_write (buf, BSD_SYMDEF_SIZE, arch)
2595 != BSD_SYMDEF_SIZE)
2596 return false;
2599 /* Now write the strings themselves. */
2600 H_PUT_32 (arch, stringsize, temp);
2601 if (bfd_write (temp, sizeof (temp), arch) != sizeof (temp))
2602 return false;
2603 for (count = 0; count < orl_count; count++)
2605 size_t len = strlen (*map[count].name) + 1;
2607 if (bfd_write (*map[count].name, len, arch) != len)
2608 return false;
2611 /* The spec sez this should be a newline. But in order to be
2612 bug-compatible for sun's ar we use a null. */
2613 if (padit)
2615 if (bfd_write ("", 1, arch) != 1)
2616 return false;
2619 return true;
2622 /* At the end of archive file handling, update the timestamp in the
2623 file, so older linkers will accept it. (This does not apply to
2624 ld.bfd or ld.gold).
2626 Return TRUE if the timestamp was OK, or an unusual problem happened.
2627 Return FALSE if we updated the timestamp. */
2629 bool
2630 _bfd_archive_bsd_update_armap_timestamp (bfd *arch)
2632 struct stat archstat;
2633 struct ar_hdr hdr;
2635 /* If creating deterministic archives, just leave the timestamp as-is. */
2636 if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
2637 return true;
2639 /* Flush writes, get last-write timestamp from file, and compare it
2640 to the timestamp IN the file. */
2641 bfd_flush (arch);
2642 if (bfd_stat (arch, &archstat) == -1)
2644 bfd_perror (_("Reading archive file mod timestamp"));
2646 /* Can't read mod time for some reason. */
2647 return true;
2650 if (((long) archstat.st_mtime) <= bfd_ardata (arch)->armap_timestamp)
2651 /* OK by the linker's rules. */
2652 return true;
2654 if (getenv ("SOURCE_DATE_EPOCH") != NULL
2655 && bfd_ardata (arch)->armap_timestamp == bfd_get_current_time (0) + ARMAP_TIME_OFFSET)
2656 /* If the archive's timestamp has been set to SOURCE_DATE_EPOCH
2657 then leave it as-is. */
2658 return true;
2660 /* Update the timestamp. */
2661 bfd_ardata (arch)->armap_timestamp = archstat.st_mtime + ARMAP_TIME_OFFSET;
2663 /* Prepare an ASCII version suitable for writing. */
2664 memset (hdr.ar_date, ' ', sizeof (hdr.ar_date));
2665 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2666 bfd_ardata (arch)->armap_timestamp);
2668 /* Write it into the file. */
2669 bfd_ardata (arch)->armap_datepos = (SARMAG
2670 + offsetof (struct ar_hdr, ar_date[0]));
2671 if (bfd_seek (arch, bfd_ardata (arch)->armap_datepos, SEEK_SET) != 0
2672 || (bfd_write (hdr.ar_date, sizeof (hdr.ar_date), arch)
2673 != sizeof (hdr.ar_date)))
2675 bfd_perror (_("Writing updated armap timestamp"));
2677 /* Some error while writing. */
2678 return true;
2681 /* We updated the timestamp successfully. */
2682 return false;
2685 /* A coff armap looks like :
2686 lARMAG
2687 struct ar_hdr with name = '/'
2688 number of symbols
2689 offset of file for symbol 0
2690 offset of file for symbol 1
2692 offset of file for symbol n-1
2693 symbol name 0
2694 symbol name 1
2696 symbol name n-1 */
2698 bool
2699 _bfd_coff_write_armap (bfd *arch,
2700 unsigned int elength,
2701 struct orl *map,
2702 unsigned int symbol_count,
2703 int stridx)
2705 /* The size of the ranlib is the number of exported symbols in the
2706 archive * the number of bytes in an int, + an int for the count. */
2707 unsigned int ranlibsize = (symbol_count * 4) + 4;
2708 unsigned int stringsize = stridx;
2709 unsigned int mapsize = stringsize + ranlibsize;
2710 file_ptr archive_member_file_ptr;
2711 file_ptr first_archive_member_file_ptr;
2712 bfd *current = arch->archive_head;
2713 unsigned int count;
2714 struct ar_hdr hdr;
2715 int padit = mapsize & 1;
2717 if (padit)
2718 mapsize++;
2720 /* Work out where the first object file will go in the archive. */
2721 first_archive_member_file_ptr = (mapsize
2722 + elength
2723 + sizeof (struct ar_hdr)
2724 + SARMAG);
2726 #ifdef BFD64
2727 current = arch->archive_head;
2728 count = 0;
2729 archive_member_file_ptr = first_archive_member_file_ptr;
2730 while (current != NULL && count < symbol_count)
2732 /* For each symbol which is used defined in this object, write
2733 out the object file's address in the archive. */
2735 while (count < symbol_count && map[count].u.abfd == current)
2737 unsigned int offset = (unsigned int) archive_member_file_ptr;
2739 /* Generate 64-bit archive if an archive is past its 4Gb
2740 limit. */
2741 if (archive_member_file_ptr != (file_ptr) offset)
2742 return _bfd_archive_64_bit_write_armap (arch, elength, map,
2743 symbol_count, stridx);
2744 count++;
2746 archive_member_file_ptr += sizeof (struct ar_hdr);
2747 if (! bfd_is_thin_archive (arch))
2749 /* Add size of this archive entry. */
2750 archive_member_file_ptr += arelt_size (current);
2751 /* Remember about the even alignment. */
2752 archive_member_file_ptr += archive_member_file_ptr % 2;
2754 current = current->archive_next;
2756 #endif
2758 memset (&hdr, ' ', sizeof (struct ar_hdr));
2759 hdr.ar_name[0] = '/';
2760 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
2761 return false;
2762 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2763 ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0
2764 ? time (NULL) : 0));
2765 /* This, at least, is what Intel coff sets the values to. */
2766 _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", 0);
2767 _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", 0);
2768 _bfd_ar_spacepad (hdr.ar_mode, sizeof (hdr.ar_mode), "%-7lo", 0);
2769 memcpy (hdr.ar_fmag, ARFMAG, 2);
2771 /* Write the ar header for this item and the number of symbols. */
2772 if (bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2773 != sizeof (struct ar_hdr))
2774 return false;
2776 if (!bfd_write_bigendian_4byte_int (arch, symbol_count))
2777 return false;
2779 /* Two passes, first write the file offsets for each symbol -
2780 remembering that each offset is on a two byte boundary. */
2782 /* Write out the file offset for the file associated with each
2783 symbol, and remember to keep the offsets padded out. */
2785 current = arch->archive_head;
2786 count = 0;
2787 archive_member_file_ptr = first_archive_member_file_ptr;
2788 while (current != NULL && count < symbol_count)
2790 /* For each symbol which is used defined in this object, write
2791 out the object file's address in the archive. */
2793 while (count < symbol_count && map[count].u.abfd == current)
2795 unsigned int offset = (unsigned int) archive_member_file_ptr;
2797 /* Catch an attempt to grow an archive past its 4Gb limit. */
2798 if (archive_member_file_ptr != (file_ptr) offset)
2800 bfd_set_error (bfd_error_file_truncated);
2801 return false;
2803 if (!bfd_write_bigendian_4byte_int (arch, offset))
2804 return false;
2805 count++;
2807 archive_member_file_ptr += sizeof (struct ar_hdr);
2808 if (! bfd_is_thin_archive (arch))
2810 /* Add size of this archive entry. */
2811 archive_member_file_ptr += arelt_size (current);
2812 /* Remember about the even alignment. */
2813 archive_member_file_ptr += archive_member_file_ptr % 2;
2815 current = current->archive_next;
2818 /* Now write the strings themselves. */
2819 for (count = 0; count < symbol_count; count++)
2821 size_t len = strlen (*map[count].name) + 1;
2823 if (bfd_write (*map[count].name, len, arch) != len)
2824 return false;
2827 /* The spec sez this should be a newline. But in order to be
2828 bug-compatible for arc960 we use a null. */
2829 if (padit)
2831 if (bfd_write ("", 1, arch) != 1)
2832 return false;
2835 return true;
2838 bool
2839 _bfd_noarchive_write_armap
2840 (bfd *arch ATTRIBUTE_UNUSED,
2841 unsigned int elength ATTRIBUTE_UNUSED,
2842 struct orl *map ATTRIBUTE_UNUSED,
2843 unsigned int orl_count ATTRIBUTE_UNUSED,
2844 int stridx ATTRIBUTE_UNUSED)
2846 return true;
2849 static int
2850 archive_close_worker (void **slot, void *inf ATTRIBUTE_UNUSED)
2852 struct ar_cache *ent = (struct ar_cache *) *slot;
2854 bfd_close_all_done (ent->arbfd);
2855 return 1;
2858 void
2859 _bfd_unlink_from_archive_parent (bfd *abfd)
2861 if (arch_eltdata (abfd) != NULL)
2863 struct areltdata *ared = arch_eltdata (abfd);
2864 htab_t htab = (htab_t) ared->parent_cache;
2866 if (htab)
2868 struct ar_cache ent;
2869 void **slot;
2871 ent.ptr = ared->key;
2872 slot = htab_find_slot (htab, &ent, NO_INSERT);
2873 if (slot != NULL)
2875 BFD_ASSERT (((struct ar_cache *) *slot)->arbfd == abfd);
2876 htab_clear_slot (htab, slot);
2882 bool
2883 _bfd_archive_close_and_cleanup (bfd *abfd)
2885 if (bfd_write_p (abfd) && abfd->format == bfd_archive)
2887 bfd *current;
2888 while ((current = abfd->archive_head) != NULL)
2890 abfd->archive_head = current->archive_next;
2891 bfd_close_all_done (current);
2894 if (bfd_read_p (abfd) && abfd->format == bfd_archive)
2896 bfd *nbfd;
2897 bfd *next;
2898 htab_t htab;
2900 /* Close nested archives (if this bfd is a thin archive). */
2901 for (nbfd = abfd->nested_archives; nbfd; nbfd = next)
2903 next = nbfd->archive_next;
2904 bfd_close (nbfd);
2907 htab = bfd_ardata (abfd)->cache;
2908 if (htab)
2910 htab_traverse_noresize (htab, archive_close_worker, NULL);
2911 htab_delete (htab);
2912 bfd_ardata (abfd)->cache = NULL;
2915 /* Close the archive plugin file descriptor if needed. */
2916 if (abfd->archive_plugin_fd > 0)
2917 close (abfd->archive_plugin_fd);
2920 _bfd_unlink_from_archive_parent (abfd);
2922 if (abfd->is_linker_output)
2923 (*abfd->link.hash->hash_table_free) (abfd);
2925 return true;