archive.c revision 1.1.1.8 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.
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 file_ptr origin = new_areldata->origin;
719
720 free (new_areldata);
721 if (ext_arch == NULL
722 || ! bfd_check_format (ext_arch, bfd_archive))
723 return NULL;
724 n_bfd = _bfd_get_elt_at_filepos (ext_arch, origin, info);
725 if (n_bfd == NULL)
726 return NULL;
727 n_bfd->proxy_origin = bfd_tell (archive);
728
729 /* Copy BFD_COMPRESS, BFD_DECOMPRESS and BFD_COMPRESS_GABI
730 flags. */
731 n_bfd->flags |= archive->flags & (BFD_COMPRESS
732 | BFD_DECOMPRESS
733 | BFD_COMPRESS_GABI);
734
735 return n_bfd;
736 }
737
738 /* It's not an element of a nested archive;
739 open the external file as a bfd. */
740 bfd_set_error (bfd_error_no_error);
741 n_bfd = open_nested_file (filename, archive);
742 if (n_bfd == NULL)
743 {
744 switch (bfd_get_error ())
745 {
746 default:
747 break;
748 case bfd_error_no_error:
749 bfd_set_error (bfd_error_malformed_archive);
750 break;
751 case bfd_error_system_call:
752 if (info != NULL)
753 {
754 info->callbacks->fatal
755 (_("%P: %pB(%s): error opening thin archive member: %E\n"),
756 archive, filename);
757 break;
758 }
759 break;
760 }
761 }
762 }
763 else
764 {
765 n_bfd = _bfd_create_empty_archive_element_shell (archive);
766 }
767
768 if (n_bfd == NULL)
769 {
770 free (new_areldata);
771 return NULL;
772 }
773
774 n_bfd->proxy_origin = bfd_tell (archive);
775
776 if (bfd_is_thin_archive (archive))
777 {
778 n_bfd->origin = 0;
779 }
780 else
781 {
782 n_bfd->origin = n_bfd->proxy_origin;
783 if (!bfd_set_filename (n_bfd, filename))
784 goto out;
785 }
786
787 n_bfd->arelt_data = new_areldata;
788
789 /* Copy BFD_COMPRESS, BFD_DECOMPRESS and BFD_COMPRESS_GABI flags. */
790 n_bfd->flags |= archive->flags & (BFD_COMPRESS
791 | BFD_DECOMPRESS
792 | BFD_COMPRESS_GABI);
793
794 /* Copy is_linker_input. */
795 n_bfd->is_linker_input = archive->is_linker_input;
796
797 if (archive->no_element_cache
798 || _bfd_add_bfd_to_archive_cache (archive, filepos, n_bfd))
799 return n_bfd;
800
801 out:
802 free (new_areldata);
803 n_bfd->arelt_data = NULL;
804 bfd_close (n_bfd);
805 return NULL;
806 }
807
808 /* Return the BFD which is referenced by the symbol in ABFD indexed by
809 SYM_INDEX. SYM_INDEX should have been returned by bfd_get_next_mapent. */
810
811 bfd *
812 _bfd_generic_get_elt_at_index (bfd *abfd, symindex sym_index)
813 {
814 carsym *entry;
815
816 entry = bfd_ardata (abfd)->symdefs + sym_index;
817 return _bfd_get_elt_at_filepos (abfd, entry->file_offset, NULL);
818 }
819
820 bfd *
821 _bfd_noarchive_get_elt_at_index (bfd *abfd,
822 symindex sym_index ATTRIBUTE_UNUSED)
823 {
824 return (bfd *) _bfd_ptr_bfd_null_error (abfd);
825 }
826
827 /*
828 FUNCTION
829 bfd_openr_next_archived_file
830
831 SYNOPSIS
832 bfd *bfd_openr_next_archived_file (bfd *archive, bfd *previous);
833
834 DESCRIPTION
835 Provided a BFD, @var{archive}, containing an archive and NULL, open
836 an input BFD on the first contained element and returns that.
837 Subsequent calls should pass the archive and the previous return
838 value to return a created BFD to the next contained element. NULL
839 is returned when there are no more.
840 Note - if you want to process the bfd returned by this call be
841 sure to call bfd_check_format() on it first.
842 */
843
844 bfd *
845 bfd_openr_next_archived_file (bfd *archive, bfd *last_file)
846 {
847 if ((bfd_get_format (archive) != bfd_archive)
848 || (archive->direction == write_direction))
849 {
850 bfd_set_error (bfd_error_invalid_operation);
851 return NULL;
852 }
853
854 return BFD_SEND (archive,
855 openr_next_archived_file, (archive, last_file));
856 }
857
858 bfd *
859 bfd_generic_openr_next_archived_file (bfd *archive, bfd *last_file)
860 {
861 ufile_ptr filestart;
862
863 if (!last_file)
864 filestart = bfd_ardata (archive)->first_file_filepos;
865 else
866 {
867 filestart = last_file->proxy_origin;
868 if (! bfd_is_thin_archive (archive))
869 {
870 bfd_size_type size = arelt_size (last_file);
871
872 filestart += size;
873 /* Pad to an even boundary...
874 Note that last_file->origin can be odd in the case of
875 BSD-4.4-style element with a long odd size. */
876 filestart += filestart % 2;
877 if (filestart < last_file->proxy_origin)
878 {
879 /* Prevent looping. See PR19256. */
880 bfd_set_error (bfd_error_malformed_archive);
881 return NULL;
882 }
883 }
884 }
885
886 return _bfd_get_elt_at_filepos (archive, filestart, NULL);
887 }
888
889 bfd *
890 _bfd_noarchive_openr_next_archived_file (bfd *archive,
891 bfd *last_file ATTRIBUTE_UNUSED)
892 {
893 return (bfd *) _bfd_ptr_bfd_null_error (archive);
894 }
895
896 bfd_cleanup
897 bfd_generic_archive_p (bfd *abfd)
898 {
899 char armag[SARMAG + 1];
900 size_t amt;
901
902 if (bfd_read (armag, SARMAG, abfd) != SARMAG)
903 {
904 if (bfd_get_error () != bfd_error_system_call)
905 bfd_set_error (bfd_error_wrong_format);
906 return NULL;
907 }
908
909 bfd_set_thin_archive (abfd, strncmp (armag, ARMAGT, SARMAG) == 0);
910
911 if (strncmp (armag, ARMAG, SARMAG) != 0
912 && ! bfd_is_thin_archive (abfd))
913 {
914 bfd_set_error (bfd_error_wrong_format);
915 return NULL;
916 }
917
918 amt = sizeof (struct artdata);
919 bfd_ardata (abfd) = (struct artdata *) bfd_zalloc (abfd, amt);
920 if (bfd_ardata (abfd) == NULL)
921 return NULL;
922
923 bfd_ardata (abfd)->first_file_filepos = SARMAG;
924
925 if (!BFD_SEND (abfd, _bfd_slurp_armap, (abfd))
926 || !BFD_SEND (abfd, _bfd_slurp_extended_name_table, (abfd)))
927 {
928 if (bfd_get_error () != bfd_error_system_call)
929 bfd_set_error (bfd_error_wrong_format);
930 bfd_release (abfd, bfd_ardata (abfd));
931 return NULL;
932 }
933
934 if (abfd->target_defaulted && bfd_has_map (abfd))
935 {
936 bfd *first;
937 unsigned int save;
938
939 /* This archive has a map, so we may presume that the contents
940 are object files. Make sure that if the first file in the
941 archive can be recognized as an object file, it is for this
942 target. If not, assume that this is the wrong format. If
943 the first file is not an object file, somebody is doing
944 something weird, and we permit it so that ar -t will work.
945
946 This is done because any normal format will recognize any
947 normal archive, regardless of the format of the object files.
948 We do accept an empty archive. */
949
950 save = abfd->no_element_cache;
951 abfd->no_element_cache = 1;
952 first = bfd_openr_next_archived_file (abfd, NULL);
953 abfd->no_element_cache = save;
954 if (first != NULL)
955 {
956 first->target_defaulted = false;
957 if (bfd_check_format (first, bfd_object)
958 && first->xvec != abfd->xvec)
959 bfd_set_error (bfd_error_wrong_object_format);
960 bfd_close (first);
961 }
962 }
963
964 return _bfd_no_cleanup;
965 }
966
967 /* Some constants for a 32 bit BSD archive structure. We do not
968 support 64 bit archives presently; so far as I know, none actually
969 exist. Supporting them would require changing these constants, and
970 changing some H_GET_32 to H_GET_64. */
971
972 /* The size of an external symdef structure. */
973 #define BSD_SYMDEF_SIZE 8
974
975 /* The offset from the start of a symdef structure to the file offset. */
976 #define BSD_SYMDEF_OFFSET_SIZE 4
977
978 /* The size of the symdef count. */
979 #define BSD_SYMDEF_COUNT_SIZE 4
980
981 /* The size of the string count. */
982 #define BSD_STRING_COUNT_SIZE 4
983
984 /* Read a BSD-style archive symbol table. Returns FALSE on error,
985 TRUE otherwise. */
986
987 static bool
988 do_slurp_bsd_armap (bfd *abfd)
989 {
990 struct areltdata *mapdata;
991 size_t counter;
992 bfd_byte *raw_armap, *rbase;
993 struct artdata *ardata = bfd_ardata (abfd);
994 char *stringbase;
995 bfd_size_type parsed_size;
996 size_t amt, string_size;
997 carsym *set;
998
999 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1000 if (mapdata == NULL)
1001 return false;
1002 parsed_size = mapdata->parsed_size;
1003 free (mapdata);
1004 /* PR 17512: file: 883ff754. */
1005 /* PR 17512: file: 0458885f. */
1006 if (parsed_size < BSD_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE)
1007 {
1008 bfd_set_error (bfd_error_malformed_archive);
1009 return false;
1010 }
1011
1012 raw_armap = (bfd_byte *) _bfd_alloc_and_read (abfd, parsed_size, parsed_size);
1013 if (raw_armap == NULL)
1014 return false;
1015
1016 parsed_size -= BSD_SYMDEF_COUNT_SIZE + BSD_STRING_COUNT_SIZE;
1017 amt = H_GET_32 (abfd, raw_armap);
1018 if (amt > parsed_size
1019 || amt % BSD_SYMDEF_SIZE != 0)
1020 {
1021 /* Probably we're using the wrong byte ordering. */
1022 bfd_set_error (bfd_error_wrong_format);
1023 goto release_armap;
1024 }
1025
1026 rbase = raw_armap + BSD_SYMDEF_COUNT_SIZE;
1027 stringbase = (char *) rbase + amt + BSD_STRING_COUNT_SIZE;
1028 string_size = parsed_size - amt;
1029
1030 ardata->symdef_count = amt / BSD_SYMDEF_SIZE;
1031 if (_bfd_mul_overflow (ardata->symdef_count, sizeof (carsym), &amt))
1032 {
1033 bfd_set_error (bfd_error_no_memory);
1034 goto release_armap;
1035 }
1036 ardata->symdefs = (struct carsym *) bfd_alloc (abfd, amt);
1037 if (!ardata->symdefs)
1038 goto release_armap;
1039
1040 for (counter = 0, set = ardata->symdefs;
1041 counter < ardata->symdef_count;
1042 counter++, set++, rbase += BSD_SYMDEF_SIZE)
1043 {
1044 unsigned nameoff = H_GET_32 (abfd, rbase);
1045 if (nameoff >= string_size)
1046 {
1047 bfd_set_error (bfd_error_malformed_archive);
1048 goto release_armap;
1049 }
1050 set->name = stringbase + nameoff;
1051 set->file_offset = H_GET_32 (abfd, rbase + BSD_SYMDEF_OFFSET_SIZE);
1052 }
1053
1054 ardata->first_file_filepos = bfd_tell (abfd);
1055 /* Pad to an even boundary if you have to. */
1056 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1057 /* FIXME, we should provide some way to free raw_ardata when
1058 we are done using the strings from it. For now, it seems
1059 to be allocated on an objalloc anyway... */
1060 abfd->has_armap = true;
1061 return true;
1062
1063 release_armap:
1064 ardata->symdef_count = 0;
1065 ardata->symdefs = NULL;
1066 bfd_release (abfd, raw_armap);
1067 return false;
1068 }
1069
1070 /* Read a COFF archive symbol table. Returns FALSE on error, TRUE
1071 otherwise. */
1072
1073 static bool
1074 do_slurp_coff_armap (bfd *abfd)
1075 {
1076 struct areltdata *mapdata;
1077 int *raw_armap, *rawptr;
1078 struct artdata *ardata = bfd_ardata (abfd);
1079 char *stringbase;
1080 char *stringend;
1081 bfd_size_type stringsize;
1082 bfd_size_type parsed_size;
1083 ufile_ptr filesize;
1084 size_t nsymz, carsym_size, ptrsize, i;
1085 carsym *carsyms;
1086 bfd_vma (*swap) (const void *);
1087 char int_buf[4];
1088 struct areltdata *tmp;
1089
1090 mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1091 if (mapdata == NULL)
1092 return false;
1093 parsed_size = mapdata->parsed_size;
1094 free (mapdata);
1095
1096 if (bfd_read (int_buf, 4, abfd) != 4)
1097 return false;
1098
1099 /* It seems that all numeric information in a coff archive is always
1100 in big endian format, no matter the host or target. */
1101 swap = bfd_getb32;
1102 nsymz = bfd_getb32 (int_buf);
1103
1104 /* The coff armap must be read sequentially. So we construct a
1105 bsd-style one in core all at once, for simplicity. */
1106
1107 if (_bfd_mul_overflow (nsymz, sizeof (carsym), &carsym_size))
1108 {
1109 bfd_set_error (bfd_error_no_memory);
1110 return false;
1111 }
1112
1113 filesize = bfd_get_file_size (abfd);
1114 ptrsize = 4 * nsymz;
1115 if ((filesize != 0 && parsed_size > filesize)
1116 || parsed_size < 4
1117 || parsed_size - 4 < ptrsize)
1118 {
1119 bfd_set_error (bfd_error_malformed_archive);
1120 return false;
1121 }
1122
1123 stringsize = parsed_size - ptrsize - 4;
1124
1125 if (carsym_size + stringsize + 1 <= carsym_size)
1126 {
1127 bfd_set_error (bfd_error_no_memory);
1128 return false;
1129 }
1130
1131 /* Allocate and read in the raw offsets. */
1132 raw_armap = (int *) _bfd_malloc_and_read (abfd, ptrsize, ptrsize);
1133 if (raw_armap == NULL)
1134 return false;
1135
1136 ardata->symdefs = (struct carsym *) bfd_alloc (abfd,
1137 carsym_size + stringsize + 1);
1138 if (ardata->symdefs == NULL)
1139 goto free_armap;
1140 carsyms = ardata->symdefs;
1141 stringbase = ((char *) ardata->symdefs) + carsym_size;
1142
1143 if (bfd_read (stringbase, stringsize, abfd) != stringsize)
1144 goto release_symdefs;
1145
1146 /* OK, build the carsyms. */
1147 stringend = stringbase + stringsize;
1148 *stringend = 0;
1149 for (i = 0; i < nsymz; i++)
1150 {
1151 rawptr = raw_armap + i;
1152 carsyms->file_offset = swap ((bfd_byte *) rawptr);
1153 carsyms->name = stringbase;
1154 stringbase += strlen (stringbase);
1155 if (stringbase != stringend)
1156 ++stringbase;
1157 carsyms++;
1158 }
1159
1160 ardata->symdef_count = nsymz;
1161 ardata->first_file_filepos = bfd_tell (abfd);
1162 /* Pad to an even boundary if you have to. */
1163 ardata->first_file_filepos += (ardata->first_file_filepos) % 2;
1164 if (bfd_seek (abfd, ardata->first_file_filepos, SEEK_SET) != 0)
1165 goto release_symdefs;
1166
1167 abfd->has_armap = true;
1168 free (raw_armap);
1169
1170 /* Check for a second archive header (as used by PE). */
1171 tmp = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1172 if (tmp != NULL)
1173 {
1174 if (tmp->arch_header[0] == '/'
1175 && tmp->arch_header[1] == ' ')
1176 ardata->first_file_filepos
1177 += (tmp->parsed_size + sizeof (struct ar_hdr) + 1) & ~(unsigned) 1;
1178 free (tmp);
1179 }
1180
1181 return true;
1182
1183 release_symdefs:
1184 bfd_release (abfd, (ardata)->symdefs);
1185 free_armap:
1186 free (raw_armap);
1187 return false;
1188 }
1189
1190 /* This routine can handle either coff-style or bsd-style armaps
1191 (archive symbol table). Returns FALSE on error, TRUE otherwise */
1192
1193 bool
1194 bfd_slurp_armap (bfd *abfd)
1195 {
1196 char nextname[17];
1197 int i = bfd_read (nextname, 16, abfd);
1198
1199 if (i == 0)
1200 return true;
1201 if (i != 16)
1202 return false;
1203
1204 if (bfd_seek (abfd, -16, SEEK_CUR) != 0)
1205 return false;
1206
1207 if (startswith (nextname, "__.SYMDEF ")
1208 || startswith (nextname, "__.SYMDEF/ ")) /* Old Linux archives. */
1209 return do_slurp_bsd_armap (abfd);
1210 else if (startswith (nextname, "/ "))
1211 return do_slurp_coff_armap (abfd);
1212 else if (startswith (nextname, "/SYM64/ "))
1213 {
1214 /* 64bit (Irix 6) archive. */
1215 #ifdef BFD64
1216 return _bfd_archive_64_bit_slurp_armap (abfd);
1217 #else
1218 bfd_set_error (bfd_error_wrong_format);
1219 return false;
1220 #endif
1221 }
1222 else if (startswith (nextname, "#1/20 "))
1223 {
1224 /* Mach-O has a special name for armap when the map is sorted by name.
1225 However because this name has a space it is slightly more difficult
1226 to check it. */
1227 struct ar_hdr hdr;
1228 char extname[21];
1229
1230 if (bfd_read (&hdr, sizeof (hdr), abfd) != sizeof (hdr))
1231 return false;
1232 /* Read the extended name. We know its length. */
1233 if (bfd_read (extname, 20, abfd) != 20)
1234 return false;
1235 if (bfd_seek (abfd, -(file_ptr) (sizeof (hdr) + 20), SEEK_CUR) != 0)
1236 return false;
1237 extname[20] = 0;
1238 if (startswith (extname, "__.SYMDEF SORTED")
1239 || startswith (extname, "__.SYMDEF"))
1240 return do_slurp_bsd_armap (abfd);
1241 }
1242
1243 abfd->has_armap = false;
1244 return true;
1245 }
1246
1247 /** Extended name table.
1249
1250 Normally archives support only 14-character filenames.
1251
1252 Intel has extended the format: longer names are stored in a special
1253 element (the first in the archive, or second if there is an armap);
1254 the name in the ar_hdr is replaced by <space><index into filename
1255 element>. Index is the P.R. of an int (decimal). Data General have
1256 extended the format by using the prefix // for the special element. */
1257
1258 /* Returns FALSE on error, TRUE otherwise. */
1259
1260 bool
1261 _bfd_slurp_extended_name_table (bfd *abfd)
1262 {
1263 char nextname[17];
1264
1265 /* FIXME: Formatting sucks here, and in case of failure of BFD_READ,
1266 we probably don't want to return TRUE. */
1267 if (bfd_seek (abfd, bfd_ardata (abfd)->first_file_filepos, SEEK_SET) != 0)
1268 return false;
1269
1270 if (bfd_read (nextname, 16, abfd) == 16)
1271 {
1272 struct areltdata *namedata;
1273 bfd_size_type amt;
1274 ufile_ptr filesize;
1275
1276 if (bfd_seek (abfd, -16, SEEK_CUR) != 0)
1277 return false;
1278
1279 if (! startswith (nextname, "ARFILENAMES/ ")
1280 && ! startswith (nextname, "// "))
1281 {
1282 bfd_ardata (abfd)->extended_names = NULL;
1283 bfd_ardata (abfd)->extended_names_size = 0;
1284 return true;
1285 }
1286
1287 namedata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
1288 if (namedata == NULL)
1289 return false;
1290
1291 filesize = bfd_get_file_size (abfd);
1292 amt = namedata->parsed_size;
1293 if (amt + 1 == 0 || (filesize != 0 && amt > filesize))
1294 {
1295 bfd_set_error (bfd_error_malformed_archive);
1296 goto byebye;
1297 }
1298
1299 bfd_ardata (abfd)->extended_names_size = amt;
1300 bfd_ardata (abfd)->extended_names = (char *) bfd_alloc (abfd, amt + 1);
1301 if (bfd_ardata (abfd)->extended_names == NULL)
1302 {
1303 byebye:
1304 free (namedata);
1305 bfd_ardata (abfd)->extended_names = NULL;
1306 bfd_ardata (abfd)->extended_names_size = 0;
1307 return false;
1308 }
1309
1310 if (bfd_read (bfd_ardata (abfd)->extended_names, amt, abfd) != amt)
1311 {
1312 if (bfd_get_error () != bfd_error_system_call)
1313 bfd_set_error (bfd_error_malformed_archive);
1314 bfd_release (abfd, (bfd_ardata (abfd)->extended_names));
1315 bfd_ardata (abfd)->extended_names = NULL;
1316 goto byebye;
1317 }
1318 bfd_ardata (abfd)->extended_names[amt] = 0;
1319
1320 /* Since the archive is supposed to be printable if it contains
1321 text, the entries in the list are newline-padded, not null
1322 padded. In SVR4-style archives, the names also have a
1323 trailing '/'. DOS/NT created archive often have \ in them
1324 We'll fix all problems here. */
1325 {
1326 char *ext_names = bfd_ardata (abfd)->extended_names;
1327 char *temp = ext_names;
1328 char *limit = temp + namedata->parsed_size;
1329
1330 for (; temp < limit; ++temp)
1331 {
1332 if (*temp == ARFMAG[1])
1333 temp[temp > ext_names && temp[-1] == '/' ? -1 : 0] = '\0';
1334 if (*temp == '\\')
1335 *temp = '/';
1336 }
1337 *limit = '\0';
1338 }
1339
1340 /* Pad to an even boundary if you have to. */
1341 bfd_ardata (abfd)->first_file_filepos = bfd_tell (abfd);
1342 bfd_ardata (abfd)->first_file_filepos +=
1343 (bfd_ardata (abfd)->first_file_filepos) % 2;
1344
1345 free (namedata);
1346 }
1347 return true;
1348 }
1349
1350 #ifdef VMS
1351
1352 /* Return a copy of the stuff in the filename between any :]> and a
1353 semicolon. */
1354
1355 static const char *
1356 normalize (bfd *abfd, const char *file)
1357 {
1358 const char *first;
1359 const char *last;
1360 char *copy;
1361
1362 if (abfd->flags & BFD_ARCHIVE_FULL_PATH)
1363 return file;
1364
1365 first = file + strlen (file) - 1;
1366 last = first + 1;
1367
1368 while (first != file)
1369 {
1370 if (*first == ';')
1371 last = first;
1372 if (*first == ':' || *first == ']' || *first == '>')
1373 {
1374 first++;
1375 break;
1376 }
1377 first--;
1378 }
1379
1380 copy = bfd_alloc (abfd, last - first + 1);
1381 if (copy == NULL)
1382 return NULL;
1383
1384 memcpy (copy, first, last - first);
1385 copy[last - first] = 0;
1386
1387 return copy;
1388 }
1389
1390 #else
1391 static const char *
1392 normalize (bfd *abfd, const char *file)
1393 {
1394 if (abfd->flags & BFD_ARCHIVE_FULL_PATH)
1395 return file;
1396 return lbasename (file);
1397 }
1398 #endif
1399
1400 /* Adjust a relative path name based on the reference path.
1401 For example:
1402
1403 Relative path Reference path Result
1404 ------------- -------------- ------
1405 bar.o lib.a bar.o
1406 foo/bar.o lib.a foo/bar.o
1407 bar.o foo/lib.a ../bar.o
1408 foo/bar.o baz/lib.a ../foo/bar.o
1409 bar.o ../lib.a <parent of current dir>/bar.o
1410 ; ../bar.o ../lib.a bar.o
1411 ; ../bar.o lib.a ../bar.o
1412 foo/bar.o ../lib.a <parent of current dir>/foo/bar.o
1413 bar.o ../../lib.a <grandparent>/<parent>/bar.o
1414 bar.o foo/baz/lib.a ../../bar.o
1415
1416 Note - the semicolons above are there to prevent the BFD chew
1417 utility from interpreting those lines as prototypes to put into
1418 the autogenerated bfd.h header...
1419
1420 Note - the string is returned in a static buffer. */
1421
1422 static const char *
1423 adjust_relative_path (const char * path, const char * ref_path)
1424 {
1425 static char *pathbuf = NULL;
1426 static unsigned int pathbuf_len = 0;
1427 const char *pathp;
1428 const char *refp;
1429 char * lpath;
1430 char * rpath;
1431 unsigned int len;
1432 unsigned int dir_up = 0;
1433 unsigned int dir_down = 0;
1434 char *newp;
1435 char * pwd = getpwd ();
1436 const char * down;
1437
1438 /* Remove symlinks, '.' and '..' from the paths, if possible. */
1439 lpath = lrealpath (path);
1440 pathp = lpath == NULL ? path : lpath;
1441
1442 rpath = lrealpath (ref_path);
1443 refp = rpath == NULL ? ref_path : rpath;
1444
1445 /* Remove common leading path elements. */
1446 for (;;)
1447 {
1448 const char *e1 = pathp;
1449 const char *e2 = refp;
1450
1451 while (*e1 && ! IS_DIR_SEPARATOR (*e1))
1452 ++e1;
1453 while (*e2 && ! IS_DIR_SEPARATOR (*e2))
1454 ++e2;
1455 if (*e1 == '\0' || *e2 == '\0' || e1 - pathp != e2 - refp
1456 || filename_ncmp (pathp, refp, e1 - pathp) != 0)
1457 break;
1458 pathp = e1 + 1;
1459 refp = e2 + 1;
1460 }
1461
1462 len = strlen (pathp) + 1;
1463 /* For each leading path element in the reference path,
1464 insert "../" into the path. */
1465 for (; *refp; ++refp)
1466 if (IS_DIR_SEPARATOR (*refp))
1467 {
1468 /* PR 12710: If the path element is "../" then instead of
1469 inserting "../" we need to insert the name of the directory
1470 at the current level. */
1471 if (refp > ref_path + 1
1472 && refp[-1] == '.'
1473 && refp[-2] == '.')
1474 dir_down ++;
1475 else
1476 dir_up ++;
1477 }
1478
1479 /* If the lrealpath calls above succeeded then we should never
1480 see dir_up and dir_down both being non-zero. */
1481
1482 len += 3 * dir_up;
1483
1484 if (dir_down)
1485 {
1486 down = pwd + strlen (pwd) - 1;
1487
1488 while (dir_down && down > pwd)
1489 {
1490 if (IS_DIR_SEPARATOR (*down))
1491 --dir_down;
1492 }
1493 BFD_ASSERT (dir_down == 0);
1494 len += strlen (down) + 1;
1495 }
1496 else
1497 down = NULL;
1498
1499 if (len > pathbuf_len)
1500 {
1501 free (pathbuf);
1502 pathbuf_len = 0;
1503 pathbuf = (char *) bfd_malloc (len);
1504 if (pathbuf == NULL)
1505 goto out;
1506 pathbuf_len = len;
1507 }
1508
1509 newp = pathbuf;
1510 while (dir_up-- > 0)
1511 {
1512 /* FIXME: Support Windows style path separators as well. */
1513 strcpy (newp, "../");
1514 newp += 3;
1515 }
1516
1517 if (down)
1518 sprintf (newp, "%s/%s", down, pathp);
1519 else
1520 strcpy (newp, pathp);
1521
1522 out:
1523 free (lpath);
1524 free (rpath);
1525 return pathbuf;
1526 }
1527
1528 /* Build a BFD style extended name table. */
1529
1530 bool
1531 _bfd_archive_bsd_construct_extended_name_table (bfd *abfd,
1532 char **tabloc,
1533 bfd_size_type *tablen,
1534 const char **name)
1535 {
1536 *name = "ARFILENAMES/";
1537 return _bfd_construct_extended_name_table (abfd, false, tabloc, tablen);
1538 }
1539
1540 /* Build an SVR4 style extended name table. */
1541
1542 bool
1543 _bfd_archive_coff_construct_extended_name_table (bfd *abfd,
1544 char **tabloc,
1545 bfd_size_type *tablen,
1546 const char **name)
1547 {
1548 *name = "//";
1549 return _bfd_construct_extended_name_table (abfd, true, tabloc, tablen);
1550 }
1551
1552 bool
1553 _bfd_noarchive_construct_extended_name_table (bfd *abfd ATTRIBUTE_UNUSED,
1554 char **tabloc ATTRIBUTE_UNUSED,
1555 bfd_size_type *len ATTRIBUTE_UNUSED,
1556 const char **name ATTRIBUTE_UNUSED)
1557 {
1558 return true;
1559 }
1560
1561 /* Follows archive_head and produces an extended name table if
1562 necessary. Returns (in tabloc) a pointer to an extended name
1563 table, and in tablen the length of the table. If it makes an entry
1564 it clobbers the filename so that the element may be written without
1565 further massage. Returns TRUE if it ran successfully, FALSE if
1566 something went wrong. A successful return may still involve a
1567 zero-length tablen! */
1568
1569 bool
1570 _bfd_construct_extended_name_table (bfd *abfd,
1571 bool trailing_slash,
1572 char **tabloc,
1573 bfd_size_type *tablen)
1574 {
1575 unsigned int maxname = ar_maxnamelen (abfd);
1576 bfd_size_type total_namelen = 0;
1577 bfd *current;
1578 char *strptr;
1579 const char *last_filename;
1580 long last_stroff;
1581
1582 *tablen = 0;
1583 last_filename = NULL;
1584
1585 /* Figure out how long the table should be. */
1586 for (current = abfd->archive_head;
1587 current != NULL;
1588 current = current->archive_next)
1589 {
1590 const char *normal;
1591 unsigned int thislen;
1592
1593 if (bfd_is_thin_archive (abfd))
1594 {
1595 const char *filename = bfd_get_filename (current);
1596
1597 /* If the element being added is a member of another archive
1598 (i.e., we are flattening), use the containing archive's name. */
1599 if (current->my_archive
1600 && ! bfd_is_thin_archive (current->my_archive))
1601 filename = bfd_get_filename (current->my_archive);
1602
1603 /* If the path is the same as the previous path seen,
1604 reuse it. This can happen when flattening a thin
1605 archive that contains other archives. */
1606 if (last_filename && filename_cmp (last_filename, filename) == 0)
1607 continue;
1608
1609 last_filename = filename;
1610
1611 /* If the path is relative, adjust it relative to
1612 the containing archive. */
1613 if (! IS_ABSOLUTE_PATH (filename)
1614 && ! IS_ABSOLUTE_PATH (bfd_get_filename (abfd)))
1615 normal = adjust_relative_path (filename, bfd_get_filename (abfd));
1616 else
1617 normal = filename;
1618
1619 /* In a thin archive, always store the full pathname
1620 in the extended name table. */
1621 total_namelen += strlen (normal) + 1;
1622 if (trailing_slash)
1623 /* Leave room for trailing slash. */
1624 ++total_namelen;
1625
1626 continue;
1627 }
1628
1629 normal = normalize (abfd, bfd_get_filename (current));
1630 if (normal == NULL)
1631 return false;
1632
1633 thislen = strlen (normal);
1634
1635 if (thislen > maxname
1636 && (bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
1637 thislen = maxname;
1638
1639 if (thislen > maxname)
1640 {
1641 /* Add one to leave room for \n. */
1642 total_namelen += thislen + 1;
1643 if (trailing_slash)
1644 {
1645 /* Leave room for trailing slash. */
1646 ++total_namelen;
1647 }
1648 }
1649 else
1650 {
1651 struct ar_hdr *hdr = arch_hdr (current);
1652 if (filename_ncmp (normal, hdr->ar_name, thislen) != 0
1653 || (thislen < sizeof hdr->ar_name
1654 && hdr->ar_name[thislen] != ar_padchar (current)))
1655 {
1656 /* Must have been using extended format even though it
1657 didn't need to. Fix it to use normal format. */
1658 memcpy (hdr->ar_name, normal, thislen);
1659 if (thislen < maxname
1660 || (thislen == maxname && thislen < sizeof hdr->ar_name))
1661 hdr->ar_name[thislen] = ar_padchar (current);
1662 }
1663 }
1664 }
1665
1666 if (total_namelen == 0)
1667 return true;
1668
1669 *tabloc = (char *) bfd_alloc (abfd, total_namelen);
1670 if (*tabloc == NULL)
1671 return false;
1672
1673 *tablen = total_namelen;
1674 strptr = *tabloc;
1675
1676 last_filename = NULL;
1677 last_stroff = 0;
1678
1679 for (current = abfd->archive_head;
1680 current != NULL;
1681 current = current->archive_next)
1682 {
1683 const char *normal;
1684 unsigned int thislen;
1685 long stroff;
1686 const char *filename = bfd_get_filename (current);
1687
1688 if (bfd_is_thin_archive (abfd))
1689 {
1690 /* If the element being added is a member of another archive
1691 (i.e., we are flattening), use the containing archive's name. */
1692 if (current->my_archive
1693 && ! bfd_is_thin_archive (current->my_archive))
1694 filename = bfd_get_filename (current->my_archive);
1695 /* If the path is the same as the previous path seen,
1696 reuse it. This can happen when flattening a thin
1697 archive that contains other archives.
1698 If the path is relative, adjust it relative to
1699 the containing archive. */
1700 if (last_filename && filename_cmp (last_filename, filename) == 0)
1701 normal = last_filename;
1702 else if (! IS_ABSOLUTE_PATH (filename)
1703 && ! IS_ABSOLUTE_PATH (bfd_get_filename (abfd)))
1704 normal = adjust_relative_path (filename, bfd_get_filename (abfd));
1705 else
1706 normal = filename;
1707 }
1708 else
1709 {
1710 normal = normalize (abfd, filename);
1711 if (normal == NULL)
1712 return false;
1713 }
1714
1715 thislen = strlen (normal);
1716 if (thislen > maxname || bfd_is_thin_archive (abfd))
1717 {
1718 /* Works for now; may need to be re-engineered if we
1719 encounter an oddball archive format and want to
1720 generalise this hack. */
1721 struct ar_hdr *hdr = arch_hdr (current);
1722 if (normal == last_filename)
1723 stroff = last_stroff;
1724 else
1725 {
1726 last_filename = filename;
1727 stroff = strptr - *tabloc;
1728 last_stroff = stroff;
1729 memcpy (strptr, normal, thislen);
1730 strptr += thislen;
1731 if (trailing_slash)
1732 *strptr++ = '/';
1733 *strptr++ = ARFMAG[1];
1734 }
1735 hdr->ar_name[0] = ar_padchar (current);
1736 if (bfd_is_thin_archive (abfd) && current->origin > 0)
1737 {
1738 int len = snprintf (hdr->ar_name + 1, maxname - 1, "%-ld:",
1739 stroff);
1740 _bfd_ar_spacepad (hdr->ar_name + 1 + len, maxname - 1 - len,
1741 "%-ld",
1742 current->origin - sizeof (struct ar_hdr));
1743 }
1744 else
1745 _bfd_ar_spacepad (hdr->ar_name + 1, maxname - 1, "%-ld", stroff);
1746 }
1747 }
1748
1749 return true;
1750 }
1751
1752 /* Do not construct an extended name table but transforms name field into
1753 its extended form. */
1754
1755 bool
1756 _bfd_archive_bsd44_construct_extended_name_table (bfd *abfd,
1757 char **tabloc,
1758 bfd_size_type *tablen,
1759 const char **name)
1760 {
1761 unsigned int maxname = ar_maxnamelen (abfd);
1762 bfd *current;
1763
1764 *tablen = 0;
1765 *tabloc = NULL;
1766 *name = NULL;
1767
1768 for (current = abfd->archive_head;
1769 current != NULL;
1770 current = current->archive_next)
1771 {
1772 const char *normal = normalize (abfd, bfd_get_filename (current));
1773 int has_space = 0;
1774 unsigned int len;
1775
1776 if (normal == NULL)
1777 return false;
1778
1779 for (len = 0; normal[len]; len++)
1780 if (normal[len] == ' ')
1781 has_space = 1;
1782
1783 if (len > maxname || has_space)
1784 {
1785 struct ar_hdr *hdr = arch_hdr (current);
1786
1787 len = (len + 3) & ~3;
1788 arch_eltdata (current)->extra_size = len;
1789 _bfd_ar_spacepad (hdr->ar_name, maxname, "#1/%lu", len);
1790 }
1791 }
1792
1793 return true;
1794 }
1795
1796 /* Write an archive header. */
1798
1799 bool
1800 _bfd_generic_write_ar_hdr (bfd *archive, bfd *abfd)
1801 {
1802 struct ar_hdr *hdr = arch_hdr (abfd);
1803
1804 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1805 return false;
1806 return true;
1807 }
1808
1809 /* Write an archive header using BSD4.4 convention. */
1810
1811 bool
1812 _bfd_bsd44_write_ar_hdr (bfd *archive, bfd *abfd)
1813 {
1814 struct ar_hdr *hdr = arch_hdr (abfd);
1815
1816 if (is_bsd44_extended_name (hdr->ar_name))
1817 {
1818 /* This is a BSD 4.4 extended name. */
1819 const char *fullname = normalize (abfd, bfd_get_filename (abfd));
1820 unsigned int len = strlen (fullname);
1821 unsigned int padded_len = (len + 3) & ~3;
1822
1823 BFD_ASSERT (padded_len == arch_eltdata (abfd)->extra_size);
1824
1825 if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size),
1826 arch_eltdata (abfd)->parsed_size + padded_len))
1827 return false;
1828
1829 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1830 return false;
1831
1832 if (bfd_write (fullname, len, archive) != len)
1833 return false;
1834
1835 if (len & 3)
1836 {
1837 static const char pad[3] = { 0, 0, 0 };
1838
1839 len = 4 - (len & 3);
1840 if (bfd_write (pad, len, archive) != len)
1841 return false;
1842 }
1843 }
1844 else
1845 {
1846 if (bfd_write (hdr, sizeof (*hdr), archive) != sizeof (*hdr))
1847 return false;
1848 }
1849 return true;
1850 }
1851
1852 bool
1853 _bfd_noarchive_write_ar_hdr (bfd *archive, bfd *abfd ATTRIBUTE_UNUSED)
1854 {
1855 return _bfd_bool_bfd_false_error (archive);
1856 }
1857
1858 /* A couple of functions for creating ar_hdrs. */
1860
1861 #ifdef HPUX_LARGE_AR_IDS
1862 /* Function to encode large UID/GID values according to HP. */
1863
1864 static void
1865 hpux_uid_gid_encode (char str[6], long int id)
1866 {
1867 int cnt;
1868
1869 str[5] = '@' + (id & 3);
1870 id >>= 2;
1871
1872 for (cnt = 4; cnt >= 0; --cnt, id >>= 6)
1873 str[cnt] = ' ' + (id & 0x3f);
1874 }
1875 #endif /* HPUX_LARGE_AR_IDS */
1876
1877 /* Takes a filename, returns an arelt_data for it, or NULL if it can't
1878 make one. The filename must refer to a filename in the filesystem.
1879 The filename field of the ar_hdr will NOT be initialized. If member
1880 is set, and it's an in-memory bfd, we fake it. */
1881
1882 static struct areltdata *
1883 bfd_ar_hdr_from_filesystem (bfd *abfd, const char *filename, bfd *member)
1884 {
1885 struct stat status;
1886 struct areltdata *ared;
1887 struct ar_hdr *hdr;
1888 size_t amt;
1889
1890 if (member && (member->flags & BFD_IN_MEMORY) != 0)
1891 {
1892 /* Assume we just "made" the member, and fake it. */
1893 struct bfd_in_memory *bim = (struct bfd_in_memory *) member->iostream;
1894 status.st_mtime = bfd_get_current_time (0);
1895 status.st_uid = getuid ();
1896 status.st_gid = getgid ();
1897 status.st_mode = 0644;
1898 status.st_size = bim->size;
1899 }
1900 else if (stat (filename, &status) != 0)
1901 {
1902 bfd_set_error (bfd_error_system_call);
1903 return NULL;
1904 }
1905 else
1906 {
1907 /* The call to stat() above has filled in the st_mtime field
1908 with the real time that the object was modified. But if
1909 we are trying to generate deterministic archives based upon
1910 the SOURCE_DATE_EPOCH environment variable then we want to
1911 override that. */
1912 status.st_mtime = bfd_get_current_time (status.st_mtime);
1913 }
1914
1915 /* If the caller requested that the BFD generate deterministic output,
1916 fake values for modification time, UID, GID, and file mode. */
1917 if ((abfd->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
1918 {
1919 status.st_mtime = 0;
1920 status.st_uid = 0;
1921 status.st_gid = 0;
1922 status.st_mode = 0644;
1923 }
1924
1925 amt = sizeof (struct ar_hdr) + sizeof (struct areltdata);
1926 ared = (struct areltdata *) bfd_zmalloc (amt);
1927 if (ared == NULL)
1928 return NULL;
1929 hdr = (struct ar_hdr *) (((char *) ared) + sizeof (struct areltdata));
1930
1931 /* ar headers are space padded, not null padded! */
1932 memset (hdr, ' ', sizeof (struct ar_hdr));
1933
1934 _bfd_ar_spacepad (hdr->ar_date, sizeof (hdr->ar_date), "%-12ld",
1935 status.st_mtime);
1936 #ifdef HPUX_LARGE_AR_IDS
1937 /* HP has a very "special" way to handle UID/GID's with numeric values
1938 > 99999. */
1939 if (status.st_uid > 99999)
1940 hpux_uid_gid_encode (hdr->ar_uid, (long) status.st_uid);
1941 else
1942 #endif
1943 _bfd_ar_spacepad (hdr->ar_uid, sizeof (hdr->ar_uid), "%ld",
1944 status.st_uid);
1945 #ifdef HPUX_LARGE_AR_IDS
1946 /* HP has a very "special" way to handle UID/GID's with numeric values
1947 > 99999. */
1948 if (status.st_gid > 99999)
1949 hpux_uid_gid_encode (hdr->ar_gid, (long) status.st_gid);
1950 else
1951 #endif
1952 _bfd_ar_spacepad (hdr->ar_gid, sizeof (hdr->ar_gid), "%ld",
1953 status.st_gid);
1954 _bfd_ar_spacepad (hdr->ar_mode, sizeof (hdr->ar_mode), "%-8lo",
1955 status.st_mode);
1956 if (status.st_size - (bfd_size_type) status.st_size != 0)
1957 {
1958 bfd_set_error (bfd_error_file_too_big);
1959 free (ared);
1960 return NULL;
1961 }
1962 if (!_bfd_ar_sizepad (hdr->ar_size, sizeof (hdr->ar_size), status.st_size))
1963 {
1964 free (ared);
1965 return NULL;
1966 }
1967 memcpy (hdr->ar_fmag, ARFMAG, 2);
1968 ared->parsed_size = status.st_size;
1969 ared->arch_header = (char *) hdr;
1970
1971 return ared;
1972 }
1973
1974 /* Analogous to stat call. */
1975
1976 int
1977 bfd_generic_stat_arch_elt (bfd *abfd, struct stat *buf)
1978 {
1979 struct ar_hdr *hdr;
1980 char *aloser;
1981
1982 if (abfd->arelt_data == NULL)
1983 {
1984 bfd_set_error (bfd_error_invalid_operation);
1985 return -1;
1986 }
1987
1988 hdr = arch_hdr (abfd);
1989 /* PR 17512: file: 3d9e9fe9. */
1990 if (hdr == NULL)
1991 return -1;
1992 #define foo(arelt, stelt, size) \
1993 buf->stelt = strtol (hdr->arelt, &aloser, size); \
1994 if (aloser == hdr->arelt) \
1995 return -1;
1996
1997 /* Some platforms support special notations for large IDs. */
1998 #ifdef HPUX_LARGE_AR_IDS
1999 # define foo2(arelt, stelt, size) \
2000 if (hdr->arelt[5] == ' ') \
2001 { \
2002 foo (arelt, stelt, size); \
2003 } \
2004 else \
2005 { \
2006 int cnt; \
2007 for (buf->stelt = cnt = 0; cnt < 5; ++cnt) \
2008 { \
2009 if (hdr->arelt[cnt] < ' ' || hdr->arelt[cnt] > ' ' + 0x3f) \
2010 return -1; \
2011 buf->stelt <<= 6; \
2012 buf->stelt += hdr->arelt[cnt] - ' '; \
2013 } \
2014 if (hdr->arelt[5] < '@' || hdr->arelt[5] > '@' + 3) \
2015 return -1; \
2016 buf->stelt <<= 2; \
2017 buf->stelt += hdr->arelt[5] - '@'; \
2018 }
2019 #else
2020 # define foo2(arelt, stelt, size) foo (arelt, stelt, size)
2021 #endif
2022
2023 foo (ar_date, st_mtime, 10);
2024 foo2 (ar_uid, st_uid, 10);
2025 foo2 (ar_gid, st_gid, 10);
2026 foo (ar_mode, st_mode, 8);
2027
2028 buf->st_size = arch_eltdata (abfd)->parsed_size;
2029
2030 return 0;
2031 }
2032
2033 void
2034 bfd_dont_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2035 {
2036 /* FIXME: This interacts unpleasantly with ar's quick-append option.
2037 Fortunately ic960 users will never use that option. Fixing this
2038 is very hard; fortunately I know how to do it and will do so once
2039 intel's release is out the door. */
2040
2041 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2042 size_t length;
2043 const char *filename;
2044 size_t maxlen = ar_maxnamelen (abfd);
2045
2046 if ((bfd_get_file_flags (abfd) & BFD_TRADITIONAL_FORMAT) != 0)
2047 {
2048 bfd_bsd_truncate_arname (abfd, pathname, arhdr);
2049 return;
2050 }
2051
2052 filename = normalize (abfd, pathname);
2053 if (filename == NULL)
2054 {
2055 /* FIXME */
2056 abort ();
2057 }
2058
2059 length = strlen (filename);
2060
2061 if (length <= maxlen)
2062 memcpy (hdr->ar_name, filename, length);
2063
2064 /* Add the padding character if there is room for it. */
2065 if (length < maxlen
2066 || (length == maxlen && length < sizeof hdr->ar_name))
2067 (hdr->ar_name)[length] = ar_padchar (abfd);
2068 }
2069
2070 void
2071 bfd_bsd_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2072 {
2073 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2074 size_t length;
2075 const char *filename = lbasename (pathname);
2076 size_t maxlen = ar_maxnamelen (abfd);
2077
2078 length = strlen (filename);
2079
2080 if (length <= maxlen)
2081 memcpy (hdr->ar_name, filename, length);
2082 else
2083 {
2084 /* pathname: meet procrustes */
2085 memcpy (hdr->ar_name, filename, maxlen);
2086 length = maxlen;
2087 }
2088
2089 if (length < maxlen)
2090 (hdr->ar_name)[length] = ar_padchar (abfd);
2091 }
2092
2093 /* Store name into ar header. Truncates the name to fit.
2094 1> strip pathname to be just the basename.
2095 2> if it's short enuf to fit, stuff it in.
2096 3> If it doesn't end with .o, truncate it to fit
2097 4> truncate it before the .o, append .o, stuff THAT in. */
2098
2099 /* This is what gnu ar does. It's better but incompatible with the
2100 bsd ar. */
2101
2102 void
2103 bfd_gnu_truncate_arname (bfd *abfd, const char *pathname, char *arhdr)
2104 {
2105 struct ar_hdr *hdr = (struct ar_hdr *) arhdr;
2106 size_t length;
2107 const char *filename = lbasename (pathname);
2108 size_t maxlen = ar_maxnamelen (abfd);
2109
2110 length = strlen (filename);
2111
2112 if (length <= maxlen)
2113 memcpy (hdr->ar_name, filename, length);
2114 else
2115 {
2116 /* pathname: meet procrustes. */
2117 memcpy (hdr->ar_name, filename, maxlen);
2118 if ((filename[length - 2] == '.') && (filename[length - 1] == 'o'))
2119 {
2120 hdr->ar_name[maxlen - 2] = '.';
2121 hdr->ar_name[maxlen - 1] = 'o';
2122 }
2123 length = maxlen;
2124 }
2125
2126 if (length < 16)
2127 (hdr->ar_name)[length] = ar_padchar (abfd);
2128 }
2129
2130 void
2131 _bfd_noarchive_truncate_arname (bfd *abfd ATTRIBUTE_UNUSED,
2132 const char *pathname ATTRIBUTE_UNUSED,
2133 char *arhdr ATTRIBUTE_UNUSED)
2134 {
2135 }
2136
2137 /* The BFD is open for write and has its format set to bfd_archive. */
2139
2140 bool
2141 _bfd_write_archive_contents (bfd *arch)
2142 {
2143 bfd *current;
2144 char *etable = NULL;
2145 bfd_size_type elength = 0;
2146 const char *ename = NULL;
2147 bool makemap = bfd_has_map (arch);
2148 /* If no .o's, don't bother to make a map. */
2149 bool hasobjects = false;
2150 bfd_size_type wrote;
2151 int tries;
2152 char *armag;
2153 char *buffer = NULL;
2154
2155 /* Verify the viability of all entries; if any of them live in the
2156 filesystem (as opposed to living in an archive open for input)
2157 then construct a fresh ar_hdr for them. */
2158 for (current = arch->archive_head;
2159 current != NULL;
2160 current = current->archive_next)
2161 {
2162 /* This check is checking the bfds for the objects we're reading
2163 from (which are usually either an object file or archive on
2164 disk), not the archive entries we're writing to. We don't
2165 actually create bfds for the archive members, we just copy
2166 them byte-wise when we write out the archive. */
2167 if (bfd_write_p (current))
2168 {
2169 bfd_set_error (bfd_error_invalid_operation);
2170 goto input_err;
2171 }
2172 if (!current->arelt_data)
2173 {
2174 current->arelt_data =
2175 bfd_ar_hdr_from_filesystem (arch, bfd_get_filename (current),
2176 current);
2177 if (!current->arelt_data)
2178 goto input_err;
2179
2180 /* Put in the file name. */
2181 BFD_SEND (arch, _bfd_truncate_arname,
2182 (arch, bfd_get_filename (current),
2183 (char *) arch_hdr (current)));
2184 }
2185
2186 if (makemap && ! hasobjects)
2187 { /* Don't bother if we won't make a map! */
2188 if ((bfd_check_format (current, bfd_object)))
2189 hasobjects = true;
2190 }
2191 }
2192
2193 if (!BFD_SEND (arch, _bfd_construct_extended_name_table,
2194 (arch, &etable, &elength, &ename)))
2195 return false;
2196
2197 if (bfd_seek (arch, 0, SEEK_SET) != 0)
2198 return false;
2199 armag = ARMAG;
2200 if (bfd_is_thin_archive (arch))
2201 armag = ARMAGT;
2202 wrote = bfd_write (armag, SARMAG, arch);
2203 if (wrote != SARMAG)
2204 return false;
2205
2206 if (makemap && hasobjects)
2207 {
2208 if (! _bfd_compute_and_write_armap (arch, (unsigned int) elength))
2209 return false;
2210 }
2211
2212 if (elength != 0)
2213 {
2214 struct ar_hdr hdr;
2215
2216 memset (&hdr, ' ', sizeof (struct ar_hdr));
2217 memcpy (hdr.ar_name, ename, strlen (ename));
2218 /* Round size up to even number in archive header. */
2219 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size),
2220 (elength + 1) & ~(bfd_size_type) 1))
2221 return false;
2222 memcpy (hdr.ar_fmag, ARFMAG, 2);
2223 if ((bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2224 != sizeof (struct ar_hdr))
2225 || bfd_write (etable, elength, arch) != elength)
2226 return false;
2227 if ((elength % 2) == 1)
2228 {
2229 if (bfd_write (&ARFMAG[1], 1, arch) != 1)
2230 return false;
2231 }
2232 }
2233
2234 #define AR_WRITE_BUFFERSIZE (8 * 1024 * 1024)
2235
2236 /* FIXME: Find a way to test link_info.reduce_memory_overheads
2237 and change the buffer size. */
2238 buffer = bfd_malloc (AR_WRITE_BUFFERSIZE);
2239 if (buffer == NULL)
2240 goto input_err;
2241
2242 for (current = arch->archive_head;
2243 current != NULL;
2244 current = current->archive_next)
2245 {
2246 bfd_size_type remaining = arelt_size (current);
2247 bfd_size_type saved_size = remaining;
2248 struct ar_hdr *hdr = arch_hdr (current);
2249
2250 /* Write ar header. */
2251 if (!_bfd_write_ar_hdr (arch, current))
2252 goto input_err;
2253 /* Write filename if it is a 4.4BSD extended file, and add to size. */
2254 if (!strncmp (hdr->ar_name, "#1/", 3))
2255 {
2256 const char *normal = normalize (current, current->filename);
2257 unsigned int thislen = strlen (normal);
2258 if (bfd_write (normal, thislen, arch) != thislen)
2259 goto input_err;
2260 saved_size += thislen;
2261 }
2262 if (bfd_is_thin_archive (arch))
2263 continue;
2264 if (bfd_seek (current, 0, SEEK_SET) != 0)
2265 goto input_err;
2266
2267 while (remaining)
2268 {
2269 size_t amt = AR_WRITE_BUFFERSIZE;
2270
2271 if (amt > remaining)
2272 amt = remaining;
2273 errno = 0;
2274 if (bfd_read (buffer, amt, current) != amt)
2275 goto input_err;
2276 if (bfd_write (buffer, amt, arch) != amt)
2277 goto input_err;
2278 remaining -= amt;
2279 }
2280
2281 if ((arelt_size (current) % 2) == 1)
2282 {
2283 if (bfd_write (&ARFMAG[1], 1, arch) != 1)
2284 goto input_err;
2285 }
2286 }
2287
2288 free (buffer);
2289
2290 if (makemap && hasobjects)
2291 {
2292 /* Verify the timestamp in the archive file. If it would not be
2293 accepted by the linker, rewrite it until it would be. If
2294 anything odd happens, break out and just return. (The
2295 Berkeley linker checks the timestamp and refuses to read the
2296 table-of-contents if it is >60 seconds less than the file's
2297 modified-time. That painful hack requires this painful hack. */
2298 tries = 1;
2299 do
2300 {
2301 if (bfd_update_armap_timestamp (arch))
2302 break;
2303 _bfd_error_handler
2304 (_("warning: writing archive was slow: rewriting timestamp"));
2305 }
2306 while (++tries < 6);
2307 }
2308
2309 return true;
2310
2311 input_err:
2312 bfd_set_input_error (current, bfd_get_error ());
2313 free (buffer);
2314 return false;
2315 }
2316
2317 /* Note that the namidx for the first symbol is 0. */
2319
2320 bool
2321 _bfd_compute_and_write_armap (bfd *arch, unsigned int elength)
2322 {
2323 char *first_name = NULL;
2324 bfd *current;
2325 file_ptr elt_no = 0;
2326 struct orl *map = NULL;
2327 unsigned int orl_max = 1024; /* Fine initial default. */
2328 unsigned int orl_count = 0;
2329 int stridx = 0;
2330 asymbol **syms = NULL;
2331 long syms_max = 0;
2332 bool ret;
2333 size_t amt;
2334 static bool report_plugin_err = true;
2335
2336 /* Dunno if this is the best place for this info... */
2337 if (elength != 0)
2338 elength += sizeof (struct ar_hdr);
2339 elength += elength % 2;
2340
2341 amt = orl_max * sizeof (struct orl);
2342 map = (struct orl *) bfd_malloc (amt);
2343 if (map == NULL)
2344 goto error_return;
2345
2346 /* We put the symbol names on the arch objalloc, and then discard
2347 them when done. */
2348 first_name = (char *) bfd_alloc (arch, 1);
2349 if (first_name == NULL)
2350 goto error_return;
2351
2352 /* Drop all the files called __.SYMDEF, we're going to make our own. */
2353 while (arch->archive_head
2354 && strcmp (bfd_get_filename (arch->archive_head), "__.SYMDEF") == 0)
2355 arch->archive_head = arch->archive_head->archive_next;
2356
2357 /* Map over each element. */
2358 for (current = arch->archive_head;
2359 current != NULL;
2360 current = current->archive_next, elt_no++)
2361 {
2362 if (bfd_check_format (current, bfd_object)
2363 && (bfd_get_file_flags (current) & HAS_SYMS) != 0)
2364 {
2365 long storage;
2366 long symcount;
2367 long src_count;
2368
2369 if (bfd_get_lto_type (current) == lto_slim_ir_object
2370 && report_plugin_err)
2371 {
2372 report_plugin_err = false;
2373 _bfd_error_handler
2374 (_("%pB: plugin needed to handle lto object"),
2375 current);
2376 }
2377
2378 storage = bfd_get_symtab_upper_bound (current);
2379 if (storage < 0)
2380 goto error_return;
2381
2382 if (storage != 0)
2383 {
2384 if (storage > syms_max)
2385 {
2386 free (syms);
2387 syms_max = storage;
2388 syms = (asymbol **) bfd_malloc (syms_max);
2389 if (syms == NULL)
2390 goto error_return;
2391 }
2392 symcount = bfd_canonicalize_symtab (current, syms);
2393 if (symcount < 0)
2394 goto error_return;
2395
2396 /* Now map over all the symbols, picking out the ones we
2397 want. */
2398 for (src_count = 0; src_count < symcount; src_count++)
2399 {
2400 flagword flags = (syms[src_count])->flags;
2401 asection *sec = syms[src_count]->section;
2402
2403 if (((flags & (BSF_GLOBAL
2404 | BSF_WEAK
2405 | BSF_INDIRECT
2406 | BSF_GNU_UNIQUE)) != 0
2407 || bfd_is_com_section (sec))
2408 && ! bfd_is_und_section (sec))
2409 {
2410 bfd_size_type namelen;
2411 struct orl *new_map;
2412
2413 /* This symbol will go into the archive header. */
2414 if (orl_count == orl_max)
2415 {
2416 orl_max *= 2;
2417 amt = orl_max * sizeof (struct orl);
2418 new_map = (struct orl *) bfd_realloc (map, amt);
2419 if (new_map == NULL)
2420 goto error_return;
2421
2422 map = new_map;
2423 }
2424
2425 if (bfd_lto_slim_symbol_p (current,
2426 syms[src_count]->name)
2427 && report_plugin_err)
2428 {
2429 report_plugin_err = false;
2430 _bfd_error_handler
2431 (_("%pB: plugin needed to handle lto object"),
2432 current);
2433 }
2434 namelen = strlen (syms[src_count]->name);
2435 amt = sizeof (char *);
2436 map[orl_count].name = (char **) bfd_alloc (arch, amt);
2437 if (map[orl_count].name == NULL)
2438 goto error_return;
2439 *(map[orl_count].name) = (char *) bfd_alloc (arch,
2440 namelen + 1);
2441 if (*(map[orl_count].name) == NULL)
2442 goto error_return;
2443 strcpy (*(map[orl_count].name), syms[src_count]->name);
2444 map[orl_count].u.abfd = current;
2445 map[orl_count].namidx = stridx;
2446
2447 stridx += namelen + 1;
2448 ++orl_count;
2449 }
2450 }
2451 }
2452
2453 /* Now ask the BFD to free up any cached information, so we
2454 don't fill all of memory with symbol tables. */
2455 if (! bfd_free_cached_info (current))
2456 goto error_return;
2457 }
2458 }
2459
2460 /* OK, now we have collected all the data, let's write them out. */
2461 ret = BFD_SEND (arch, write_armap,
2462 (arch, elength, map, orl_count, stridx));
2463
2464 free (syms);
2465 free (map);
2466 if (first_name != NULL)
2467 bfd_release (arch, first_name);
2468
2469 return ret;
2470
2471 error_return:
2472 free (syms);
2473 free (map);
2474 if (first_name != NULL)
2475 bfd_release (arch, first_name);
2476
2477 return false;
2478 }
2479
2480 bool
2481 _bfd_bsd_write_armap (bfd *arch,
2482 unsigned int elength,
2483 struct orl *map,
2484 unsigned int orl_count,
2485 int stridx)
2486 {
2487 int padit = stridx & 1;
2488 unsigned int ranlibsize = orl_count * BSD_SYMDEF_SIZE;
2489 unsigned int stringsize = stridx + padit;
2490 /* Include 8 bytes to store ranlibsize and stringsize in output. */
2491 unsigned int mapsize = ranlibsize + stringsize + 8;
2492 file_ptr firstreal, first;
2493 bfd *current;
2494 bfd *last_elt;
2495 bfd_byte temp[4];
2496 unsigned int count;
2497 struct ar_hdr hdr;
2498 long uid, gid;
2499
2500 first = mapsize + elength + sizeof (struct ar_hdr) + SARMAG;
2501
2502 #ifdef BFD64
2503 firstreal = first;
2504 current = arch->archive_head;
2505 last_elt = current; /* Last element arch seen. */
2506 for (count = 0; count < orl_count; count++)
2507 {
2508 unsigned int offset;
2509
2510 if (map[count].u.abfd != last_elt)
2511 {
2512 do
2513 {
2514 struct areltdata *ared = arch_eltdata (current);
2515
2516 firstreal += (ared->parsed_size + ared->extra_size
2517 + sizeof (struct ar_hdr));
2518 firstreal += firstreal % 2;
2519 current = current->archive_next;
2520 }
2521 while (current != map[count].u.abfd);
2522 }
2523
2524 /* The archive file format only has 4 bytes to store the offset
2525 of the member. Generate 64-bit archive if an archive is past
2526 its 4Gb limit. */
2527 offset = (unsigned int) firstreal;
2528 if (firstreal != (file_ptr) offset)
2529 return _bfd_archive_64_bit_write_armap (arch, elength, map,
2530 orl_count, stridx);
2531
2532 last_elt = current;
2533 }
2534 #endif
2535
2536 /* If deterministic, we use 0 as the timestamp in the map.
2537 Some linkers may require that the archive filesystem modification
2538 time is less than (or near to) the archive map timestamp. Those
2539 linkers should not be used with deterministic mode. (GNU ld and
2540 Gold do not have this restriction.) */
2541 bfd_ardata (arch)->armap_timestamp = 0;
2542 uid = 0;
2543 gid = 0;
2544 if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0)
2545 {
2546 struct stat statbuf;
2547
2548 if (stat (bfd_get_filename (arch), &statbuf) == 0)
2549 {
2550 /* If asked, replace the time with a deterministic value. */
2551 statbuf.st_mtime = bfd_get_current_time (statbuf.st_mtime);
2552
2553 bfd_ardata (arch)->armap_timestamp = (statbuf.st_mtime
2554 + ARMAP_TIME_OFFSET);
2555 }
2556 uid = getuid();
2557 gid = getgid();
2558 }
2559
2560 memset (&hdr, ' ', sizeof (struct ar_hdr));
2561 memcpy (hdr.ar_name, RANLIBMAG, strlen (RANLIBMAG));
2562 bfd_ardata (arch)->armap_datepos = (SARMAG
2563 + offsetof (struct ar_hdr, ar_date[0]));
2564 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2565 bfd_ardata (arch)->armap_timestamp);
2566 _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", uid);
2567 _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", gid);
2568 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
2569 return false;
2570 memcpy (hdr.ar_fmag, ARFMAG, 2);
2571 if (bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2572 != sizeof (struct ar_hdr))
2573 return false;
2574 H_PUT_32 (arch, ranlibsize, temp);
2575 if (bfd_write (temp, sizeof (temp), arch) != sizeof (temp))
2576 return false;
2577
2578 firstreal = first;
2579 current = arch->archive_head;
2580 last_elt = current; /* Last element arch seen. */
2581 for (count = 0; count < orl_count; count++)
2582 {
2583 unsigned int offset;
2584 bfd_byte buf[BSD_SYMDEF_SIZE];
2585
2586 if (map[count].u.abfd != last_elt)
2587 {
2588 do
2589 {
2590 #if 1
2591 bfd_size_type size = arelt_size (current);
2592 if (!strncmp(arch_hdr (current)->ar_name, "#1/", 3))
2593 size += strlen(normalize(current, current->filename));
2594 firstreal += size + sizeof (struct ar_hdr);
2595 firstreal += size % 2;
2596 #else
2597 struct areltdata *ared = arch_eltdata (current);
2598
2599 firstreal += (ared->parsed_size + ared->extra_size
2600 + sizeof (struct ar_hdr));
2601 firstreal += firstreal % 2;
2602 #endif
2603 current = current->archive_next;
2604 }
2605 while (current != map[count].u.abfd);
2606 }
2607
2608 /* The archive file format only has 4 bytes to store the offset
2609 of the member. Check to make sure that firstreal has not grown
2610 too big. */
2611 offset = (unsigned int) firstreal;
2612 if (firstreal != (file_ptr) offset)
2613 {
2614 bfd_set_error (bfd_error_file_truncated);
2615 return false;
2616 }
2617
2618 last_elt = current;
2619 H_PUT_32 (arch, map[count].namidx, buf);
2620 H_PUT_32 (arch, firstreal, buf + BSD_SYMDEF_OFFSET_SIZE);
2621 if (bfd_write (buf, BSD_SYMDEF_SIZE, arch)
2622 != BSD_SYMDEF_SIZE)
2623 return false;
2624 }
2625
2626 /* Now write the strings themselves. */
2627 H_PUT_32 (arch, stringsize, temp);
2628 if (bfd_write (temp, sizeof (temp), arch) != sizeof (temp))
2629 return false;
2630 for (count = 0; count < orl_count; count++)
2631 {
2632 size_t len = strlen (*map[count].name) + 1;
2633
2634 if (bfd_write (*map[count].name, len, arch) != len)
2635 return false;
2636 }
2637
2638 /* The spec sez this should be a newline. But in order to be
2639 bug-compatible for sun's ar we use a null. */
2640 if (padit)
2641 {
2642 if (bfd_write ("", 1, arch) != 1)
2643 return false;
2644 }
2645
2646 return true;
2647 }
2648
2649 /* At the end of archive file handling, update the timestamp in the
2650 file, so older linkers will accept it. (This does not apply to
2651 ld.bfd or ld.gold).
2652
2653 Return TRUE if the timestamp was OK, or an unusual problem happened.
2654 Return FALSE if we updated the timestamp. */
2655
2656 bool
2657 _bfd_archive_bsd_update_armap_timestamp (bfd *arch)
2658 {
2659 struct stat archstat;
2660 struct ar_hdr hdr;
2661
2662 /* If creating deterministic archives, just leave the timestamp as-is. */
2663 if ((arch->flags & BFD_DETERMINISTIC_OUTPUT) != 0)
2664 return true;
2665
2666 /* Flush writes, get last-write timestamp from file, and compare it
2667 to the timestamp IN the file. */
2668 bfd_flush (arch);
2669 if (bfd_stat (arch, &archstat) == -1)
2670 {
2671 bfd_perror (_("Reading archive file mod timestamp"));
2672
2673 /* Can't read mod time for some reason. */
2674 return true;
2675 }
2676
2677 if (((long) archstat.st_mtime) <= bfd_ardata (arch)->armap_timestamp)
2678 /* OK by the linker's rules. */
2679 return true;
2680
2681 if (getenv ("SOURCE_DATE_EPOCH") != NULL
2682 && bfd_ardata (arch)->armap_timestamp == bfd_get_current_time (0) + ARMAP_TIME_OFFSET)
2683 /* If the archive's timestamp has been set to SOURCE_DATE_EPOCH
2684 then leave it as-is. */
2685 return true;
2686
2687 /* Update the timestamp. */
2688 bfd_ardata (arch)->armap_timestamp = archstat.st_mtime + ARMAP_TIME_OFFSET;
2689
2690 /* Prepare an ASCII version suitable for writing. */
2691 memset (hdr.ar_date, ' ', sizeof (hdr.ar_date));
2692 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2693 bfd_ardata (arch)->armap_timestamp);
2694
2695 /* Write it into the file. */
2696 bfd_ardata (arch)->armap_datepos = (SARMAG
2697 + offsetof (struct ar_hdr, ar_date[0]));
2698 if (bfd_seek (arch, bfd_ardata (arch)->armap_datepos, SEEK_SET) != 0
2699 || (bfd_write (hdr.ar_date, sizeof (hdr.ar_date), arch)
2700 != sizeof (hdr.ar_date)))
2701 {
2702 bfd_perror (_("Writing updated armap timestamp"));
2703
2704 /* Some error while writing. */
2705 return true;
2706 }
2707
2708 /* We updated the timestamp successfully. */
2709 return false;
2710 }
2711
2712 /* A coff armap looks like :
2714 lARMAG
2715 struct ar_hdr with name = '/'
2716 number of symbols
2717 offset of file for symbol 0
2718 offset of file for symbol 1
2719
2720 offset of file for symbol n-1
2721 symbol name 0
2722 symbol name 1
2723
2724 symbol name n-1 */
2725
2726 bool
2727 _bfd_coff_write_armap (bfd *arch,
2728 unsigned int elength,
2729 struct orl *map,
2730 unsigned int symbol_count,
2731 int stridx)
2732 {
2733 /* The size of the ranlib is the number of exported symbols in the
2734 archive * the number of bytes in an int, + an int for the count. */
2735 unsigned int ranlibsize = (symbol_count * 4) + 4;
2736 unsigned int stringsize = stridx;
2737 unsigned int mapsize = stringsize + ranlibsize;
2738 file_ptr archive_member_file_ptr;
2739 file_ptr first_archive_member_file_ptr;
2740 bfd *current = arch->archive_head;
2741 unsigned int count;
2742 struct ar_hdr hdr;
2743 int padit = mapsize & 1;
2744
2745 if (padit)
2746 mapsize++;
2747
2748 /* Work out where the first object file will go in the archive. */
2749 first_archive_member_file_ptr = (mapsize
2750 + elength
2751 + sizeof (struct ar_hdr)
2752 + SARMAG);
2753
2754 #ifdef BFD64
2755 current = arch->archive_head;
2756 count = 0;
2757 archive_member_file_ptr = first_archive_member_file_ptr;
2758 while (current != NULL && count < symbol_count)
2759 {
2760 /* For each symbol which is used defined in this object, write
2761 out the object file's address in the archive. */
2762
2763 while (count < symbol_count && map[count].u.abfd == current)
2764 {
2765 unsigned int offset = (unsigned int) archive_member_file_ptr;
2766
2767 /* Generate 64-bit archive if an archive is past its 4Gb
2768 limit. */
2769 if (archive_member_file_ptr != (file_ptr) offset)
2770 return _bfd_archive_64_bit_write_armap (arch, elength, map,
2771 symbol_count, stridx);
2772 count++;
2773 }
2774 archive_member_file_ptr += sizeof (struct ar_hdr);
2775 if (! bfd_is_thin_archive (arch))
2776 {
2777 /* Add size of this archive entry. */
2778 archive_member_file_ptr += arelt_size (current);
2779 /* Remember about the even alignment. */
2780 archive_member_file_ptr += archive_member_file_ptr % 2;
2781 }
2782 current = current->archive_next;
2783 }
2784 #endif
2785
2786 memset (&hdr, ' ', sizeof (struct ar_hdr));
2787 hdr.ar_name[0] = '/';
2788 if (!_bfd_ar_sizepad (hdr.ar_size, sizeof (hdr.ar_size), mapsize))
2789 return false;
2790 _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
2791 ((arch->flags & BFD_DETERMINISTIC_OUTPUT) == 0
2792 ? time (NULL) : 0));
2793 /* This, at least, is what Intel coff sets the values to. */
2794 _bfd_ar_spacepad (hdr.ar_uid, sizeof (hdr.ar_uid), "%ld", 0);
2795 _bfd_ar_spacepad (hdr.ar_gid, sizeof (hdr.ar_gid), "%ld", 0);
2796 _bfd_ar_spacepad (hdr.ar_mode, sizeof (hdr.ar_mode), "%-7lo", 0);
2797 memcpy (hdr.ar_fmag, ARFMAG, 2);
2798
2799 /* Write the ar header for this item and the number of symbols. */
2800 if (bfd_write (&hdr, sizeof (struct ar_hdr), arch)
2801 != sizeof (struct ar_hdr))
2802 return false;
2803
2804 if (!bfd_write_bigendian_4byte_int (arch, symbol_count))
2805 return false;
2806
2807 /* Two passes, first write the file offsets for each symbol -
2808 remembering that each offset is on a two byte boundary. */
2809
2810 /* Write out the file offset for the file associated with each
2811 symbol, and remember to keep the offsets padded out. */
2812
2813 current = arch->archive_head;
2814 count = 0;
2815 archive_member_file_ptr = first_archive_member_file_ptr;
2816 while (current != NULL && count < symbol_count)
2817 {
2818 /* For each symbol which is used defined in this object, write
2819 out the object file's address in the archive. */
2820
2821 while (count < symbol_count && map[count].u.abfd == current)
2822 {
2823 unsigned int offset = (unsigned int) archive_member_file_ptr;
2824
2825 /* Catch an attempt to grow an archive past its 4Gb limit. */
2826 if (archive_member_file_ptr != (file_ptr) offset)
2827 {
2828 bfd_set_error (bfd_error_file_truncated);
2829 return false;
2830 }
2831 if (!bfd_write_bigendian_4byte_int (arch, offset))
2832 return false;
2833 count++;
2834 }
2835 archive_member_file_ptr += sizeof (struct ar_hdr);
2836 if (! bfd_is_thin_archive (arch))
2837 {
2838 /* Add size of this archive entry. */
2839 archive_member_file_ptr += arelt_size (current);
2840 /* Remember about the even alignment. */
2841 archive_member_file_ptr += archive_member_file_ptr % 2;
2842 }
2843 current = current->archive_next;
2844 }
2845
2846 /* Now write the strings themselves. */
2847 for (count = 0; count < symbol_count; count++)
2848 {
2849 size_t len = strlen (*map[count].name) + 1;
2850
2851 if (bfd_write (*map[count].name, len, arch) != len)
2852 return false;
2853 }
2854
2855 /* The spec sez this should be a newline. But in order to be
2856 bug-compatible for arc960 we use a null. */
2857 if (padit)
2858 {
2859 if (bfd_write ("", 1, arch) != 1)
2860 return false;
2861 }
2862
2863 return true;
2864 }
2865
2866 bool
2867 _bfd_noarchive_write_armap
2868 (bfd *arch ATTRIBUTE_UNUSED,
2869 unsigned int elength ATTRIBUTE_UNUSED,
2870 struct orl *map ATTRIBUTE_UNUSED,
2871 unsigned int orl_count ATTRIBUTE_UNUSED,
2872 int stridx ATTRIBUTE_UNUSED)
2873 {
2874 return true;
2875 }
2876
2877 static int
2878 archive_close_worker (void **slot, void *inf ATTRIBUTE_UNUSED)
2879 {
2880 struct ar_cache *ent = (struct ar_cache *) *slot;
2881
2882 bfd_close_all_done (ent->arbfd);
2883 return 1;
2884 }
2885
2886 void
2887 _bfd_unlink_from_archive_parent (bfd *abfd)
2888 {
2889 if (arch_eltdata (abfd) != NULL)
2890 {
2891 struct areltdata *ared = arch_eltdata (abfd);
2892 htab_t htab = (htab_t) ared->parent_cache;
2893
2894 if (htab)
2895 {
2896 struct ar_cache ent;
2897 void **slot;
2898
2899 ent.ptr = ared->key;
2900 slot = htab_find_slot (htab, &ent, NO_INSERT);
2901 if (slot != NULL)
2902 {
2903 BFD_ASSERT (((struct ar_cache *) *slot)->arbfd == abfd);
2904 htab_clear_slot (htab, slot);
2905 }
2906 }
2907 }
2908 }
2909
2910 bool
2911 _bfd_archive_close_and_cleanup (bfd *abfd)
2912 {
2913 if (bfd_write_p (abfd) && abfd->format == bfd_archive)
2914 {
2915 bfd *current;
2916 while ((current = abfd->archive_head) != NULL)
2917 {
2918 abfd->archive_head = current->archive_next;
2919 bfd_close_all_done (current);
2920 }
2921 }
2922 if (bfd_read_p (abfd) && abfd->format == bfd_archive)
2923 {
2924 bfd *nbfd;
2925 bfd *next;
2926 htab_t htab;
2927
2928 /* Close nested archives (if this bfd is a thin archive). */
2929 for (nbfd = abfd->nested_archives; nbfd; nbfd = next)
2930 {
2931 next = nbfd->archive_next;
2932 bfd_close (nbfd);
2933 }
2934
2935 htab = bfd_ardata (abfd)->cache;
2936 if (htab)
2937 {
2938 htab_traverse_noresize (htab, archive_close_worker, NULL);
2939 htab_delete (htab);
2940 bfd_ardata (abfd)->cache = NULL;
2941 }
2942
2943 /* Close the archive plugin file descriptor if needed. */
2944 if (abfd->archive_plugin_fd > 0)
2945 close (abfd->archive_plugin_fd);
2946 }
2947
2948 _bfd_unlink_from_archive_parent (abfd);
2949
2950 if (abfd->is_linker_output)
2951 (*abfd->link.hash->hash_table_free) (abfd);
2952
2953 return true;
2954 }
2955