archive.c revision 1.9 1 /* BFD back-end for archive files (libraries).
2 Copyright (C) 1990-2024 Free Software Foundation, Inc.
3 Written by Cygnus Support. Mostly Gumby Henkel-Wallace's fault.
4
5 This file is part of BFD, the Binary File Descriptor library.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */
20
21 /*
22 @setfilename archive-info
23 SECTION
24 Archives
25
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.
29
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.
37
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.
42
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.
48
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.
54
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!
60
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.
71
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.
78
79 Archives are supported in BFD in <<archive.c>>.
80
81 SUBSECTION
82 Archive functions
83 */
84
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).
89 */
90
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.
99
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.
103
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.
108
109 BSD 4.4 uses a third scheme: It writes a long filename
110 directly after the header. This allows 'ar q' to work.
111 */
112
113 /* Summary of archive member names:
114
115 Symbol table (must be first):
116 "__.SYMDEF " - Symbol table, Berkeley style, produced by ranlib.
117 "/ " - Symbol table, system 5 style.
118
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).
122
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).
126
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.
132 */
133
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"
144
145 #ifndef errno
146 extern int errno;
147 #endif
148
149 /*
150 EXTERNAL
151 .{* A canonical archive symbol. *}
152 .{* This is a type pun with struct symdef/struct ranlib on purpose! *}
153 .typedef struct carsym
154 .{
155 . const char *name;
156 . file_ptr file_offset; {* Look here to find the file. *}
157 .}
158 .carsym;
159 .
160 .{* A count of carsyms (canonical archive symbols). *}
161 . typedef unsigned long symindex;
162 .#define BFD_NO_MORE_SYMBOLS ((symindex) ~0)
163 .
164
165 INTERNAL
166 .{* Used in generating armaps (archive tables of contents). *}
167 .struct orl {* Output ranlib. *}
168 .{
169 . char **name; {* Symbol name. *}
170 . union
171 . {
172 . file_ptr pos;
173 . bfd *abfd;
174 . } u; {* bfd* or file position. *}
175 . int namidx; {* Index into string table. *}
176 .};
177 .
178 */
179
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
187 {
188 file_ptr ptr;
189 bfd *arbfd;
190 };
191
192 #define ar_padchar(abfd) ((abfd)->xvec->ar_pad_char)
193 #define ar_maxnamelen(abfd) ((abfd)->xvec->ar_max_namelen)
194
195 #define arch_eltdata(bfd) ((struct areltdata *) ((bfd)->arelt_data))
196
197 static const char * normalize (bfd *, const char *);
198
199 #define arch_hdr(bfd) ((struct ar_hdr *) arch_eltdata (bfd)->arch_header)
200
201 /* True iff NAME designated a BSD 4.4 extended name. */
202
203 #define is_bsd44_extended_name(NAME) \
204 (NAME[0] == '#' && NAME[1] == '1' && NAME[2] == '/' && ISDIGIT (NAME[3]))
205
206 void
208 _bfd_ar_spacepad (char *p, size_t n, const char *fmt, long val)
209 {
210 char buf[20];
211 size_t len;
212
213 snprintf (buf, sizeof (buf), fmt, val);
214 len = strlen (buf);
215 if (len < n)
216 {
217 memcpy (p, buf, len);
218 memset (p + len, ' ', n - len);
219 }
220 else
221 memcpy (p, buf, n);
222 }
223
224 bool
225 _bfd_ar_sizepad (char *p, size_t n, bfd_size_type size)
226 {
227 char buf[21];
228 size_t len;
229
230 snprintf (buf, sizeof (buf), "%-10" PRIu64, (uint64_t) size);
231 len = strlen (buf);
232 if (len > n)
233 {
234 bfd_set_error (bfd_error_file_too_big);
235 return false;
236 }
237 if (len < n)
238 {
239 memcpy (p, buf, len);
240 memset (p + len, ' ', n - len);
241 }
242 else
243 memcpy (p, buf, n);
244 return true;
245 }
246
247 bool
249 _bfd_generic_mkarchive (bfd *abfd)
250 {
251 size_t amt = sizeof (struct artdata);
252
253 abfd->tdata.aout_ar_data = (struct artdata *) bfd_zalloc (abfd, amt);
254 return bfd_ardata (abfd) != NULL;
255 }
256
257 /*
258 FUNCTION
259 bfd_get_next_mapent
260
261 SYNOPSIS
262 symindex bfd_get_next_mapent
263 (bfd *abfd, symindex previous, carsym **sym);
264
265 DESCRIPTION
266 Step through archive @var{abfd}'s symbol table (if it
267 has one). Successively update @var{sym} with the next symbol's
268 information, returning that symbol's (internal) index into the
269 symbol table.
270
271 Supply <<BFD_NO_MORE_SYMBOLS>> as the @var{previous} entry to get
272 the first one; returns <<BFD_NO_MORE_SYMBOLS>> when you've already
273 got the last one.
274
275 A <<carsym>> is a canonical archive symbol. The only
276 user-visible element is its name, a null-terminated string.
277 */
278
279 symindex
280 bfd_get_next_mapent (bfd *abfd, symindex prev, carsym **entry)
281 {
282 if (!bfd_has_map (abfd))
283 {
284 bfd_set_error (bfd_error_invalid_operation);
285 return BFD_NO_MORE_SYMBOLS;
286 }
287
288 if (prev == BFD_NO_MORE_SYMBOLS)
289 prev = 0;
290 else
291 ++prev;
292 if (prev >= bfd_ardata (abfd)->symdef_count)
293 return BFD_NO_MORE_SYMBOLS;
294
295 *entry = (bfd_ardata (abfd)->symdefs + prev);
296 return prev;
297 }
298
299 /* To be called by backends only. */
300
301 bfd *
302 _bfd_create_empty_archive_element_shell (bfd *obfd)
303 {
304 return _bfd_new_bfd_contained_in (obfd);
305 }
306
307 /*
308 FUNCTION
309 bfd_set_archive_head
310
311 SYNOPSIS
312 bool bfd_set_archive_head (bfd *output, bfd *new_head);
313
314 DESCRIPTION
315 Set the head of the chain of
316 BFDs contained in the archive @var{output} to @var{new_head}.
317 */
318
319 bool
320 bfd_set_archive_head (bfd *output_archive, bfd *new_head)
321 {
322 output_archive->archive_head = new_head;
323 return true;
324 }
325
326 bfd *
327 _bfd_look_for_bfd_in_cache (bfd *arch_bfd, file_ptr filepos)
328 {
329 htab_t hash_table = bfd_ardata (arch_bfd)->cache;
330 struct ar_cache m;
331
332 m.ptr = filepos;
333
334 if (hash_table)
335 {
336 struct ar_cache *entry = (struct ar_cache *) htab_find (hash_table, &m);
337 if (!entry)
338 return NULL;
339
340 /* Unfortunately this flag is set after checking that we have
341 an archive, and checking for an archive means one element has
342 sneaked into the cache. */
343 entry->arbfd->no_export = arch_bfd->no_export;
344 return entry->arbfd;
345 }
346 else
347 return NULL;
348 }
349
350 static hashval_t
351 hash_file_ptr (const void * p)
352 {
353 return (hashval_t) (((struct ar_cache *) p)->ptr);
354 }
355
356 /* Returns non-zero if P1 and P2 are equal. */
357
358 static int
359 eq_file_ptr (const void * p1, const void * p2)
360 {
361 struct ar_cache *arc1 = (struct ar_cache *) p1;
362 struct ar_cache *arc2 = (struct ar_cache *) p2;
363 return arc1->ptr == arc2->ptr;
364 }
365
366 /* The calloc function doesn't always take size_t (e.g. on VMS)
367 so wrap it to avoid a compile time warning. */
368
369 static void *
370 _bfd_calloc_wrapper (size_t a, size_t b)
371 {
372 return calloc (a, b);
373 }
374
375 /* Kind of stupid to call cons for each one, but we don't do too many. */
376
377 bool
378 _bfd_add_bfd_to_archive_cache (bfd *arch_bfd, file_ptr filepos, bfd *new_elt)
379 {
380 struct ar_cache *cache;
381 htab_t hash_table = bfd_ardata (arch_bfd)->cache;
382
383 /* If the hash table hasn't been created, create it. */
384 if (hash_table == NULL)
385 {
386 hash_table = htab_create_alloc (16, hash_file_ptr, eq_file_ptr,
387 NULL, _bfd_calloc_wrapper, free);
388 if (hash_table == NULL)
389 return false;
390 bfd_ardata (arch_bfd)->cache = hash_table;
391 }
392
393 /* Insert new_elt into the hash table by filepos. */
394 cache = (struct ar_cache *) bfd_zalloc (arch_bfd, sizeof (struct ar_cache));
395 cache->ptr = filepos;
396 cache->arbfd = new_elt;
397 *htab_find_slot (hash_table, (const void *) cache, INSERT) = cache;
398
399 /* Provide a means of accessing this from child. */
400 arch_eltdata (new_elt)->parent_cache = hash_table;
401 arch_eltdata (new_elt)->key = filepos;
402
403 return true;
404 }
405
406 static bfd *
408 open_nested_file (const char *filename, bfd *archive)
409 {
410 const char *target;
411 bfd *n_bfd;
412
413 target = NULL;
414 if (!archive->target_defaulted)
415 target = archive->xvec->name;
416 n_bfd = bfd_openr (filename, target);
417 if (n_bfd != NULL)
418 {
419 n_bfd->lto_output = archive->lto_output;
420 n_bfd->no_export = archive->no_export;
421 n_bfd->my_archive = archive;
422 }
423 return n_bfd;
424 }
425
426 static bfd *
427 find_nested_archive (const char *filename, bfd *arch_bfd)
428 {
429 bfd *abfd;
430
431 /* PR 15140: Don't allow a nested archive pointing to itself. */
432 if (filename_cmp (filename, bfd_get_filename (arch_bfd)) == 0)
433 {
434 bfd_set_error (bfd_error_malformed_archive);
435 return NULL;
436 }
437
438 for (abfd = arch_bfd->nested_archives;
439 abfd != NULL;
440 abfd = abfd->archive_next)
441 {
442 if (filename_cmp (filename, bfd_get_filename (abfd)) == 0)
443 return abfd;
444 }
445 abfd = open_nested_file (filename, arch_bfd);
446 if (abfd)
447 {
448 abfd->archive_next = arch_bfd->nested_archives;
449 arch_bfd->nested_archives = abfd;
450 }
451 return abfd;
452 }
453
454 /* The name begins with space. Hence the rest of the name is an index into
455 the string table. */
456
457 static char *
458 get_extended_arelt_filename (bfd *arch, const char *name, file_ptr *originp)
459 {
460 unsigned long table_index = 0;
461 const char *endp;
462
463 /* Should extract string so that I can guarantee not to overflow into
464 the next region, but I'm too lazy. */
465 errno = 0;
466 /* Skip first char, which is '/' in SVR4 or ' ' in some other variants. */
467 table_index = strtol (name + 1, (char **) &endp, 10);
468 if (errno != 0 || table_index >= bfd_ardata (arch)->extended_names_size)
469 {
470 bfd_set_error (bfd_error_malformed_archive);
471 return NULL;
472 }
473 /* In a thin archive, a member of an archive-within-an-archive
474 will have the offset in the inner archive encoded here. */
475 if (bfd_is_thin_archive (arch) && endp != NULL && *endp == ':')
476 {
477 file_ptr origin = strtol (endp + 1, NULL, 10);
478
479 if (errno != 0)
480 {
481 bfd_set_error (bfd_error_malformed_archive);
482 return NULL;
483 }
484 *originp = origin;
485 }
486 else
487 *originp = 0;
488
489 return bfd_ardata (arch)->extended_names + table_index;
490 }
491
492 /* This functions reads an arch header and returns an areltdata pointer, or
493 NULL on error.
494
495 Presumes the file pointer is already in the right place (ie pointing
496 to the ar_hdr in the file). Moves the file pointer; on success it
497 should be pointing to the front of the file contents; on failure it
498 could have been moved arbitrarily. */
499
500 void *
501 _bfd_generic_read_ar_hdr (bfd *abfd)
502 {
503 return _bfd_generic_read_ar_hdr_mag (abfd, NULL);
504 }
505
506 /* Alpha ECOFF uses an optional different ARFMAG value, so we have a
507 variant of _bfd_generic_read_ar_hdr which accepts a magic string. */
508
509 void *
510 _bfd_generic_read_ar_hdr_mag (bfd *abfd, const char *mag)
511 {
512 struct ar_hdr hdr;
513 char *hdrp = (char *) &hdr;
514 uint64_t parsed_size;
515 struct areltdata *ared;
516 char *filename = NULL;
517 ufile_ptr filesize;
518 bfd_size_type namelen = 0;
519 bfd_size_type allocsize = sizeof (struct areltdata) + sizeof (struct ar_hdr);
520 char *allocptr = 0;
521 file_ptr origin = 0;
522 unsigned int extra_size = 0;
523 char fmag_save;
524 int scan;
525
526 if (bfd_read (hdrp, sizeof (struct ar_hdr), abfd) != sizeof (struct ar_hdr))
527 {
528 if (bfd_get_error () != bfd_error_system_call)
529 bfd_set_error (bfd_error_no_more_archived_files);
530 return NULL;
531 }
532 if (strncmp (hdr.ar_fmag, ARFMAG, 2) != 0
533 && (mag == NULL
534 || strncmp (hdr.ar_fmag, mag, 2) != 0))
535 {
536 bfd_set_error (bfd_error_malformed_archive);
537 return NULL;
538 }
539
540 errno = 0;
541 fmag_save = hdr.ar_fmag[0];
542 hdr.ar_fmag[0] = 0;
543 scan = sscanf (hdr.ar_size, "%" SCNu64, &parsed_size);
544 hdr.ar_fmag[0] = fmag_save;
545 if (scan != 1)
546 {
547 bfd_set_error (bfd_error_malformed_archive);
548 return NULL;
549 }
550
551 /* Extract the filename from the archive - there are two ways to
552 specify an extended name table, either the first char of the
553 name is a space, or it's a slash. */
554 if ((hdr.ar_name[0] == '/'
555 || (hdr.ar_name[0] == ' '
556 && memchr (hdr.ar_name, '/', ar_maxnamelen (abfd)) == NULL))
557 && bfd_ardata (abfd)->extended_names != NULL)
558 {
559 filename = get_extended_arelt_filename (abfd, hdr.ar_name, &origin);
560 if (filename == NULL)
561 return NULL;
562 }
563 /* BSD4.4-style long filename. */
564 else if (is_bsd44_extended_name (hdr.ar_name))
565 {
566 /* BSD-4.4 extended name */
567 namelen = atoi (&hdr.ar_name[3]);
568 filesize = bfd_get_file_size (abfd);
569 if (namelen > parsed_size
570 || namelen > -allocsize - 2
571 || (filesize != 0 && namelen > filesize))
572 {
573 bfd_set_error (bfd_error_malformed_archive);
574 return NULL;
575 }
576 allocsize += namelen + 1;
577 parsed_size -= namelen;
578 extra_size = namelen;
579
580 allocptr = (char *) bfd_malloc (allocsize);
581 if (allocptr == NULL)
582 return NULL;
583 filename = (allocptr
584 + sizeof (struct areltdata)
585 + sizeof (struct ar_hdr));
586 if (bfd_read (filename, namelen, abfd) != namelen)
587 {
588 free (allocptr);
589 if (bfd_get_error () != bfd_error_system_call)
590 bfd_set_error (bfd_error_no_more_archived_files);
591 return NULL;
592 }
593 filename[namelen] = '\0';
594 }
595 else
596 {
597 /* We judge the end of the name by looking for '/' or ' '.
598 Note: The SYSV format (terminated by '/') allows embedded
599 spaces, so only look for ' ' if we don't find '/'. */
600
601 char *e;
602 e = (char *) memchr (hdr.ar_name, '\0', ar_maxnamelen (abfd));
603 if (e == NULL)
604 {
605 e = (char *) memchr (hdr.ar_name, '/', ar_maxnamelen (abfd));
606 if (e == NULL)
607 e = (char *) memchr (hdr.ar_name, ' ', ar_maxnamelen (abfd));
608 }
609
610 if (e != NULL)
611 namelen = e - hdr.ar_name;
612 else
613 {
614 /* If we didn't find a termination character, then the name
615 must be the entire field. */
616 namelen = ar_maxnamelen (abfd);
617 }
618
619 allocsize += namelen + 1;
620 }
621
622 if (!allocptr)
623 {
624 allocptr = (char *) bfd_malloc (allocsize);
625 if (allocptr == NULL)
626 return NULL;
627 }
628
629 memset (allocptr, 0, sizeof (struct areltdata));
630 ared = (struct areltdata *) allocptr;
631 ared->arch_header = allocptr + sizeof (struct areltdata);
632 memcpy (ared->arch_header, &hdr, sizeof (struct ar_hdr));
633 ared->parsed_size = parsed_size;
634 ared->extra_size = extra_size;
635 ared->origin = origin;
636
637 if (filename != NULL)
638 ared->filename = filename;
639 else
640 {
641 ared->filename = allocptr + (sizeof (struct areltdata) +
642 sizeof (struct ar_hdr));
643 if (namelen)
644 memcpy (ared->filename, hdr.ar_name, namelen);
645 ared->filename[namelen] = '\0';
646 }
647
648 return ared;
649 }
650
651 /* Append the relative pathname for a member of the thin archive
653 to the pathname of the directory containing the archive. */
654
655 char *
656 _bfd_append_relative_path (bfd *arch, char *elt_name)
657 {
658 const char *arch_name = bfd_get_filename (arch);
659 const char *base_name = lbasename (arch_name);
660 size_t prefix_len;
661 char *filename;
662
663 if (base_name == arch_name)
664 return elt_name;
665
666 prefix_len = base_name - arch_name;
667 filename = (char *) bfd_alloc (arch, prefix_len + strlen (elt_name) + 1);
668 if (filename == NULL)
669 return NULL;
670
671 strncpy (filename, arch_name, prefix_len);
672 strcpy (filename + prefix_len, elt_name);
673 return filename;
674 }
675
676 /* This is an internal function; it's mainly used when indexing
677 through the archive symbol table, but also used to get the next
678 element, since it handles the bookkeeping so nicely for us. */
679
680 bfd *
681 _bfd_get_elt_at_filepos (bfd *archive, file_ptr filepos,
682 struct bfd_link_info *info)
683 {
684 struct areltdata *new_areldata;
685 bfd *n_bfd;
686 char *filename;
687
688 n_bfd = _bfd_look_for_bfd_in_cache (archive, filepos);
689 if (n_bfd)
690 return n_bfd;
691
692 if (0 > bfd_seek (archive, filepos, SEEK_SET))
693 return NULL;
694
695 if ((new_areldata = (struct areltdata *) _bfd_read_ar_hdr (archive)) == NULL)
696 return NULL;
697
698 filename = new_areldata->filename;
699
700 if (bfd_is_thin_archive (archive))
701 {
702 /* This is a proxy entry for an external file. */
703 if (! IS_ABSOLUTE_PATH (filename))
704 {
705 filename = _bfd_append_relative_path (archive, filename);
706 if (filename == NULL)
707 {
708 free (new_areldata);
709 return NULL;
710 }
711 }
712
713 if (new_areldata->origin > 0)
714 {
715 /* This proxy entry refers to an element of a nested archive.
716 Locate the member of that archive and return a bfd for it. */
717 bfd *ext_arch = find_nested_archive (filename, archive);
718
719 if (ext_arch == NULL
720 || ! bfd_check_format (ext_arch, bfd_archive))
721 {
722 free (new_areldata);
723 return NULL;
724 }
725 n_bfd = _bfd_get_elt_at_filepos (ext_arch,
726 new_areldata->origin, info);
727 if (n_bfd == NULL)
728 {
729 free (new_areldata);
730 return NULL;
731 }
732 n_bfd->proxy_origin = bfd_tell (archive);
733
734 /* Copy BFD_COMPRESS, BFD_DECOMPRESS and BFD_COMPRESS_GABI
735 flags. */
736 n_bfd->flags |= archive->flags & (BFD_COMPRESS
737 | BFD_DECOMPRESS
738 | BFD_COMPRESS_GABI);
739
740 return n_bfd;
741 }
742
743 /* It's not an element of a nested archive;
744 open the external file as a bfd. */
745 bfd_set_error (bfd_error_no_error);
746 n_bfd = open_nested_file (filename, archive);
747 if (n_bfd == NULL)
748 {
749 switch (bfd_get_error ())
750 {
751 default:
752 break;
753 case bfd_error_no_error:
754 bfd_set_error (bfd_error_malformed_archive);
755 break;
756 case bfd_error_system_call:
757 if (info != NULL)
758 {
759 info->callbacks->einfo
760 (_("%F%P: %pB(%s): error opening thin archive member: %E\n"),
761 archive, filename);
762 break;
763 }
764 break;
765 }
766 }
767 }
768 else
769 {
770 n_bfd = _bfd_create_empty_archive_element_shell (archive);
771 }
772
773 if (n_bfd == NULL)
774 {
775 free (new_areldata);
776 return NULL;
777 }
778
779 n_bfd->proxy_origin = bfd_tell (archive);
780
781 if (bfd_is_thin_archive (archive))
782 {
783 n_bfd->origin = 0;
784 }
785 else
786 {
787 n_bfd->origin = n_bfd->proxy_origin;
788 if (!bfd_set_filename (n_bfd, filename))
789 goto out;
790 }
791
792 n_bfd->arelt_data = new_areldata;
793
794 /* Copy BFD_COMPRESS, BFD_DECOMPRESS and BFD_COMPRESS_GABI flags. */
795 n_bfd->flags |= archive->flags & (BFD_COMPRESS
796 | BFD_DECOMPRESS
797 | BFD_COMPRESS_GABI);
798
799 /* Copy is_linker_input. */
800 n_bfd->is_linker_input = archive->is_linker_input;
801
802 if (archive->no_element_cache
803 || _bfd_add_bfd_to_archive_cache (archive, filepos, n_bfd))
804 return n_bfd;
805
806 out:
807 free (new_areldata);
808 n_bfd->arelt_data = NULL;
809 bfd_close (n_bfd);
810 return NULL;
811 }
812
813 /* Return the BFD which is referenced by the symbol in ABFD indexed by
814 SYM_INDEX. SYM_INDEX should have been returned by bfd_get_next_mapent. */
815
816 bfd *
817 _bfd_generic_get_elt_at_index (bfd *abfd, symindex sym_index)
818 {
819 carsym *entry;
820
821 entry = bfd_ardata (abfd)->symdefs + sym_index;
822 return _bfd_get_elt_at_filepos (abfd, entry->file_offset, NULL);
823 }
824
825 bfd *
826 _bfd_noarchive_get_elt_at_index (bfd *abfd,
827 symindex sym_index ATTRIBUTE_UNUSED)
828 {
829 return (bfd *) _bfd_ptr_bfd_null_error (abfd);
830 }
831
832 /*
833 FUNCTION
834 bfd_openr_next_archived_file
835
836 SYNOPSIS
837 bfd *bfd_openr_next_archived_file (bfd *archive, bfd *previous);
838
839 DESCRIPTION
840 Provided a BFD, @var{archive}, containing an archive and NULL, open
841 an input BFD on the first contained element and returns that.
842 Subsequent calls should pass the archive and the previous return
843 value to return a created BFD to the next contained element. NULL
844 is returned when there are no more.
845 Note - if you want to process the bfd returned by this call be
846 sure to call bfd_check_format() on it first.
847 */
848
849 bfd *
850 bfd_openr_next_archived_file (bfd *archive, bfd *last_file)
851 {
852 if ((bfd_get_format (archive) != bfd_archive)
853 || (archive->direction == write_direction))
854 {
855 bfd_set_error (bfd_error_invalid_operation);
856 return NULL;
857 }
858
859 return BFD_SEND (archive,
860 openr_next_archived_file, (archive, last_file));
861 }
862
863 bfd *
864 bfd_generic_openr_next_archived_file (bfd *archive, bfd *last_file)
865 {
866 ufile_ptr filestart;
867
868 if (!last_file)
869 filestart = bfd_ardata (archive)->first_file_filepos;
870 else
871 {
872 filestart = last_file->proxy_origin;
873 if (! bfd_is_thin_archive (archive))
874 {
875 bfd_size_type size = arelt_size (last_file);
876
877 filestart += size;
878 /* Pad to an even boundary...
879 Note that last_file->origin can be odd in the case of
880 BSD-4.4-style element with a long odd size. */
881 filestart += filestart % 2;
882 if (filestart < last_file->proxy_origin)
883 {
884 /* Prevent looping. See PR19256. */
885 bfd_set_error (bfd_error_malformed_archive);
886 return NULL;
887 }
888 }
889 }
890
891 return _bfd_get_elt_at_filepos (archive, filestart, NULL);
892 }
893
894 bfd *
895 _bfd_noarchive_openr_next_archived_file (bfd *archive,
896 bfd *last_file ATTRIBUTE_UNUSED)
897 {
898 return (bfd *) _bfd_ptr_bfd_null_error (archive);
899 }
900
901 bfd_cleanup
902 bfd_generic_archive_p (bfd *abfd)
903 {
904 struct artdata *tdata_hold;
905 char armag[SARMAG + 1];
906 size_t amt;
907
908 if (bfd_read (armag, SARMAG, abfd) != SARMAG)
909 {
910 if (bfd_get_error () != bfd_error_system_call)
911 bfd_set_error (bfd_error_wrong_format);
912 return NULL;
913 }
914
915 bfd_set_thin_archive (abfd, strncmp (armag, ARMAGT, SARMAG) == 0);
916
917 if (strncmp (armag, ARMAG, SARMAG) != 0
918 && ! bfd_is_thin_archive (abfd))
919 {
920 bfd_set_error (bfd_error_wrong_format);
921 return NULL;
922 }
923
924 tdata_hold = bfd_ardata (abfd);
925
926 amt = sizeof (struct artdata);
927 bfd_ardata (abfd) = (struct artdata *) bfd_zalloc (abfd, amt);
928 if (bfd_ardata (abfd) == NULL)
929 {
930 bfd_ardata (abfd) = tdata_hold;
931 return NULL;
932 }
933
934 bfd_ardata (abfd)->first_file_filepos = SARMAG;
935
936 if (!BFD_SEND (abfd, _bfd_slurp_armap, (abfd))
937 || !BFD_SEND (abfd, _bfd_slurp_extended_name_table, (abfd)))
938 {
939 if (bfd_get_error () != bfd_error_system_call)
940 bfd_set_error (bfd_error_wrong_format);
941 bfd_release (abfd, bfd_ardata (abfd));
942 bfd_ardata (abfd) = tdata_hold;
943 return NULL;
944 }
945
946 if (abfd->target_defaulted && bfd_has_map (abfd))
947 {
948 bfd *first;
949 unsigned int save;
950
951 /* This archive has a map, so we may presume that the contents
952 are object files. Make sure that if the first file in the
953 archive can be recognized as an object file, it is for this
954 target. If not, assume that this is the wrong format. If
955 the first file is not an object file, somebody is doing
956 something weird, and we permit it so that ar -t will work.
957
958 This is done because any normal format will recognize any
959 normal archive, regardless of the format of the object files.
960 We do accept an empty archive. */
961
962 save = abfd->no_element_cache;
963 abfd->no_element_cache = 1;
964 first = bfd_openr_next_archived_file (abfd, NULL);
965 abfd->no_element_cache = save;
966 if (first != NULL)
967 {
968 first->target_defaulted = false;
969 if (bfd_check_format (first, bfd_object)
970 && first->xvec != abfd->xvec)
971 bfd_set_error (bfd_error_wrong_object_format);
972 bfd_close (first);
973 }
974 }
975
976 return _bfd_no_cleanup;
977 }
978
979 /* Some constants for a 32 bit BSD archive structure. We do not
980 support 64 bit archives presently; so far as I know, none actually
981 exist. Supporting them would require changing these constants, and
982 changing some H_GET_32 to H_GET_64. */
983
984 /* The size of an external symdef structure. */
985 #define BSD_SYMDEF_SIZE 8
986
987 /* The offset from the start of a symdef structure to the file offset. */
988 #define BSD_SYMDEF_OFFSET_SIZE 4
989
990 /* The size of the symdef count. */
991 #define BSD_SYMDEF_COUNT_SIZE 4
992
993 /* The size of the string count. */
994 #define BSD_STRING_COUNT_SIZE 4
995
996 /* Read a BSD-style archive symbol table. Returns FALSE on error,
997 TRUE otherwise. */
998
999 static bool
1000 do_slurp_bsd_armap (bfd *abfd)
1001 {
1002 struct areltdata *mapdata;
1003 size_t counter;
1004 bfd_byte *raw_armap, *rbase;
1005 struct artdata *ardata = bfd_ardata (abfd);
1006 char *stringbase;
1007 bfd_size_type parsed_size;
1008 size_t amt, string_size;
1009 carsym *set;
1010
1011 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1012 if (mapdata == NULL)
1013 return false;
1014 parsed_size = mapdata->parsed_size;
1015 free (mapdata);
1016 /* PR 17512: file: 883ff754. */
1017 /* PR 17512: file: 0458885f. */
1018 if (parsed_size < BSD_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE)
1019 {
1020 bfd_set_error (bfd_error_malformed_archive);
1021 return false;
1022 }
1023
1024 raw_armap = (bfd_byte *) _bfd_alloc_and_read (abfd, parsed_size, parsed_size);
1025 if (raw_armap == NULL)
1026 return false;
1027
1028 parsed_size -= BSD_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE;
1029 amt = H_GET_32 (abfd, raw_armap);
1030 if (amt > parsed_size
1031 || amt % BSD_SYMDEF_SIZE != 0)
1032 {
1033 /* Probably we're using the wrong byte ordering. */
1034 bfd_set_error (bfd_error_wrong_format);
1035 goto release_armap;
1036 }
1037
1038 rbase = raw_armap + BSD_SYMDEF_COUNT_SIZE;
1039 stringbase = (char *) rbase + amt + BSD_STRING_COUNT_SIZE;
1040 string_size = parsed_size - amt;
1041
1042 ardata->symdef_count = amt / BSD_SYMDEF_SIZE;
1043 if (_bfd_mul_overflow (ardata->symdef_count, sizeof (carsym), &amt))
1044 {
1045 bfd_set_error (bfd_error_no_memory);
1046 goto release_armap;
1047 }
1048 ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
1049 if (!ardata->symdefs)
1050 goto release_armap;
1051
1052 for (counter = 0, set = ardata->symdefs;
1053 counter < ardata->symdef_count;
1054 counter++, set++, rbase += BSD_SYMDEF_SIZE)
1055 {
1056 unsigned nameoff = H_GET_32 (abfd, rbase);
1057 if (nameoff >= string_size)
1058 {
1059 bfd_set_error (bfd_error_malformed_archive);
1060 goto release_armap;
1061 }
1062 set->name = stringbase + nameoff;
1063 set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
1064 }
1065
1066 ardata->first_file_filepos = bfd_tell (abfd);
1067 /* Pad to an even boundary if you have to. */
1068 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1069 /* FIXME, we should provide some way to free raw_ardata when
1070 we are done using the strings from it. For now, it seems
1071 to be allocated on an objalloc anyway... */
1072 abfd->has_armap = true;
1073 return true;
1074
1075 release_armap:
1076 ardata->symdef_count = 0;
1077 ardata->symdefs = NULL;
1078 bfd_release (abfd, raw_armap);
1079 return false;
1080 }
1081
1082 /* Read a COFF archive symbol table. Returns FALSE on error, TRUE
1083 otherwise. */
1084
1085 static bool
1086 do_slurp_coff_armap (bfd *abfd)
1087 {
1088 struct areltdata *mapdata;
1089 int *raw_armap, *rawptr;
1090 struct artdata *ardata = bfd_ardata (abfd);
1091 char *stringbase;
1092 char *stringend;
1093 bfd_size_type stringsize;
1094 bfd_size_type parsed_size;
1095 ufile_ptr filesize;
1096 size_t nsymz, carsym_size, ptrsize, i;
1097 carsym *carsyms;
1098 bfd_vma (*swap) (const void *);
1099 char int_buf[4];
1100 struct areltdata *tmp;
1101
1102 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1103 if (mapdata == NULL)
1104 return false;
1105 parsed_size = mapdata->parsed_size;
1106 free (mapdata);
1107
1108 if (bfd_read (int_buf, 4, abfd) != 4)
1109 return false;
1110
1111 /* It seems that all numeric information in a coff archive is always
1112 in big endian format, no matter the host or target. */
1113 swap = bfd_getb32;
1114 nsymz = bfd_getb32 (int_buf);
1115
1116 /* The coff armap must be read sequentially. So we construct a
1117 bsd-style one in core all at once, for simplicity. */
1118
1119 if (_bfd_mul_overflow (nsymz, sizeof (carsym), &carsym_size))
1120 {
1121 bfd_set_error (bfd_error_no_memory);
1122 return false;
1123 }
1124
1125 filesize = bfd_get_file_size (abfd);
1126 ptrsize = 4 * nsymz;
1127 if ((filesize != 0 && parsed_size > filesize)
1128 || parsed_size < 4
1129 || parsed_size - 4 < ptrsize)
1130 {
1131 bfd_set_error (bfd_error_malformed_archive);
1132 return false;
1133 }
1134
1135 stringsize = parsed_size - ptrsize - 4;
1136
1137 if (carsym_size + stringsize + 1 <= carsym_size)
1138 {
1139 bfd_set_error (bfd_error_no_memory);
1140 return false;
1141 }
1142
1143 /* Allocate and read in the raw offsets. */
1144 raw_armap = (int *) _bfd_malloc_and_read (abfd, ptrsize, ptrsize);
1145 if (raw_armap == NULL)
1146 return false;
1147
1148 ardata->symdefs = (struct carsym *) bfd_alloc (abfd,
1149 carsym_size + stringsize + 1);
1150 if (ardata->symdefs == NULL)
1151 goto free_armap;
1152 carsyms = ardata->symdefs;
1153 stringbase = ((char *) ardata->symdefs) + carsym_size;
1154
1155 if (bfd_read (stringbase, stringsize, abfd) != stringsize)
1156 goto release_symdefs;
1157
1158 /* OK, build the carsyms. */
1159 stringend = stringbase + stringsize;
1160 *stringend = 0;
1161 for (i = 0; i < nsymz; i++)
1162 {
1163 rawptr = raw_armap + i;
1164 carsyms->file_offset = swap ((bfd_byte *) rawptr);
1165 carsyms->name = stringbase;
1166 stringbase += strlen (stringbase);
1167 if (stringbase != stringend)
1168 ++stringbase;
1169 carsyms++;
1170 }
1171
1172 ardata->symdef_count = nsymz;
1173 ardata->first_file_filepos = bfd_tell (abfd);
1174 /* Pad to an even boundary if you have to. */
1175 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1176 if (bfd_seek (abfd, ardata->first_file_filepos, SEEK_SET) != 0)
1177 goto release_symdefs;
1178
1179 abfd->has_armap = true;
1180 free (raw_armap);
1181
1182 /* Check for a second archive header (as used by PE). */
1183 tmp = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1184 if (tmp != NULL)
1185 {
1186 if (tmp->arch_header[0] == '/'
1187 && tmp->arch_header[1] == ' ')
1188 ardata->first_file_filepos
1189 += (tmp->parsed_size + sizeof (struct ar_hdr) + 1) & ~(unsigned) 1;
1190 free (tmp);
1191 }
1192
1193 return true;
1194
1195 release_symdefs:
1196 bfd_release (abfd, (ardata)->symdefs);
1197 free_armap:
1198 free (raw_armap);
1199 return false;
1200 }
1201
1202 /* This routine can handle either coff-style or bsd-style armaps
1203 (archive symbol table). Returns FALSE on error, TRUE otherwise */
1204
1205 bool
1206 bfd_slurp_armap (bfd *abfd)
1207 {
1208 char nextname[17];
1209 int i = bfd_read (nextname, 16, abfd);
1210
1211 if (i == 0)
1212 return true;
1213 if (i != 16)
1214 return false;
1215
1216 if (bfd_seek (abfd, -16, SEEK_CUR) != 0)
1217 return false;
1218
1219 if (startswith (nextname, "__.SYMDEF ")
1220 || startswith (nextname, "__.SYMDEF/ ")) /* Old Linux archives. */
1221 return do_slurp_bsd_armap (abfd);
1222 else if (startswith (nextname, "/ "))
1223 return do_slurp_coff_armap (abfd);
1224 else if (startswith (nextname, "/SYM64/ "))
1225 {
1226 /* 64bit (Irix 6) archive. */
1227 #ifdef BFD64
1228 return _bfd_archive_64_bit_slurp_armap (abfd);
1229 #else
1230 bfd_set_error (bfd_error_wrong_format);
1231 return false;
1232 #endif
1233 }
1234 else if (startswith (nextname, "#1/20 "))
1235 {
1236 /* Mach-O has a special name for armap when the map is sorted by name.
1237 However because this name has a space it is slightly more difficult
1238 to check it. */
1239 struct ar_hdr hdr;
1240 char extname[21];
1241
1242 if (bfd_read (&hdr, sizeof (hdr), abfd) != sizeof (hdr))
1243 return false;
1244 /* Read the extended name. We know its length. */
1245 if (bfd_read (extname, 20, abfd) != 20)
1246 return false;
1247 if (bfd_seek (abfd, -(file_ptr) (sizeof (hdr) + 20), SEEK_CUR) != 0)
1248 return false;
1249 extname[20] = 0;
1250 if (startswith (extname, "__.SYMDEF SORTED")
1251 || startswith (extname, "__.SYMDEF"))
1252 return do_slurp_bsd_armap (abfd);
1253 }
1254
1255 abfd->has_armap = false;
1256 return true;
1257 }
1258
1259 /** Extended name table.
1261
1262 Normally archives support only 14-character filenames.
1263
1264 Intel has extended the format: longer names are stored in a special
1265 element (the first in the archive, or second if there is an armap);
1266 the name in the ar_hdr is replaced by <space><index into filename
1267 element>. Index is the P.R. of an int (decimal). Data General have
1268 extended the format by using the prefix // for the special element. */
1269
1270 /* Returns FALSE on error, TRUE otherwise. */
1271
1272 bool
1273 _bfd_slurp_extended_name_table (bfd *abfd)
1274 {
1275 char nextname[17];
1276
1277 /* FIXME: Formatting sucks here, and in case of failure of BFD_READ,
1278 we probably don't want to return TRUE. */
1279 if (bfd_seek (abfd, bfd_ardata (abfd)->first_file_filepos, SEEK_SET) != 0)
1280 return false;
1281
1282 if (bfd_read (nextname, 16, abfd) == 16)
1283 {
1284 struct areltdata *namedata;
1285 bfd_size_type amt;
1286 ufile_ptr filesize;
1287
1288 if (bfd_seek (abfd, -16, SEEK_CUR) != 0)
1289 return false;
1290
1291 if (! startswith (nextname, "ARFILENAMES/ ")
1292 && ! startswith (nextname, "// "))
1293 {
1294 bfd_ardata (abfd)->extended_names = NULL;
1295 bfd_ardata (abfd)->extended_names_size = 0;
1296 return true;
1297 }
1298
1299 namedata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1300 if (namedata == NULL)
1301 return false;
1302
1303 filesize = bfd_get_file_size (abfd);
1304 amt = namedata->parsed_size;
1305 if (amt + 1 == 0 || (filesize != 0 && amt > filesize))
1306 {
1307 bfd_set_error (bfd_error_malformed_archive);
1308 goto byebye;
1309 }
1310
1311 bfd_ardata (abfd)->extended_names_size = amt;
1312 bfd_ardata (abfd)->extended_names = (char *) bfd_alloc (abfd, amt + 1);
1313 if (bfd_ardata (abfd)->extended_names == NULL)
1314 {
1315 byebye:
1316 free (namedata);
1317 bfd_ardata (abfd)->extended_names = NULL;
1318 bfd_ardata (abfd)->extended_names_size = 0;
1319 return false;
1320 }
1321
1322 if (bfd_read (bfd_ardata (abfd)->extended_names, amt, abfd) != amt)
1323 {
1324 if (bfd_get_error () != bfd_error_system_call)
1325 bfd_set_error (bfd_error_malformed_archive);
1326 bfd_release (abfd, (bfd_ardata (abfd)->extended_names));
1327 bfd_ardata (abfd)->extended_names = NULL;
1328 goto byebye;
1329 }
1330 bfd_ardata (abfd)->extended_names[amt] = 0;
1331
1332 /* Since the archive is supposed to be printable if it contains
1333 text, the entries in the list are newline-padded, not null
1334 padded. In SVR4-style archives, the names also have a
1335 trailing '/'. DOS/NT created archive often have \ in them
1336 We'll fix all problems here. */
1337 {
1338 char *ext_names = bfd_ardata (abfd)->extended_names;
1339 char *temp = ext_names;
1340 char *limit = temp + namedata->parsed_size;
1341
1342 for (; temp < limit; ++temp)
1343 {
1344 if (*temp == ARFMAG[1])
1345 temp[temp > ext_names && temp[-1] == '/' ? -1 : 0] = '\0';
1346 if (*temp == '\\')
1347 *temp = '/';
1348 }
1349 *limit = '\0';
1350 }
1351
1352 /* Pad to an even boundary if you have to. */
1353 bfd_ardata (abfd)->first_file_filepos = bfd_tell (abfd);
1354 bfd_ardata (abfd)->first_file_filepos +=
1355 (bfd_ardata (abfd)->first_file_filepos) % 2;
1356
1357 free (namedata);
1358 }
1359 return true;
1360 }
1361
1362 #ifdef VMS
1363
1364 /* Return a copy of the stuff in the filename between any :]> and a
1365 semicolon. */
1366
1367 static const char *
1368 normalize (bfd *abfd, const char *file)
1369 {
1370 const char *first;
1371 const char *last;
1372 char *copy;
1373
1374 if (abfd->flags & BFD_ARCHIVE_FULL_PATH)
1375 return file;
1376
1377 first = file + strlen (file) - 1;
1378 last = first + 1;
1379
1380 while (first != file)
1381 {
1382 if (*first == ';')
1383 last = first;
1384 if (*first == ':' || *first == ']' || *first == '>')
1385 {
1386 first++;
1387 break;
1388 }
1389 first--;
1390 }
1391
1392 copy = bfd_alloc (abfd, last - first + 1);
1393 if (copy == NULL)
1394 return NULL;
1395
1396 memcpy (copy, first, last - first);
1397 copy[last - first] = 0;
1398
1399 return copy;
1400 }
1401
1402 #else
1403 static const char *
1404 normalize (bfd *abfd, const char *file)
1405 {
1406 if (abfd->flags & BFD_ARCHIVE_FULL_PATH)
1407 return file;
1408 return lbasename (file);
1409 }
1410 #endif
1411
1412 /* Adjust a relative path name based on the reference path.
1413 For example:
1414
1415 Relative path Reference path Result
1416 ------------- -------------- ------
1417 bar.o lib.a bar.o
1418 foo/bar.o lib.a foo/bar.o
1419 bar.o foo/lib.a ../bar.o
1420 foo/bar.o baz/lib.a ../foo/bar.o
1421 bar.o ../lib.a <parent of current dir>/bar.o
1422 ; ../bar.o ../lib.a bar.o
1423 ; ../bar.o lib.a ../bar.o
1424 foo/bar.o ../lib.a <parent of current dir>/foo/bar.o
1425 bar.o ../../lib.a <grandparent>/<parent>/bar.o
1426 bar.o foo/baz/lib.a ../../bar.o
1427
1428 Note - the semicolons above are there to prevent the BFD chew
1429 utility from interpreting those lines as prototypes to put into
1430 the autogenerated bfd.h header...
1431
1432 Note - the string is returned in a static buffer. */
1433
1434 static const char *
1435 adjust_relative_path (const char * path, const char * ref_path)
1436 {
1437 static char *pathbuf = NULL;
1438 static unsigned int pathbuf_len = 0;
1439 const char *pathp;
1440 const char *refp;
1441 char * lpath;
1442 char * rpath;
1443 unsigned int len;
1444 unsigned int dir_up = 0;
1445 unsigned int dir_down = 0;
1446 char *newp;
1447 char * pwd = getpwd ();
1448 const char * down;
1449
1450 /* Remove symlinks, '.' and '..' from the paths, if possible. */
1451 lpath = lrealpath (path);
1452 pathp = lpath == NULL ? path : lpath;
1453
1454 rpath = lrealpath (ref_path);
1455 refp = rpath == NULL ? ref_path : rpath;
1456
1457 /* Remove common leading path elements. */
1458 for (;;)
1459 {
1460 const char *e1 = pathp;
1461 const char *e2 = refp;
1462
1463 while (*e1 && ! IS_DIR_SEPARATOR (*e1))
1464 ++e1;
1465 while (*e2 && ! IS_DIR_SEPARATOR (*e2))
1466 ++e2;
1467 if (*e1 == '\0' || *e2 == '\0' || e1 - pathp != e2 - refp
1468 || filename_ncmp (pathp, refp, e1 - pathp) != 0)
1469 break;
1470 pathp = e1 + 1;
1471 refp = e2 + 1;
1472 }
1473
1474 len = strlen (pathp) + 1;
1475 /* For each leading path element in the reference path,
1476 insert "../" into the path. */
1477 for (; *refp; ++refp)
1478 if (IS_DIR_SEPARATOR (*refp))
1479 {
1480 /* PR 12710: If the path element is "../" then instead of
1481 inserting "../" we need to insert the name of the directory
1482 at the current level. */
1483 if (refp > ref_path + 1
1484 && refp[-1] == '.'
1485 && refp[-2] == '.')
1486 dir_down ++;
1487 else
1488 dir_up ++;
1489 }
1490
1491 /* If the lrealpath calls above succeeded then we should never
1492 see dir_up and dir_down both being non-zero. */
1493
1494 len += 3 * dir_up;
1495
1496 if (dir_down)
1497 {
1498 down = pwd + strlen (pwd) - 1;
1499
1500 while (dir_down && down > pwd)
1501 {
1502 if (IS_DIR_SEPARATOR (*down))
1503 --dir_down;
1504 }
1505 BFD_ASSERT (dir_down == 0);
1506 len += strlen (down) + 1;
1507 }
1508 else
1509 down = NULL;
1510
1511 if (len > pathbuf_len)
1512 {
1513 free (pathbuf);
1514 pathbuf_len = 0;
1515 pathbuf = (char *) bfd_malloc (len);
1516 if (pathbuf == NULL)
1517 goto out;
1518 pathbuf_len = len;
1519 }
1520
1521 newp = pathbuf;
1522 while (dir_up-- > 0)
1523 {
1524 /* FIXME: Support Windows style path separators as well. */
1525 strcpy (newp, "../");
1526 newp += 3;
1527 }
1528
1529 if (down)
1530 sprintf (newp, "%s/%s", down, pathp);
1531 else
1532 strcpy (newp, pathp);
1533
1534 out:
1535 free (lpath);
1536 free (rpath);
1537 return pathbuf;
1538 }
1539
1540 /* Build a BFD style extended name table. */
1541
1542 bool
1543 _bfd_archive_bsd_construct_extended_name_table (bfd *abfd,
1544 char **tabloc,
1545 bfd_size_type *tablen,
1546 const char **name)
1547 {
1548 *name = "ARFILENAMES/";
1549 return _bfd_construct_extended_name_table (abfd, false, tabloc, tablen);
1550 }
1551
1552 /* Build an SVR4 style extended name table. */
1553
1554 bool
1555 _bfd_archive_coff_construct_extended_name_table (bfd *abfd,
1556 char **tabloc,
1557 bfd_size_type *tablen,
1558 const char **name)
1559 {
1560 *name = "//";
1561 return _bfd_construct_extended_name_table (abfd, true, tabloc, tablen);
1562 }
1563
1564 bool
1565 _bfd_noarchive_construct_extended_name_table (bfd *abfd ATTRIBUTE_UNUSED,
1566 char **tabloc ATTRIBUTE_UNUSED,
1567 bfd_size_type *len ATTRIBUTE_UNUSED,
1568 const char **name ATTRIBUTE_UNUSED)
1569 {
1570 return true;
1571 }
1572
1573 /* Follows archive_head and produces an extended name table if
1574 necessary. Returns (in tabloc) a pointer to an extended name
1575 table, and in tablen the length of the table. If it makes an entry
1576 it clobbers the filename so that the element may be written without
1577 further massage. Returns TRUE if it ran successfully, FALSE if
1578 something went wrong. A successful return may still involve a
1579 zero-length tablen! */
1580
1581 bool
1582 _bfd_construct_extended_name_table (bfd *abfd,
1583 bool trailing_slash,
1584 char **tabloc,
1585 bfd_size_type *tablen)
1586 {
1587 unsigned int maxname = ar_maxnamelen (abfd);
1588 bfd_size_type total_namelen = 0;
1589 bfd *current;
1590 char *strptr;
1591 const char *last_filename;
1592 long last_stroff;
1593
1594 *tablen = 0;
1595 last_filename = NULL;
1596
1597 /* Figure out how long the table should be. */
1598 for (current = abfd->archive_head;
1599 current != NULL;
1600 current = current->archive_next)
1601 {
1602 const char *normal;
1603 unsigned int thislen;
1604
1605 if (bfd_is_thin_archive (abfd))
1606 {
1607 const char *filename = bfd_get_filename (current);
1608
1609 /* If the element being added is a member of another archive
1610 (i.e., we are flattening), use the containing archive's name. */
1611 if (current->my_archive
1612 && ! bfd_is_thin_archive (current->my_archive))
1613 filename = bfd_get_filename (current->my_archive);
1614
1615 /* If the path is the same as the previous path seen,
1616 reuse it. This can happen when flattening a thin
1617 archive that contains other archives. */
1618 if (last_filename && filename_cmp (last_filename, filename) == 0)
1619 continue;
1620
1621 last_filename = filename;
1622
1623 /* If the path is relative, adjust it relative to
1624 the containing archive. */
1625 if (! IS_ABSOLUTE_PATH (filename)
1626 && ! IS_ABSOLUTE_PATH (bfd_get_filename (abfd)))
1627 normal = adjust_relative_path (filename, bfd_get_filename (abfd));
1628 else
1629 normal = filename;
1630
1631 /* In a thin archive, always store the full pathname
1632 in the extended name table. */
1633 total_namelen += strlen (normal) + 1;
1634 if (trailing_slash)
1635 /* Leave room for trailing slash. */
1636 ++total_namelen;
1637
1638 continue;
1639 }
1640
1641 normal = normalize (abfd, bfd_get_filename (current));
1642 if (normal == NULL)
1643 return false;
1644
1645 thislen = strlen (normal);
1646
1647 if (thislen > maxname
1648 && (bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
1649 thislen = maxname;
1650
1651 if (thislen > maxname)
1652 {
1653 /* Add one to leave room for \n. */
1654 total_namelen += thislen + 1;
1655 if (trailing_slash)
1656 {
1657 /* Leave room for trailing slash. */
1658 ++total_namelen;
1659 }
1660 }
1661 else
1662 {
1663 struct ar_hdr *hdr = arch_hdr (current);
1664 if (filename_ncmp (normal, hdr->ar_name, thislen) != 0
1665 || (thislen < sizeof hdr->ar_name
1666 && hdr->ar_name[thislen] != ar_padchar (current)))
1667 {
1668 /* Must have been using extended format even though it
1669 didn't need to. Fix it to use normal format. */
1670 memcpy (hdr->ar_name, normal, thislen);
1671 if (thislen < maxname
1672 || (thislen == maxname && thislen < sizeof hdr->ar_name))
1673 hdr->ar_name[thislen] = ar_padchar (current);
1674 }
1675 }
1676 }
1677
1678 if (total_namelen == 0)
1679 return true;
1680
1681 *tabloc = (char *) bfd_alloc (abfd, total_namelen);
1682 if (*tabloc == NULL)
1683 return false;
1684
1685 *tablen = total_namelen;
1686 strptr = *tabloc;
1687
1688 last_filename = NULL;
1689 last_stroff = 0;
1690
1691 for (current = abfd->archive_head;
1692 current != NULL;
1693 current = current->archive_next)
1694 {
1695 const char *normal;
1696 unsigned int thislen;
1697 long stroff;
1698 const char *filename = bfd_get_filename (current);
1699
1700 if (bfd_is_thin_archive (abfd))
1701 {
1702 /* If the element being added is a member of another archive
1703 (i.e., we are flattening), use the containing archive's name. */
1704 if (current->my_archive
1705 && ! bfd_is_thin_archive (current->my_archive))
1706 filename = bfd_get_filename (current->my_archive);
1707 /* If the path is the same as the previous path seen,
1708 reuse it. This can happen when flattening a thin
1709 archive that contains other archives.
1710 If the path is relative, adjust it relative to
1711 the containing archive. */
1712 if (last_filename && filename_cmp (last_filename, filename) == 0)
1713 normal = last_filename;
1714 else if (! IS_ABSOLUTE_PATH (filename)
1715 && ! IS_ABSOLUTE_PATH (bfd_get_filename (abfd)))
1716 normal = adjust_relative_path (filename, bfd_get_filename (abfd));
1717 else
1718 normal = filename;
1719 }
1720 else
1721 {
1722 normal = normalize (abfd, filename);
1723 if (normal == NULL)
1724 return false;
1725 }
1726
1727 thislen = strlen (normal);
1728 if (thislen > maxname || bfd_is_thin_archive (abfd))
1729 {
1730 /* Works for now; may need to be re-engineered if we
1731 encounter an oddball archive format and want to
1732 generalise this hack. */
1733 struct ar_hdr *hdr = arch_hdr (current);
1734 if (normal == last_filename)
1735 stroff = last_stroff;
1736 else
1737 {
1738 last_filename = filename;
1739 stroff = strptr - *tabloc;
1740 last_stroff = stroff;
1741 memcpy (strptr, normal, thislen);
1742 strptr += thislen;
1743 if (trailing_slash)
1744 *strptr++ = '/';
1745 *strptr++ = ARFMAG[1];
1746 }
1747 hdr->ar_name[0] = ar_padchar (current);
1748 if (bfd_is_thin_archive (abfd) && current->origin > 0)
1749 {
1750 int len = snprintf (hdr->ar_name + 1, maxname - 1, "%-ld:",
1751 stroff);
1752 _bfd_ar_spacepad (hdr->ar_name + 1 + len, maxname - 1 - len,
1753 "%-ld",
1754 current->origin - sizeof (struct ar_hdr));
1755 }
1756 else
1757 _bfd_ar_spacepad (hdr->ar_name + 1, maxname - 1, "%-ld", stroff);
1758 }
1759 }
1760
1761 return true;
1762 }
1763
1764 /* Do not construct an extended name table but transforms name field into
1765 its extended form. */
1766
1767 bool
1768 _bfd_archive_bsd44_construct_extended_name_table (bfd *abfd,
1769 char **tabloc,
1770 bfd_size_type *tablen,
1771 const char **name)
1772 {
1773 unsigned int maxname = ar_maxnamelen (abfd);
1774 bfd *current;
1775
1776 *tablen = 0;
1777 *tabloc = NULL;
1778 *name = NULL;
1779
1780 for (current = abfd->archive_head;
1781 current != NULL;
1782 current = current->archive_next)
1783 {
1784 const char *normal = normalize (abfd, bfd_get_filename (current));
1785 int has_space = 0;
1786 unsigned int len;
1787
1788 if (normal == NULL)
1789 return false;
1790
1791 for (len = 0; normal[len]; len++)
1792 if (normal[len] == ' ')
1793 has_space = 1;
1794
1795 if (len > maxname || has_space)
1796 {
1797 struct ar_hdr *hdr = arch_hdr (current);
1798
1799 len = (len + 3) & ~3;
1800 arch_eltdata (current)->extra_size = len;
1801 _bfd_ar_spacepad (hdr->ar_name, maxname, "#1/%lu", len);
1802 }
1803 }
1804
1805 return true;
1806 }
1807
1808 /* Write an archive header. */
1810
1811 bool
1812 _bfd_generic_write_ar_hdr (bfd *archive, bfd *abfd)
1813 {
1814 struct ar_hdr *hdr = arch_hdr (abfd);
1815
1816 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1817 return false;
1818 return true;
1819 }
1820
1821 /* Write an archive header using BSD4.4 convention. */
1822
1823 bool
1824 _bfd_bsd44_write_ar_hdr (bfd *archive, bfd *abfd)
1825 {
1826 struct ar_hdr *hdr = arch_hdr (abfd);
1827
1828 if (is_bsd44_extended_name (hdr->ar_name))
1829 {
1830 /* This is a BSD 4.4 extended name. */
1831 const char *fullname = normalize (abfd, bfd_get_filename (abfd));
1832 unsigned int len = strlen (fullname);
1833 unsigned int padded_len = (len + 3) & ~3;
1834
1835 BFD_ASSERT (padded_len == arch_eltdata (abfd)->extra_size);
1836
1837 if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size),
1838 arch_eltdata (abfd)->parsed_size + padded_len))
1839 return false;
1840
1841 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1842 return false;
1843
1844 if (bfd_write (fullname, len, archive) != len)
1845 return false;
1846
1847 if (len & 3)
1848 {
1849 static const char pad[3] = { 0, 0, 0 };
1850
1851 len = 4 - (len & 3);
1852 if (bfd_write (pad, len, archive) != len)
1853 return false;
1854 }
1855 }
1856 else
1857 {
1858 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1859 return false;
1860 }
1861 return true;
1862 }
1863
1864 bool
1865 _bfd_noarchive_write_ar_hdr (bfd *archive, bfd *abfd ATTRIBUTE_UNUSED)
1866 {
1867 return _bfd_bool_bfd_false_error (archive);
1868 }
1869
1870 /* A couple of functions for creating ar_hdrs. */
1872
1873 #ifdef HPUX_LARGE_AR_IDS
1874 /* Function to encode large UID/GID values according to HP. */
1875
1876 static void
1877 hpux_uid_gid_encode (char str[6], long int id)
1878 {
1879 int cnt;
1880
1881 str[5] = '@' + (id & 3);
1882 id >>= 2;
1883
1884 for (cnt = 4; cnt >= 0; --cnt, id >>= 6)
1885 str[cnt] = ' ' + (id & 0x3f);
1886 }
1887 #endif /* HPUX_LARGE_AR_IDS */
1888
1889 /* Takes a filename, returns an arelt_data for it, or NULL if it can't
1890 make one. The filename must refer to a filename in the filesystem.
1891 The filename field of the ar_hdr will NOT be initialized. If member
1892 is set, and it's an in-memory bfd, we fake it. */
1893
1894 static struct areltdata *
1895 bfd_ar_hdr_from_filesystem (bfd *abfd, const char *filename, bfd *member)
1896 {
1897 struct stat status;
1898 struct areltdata *ared;
1899 struct ar_hdr *hdr;
1900 size_t amt;
1901
1902 if (member && (member->flags & BFD_IN_MEMORY) != 0)
1903 {
1904 /* Assume we just "made" the member, and fake it. */
1905 struct bfd_in_memory *bim = (struct bfd_in_memory *) member->iostream;
1906 status.st_mtime = bfd_get_current_time (0);
1907 status.st_uid = getuid ();
1908 status.st_gid = getgid ();
1909 status.st_mode = 0644;
1910 status.st_size = bim->size;
1911 }
1912 else if (stat (filename, &status) != 0)
1913 {
1914 bfd_set_error (bfd_error_system_call);
1915 return NULL;
1916 }
1917 else
1918 {
1919 /* The call to stat() above has filled in the st_mtime field
1920 with the real time that the object was modified. But if
1921 we are trying to generate deterministic archives based upon
1922 the SOURCE_DATE_EPOCH environment variable then we want to
1923 override that. */
1924 status.st_mtime = bfd_get_current_time (status.st_mtime);
1925 }
1926
1927 /* If the caller requested that the BFD generate deterministic output,
1928 fake values for modification time, UID, GID, and file mode. */
1929 if ((abfd->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
1930 {
1931 status.st_mtime = 0;
1932 status.st_uid = 0;
1933 status.st_gid = 0;
1934 status.st_mode = 0644;
1935 }
1936
1937 amt = sizeof (struct ar_hdr) + sizeof (struct areltdata);
1938 ared = (struct areltdata *) bfd_zmalloc (amt);
1939 if (ared == NULL)
1940 return NULL;
1941 hdr = (struct ar_hdr *) (((char *) ared) + sizeof (struct areltdata));
1942
1943 /* ar headers are space padded, not null padded! */
1944 memset (hdr, ' ', sizeof (struct ar_hdr));
1945
1946 _bfd_ar_spacepad (hdr->ar_date, sizeof (hdr->ar_date), "%-12ld",
1947 status.st_mtime);
1948 #ifdef HPUX_LARGE_AR_IDS
1949 /* HP has a very "special" way to handle UID/GID's with numeric values
1950 > 99999. */
1951 if (status.st_uid > 99999)
1952 hpux_uid_gid_encode (hdr->ar_uid, (long) status.st_uid);
1953 else
1954 #endif
1955 _bfd_ar_spacepad (hdr->ar_uid, sizeof (hdr->ar_uid), "%ld",
1956 status.st_uid);
1957 #ifdef HPUX_LARGE_AR_IDS
1958 /* HP has a very "special" way to handle UID/GID's with numeric values
1959 > 99999. */
1960 if (status.st_gid > 99999)
1961 hpux_uid_gid_encode (hdr->ar_gid, (long) status.st_gid);
1962 else
1963 #endif
1964 _bfd_ar_spacepad (hdr->ar_gid, sizeof (hdr->ar_gid), "%ld",
1965 status.st_gid);
1966 _bfd_ar_spacepad (hdr->ar_mode, sizeof (hdr->ar_mode), "%-8lo",
1967 status.st_mode);
1968 if (status.st_size - (bfd_size_type) status.st_size != 0)
1969 {
1970 bfd_set_error (bfd_error_file_too_big);
1971 free (ared);
1972 return NULL;
1973 }
1974 if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size), status.st_size))
1975 {
1976 free (ared);
1977 return NULL;
1978 }
1979 memcpy (hdr->ar_fmag, ARFMAG, 2);
1980 ared->parsed_size = status.st_size;
1981 ared->arch_header = (char *) hdr;
1982
1983 return ared;
1984 }
1985
1986 /* Analogous to stat call. */
1987
1988 int
1989 bfd_generic_stat_arch_elt (bfd *abfd, struct stat *buf)
1990 {
1991 struct ar_hdr *hdr;
1992 char *aloser;
1993
1994 if (abfd->arelt_data == NULL)
1995 {
1996 bfd_set_error (bfd_error_invalid_operation);
1997 return -1;
1998 }
1999
2000 hdr = arch_hdr (abfd);
2001 /* PR 17512: file: 3d9e9fe9. */
2002 if (hdr == NULL)
2003 return -1;
2004 #define foo(arelt, stelt, size) \
2005 buf->stelt = strtol (hdr->arelt, &aloser, size); \
2006 if (aloser == hdr->arelt) \
2007 return -1;
2008
2009 /* Some platforms support special notations for large IDs. */
2010 #ifdef HPUX_LARGE_AR_IDS
2011 # define foo2(arelt, stelt, size) \
2012 if (hdr->arelt[5] == ' ') \
2013 { \
2014 foo (arelt, stelt, size); \
2015 } \
2016 else \
2017 { \
2018 int cnt; \
2019 for (buf->stelt = cnt = 0; cnt < 5; ++cnt) \
2020 { \
2021 if (hdr->arelt[cnt] < ' ' || hdr->arelt[cnt] > ' ' + 0x3f) \
2022 return -1; \
2023 buf->stelt <<= 6; \
2024 buf->stelt += hdr->arelt[cnt] - ' '; \
2025 } \
2026 if (hdr->arelt[5] < '@' || hdr->arelt[5] > '@' + 3) \
2027 return -1; \
2028 buf->stelt <<= 2; \
2029 buf->stelt += hdr->arelt[5] - '@'; \
2030 }
2031 #else
2032 # define foo2(arelt, stelt, size) foo (arelt, stelt, size)
2033 #endif
2034
2035 foo (ar_date, st_mtime, 10);
2036 foo2 (ar_uid, st_uid, 10);
2037 foo2 (ar_gid, st_gid, 10);
2038 foo (ar_mode, st_mode, 8);
2039
2040 buf->st_size = arch_eltdata (abfd)->parsed_size;
2041
2042 return 0;
2043 }
2044
2045 void
2046 bfd_dont_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2047 {
2048 /* FIXME: This interacts unpleasantly with ar's quick-append option.
2049 Fortunately ic960 users will never use that option. Fixing this
2050 is very hard; fortunately I know how to do it and will do so once
2051 intel's release is out the door. */
2052
2053 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2054 size_t length;
2055 const char *filename;
2056 size_t maxlen = ar_maxnamelen (abfd);
2057
2058 if ((bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
2059 {
2060 bfd_bsd_truncate_arname (abfd, pathname, arhdr);
2061 return;
2062 }
2063
2064 filename = normalize (abfd, pathname);
2065 if (filename == NULL)
2066 {
2067 /* FIXME */
2068 abort ();
2069 }
2070
2071 length = strlen (filename);
2072
2073 if (length <= maxlen)
2074 memcpy (hdr->ar_name, filename, length);
2075
2076 /* Add the padding character if there is room for it. */
2077 if (length < maxlen
2078 || (length == maxlen && length < sizeof hdr->ar_name))
2079 (hdr->ar_name)[length] = ar_padchar (abfd);
2080 }
2081
2082 void
2083 bfd_bsd_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2084 {
2085 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2086 size_t length;
2087 const char *filename = lbasename (pathname);
2088 size_t maxlen = ar_maxnamelen (abfd);
2089
2090 length = strlen (filename);
2091
2092 if (length <= maxlen)
2093 memcpy (hdr->ar_name, filename, length);
2094 else
2095 {
2096 /* pathname: meet procrustes */
2097 memcpy (hdr->ar_name, filename, maxlen);
2098 length = maxlen;
2099 }
2100
2101 if (length < maxlen)
2102 (hdr->ar_name)[length] = ar_padchar (abfd);
2103 }
2104
2105 /* Store name into ar header. Truncates the name to fit.
2106 1> strip pathname to be just the basename.
2107 2> if it's short enuf to fit, stuff it in.
2108 3> If it doesn't end with .o, truncate it to fit
2109 4> truncate it before the .o, append .o, stuff THAT in. */
2110
2111 /* This is what gnu ar does. It's better but incompatible with the
2112 bsd ar. */
2113
2114 void
2115 bfd_gnu_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2116 {
2117 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2118 size_t length;
2119 const char *filename = lbasename (pathname);
2120 size_t maxlen = ar_maxnamelen (abfd);
2121
2122 length = strlen (filename);
2123
2124 if (length <= maxlen)
2125 memcpy (hdr->ar_name, filename, length);
2126 else
2127 {
2128 /* pathname: meet procrustes. */
2129 memcpy (hdr->ar_name, filename, maxlen);
2130 if ((filename[length - 2] == '.') && (filename[length - 1] == 'o'))
2131 {
2132 hdr->ar_name[maxlen - 2] = '.';
2133 hdr->ar_name[maxlen - 1] = 'o';
2134 }
2135 length = maxlen;
2136 }
2137
2138 if (length < 16)
2139 (hdr->ar_name)[length] = ar_padchar (abfd);
2140 }
2141
2142 void
2143 _bfd_noarchive_truncate_arname (bfd *abfd ATTRIBUTE_UNUSED,
2144 const char *pathname ATTRIBUTE_UNUSED,
2145 char *arhdr ATTRIBUTE_UNUSED)
2146 {
2147 }
2148
2149 /* The BFD is open for write and has its format set to bfd_archive. */
2151
2152 bool
2153 _bfd_write_archive_contents (bfd *arch)
2154 {
2155 bfd *current;
2156 char *etable = NULL;
2157 bfd_size_type elength = 0;
2158 const char *ename = NULL;
2159 bool makemap = bfd_has_map (arch);
2160 /* If no .o's, don't bother to make a map. */
2161 bool hasobjects = false;
2162 bfd_size_type wrote;
2163 int tries;
2164 char *armag;
2165 char *buffer = NULL;
2166
2167 /* Verify the viability of all entries; if any of them live in the
2168 filesystem (as opposed to living in an archive open for input)
2169 then construct a fresh ar_hdr for them. */
2170 for (current = arch->archive_head;
2171 current != NULL;
2172 current = current->archive_next)
2173 {
2174 /* This check is checking the bfds for the objects we're reading
2175 from (which are usually either an object file or archive on
2176 disk), not the archive entries we're writing to. We don't
2177 actually create bfds for the archive members, we just copy
2178 them byte-wise when we write out the archive. */
2179 if (bfd_write_p (current))
2180 {
2181 bfd_set_error (bfd_error_invalid_operation);
2182 goto input_err;
2183 }
2184 if (!current->arelt_data)
2185 {
2186 current->arelt_data =
2187 bfd_ar_hdr_from_filesystem (arch, bfd_get_filename (current),
2188 current);
2189 if (!current->arelt_data)
2190 goto input_err;
2191
2192 /* Put in the file name. */
2193 BFD_SEND (arch, _bfd_truncate_arname,
2194 (arch, bfd_get_filename (current),
2195 (char *) arch_hdr (current)));
2196 }
2197
2198 if (makemap && ! hasobjects)
2199 { /* Don't bother if we won't make a map! */
2200 if ((bfd_check_format (current, bfd_object)))
2201 hasobjects = true;
2202 }
2203 }
2204
2205 if (!BFD_SEND (arch, _bfd_construct_extended_name_table,
2206 (arch, &etable, &elength, &ename)))
2207 return false;
2208
2209 if (bfd_seek (arch, 0, SEEK_SET) != 0)
2210 return false;
2211 armag = ARMAG;
2212 if (bfd_is_thin_archive (arch))
2213 armag = ARMAGT;
2214 wrote = bfd_write (armag, SARMAG, arch);
2215 if (wrote != SARMAG)
2216 return false;
2217
2218 if (makemap && hasobjects)
2219 {
2220 if (! _bfd_compute_and_write_armap (arch, (unsigned int) elength))
2221 return false;
2222 }
2223
2224 if (elength != 0)
2225 {
2226 struct ar_hdr hdr;
2227
2228 memset (&hdr, ' ', sizeof (struct ar_hdr));
2229 memcpy (hdr.ar_name, ename, strlen (ename));
2230 /* Round size up to even number in archive header. */
2231 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size),
2232 (elength + 1) & ~(bfd_size_type) 1))
2233 return false;
2234 memcpy (hdr.ar_fmag, ARFMAG, 2);
2235 if ((bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2236 != sizeof (struct ar_hdr))
2237 || bfd_write (etable, elength, arch) != elength)
2238 return false;
2239 if ((elength % 2) == 1)
2240 {
2241 if (bfd_write (&ARFMAG[1], 1, arch) != 1)
2242 return false;
2243 }
2244 }
2245
2246 #define AR_WRITE_BUFFERSIZE (8 * 1024 * 1024)
2247
2248 /* FIXME: Find a way to test link_info.reduce_memory_overheads
2249 and change the buffer size. */
2250 buffer = bfd_malloc (AR_WRITE_BUFFERSIZE);
2251 if (buffer == NULL)
2252 goto input_err;
2253
2254 for (current = arch->archive_head;
2255 current != NULL;
2256 current = current->archive_next)
2257 {
2258 bfd_size_type remaining = arelt_size (current);
2259 bfd_size_type saved_size = remaining;
2260 struct ar_hdr *hdr = arch_hdr (current);
2261
2262 /* Write ar header. */
2263 if (!_bfd_write_ar_hdr (arch, current))
2264 goto input_err;
2265 /* Write filename if it is a 4.4BSD extended file, and add to size. */
2266 if (!strncmp (hdr->ar_name, "#1/", 3))
2267 {
2268 const char *normal = normalize (current, current->filename);
2269 unsigned int thislen = strlen (normal);
2270 if (bfd_write (normal, thislen, arch) != thislen)
2271 goto input_err;
2272 saved_size += thislen;
2273 }
2274 if (bfd_is_thin_archive (arch))
2275 continue;
2276 if (bfd_seek (current, 0, SEEK_SET) != 0)
2277 goto input_err;
2278
2279 while (remaining)
2280 {
2281 size_t amt = AR_WRITE_BUFFERSIZE;
2282
2283 if (amt > remaining)
2284 amt = remaining;
2285 errno = 0;
2286 if (bfd_read (buffer, amt, current) != amt)
2287 goto input_err;
2288 if (bfd_write (buffer, amt, arch) != amt)
2289 goto input_err;
2290 remaining -= amt;
2291 }
2292
2293 if ((arelt_size (current) % 2) == 1)
2294 {
2295 if (bfd_write (&ARFMAG[1], 1, arch) != 1)
2296 goto input_err;
2297 }
2298 }
2299
2300 free (buffer);
2301
2302 if (makemap && hasobjects)
2303 {
2304 /* Verify the timestamp in the archive file. If it would not be
2305 accepted by the linker, rewrite it until it would be. If
2306 anything odd happens, break out and just return. (The
2307 Berkeley linker checks the timestamp and refuses to read the
2308 table-of-contents if it is >60 seconds less than the file's
2309 modified-time. That painful hack requires this painful hack. */
2310 tries = 1;
2311 do
2312 {
2313 if (bfd_update_armap_timestamp (arch))
2314 break;
2315 _bfd_error_handler
2316 (_("warning: writing archive was slow: rewriting timestamp"));
2317 }
2318 while (++tries < 6);
2319 }
2320
2321 return true;
2322
2323 input_err:
2324 bfd_set_input_error (current, bfd_get_error ());
2325 free (buffer);
2326 return false;
2327 }
2328
2329 /* Note that the namidx for the first symbol is 0. */
2331
2332 bool
2333 _bfd_compute_and_write_armap (bfd *arch, unsigned int elength)
2334 {
2335 char *first_name = NULL;
2336 bfd *current;
2337 file_ptr elt_no = 0;
2338 struct orl *map = NULL;
2339 unsigned int orl_max = 1024; /* Fine initial default. */
2340 unsigned int orl_count = 0;
2341 int stridx = 0;
2342 asymbol **syms = NULL;
2343 long syms_max = 0;
2344 bool ret;
2345 size_t amt;
2346 static bool report_plugin_err = true;
2347
2348 /* Dunno if this is the best place for this info... */
2349 if (elength != 0)
2350 elength += sizeof (struct ar_hdr);
2351 elength += elength % 2;
2352
2353 amt = orl_max * sizeof (struct orl);
2354 map = (struct orl *) bfd_malloc (amt);
2355 if (map == NULL)
2356 goto error_return;
2357
2358 /* We put the symbol names on the arch objalloc, and then discard
2359 them when done. */
2360 first_name = (char *) bfd_alloc (arch, 1);
2361 if (first_name == NULL)
2362 goto error_return;
2363
2364 /* Drop all the files called __.SYMDEF, we're going to make our own. */
2365 while (arch->archive_head
2366 && strcmp (bfd_get_filename (arch->archive_head), "__.SYMDEF") == 0)
2367 arch->archive_head = arch->archive_head->archive_next;
2368
2369 /* Map over each element. */
2370 for (current = arch->archive_head;
2371 current != NULL;
2372 current = current->archive_next, elt_no++)
2373 {
2374 if (bfd_check_format (current, bfd_object)
2375 && (bfd_get_file_flags (current) & HAS_SYMS) != 0)
2376 {
2377 long storage;
2378 long symcount;
2379 long src_count;
2380
2381 if (current->lto_slim_object && report_plugin_err)
2382 {
2383 report_plugin_err = false;
2384 _bfd_error_handler
2385 (_("%pB: plugin needed to handle lto object"),
2386 current);
2387 }
2388
2389 storage = bfd_get_symtab_upper_bound (current);
2390 if (storage < 0)
2391 goto error_return;
2392
2393 if (storage != 0)
2394 {
2395 if (storage > syms_max)
2396 {
2397 free (syms);
2398 syms_max = storage;
2399 syms = (asymbol **) bfd_malloc (syms_max);
2400 if (syms == NULL)
2401 goto error_return;
2402 }
2403 symcount = bfd_canonicalize_symtab (current, syms);
2404 if (symcount < 0)
2405 goto error_return;
2406
2407 /* Now map over all the symbols, picking out the ones we
2408 want. */
2409 for (src_count = 0; src_count < symcount; src_count++)
2410 {
2411 flagword flags = (syms[src_count])->flags;
2412 asection *sec = syms[src_count]->section;
2413
2414 if (((flags & (BSF_GLOBAL
2415 | BSF_WEAK
2416 | BSF_INDIRECT
2417 | BSF_GNU_UNIQUE)) != 0
2418 || bfd_is_com_section (sec))
2419 && ! bfd_is_und_section (sec))
2420 {
2421 bfd_size_type namelen;
2422 struct orl *new_map;
2423
2424 /* This symbol will go into the archive header. */
2425 if (orl_count == orl_max)
2426 {
2427 orl_max *= 2;
2428 amt = orl_max * sizeof (struct orl);
2429 new_map = (struct orl *) bfd_realloc (map, amt);
2430 if (new_map == NULL)
2431 goto error_return;
2432
2433 map = new_map;
2434 }
2435
2436 if (syms[src_count]->name != NULL
2437 && syms[src_count]->name[0] == '_'
2438 && syms[src_count]->name[1] == '_'
2439 && strcmp (syms[src_count]->name
2440 + (syms[src_count]->name[2] == '_'),
2441 "__gnu_lto_slim") == 0
2442 && report_plugin_err)
2443 {
2444 report_plugin_err = false;
2445 _bfd_error_handler
2446 (_("%pB: plugin needed to handle lto object"),
2447 current);
2448 }
2449 namelen = strlen (syms[src_count]->name);
2450 amt = sizeof (char *);
2451 map[orl_count].name = (char **) bfd_alloc (arch, amt);
2452 if (map[orl_count].name == NULL)
2453 goto error_return;
2454 *(map[orl_count].name) = (char *) bfd_alloc (arch,
2455 namelen + 1);
2456 if (*(map[orl_count].name) == NULL)
2457 goto error_return;
2458 strcpy (*(map[orl_count].name), syms[src_count]->name);
2459 map[orl_count].u.abfd = current;
2460 map[orl_count].namidx = stridx;
2461
2462 stridx += namelen + 1;
2463 ++orl_count;
2464 }
2465 }
2466 }
2467
2468 /* Now ask the BFD to free up any cached information, so we
2469 don't fill all of memory with symbol tables. */
2470 if (! bfd_free_cached_info (current))
2471 goto error_return;
2472 }
2473 }
2474
2475 /* OK, now we have collected all the data, let's write them out. */
2476 ret = BFD_SEND (arch, write_armap,
2477 (arch, elength, map, orl_count, stridx));
2478
2479 free (syms);
2480 free (map);
2481 if (first_name != NULL)
2482 bfd_release (arch, first_name);
2483
2484 return ret;
2485
2486 error_return:
2487 free (syms);
2488 free (map);
2489 if (first_name != NULL)
2490 bfd_release (arch, first_name);
2491
2492 return false;
2493 }
2494
2495 bool
2496 _bfd_bsd_write_armap (bfd *arch,
2497 unsigned int elength,
2498 struct orl *map,
2499 unsigned int orl_count,
2500 int stridx)
2501 {
2502 int padit = stridx & 1;
2503 unsigned int ranlibsize = orl_count * BSD_SYMDEF_SIZE;
2504 unsigned int stringsize = stridx + padit;
2505 /* Include 8 bytes to store ranlibsize and stringsize in output. */
2506 unsigned int mapsize = ranlibsize + stringsize + 8;
2507 file_ptr firstreal, first;
2508 bfd *current;
2509 bfd *last_elt;
2510 bfd_byte temp[4];
2511 unsigned int count;
2512 struct ar_hdr hdr;
2513 long uid, gid;
2514
2515 first = mapsize + elength + sizeof (struct ar_hdr) + SARMAG;
2516
2517 #ifdef BFD64
2518 firstreal = first;
2519 current = arch->archive_head;
2520 last_elt = current; /* Last element arch seen. */
2521 for (count = 0; count < orl_count; count++)
2522 {
2523 unsigned int offset;
2524
2525 if (map[count].u.abfd != last_elt)
2526 {
2527 do
2528 {
2529 struct areltdata *ared = arch_eltdata (current);
2530
2531 firstreal += (ared->parsed_size + ared->extra_size
2532 + sizeof (struct ar_hdr));
2533 firstreal += firstreal % 2;
2534 current = current->archive_next;
2535 }
2536 while (current != map[count].u.abfd);
2537 }
2538
2539 /* The archive file format only has 4 bytes to store the offset
2540 of the member. Generate 64-bit archive if an archive is past
2541 its 4Gb limit. */
2542 offset = (unsigned int) firstreal;
2543 if (firstreal != (file_ptr) offset)
2544 return _bfd_archive_64_bit_write_armap (arch, elength, map,
2545 orl_count, stridx);
2546
2547 last_elt = current;
2548 }
2549 #endif
2550
2551 /* If deterministic, we use 0 as the timestamp in the map.
2552 Some linkers may require that the archive filesystem modification
2553 time is less than (or near to) the archive map timestamp. Those
2554 linkers should not be used with deterministic mode. (GNU ld and
2555 Gold do not have this restriction.) */
2556 bfd_ardata (arch)->armap_timestamp = 0;
2557 uid = 0;
2558 gid = 0;
2559 if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0)
2560 {
2561 struct stat statbuf;
2562
2563 if (stat (bfd_get_filename (arch), &statbuf) == 0)
2564 {
2565 /* If asked, replace the time with a deterministic value. */
2566 statbuf.st_mtime = bfd_get_current_time (statbuf.st_mtime);
2567
2568 bfd_ardata (arch)->armap_timestamp = (statbuf.st_mtime
2569 + ARMAP_TIME_OFFSET);
2570 }
2571 uid = getuid();
2572 gid = getgid();
2573 }
2574
2575 memset (&hdr, ' ', sizeof (struct ar_hdr));
2576 memcpy (hdr.ar_name, RANLIBMAG, strlen (RANLIBMAG));
2577 bfd_ardata (arch)->armap_datepos = (SARMAG
2578 + offsetof (struct ar_hdr, ar_date[0]));
2579 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2580 bfd_ardata (arch)->armap_timestamp);
2581 _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", uid);
2582 _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", gid);
2583 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
2584 return false;
2585 memcpy (hdr.ar_fmag, ARFMAG, 2);
2586 if (bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2587 != sizeof (struct ar_hdr))
2588 return false;
2589 H_PUT_32 (arch, ranlibsize, temp);
2590 if (bfd_write (temp, sizeof (temp), arch) != sizeof (temp))
2591 return false;
2592
2593 firstreal = first;
2594 current = arch->archive_head;
2595 last_elt = current; /* Last element arch seen. */
2596 for (count = 0; count < orl_count; count++)
2597 {
2598 unsigned int offset;
2599 bfd_byte buf[BSD_SYMDEF_SIZE];
2600
2601 if (map[count].u.abfd != last_elt)
2602 {
2603 do
2604 {
2605 #if 1
2606 bfd_size_type size = arelt_size (current);
2607 if (!strncmp(arch_hdr (current)->ar_name, "#1/", 3))
2608 size += strlen(normalize(current, current->filename));
2609 firstreal += size + sizeof (struct ar_hdr);
2610 firstreal += size % 2;
2611 #else
2612 struct areltdata *ared = arch_eltdata (current);
2613
2614 firstreal += (ared->parsed_size + ared->extra_size
2615 + sizeof (struct ar_hdr));
2616 firstreal += firstreal % 2;
2617 #endif
2618 current = current->archive_next;
2619 }
2620 while (current != map[count].u.abfd);
2621 }
2622
2623 /* The archive file format only has 4 bytes to store the offset
2624 of the member. Check to make sure that firstreal has not grown
2625 too big. */
2626 offset = (unsigned int) firstreal;
2627 if (firstreal != (file_ptr) offset)
2628 {
2629 bfd_set_error (bfd_error_file_truncated);
2630 return false;
2631 }
2632
2633 last_elt = current;
2634 H_PUT_32 (arch, map[count].namidx, buf);
2635 H_PUT_32 (arch, firstreal, buf + BSD_SYMDEF_OFFSET_SIZE);
2636 if (bfd_write (buf, BSD_SYMDEF_SIZE, arch)
2637 != BSD_SYMDEF_SIZE)
2638 return false;
2639 }
2640
2641 /* Now write the strings themselves. */
2642 H_PUT_32 (arch, stringsize, temp);
2643 if (bfd_write (temp, sizeof (temp), arch) != sizeof (temp))
2644 return false;
2645 for (count = 0; count < orl_count; count++)
2646 {
2647 size_t len = strlen (*map[count].name) + 1;
2648
2649 if (bfd_write (*map[count].name, len, arch) != len)
2650 return false;
2651 }
2652
2653 /* The spec sez this should be a newline. But in order to be
2654 bug-compatible for sun's ar we use a null. */
2655 if (padit)
2656 {
2657 if (bfd_write ("", 1, arch) != 1)
2658 return false;
2659 }
2660
2661 return true;
2662 }
2663
2664 /* At the end of archive file handling, update the timestamp in the
2665 file, so older linkers will accept it. (This does not apply to
2666 ld.bfd or ld.gold).
2667
2668 Return TRUE if the timestamp was OK, or an unusual problem happened.
2669 Return FALSE if we updated the timestamp. */
2670
2671 bool
2672 _bfd_archive_bsd_update_armap_timestamp (bfd *arch)
2673 {
2674 struct stat archstat;
2675 struct ar_hdr hdr;
2676
2677 /* If creating deterministic archives, just leave the timestamp as-is. */
2678 if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
2679 return true;
2680
2681 /* Flush writes, get last-write timestamp from file, and compare it
2682 to the timestamp IN the file. */
2683 bfd_flush (arch);
2684 if (bfd_stat (arch, &archstat) == -1)
2685 {
2686 bfd_perror (_("Reading archive file mod timestamp"));
2687
2688 /* Can't read mod time for some reason. */
2689 return true;
2690 }
2691
2692 if (((long) archstat.st_mtime) <= bfd_ardata (arch)->armap_timestamp)
2693 /* OK by the linker's rules. */
2694 return true;
2695
2696 if (getenv ("SOURCE_DATE_EPOCH") != NULL
2697 && bfd_ardata (arch)->armap_timestamp == bfd_get_current_time (0) + ARMAP_TIME_OFFSET)
2698 /* If the archive's timestamp has been set to SOURCE_DATE_EPOCH
2699 then leave it as-is. */
2700 return true;
2701
2702 /* Update the timestamp. */
2703 bfd_ardata (arch)->armap_timestamp = archstat.st_mtime + ARMAP_TIME_OFFSET;
2704
2705 /* Prepare an ASCII version suitable for writing. */
2706 memset (hdr.ar_date, ' ', sizeof (hdr.ar_date));
2707 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2708 bfd_ardata (arch)->armap_timestamp);
2709
2710 /* Write it into the file. */
2711 bfd_ardata (arch)->armap_datepos = (SARMAG
2712 + offsetof (struct ar_hdr, ar_date[0]));
2713 if (bfd_seek (arch, bfd_ardata (arch)->armap_datepos, SEEK_SET) != 0
2714 || (bfd_write (hdr.ar_date, sizeof (hdr.ar_date), arch)
2715 != sizeof (hdr.ar_date)))
2716 {
2717 bfd_perror (_("Writing updated armap timestamp"));
2718
2719 /* Some error while writing. */
2720 return true;
2721 }
2722
2723 /* We updated the timestamp successfully. */
2724 return false;
2725 }
2726
2727 /* A coff armap looks like :
2729 lARMAG
2730 struct ar_hdr with name = '/'
2731 number of symbols
2732 offset of file for symbol 0
2733 offset of file for symbol 1
2734
2735 offset of file for symbol n-1
2736 symbol name 0
2737 symbol name 1
2738
2739 symbol name n-1 */
2740
2741 bool
2742 _bfd_coff_write_armap (bfd *arch,
2743 unsigned int elength,
2744 struct orl *map,
2745 unsigned int symbol_count,
2746 int stridx)
2747 {
2748 /* The size of the ranlib is the number of exported symbols in the
2749 archive * the number of bytes in an int, + an int for the count. */
2750 unsigned int ranlibsize = (symbol_count * 4) + 4;
2751 unsigned int stringsize = stridx;
2752 unsigned int mapsize = stringsize + ranlibsize;
2753 file_ptr archive_member_file_ptr;
2754 file_ptr first_archive_member_file_ptr;
2755 bfd *current = arch->archive_head;
2756 unsigned int count;
2757 struct ar_hdr hdr;
2758 int padit = mapsize & 1;
2759
2760 if (padit)
2761 mapsize++;
2762
2763 /* Work out where the first object file will go in the archive. */
2764 first_archive_member_file_ptr = (mapsize
2765 + elength
2766 + sizeof (struct ar_hdr)
2767 + SARMAG);
2768
2769 #ifdef BFD64
2770 current = arch->archive_head;
2771 count = 0;
2772 archive_member_file_ptr = first_archive_member_file_ptr;
2773 while (current != NULL && count < symbol_count)
2774 {
2775 /* For each symbol which is used defined in this object, write
2776 out the object file's address in the archive. */
2777
2778 while (count < symbol_count && map[count].u.abfd == current)
2779 {
2780 unsigned int offset = (unsigned int) archive_member_file_ptr;
2781
2782 /* Generate 64-bit archive if an archive is past its 4Gb
2783 limit. */
2784 if (archive_member_file_ptr != (file_ptr) offset)
2785 return _bfd_archive_64_bit_write_armap (arch, elength, map,
2786 symbol_count, stridx);
2787 count++;
2788 }
2789 archive_member_file_ptr += sizeof (struct ar_hdr);
2790 if (! bfd_is_thin_archive (arch))
2791 {
2792 /* Add size of this archive entry. */
2793 archive_member_file_ptr += arelt_size (current);
2794 /* Remember about the even alignment. */
2795 archive_member_file_ptr += archive_member_file_ptr % 2;
2796 }
2797 current = current->archive_next;
2798 }
2799 #endif
2800
2801 memset (&hdr, ' ', sizeof (struct ar_hdr));
2802 hdr.ar_name[0] = '/';
2803 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
2804 return false;
2805 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2806 ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0
2807 ? time (NULL) : 0));
2808 /* This, at least, is what Intel coff sets the values to. */
2809 _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", 0);
2810 _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", 0);
2811 _bfd_ar_spacepad (hdr.ar_mode, sizeof (hdr.ar_mode), "%-7lo", 0);
2812 memcpy (hdr.ar_fmag, ARFMAG, 2);
2813
2814 /* Write the ar header for this item and the number of symbols. */
2815 if (bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2816 != sizeof (struct ar_hdr))
2817 return false;
2818
2819 if (!bfd_write_bigendian_4byte_int (arch, symbol_count))
2820 return false;
2821
2822 /* Two passes, first write the file offsets for each symbol -
2823 remembering that each offset is on a two byte boundary. */
2824
2825 /* Write out the file offset for the file associated with each
2826 symbol, and remember to keep the offsets padded out. */
2827
2828 current = arch->archive_head;
2829 count = 0;
2830 archive_member_file_ptr = first_archive_member_file_ptr;
2831 while (current != NULL && count < symbol_count)
2832 {
2833 /* For each symbol which is used defined in this object, write
2834 out the object file's address in the archive. */
2835
2836 while (count < symbol_count && map[count].u.abfd == current)
2837 {
2838 unsigned int offset = (unsigned int) archive_member_file_ptr;
2839
2840 /* Catch an attempt to grow an archive past its 4Gb limit. */
2841 if (archive_member_file_ptr != (file_ptr) offset)
2842 {
2843 bfd_set_error (bfd_error_file_truncated);
2844 return false;
2845 }
2846 if (!bfd_write_bigendian_4byte_int (arch, offset))
2847 return false;
2848 count++;
2849 }
2850 archive_member_file_ptr += sizeof (struct ar_hdr);
2851 if (! bfd_is_thin_archive (arch))
2852 {
2853 /* Add size of this archive entry. */
2854 archive_member_file_ptr += arelt_size (current);
2855 /* Remember about the even alignment. */
2856 archive_member_file_ptr += archive_member_file_ptr % 2;
2857 }
2858 current = current->archive_next;
2859 }
2860
2861 /* Now write the strings themselves. */
2862 for (count = 0; count < symbol_count; count++)
2863 {
2864 size_t len = strlen (*map[count].name) + 1;
2865
2866 if (bfd_write (*map[count].name, len, arch) != len)
2867 return false;
2868 }
2869
2870 /* The spec sez this should be a newline. But in order to be
2871 bug-compatible for arc960 we use a null. */
2872 if (padit)
2873 {
2874 if (bfd_write ("", 1, arch) != 1)
2875 return false;
2876 }
2877
2878 return true;
2879 }
2880
2881 bool
2882 _bfd_noarchive_write_armap
2883 (bfd *arch ATTRIBUTE_UNUSED,
2884 unsigned int elength ATTRIBUTE_UNUSED,
2885 struct orl *map ATTRIBUTE_UNUSED,
2886 unsigned int orl_count ATTRIBUTE_UNUSED,
2887 int stridx ATTRIBUTE_UNUSED)
2888 {
2889 return true;
2890 }
2891
2892 static int
2893 archive_close_worker (void **slot, void *inf ATTRIBUTE_UNUSED)
2894 {
2895 struct ar_cache *ent = (struct ar_cache *) *slot;
2896
2897 bfd_close_all_done (ent->arbfd);
2898 return 1;
2899 }
2900
2901 void
2902 _bfd_unlink_from_archive_parent (bfd *abfd)
2903 {
2904 if (arch_eltdata (abfd) != NULL)
2905 {
2906 struct areltdata *ared = arch_eltdata (abfd);
2907 htab_t htab = (htab_t) ared->parent_cache;
2908
2909 if (htab)
2910 {
2911 struct ar_cache ent;
2912 void **slot;
2913
2914 ent.ptr = ared->key;
2915 slot = htab_find_slot (htab, &ent, NO_INSERT);
2916 if (slot != NULL)
2917 {
2918 BFD_ASSERT (((struct ar_cache *) *slot)->arbfd == abfd);
2919 htab_clear_slot (htab, slot);
2920 }
2921 }
2922 }
2923 }
2924
2925 bool
2926 _bfd_archive_close_and_cleanup (bfd *abfd)
2927 {
2928 if (bfd_read_p (abfd) && abfd->format == bfd_archive)
2929 {
2930 bfd *nbfd;
2931 bfd *next;
2932 htab_t htab;
2933
2934 /* Close nested archives (if this bfd is a thin archive). */
2935 for (nbfd = abfd->nested_archives; nbfd; nbfd = next)
2936 {
2937 next = nbfd->archive_next;
2938 bfd_close (nbfd);
2939 }
2940
2941 htab = bfd_ardata (abfd)->cache;
2942 if (htab)
2943 {
2944 htab_traverse_noresize (htab, archive_close_worker, NULL);
2945 htab_delete (htab);
2946 bfd_ardata (abfd)->cache = NULL;
2947 }
2948
2949 /* Close the archive plugin file descriptor if needed. */
2950 if (abfd->archive_plugin_fd > 0)
2951 close (abfd->archive_plugin_fd);
2952 }
2953
2954 _bfd_unlink_from_archive_parent (abfd);
2955
2956 if (abfd->is_linker_output)
2957 (*abfd->link.hash->hash_table_free) (abfd);
2958
2959 return true;
2960 }
2961