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