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