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