x86: move fetch error handling into a helper function
[binutils-gdb.git] / binutils / ar.c
blob0c6ccf909b00b1765a40ba5a8b69b4bf23ea8eea
1 /* ar.c - Archive modify and extract.
2 Copyright (C) 1991-2023 Free Software Foundation, Inc.
4 This file is part of GNU Binutils.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19 MA 02110-1301, USA. */
22 Bugs: GNU ar used to check file against filesystem in quick_update and
23 replace operations (would check mtime). Doesn't warn when name truncated.
24 No way to specify pos_end. Error messages should be more consistent. */
26 #include "sysdep.h"
27 #include "bfd.h"
28 #include "libiberty.h"
29 #include "getopt.h"
30 #include "aout/ar.h"
31 #include "bucomm.h"
32 #include "arsup.h"
33 #include "filenames.h"
34 #include "binemul.h"
35 #include "plugin-api.h"
36 #include "plugin.h"
37 #include "ansidecl.h"
39 #ifdef __GO32___
40 #define EXT_NAME_LEN 3 /* Bufflen of addition to name if it's MS-DOS. */
41 #else
42 #define EXT_NAME_LEN 6 /* Ditto for *NIX. */
43 #endif
45 /* Static declarations. */
47 static void mri_emul (void);
48 static const char *normalize (const char *, bfd *);
49 static void remove_output (void);
50 static void map_over_members (bfd *, void (*)(bfd *), char **, int);
51 static void print_contents (bfd * member);
52 static void delete_members (bfd *, char **files_to_delete);
54 static void move_members (bfd *, char **files_to_move);
55 static void replace_members
56 (bfd *, char **files_to_replace, bool quick);
57 static void print_descr (bfd * abfd);
58 static void write_archive (bfd *);
59 static int ranlib_only (const char *archname);
60 static int ranlib_touch (const char *archname);
61 static void usage (int);
63 /** Globals and flags. */
65 static int mri_mode;
67 /* This flag distinguishes between ar and ranlib:
68 1 means this is 'ranlib'; 0 means this is 'ar'.
69 -1 means if we should use argv[0] to decide. */
70 extern int is_ranlib;
72 /* Nonzero means don't warn about creating the archive file if necessary. */
73 int silent_create = 0;
75 /* Nonzero means describe each action performed. */
76 int verbose = 0;
78 /* Nonzero means display offsets of files in the archive. */
79 int display_offsets = 0;
81 /* Nonzero means preserve dates of members when extracting them. */
82 int preserve_dates = 0;
84 /* Nonzero means don't replace existing members whose dates are more recent
85 than the corresponding files. */
86 int newer_only = 0;
88 /* Controls the writing of an archive symbol table (in BSD: a __.SYMDEF
89 member). -1 means we've been explicitly asked to not write a symbol table;
90 +1 means we've been explicitly asked to write it;
91 0 is the default.
92 Traditionally, the default in BSD has been to not write the table.
93 However, for POSIX.2 compliance the default is now to write a symbol table
94 if any of the members are object files. */
95 int write_armap = 0;
97 /* Operate in deterministic mode: write zero for timestamps, uids,
98 and gids for archive members and the archive symbol table, and write
99 consistent file modes. */
100 int deterministic = -1; /* Determinism indeterminate. */
102 /* Nonzero means it's the name of an existing member; position new or moved
103 files with respect to this one. */
104 char *posname = NULL;
106 /* Sez how to use `posname': pos_before means position before that member.
107 pos_after means position after that member. pos_end means always at end.
108 pos_default means default appropriately. For the latter two, `posname'
109 should also be zero. */
110 enum pos
112 pos_default, pos_before, pos_after, pos_end
113 } postype = pos_default;
115 enum operations
117 none = 0, del, replace, print_table,
118 print_files, extract, move, quick_append
119 } operation = none;
121 static bfd **
122 get_pos_bfd (bfd **, enum pos, const char *);
124 /* For extract/delete only. If COUNTED_NAME_MODE is TRUE, we only
125 extract the COUNTED_NAME_COUNTER instance of that name. */
126 static bool counted_name_mode = 0;
127 static int counted_name_counter = 0;
129 /* Whether to truncate names of files stored in the archive. */
130 static bool ar_truncate = false;
132 /* Whether to use a full file name match when searching an archive.
133 This is convenient for archives created by the Microsoft lib
134 program. */
135 static bool full_pathname = false;
137 /* Whether to create a "thin" archive (symbol index only -- no files). */
138 static bool make_thin_archive = false;
140 #define LIBDEPS "__.LIBDEP"
141 /* Text to store in the __.LIBDEP archive element for the linker to use. */
142 static char * libdeps = NULL;
143 static bfd * libdeps_bfd = NULL;
145 static int show_version = 0;
147 static int show_help = 0;
149 #if BFD_SUPPORTS_PLUGINS
150 static const char *plugin_target = "plugin";
151 #else
152 static const char *plugin_target = NULL;
153 #endif
155 static const char *target = NULL;
157 enum long_option_numbers
159 OPTION_PLUGIN = 201,
160 OPTION_TARGET,
161 OPTION_OUTPUT
164 static const char * output_dir = NULL;
166 static struct option long_options[] =
168 {"help", no_argument, &show_help, 1},
169 {"plugin", required_argument, NULL, OPTION_PLUGIN},
170 {"target", required_argument, NULL, OPTION_TARGET},
171 {"version", no_argument, &show_version, 1},
172 {"output", required_argument, NULL, OPTION_OUTPUT},
173 {"record-libdeps", required_argument, NULL, 'l'},
174 {"thin", no_argument, NULL, 'T'},
175 {NULL, no_argument, NULL, 0}
178 int interactive = 0;
180 static void
181 mri_emul (void)
183 interactive = isatty (fileno (stdin));
184 yyparse ();
187 /* If COUNT is 0, then FUNCTION is called once on each entry. If nonzero,
188 COUNT is the length of the FILES chain; FUNCTION is called on each entry
189 whose name matches one in FILES. */
191 static void
192 map_over_members (bfd *arch, void (*function)(bfd *), char **files, int count)
194 bfd *head;
195 int match_count;
197 if (count == 0)
199 for (head = arch->archive_next; head; head = head->archive_next)
200 function (head);
201 return;
204 /* This may appear to be a baroque way of accomplishing what we want.
205 However we have to iterate over the filenames in order to notice where
206 a filename is requested but does not exist in the archive. Ditto
207 mapping over each file each time -- we want to hack multiple
208 references. */
210 for (head = arch->archive_next; head; head = head->archive_next)
211 head->archive_pass = 0;
213 for (; count > 0; files++, count--)
215 bool found = false;
217 match_count = 0;
218 for (head = arch->archive_next; head; head = head->archive_next)
220 const char * filename;
222 /* PR binutils/15796: Once an archive element has been matched
223 do not match it again. If the user provides multiple same-named
224 parameters on the command line their intent is to match multiple
225 same-named entries in the archive, not the same entry multiple
226 times. */
227 if (head->archive_pass)
228 continue;
230 filename = bfd_get_filename (head);
231 if (filename == NULL)
233 /* Some archive formats don't get the filenames filled in
234 until the elements are opened. */
235 struct stat buf;
236 bfd_stat_arch_elt (head, &buf);
238 else if (bfd_is_thin_archive (arch))
240 /* Thin archives store full pathnames. Need to normalize. */
241 filename = normalize (filename, arch);
244 if (filename != NULL
245 && !FILENAME_CMP (normalize (*files, arch), filename))
247 ++match_count;
248 if (counted_name_mode
249 && match_count != counted_name_counter)
251 /* Counting, and didn't match on count; go on to the
252 next one. */
253 continue;
256 found = true;
257 function (head);
258 head->archive_pass = 1;
259 /* PR binutils/15796: Once a file has been matched, do not
260 match any more same-named files in the archive. If the
261 user does want to match multiple same-name files in an
262 archive they should provide multiple same-name parameters
263 to the ar command. */
264 break;
268 if (!found)
269 /* xgettext:c-format */
270 fprintf (stderr, _("no entry %s in archive\n"), *files);
274 bool operation_alters_arch = false;
276 static void
277 usage (int help)
279 FILE *s;
281 #if BFD_SUPPORTS_PLUGINS
282 /* xgettext:c-format */
283 const char *command_line
284 = _("Usage: %s [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV]"
285 " [--plugin <name>] [member-name] [count] archive-file file...\n");
287 #else
288 /* xgettext:c-format */
289 const char *command_line
290 = _("Usage: %s [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV]"
291 " [member-name] [count] archive-file file...\n");
292 #endif
293 s = help ? stdout : stderr;
295 fprintf (s, command_line, program_name);
297 /* xgettext:c-format */
298 fprintf (s, _(" %s -M [<mri-script]\n"), program_name);
299 fprintf (s, _(" commands:\n"));
300 fprintf (s, _(" d - delete file(s) from the archive\n"));
301 fprintf (s, _(" m[ab] - move file(s) in the archive\n"));
302 fprintf (s, _(" p - print file(s) found in the archive\n"));
303 fprintf (s, _(" q[f] - quick append file(s) to the archive\n"));
304 fprintf (s, _(" r[ab][f][u] - replace existing or insert new file(s) into the archive\n"));
305 fprintf (s, _(" s - act as ranlib\n"));
306 fprintf (s, _(" t[O][v] - display contents of the archive\n"));
307 fprintf (s, _(" x[o] - extract file(s) from the archive\n"));
308 fprintf (s, _(" command specific modifiers:\n"));
309 fprintf (s, _(" [a] - put file(s) after [member-name]\n"));
310 fprintf (s, _(" [b] - put file(s) before [member-name] (same as [i])\n"));
311 if (DEFAULT_AR_DETERMINISTIC)
313 fprintf (s, _("\
314 [D] - use zero for timestamps and uids/gids (default)\n"));
315 fprintf (s, _("\
316 [U] - use actual timestamps and uids/gids\n"));
318 else
320 fprintf (s, _("\
321 [D] - use zero for timestamps and uids/gids\n"));
322 fprintf (s, _("\
323 [U] - use actual timestamps and uids/gids (default)\n"));
325 fprintf (s, _(" [N] - use instance [count] of name\n"));
326 fprintf (s, _(" [f] - truncate inserted file names\n"));
327 fprintf (s, _(" [P] - use full path names when matching\n"));
328 fprintf (s, _(" [o] - preserve original dates\n"));
329 fprintf (s, _(" [O] - display offsets of files in the archive\n"));
330 fprintf (s, _(" [u] - only replace files that are newer than current archive contents\n"));
331 fprintf (s, _(" generic modifiers:\n"));
332 fprintf (s, _(" [c] - do not warn if the library had to be created\n"));
333 fprintf (s, _(" [s] - create an archive index (cf. ranlib)\n"));
334 fprintf (s, _(" [l <text> ] - specify the dependencies of this library\n"));
335 fprintf (s, _(" [S] - do not build a symbol table\n"));
336 fprintf (s, _(" [T] - deprecated, use --thin instead\n"));
337 fprintf (s, _(" [v] - be verbose\n"));
338 fprintf (s, _(" [V] - display the version number\n"));
339 fprintf (s, _(" @<file> - read options from <file>\n"));
340 fprintf (s, _(" --target=BFDNAME - specify the target object format as BFDNAME\n"));
341 fprintf (s, _(" --output=DIRNAME - specify the output directory for extraction operations\n"));
342 fprintf (s, _(" --record-libdeps=<text> - specify the dependencies of this library\n"));
343 fprintf (s, _(" --thin - make a thin archive\n"));
344 #if BFD_SUPPORTS_PLUGINS
345 fprintf (s, _(" optional:\n"));
346 fprintf (s, _(" --plugin <p> - load the specified plugin\n"));
347 #endif
349 ar_emul_usage (s);
351 list_supported_targets (program_name, s);
353 if (REPORT_BUGS_TO[0] && help)
354 fprintf (s, _("Report bugs to %s\n"), REPORT_BUGS_TO);
356 xexit (help ? 0 : 1);
359 static void
360 ranlib_usage (int help)
362 FILE *s;
364 s = help ? stdout : stderr;
366 /* xgettext:c-format */
367 fprintf (s, _("Usage: %s [options] archive\n"), program_name);
368 fprintf (s, _(" Generate an index to speed access to archives\n"));
369 fprintf (s, _(" The options are:\n\
370 @<file> Read options from <file>\n"));
371 #if BFD_SUPPORTS_PLUGINS
372 fprintf (s, _("\
373 --plugin <name> Load the specified plugin\n"));
374 #endif
375 if (DEFAULT_AR_DETERMINISTIC)
376 fprintf (s, _("\
377 -D Use zero for symbol map timestamp (default)\n\
378 -U Use an actual symbol map timestamp\n"));
379 else
380 fprintf (s, _("\
381 -D Use zero for symbol map timestamp\n\
382 -U Use actual symbol map timestamp (default)\n"));
383 fprintf (s, _("\
384 -t Update the archive's symbol map timestamp\n\
385 -h --help Print this help message\n\
386 -v --version Print version information\n"));
388 list_supported_targets (program_name, s);
390 if (REPORT_BUGS_TO[0] && help)
391 fprintf (s, _("Report bugs to %s\n"), REPORT_BUGS_TO);
393 xexit (help ? 0 : 1);
396 /* Normalize a file name specified on the command line into a file
397 name which we will use in an archive. */
399 static const char *
400 normalize (const char *file, bfd *abfd)
402 const char *filename;
404 if (full_pathname)
405 return file;
407 filename = lbasename (file);
409 if (ar_truncate
410 && abfd != NULL
411 && strlen (filename) > abfd->xvec->ar_max_namelen)
413 char *s;
415 /* Space leak. */
416 s = (char *) xmalloc (abfd->xvec->ar_max_namelen + 1);
417 memcpy (s, filename, abfd->xvec->ar_max_namelen);
418 s[abfd->xvec->ar_max_namelen] = '\0';
419 filename = s;
422 return filename;
425 /* Remove any output file. This is only called via xatexit. */
427 static const char *output_filename = NULL;
428 static FILE *output_file = NULL;
430 static void
431 remove_output (void)
433 if (output_filename != NULL)
435 if (output_file != NULL)
436 fclose (output_file);
437 unlink_if_ordinary (output_filename);
441 static char **
442 decode_options (int argc, char **argv)
444 int c;
446 /* Convert old-style ar call by exploding option element and rearranging
447 options accordingly. */
449 restart:
450 if (argc > 1 && argv[1][0] != '-')
452 int new_argc; /* argc value for rearranged arguments */
453 char **new_argv; /* argv value for rearranged arguments */
454 char *const *in; /* cursor into original argv */
455 char **out; /* cursor into rearranged argv */
456 const char *letter; /* cursor into old option letters */
457 char buffer[3]; /* constructed option buffer */
459 /* Initialize a constructed option. */
461 buffer[0] = '-';
462 buffer[2] = '\0';
464 /* Allocate a new argument array, and copy program name in it. */
466 new_argc = argc - 1 + strlen (argv[1]);
467 new_argv = xmalloc ((new_argc + 1) * sizeof (*argv));
468 in = argv;
469 out = new_argv;
470 *out++ = *in++;
472 /* Copy each old letter option as a separate option. */
474 for (letter = *in++; *letter; letter++)
476 buffer[1] = *letter;
477 *out++ = xstrdup (buffer);
480 /* Copy all remaining options. */
482 while (in < argv + argc)
483 *out++ = *in++;
484 *out = NULL;
486 /* Replace the old option list by the new one. */
488 argc = new_argc;
489 argv = new_argv;
492 while ((c = getopt_long (argc, argv, "hdmpqrtxl:coOVsSuvabiMNfPTDU",
493 long_options, NULL)) != EOF)
495 switch (c)
497 case 'd':
498 case 'm':
499 case 'p':
500 case 'q':
501 case 'r':
502 case 't':
503 case 'x':
504 if (operation != none)
505 fatal (_("two different operation options specified"));
506 break;
509 switch (c)
511 case 'h':
512 show_help = 1;
513 break;
514 case 'd':
515 operation = del;
516 operation_alters_arch = true;
517 break;
518 case 'm':
519 operation = move;
520 operation_alters_arch = true;
521 break;
522 case 'p':
523 operation = print_files;
524 break;
525 case 'q':
526 operation = quick_append;
527 operation_alters_arch = true;
528 break;
529 case 'r':
530 operation = replace;
531 operation_alters_arch = true;
532 break;
533 case 't':
534 operation = print_table;
535 break;
536 case 'x':
537 operation = extract;
538 break;
539 case 'l':
540 if (libdeps != NULL)
541 fatal (_("libdeps specified more than once"));
542 libdeps = optarg;
543 break;
544 case 'c':
545 silent_create = 1;
546 break;
547 case 'o':
548 preserve_dates = 1;
549 break;
550 case 'O':
551 display_offsets = 1;
552 break;
553 case 'V':
554 show_version = true;
555 break;
556 case 's':
557 write_armap = 1;
558 break;
559 case 'S':
560 write_armap = -1;
561 break;
562 case 'u':
563 newer_only = 1;
564 break;
565 case 'v':
566 verbose = 1;
567 break;
568 case 'a':
569 postype = pos_after;
570 break;
571 case 'b':
572 postype = pos_before;
573 break;
574 case 'i':
575 postype = pos_before;
576 break;
577 case 'M':
578 mri_mode = 1;
579 break;
580 case 'N':
581 counted_name_mode = true;
582 break;
583 case 'f':
584 ar_truncate = true;
585 break;
586 case 'P':
587 full_pathname = true;
588 break;
589 case 'T':
590 make_thin_archive = true;
591 break;
592 case 'D':
593 deterministic = true;
594 break;
595 case 'U':
596 deterministic = false;
597 break;
598 case OPTION_PLUGIN:
599 #if BFD_SUPPORTS_PLUGINS
600 bfd_plugin_set_plugin (optarg);
601 #else
602 fprintf (stderr, _("sorry - this program has been built without plugin support\n"));
603 xexit (1);
604 #endif
605 break;
606 case OPTION_TARGET:
607 target = optarg;
608 break;
609 case OPTION_OUTPUT:
610 output_dir = optarg;
611 break;
612 case 0: /* A long option that just sets a flag. */
613 break;
614 default:
615 usage (0);
619 /* PR 13256: Allow for the possibility that the first command line option
620 started with a dash (eg --plugin) but then the following option(s) are
621 old style, non-dash-prefixed versions. */
622 if (operation == none && write_armap != 1 && !mri_mode
623 && optind > 0 && optind < argc)
625 argv += (optind - 1);
626 argc -= (optind - 1);
627 optind = 0;
628 goto restart;
631 return &argv[optind];
634 /* If neither -D nor -U was specified explicitly,
635 then use the configured default. */
636 static void
637 default_deterministic (void)
639 if (deterministic < 0)
640 deterministic = DEFAULT_AR_DETERMINISTIC;
643 static void
644 ranlib_main (int argc, char **argv)
646 int arg_index, status = 0;
647 bool touch = false;
648 int c;
650 while ((c = getopt_long (argc, argv, "DhHUvVt", long_options, NULL)) != EOF)
652 switch (c)
654 case 'D':
655 deterministic = true;
656 break;
657 case 'U':
658 deterministic = false;
659 break;
660 case 'h':
661 case 'H':
662 show_help = 1;
663 break;
664 case 't':
665 touch = true;
666 break;
667 case 'v':
668 case 'V':
669 show_version = 1;
670 break;
672 /* PR binutils/13493: Support plugins. */
673 case OPTION_PLUGIN:
674 #if BFD_SUPPORTS_PLUGINS
675 bfd_plugin_set_plugin (optarg);
676 #else
677 fprintf (stderr, _("sorry - this program has been built without plugin support\n"));
678 xexit (1);
679 #endif
680 break;
684 if (argc < 2)
685 ranlib_usage (0);
687 if (show_help)
688 ranlib_usage (1);
690 if (show_version)
691 print_version ("ranlib");
693 default_deterministic ();
695 arg_index = optind;
697 while (arg_index < argc)
699 if (! touch)
700 status |= ranlib_only (argv[arg_index]);
701 else
702 status |= ranlib_touch (argv[arg_index]);
703 ++arg_index;
706 xexit (status);
709 int main (int, char **);
712 main (int argc, char **argv)
714 int arg_index;
715 char **files;
716 int file_count;
717 char *inarch_filename;
718 int i;
720 #ifdef HAVE_LC_MESSAGES
721 setlocale (LC_MESSAGES, "");
722 #endif
723 setlocale (LC_CTYPE, "");
724 bindtextdomain (PACKAGE, LOCALEDIR);
725 textdomain (PACKAGE);
727 program_name = argv[0];
728 xmalloc_set_program_name (program_name);
729 bfd_set_error_program_name (program_name);
730 #if BFD_SUPPORTS_PLUGINS
731 bfd_plugin_set_program_name (program_name);
732 #endif
734 expandargv (&argc, &argv);
736 if (is_ranlib < 0)
738 const char *temp = lbasename (program_name);
740 if (strlen (temp) >= 6
741 && FILENAME_CMP (temp + strlen (temp) - 6, "ranlib") == 0)
742 is_ranlib = 1;
743 else
744 is_ranlib = 0;
747 if (bfd_init () != BFD_INIT_MAGIC)
748 fatal (_("fatal error: libbfd ABI mismatch"));
749 set_default_bfd_target ();
751 xatexit (remove_output);
753 for (i = 1; i < argc; i++)
754 if (! ar_emul_parse_arg (argv[i]))
755 break;
756 argv += (i - 1);
757 argc -= (i - 1);
759 if (is_ranlib)
760 ranlib_main (argc, argv);
762 if (argc < 2)
763 usage (0);
765 argv = decode_options (argc, argv);
767 if (show_help)
768 usage (1);
770 if (show_version)
771 print_version ("ar");
773 arg_index = 0;
775 if (mri_mode)
777 default_deterministic ();
778 mri_emul ();
780 else
782 bfd *arch;
784 /* Fail if no files are specified on the command line.
785 (But not for MRI mode which allows for reading arguments
786 and filenames from stdin). */
787 if (argv[arg_index] == NULL)
788 usage (0);
790 /* We don't use do_quick_append any more. Too many systems
791 expect ar to always rebuild the symbol table even when q is
792 used. */
794 /* We can't write an armap when using ar q, so just do ar r
795 instead. */
796 if (operation == quick_append && write_armap)
797 operation = replace;
799 if ((operation == none || operation == print_table)
800 && write_armap == 1)
801 xexit (ranlib_only (argv[arg_index]));
803 if (operation == none)
804 fatal (_("no operation specified"));
806 if (newer_only && operation != replace)
807 fatal (_("`u' is only meaningful with the `r' option."));
809 if (newer_only && deterministic > 0)
810 fatal (_("`u' is not meaningful with the `D' option."));
812 if (newer_only && deterministic < 0 && DEFAULT_AR_DETERMINISTIC)
813 non_fatal (_("\
814 `u' modifier ignored since `D' is the default (see `U')"));
816 default_deterministic ();
818 if (postype != pos_default)
820 posname = argv[arg_index++];
821 if (posname == NULL)
822 fatal (_("missing position arg."));
825 if (counted_name_mode)
827 if (operation != extract && operation != del)
828 fatal (_("`N' is only meaningful with the `x' and `d' options."));
829 if (argv[arg_index] == NULL)
830 fatal (_("`N' missing value."));
831 counted_name_counter = atoi (argv[arg_index++]);
832 if (counted_name_counter <= 0)
833 fatal (_("Value for `N' must be positive."));
836 inarch_filename = argv[arg_index++];
837 if (inarch_filename == NULL)
838 usage (0);
840 for (file_count = 0; argv[arg_index + file_count] != NULL; file_count++)
841 continue;
843 files = (file_count > 0) ? argv + arg_index : NULL;
845 arch = open_inarch (inarch_filename,
846 files == NULL ? (char *) NULL : files[0]);
848 if (operation == extract && bfd_is_thin_archive (arch))
849 fatal (_("`x' cannot be used on thin archives."));
851 if (libdeps != NULL)
853 char **new_files;
854 bfd_size_type reclen = strlen (libdeps) + 1;
856 /* Create a bfd to contain the dependencies.
857 It inherits its type from arch, but we must set the type to
858 "binary" otherwise bfd_bwrite() will fail. After writing, we
859 must set the type back to default otherwise adding it to the
860 archive will fail. */
861 libdeps_bfd = bfd_create (LIBDEPS, arch);
862 if (libdeps_bfd == NULL)
863 fatal (_("Cannot create libdeps record."));
865 if (bfd_find_target ("binary", libdeps_bfd) == NULL)
866 fatal (_("Cannot set libdeps record type to binary."));
868 if (! bfd_set_format (libdeps_bfd, bfd_object))
869 fatal (_("Cannot set libdeps object format."));
871 if (! bfd_make_writable (libdeps_bfd))
872 fatal (_("Cannot make libdeps object writable."));
874 if (bfd_bwrite (libdeps, reclen, libdeps_bfd) != reclen)
875 fatal (_("Cannot write libdeps record."));
877 if (! bfd_make_readable (libdeps_bfd))
878 fatal (_("Cannot make libdeps object readable."));
880 if (bfd_find_target (plugin_target, libdeps_bfd) == NULL)
881 fatal (_("Cannot reset libdeps record type."));
883 /* Insert our libdeps record in 2nd slot of the list of files
884 being operated on. We shouldn't use 1st slot, but we want
885 to avoid having to search all the way to the end of an
886 archive with a large number of members at link time. */
887 new_files = xmalloc ((file_count + 2) * sizeof (*new_files));
888 if (file_count)
890 new_files[0] = files[0];
891 memcpy (new_files + 1, files, file_count * sizeof (*files));
893 new_files[file_count != 0] = LIBDEPS;
894 file_count++;
895 new_files[file_count] = NULL;
896 files = new_files;
899 switch (operation)
901 case print_table:
902 map_over_members (arch, print_descr, files, file_count);
903 break;
905 case print_files:
906 map_over_members (arch, print_contents, files, file_count);
907 break;
909 case extract:
910 map_over_members (arch, extract_file, files, file_count);
911 break;
913 case del:
914 if (files != NULL)
915 delete_members (arch, files);
916 else
917 output_filename = NULL;
918 break;
920 case move:
921 /* PR 12558: Creating and moving at the same time does
922 not make sense. Just create the archive instead. */
923 if (! silent_create)
925 if (files != NULL)
926 move_members (arch, files);
927 else
928 output_filename = NULL;
929 break;
931 /* Fall through. */
933 case replace:
934 case quick_append:
935 if (files != NULL || write_armap > 0)
936 replace_members (arch, files, operation == quick_append);
937 else
938 output_filename = NULL;
939 break;
941 /* Shouldn't happen! */
942 default:
943 /* xgettext:c-format */
944 fatal (_("internal error -- this option not implemented"));
948 xexit (0);
949 return 0;
952 bfd *
953 open_inarch (const char *archive_filename, const char *file)
955 bfd **last_one;
956 bfd *next_one;
957 struct stat sbuf;
958 bfd *arch;
959 char **matching;
961 bfd_set_error (bfd_error_no_error);
963 if (target == NULL)
964 target = plugin_target;
966 if (stat (archive_filename, &sbuf) != 0)
968 #if !defined(__GO32__) || defined(__DJGPP__)
970 /* FIXME: I don't understand why this fragment was ifndef'ed
971 away for __GO32__; perhaps it was in the days of DJGPP v1.x.
972 stat() works just fine in v2.x, so I think this should be
973 removed. For now, I enable it for DJGPP v2. -- EZ. */
975 /* KLUDGE ALERT! Temporary fix until I figger why
976 stat() is wrong ... think it's buried in GO32's IDT - Jax */
977 if (errno != ENOENT)
978 bfd_fatal (archive_filename);
979 #endif
981 if (!operation_alters_arch)
983 fprintf (stderr, "%s: ", program_name);
984 perror (archive_filename);
985 maybequit ();
986 return NULL;
989 /* If the target isn't set, try to figure out the target to use
990 for the archive from the first object on the list. */
991 if (target == NULL && file != NULL)
993 bfd *obj;
995 obj = bfd_openr (file, target);
996 if (obj != NULL)
998 if (bfd_check_format (obj, bfd_object))
999 target = bfd_get_target (obj);
1000 (void) bfd_close (obj);
1004 /* Create an empty archive. */
1005 arch = bfd_openw (archive_filename, target);
1006 if (arch == NULL
1007 || ! bfd_set_format (arch, bfd_archive)
1008 || ! bfd_close (arch))
1009 bfd_fatal (archive_filename);
1010 else if (!silent_create)
1011 non_fatal (_("creating %s"), archive_filename);
1013 /* If we die creating a new archive, don't leave it around. */
1014 output_filename = archive_filename;
1017 arch = bfd_openr (archive_filename, target);
1018 if (arch == NULL)
1020 bloser:
1021 bfd_fatal (archive_filename);
1024 if (! bfd_check_format_matches (arch, bfd_archive, &matching))
1026 bfd_nonfatal (archive_filename);
1027 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1028 list_matching_formats (matching);
1029 xexit (1);
1032 if ((operation == replace || operation == quick_append)
1033 && bfd_openr_next_archived_file (arch, NULL) != NULL)
1035 /* PR 15140: Catch attempts to convert a normal
1036 archive into a thin archive or vice versa. */
1037 if (make_thin_archive && ! bfd_is_thin_archive (arch))
1039 fatal (_("Cannot convert existing library %s to thin format"),
1040 bfd_get_filename (arch));
1041 goto bloser;
1043 else if (! make_thin_archive && bfd_is_thin_archive (arch))
1045 fatal (_("Cannot convert existing thin library %s to normal format"),
1046 bfd_get_filename (arch));
1047 goto bloser;
1051 last_one = &(arch->archive_next);
1052 /* Read all the contents right away, regardless. */
1053 for (next_one = bfd_openr_next_archived_file (arch, NULL);
1054 next_one;
1055 next_one = bfd_openr_next_archived_file (arch, next_one))
1057 *last_one = next_one;
1058 last_one = &next_one->archive_next;
1060 *last_one = (bfd *) NULL;
1061 if (bfd_get_error () != bfd_error_no_more_archived_files)
1062 goto bloser;
1063 return arch;
1066 static void
1067 print_contents (bfd *abfd)
1069 bfd_size_type ncopied = 0;
1070 bfd_size_type size;
1071 char *cbuf = (char *) xmalloc (BUFSIZE);
1072 struct stat buf;
1074 if (bfd_stat_arch_elt (abfd, &buf) != 0)
1075 /* xgettext:c-format */
1076 fatal (_("internal stat error on %s"), bfd_get_filename (abfd));
1078 if (verbose)
1079 printf ("\n<%s>\n\n", bfd_get_filename (abfd));
1081 bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
1083 size = buf.st_size;
1084 while (ncopied < size)
1086 bfd_size_type nread;
1087 bfd_size_type tocopy = size - ncopied;
1089 if (tocopy > BUFSIZE)
1090 tocopy = BUFSIZE;
1092 nread = bfd_bread (cbuf, tocopy, abfd);
1093 if (nread != tocopy)
1094 /* xgettext:c-format */
1095 fatal (_("%s is not a valid archive"),
1096 bfd_get_filename (abfd->my_archive));
1098 /* fwrite in mingw32 may return int instead of bfd_size_type. Cast the
1099 return value to bfd_size_type to avoid comparison between signed and
1100 unsigned values. */
1101 if ((bfd_size_type) fwrite (cbuf, 1, nread, stdout) != nread)
1102 fatal ("stdout: %s", strerror (errno));
1103 ncopied += tocopy;
1105 free (cbuf);
1109 static FILE * open_output_file (bfd *) ATTRIBUTE_RETURNS_NONNULL;
1111 static FILE *
1112 open_output_file (bfd * abfd)
1114 output_filename = bfd_get_filename (abfd);
1116 /* PR binutils/17533: Do not allow directory traversal
1117 outside of the current directory tree - unless the
1118 user has explicitly specified an output directory. */
1119 if (! is_valid_archive_path (output_filename))
1121 char * base = (char *) lbasename (output_filename);
1123 non_fatal (_("illegal output pathname for archive member: %s, using '%s' instead"),
1124 output_filename, base);
1125 output_filename = base;
1128 if (output_dir)
1130 size_t len = strlen (output_dir);
1132 if (len > 0)
1134 /* FIXME: There is a memory leak here, but it is not serious. */
1135 if (IS_DIR_SEPARATOR (output_dir [len - 1]))
1136 output_filename = concat (output_dir, output_filename, NULL);
1137 else
1138 output_filename = concat (output_dir, "/", output_filename, NULL);
1142 if (verbose)
1143 printf ("x - %s\n", output_filename);
1145 FILE * ostream = fopen (output_filename, FOPEN_WB);
1146 if (ostream == NULL)
1148 perror (output_filename);
1149 xexit (1);
1152 return ostream;
1155 /* Extract a member of the archive into its own file.
1157 We defer opening the new file until after we have read a BUFSIZ chunk of the
1158 old one, since we know we have just read the archive header for the old
1159 one. Since most members are shorter than BUFSIZ, this means we will read
1160 the old header, read the old data, write a new inode for the new file, and
1161 write the new data, and be done. This 'optimization' is what comes from
1162 sitting next to a bare disk and hearing it every time it seeks. -- Gnu
1163 Gilmore */
1165 void
1166 extract_file (bfd *abfd)
1168 bfd_size_type size;
1169 struct stat buf;
1171 if (preserve_dates)
1172 memset (&buf, 0, sizeof (buf));
1174 if (bfd_stat_arch_elt (abfd, &buf) != 0)
1175 /* xgettext:c-format */
1176 fatal (_("internal stat error on %s"), bfd_get_filename (abfd));
1177 size = buf.st_size;
1179 bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
1181 output_file = NULL;
1182 if (size == 0)
1184 output_file = open_output_file (abfd);
1186 else
1188 bfd_size_type ncopied = 0;
1189 char *cbuf = (char *) xmalloc (BUFSIZE);
1191 while (ncopied < size)
1193 bfd_size_type nread, tocopy;
1195 tocopy = size - ncopied;
1196 if (tocopy > BUFSIZE)
1197 tocopy = BUFSIZE;
1199 nread = bfd_bread (cbuf, tocopy, abfd);
1200 if (nread != tocopy)
1201 /* xgettext:c-format */
1202 fatal (_("%s is not a valid archive"),
1203 bfd_get_filename (abfd->my_archive));
1205 /* See comment above; this saves disk arm motion. */
1206 if (output_file == NULL)
1207 output_file = open_output_file (abfd);
1209 /* fwrite in mingw32 may return int instead of bfd_size_type. Cast
1210 the return value to bfd_size_type to avoid comparison between
1211 signed and unsigned values. */
1212 if ((bfd_size_type) fwrite (cbuf, 1, nread, output_file) != nread)
1213 fatal ("%s: %s", output_filename, strerror (errno));
1215 ncopied += tocopy;
1218 free (cbuf);
1221 fclose (output_file);
1223 output_file = NULL;
1225 chmod (output_filename, buf.st_mode);
1227 if (preserve_dates)
1229 /* Set access time to modification time. Only st_mtime is
1230 initialized by bfd_stat_arch_elt. */
1231 buf.st_atime = buf.st_mtime;
1232 set_times (output_filename, &buf);
1235 output_filename = NULL;
1238 static void
1239 write_archive (bfd *iarch)
1241 bfd *obfd;
1242 char *old_name, *new_name;
1243 bfd *contents_head = iarch->archive_next;
1244 int tmpfd = -1;
1246 old_name = xstrdup (bfd_get_filename (iarch));
1247 new_name = make_tempname (old_name, &tmpfd);
1249 if (new_name == NULL)
1250 bfd_fatal (_("could not create temporary file whilst writing archive"));
1252 output_filename = new_name;
1254 obfd = bfd_fdopenw (new_name, bfd_get_target (iarch), tmpfd);
1256 if (obfd == NULL)
1258 close (tmpfd);
1259 bfd_fatal (old_name);
1262 bfd_set_format (obfd, bfd_archive);
1264 /* Request writing the archive symbol table unless we've
1265 been explicitly requested not to. */
1266 obfd->has_armap = write_armap >= 0;
1268 if (ar_truncate)
1270 /* This should really use bfd_set_file_flags, but that rejects
1271 archives. */
1272 obfd->flags |= BFD_TRADITIONAL_FORMAT;
1275 if (deterministic)
1276 obfd->flags |= BFD_DETERMINISTIC_OUTPUT;
1278 if (full_pathname)
1279 obfd->flags |= BFD_ARCHIVE_FULL_PATH;
1281 if (make_thin_archive || bfd_is_thin_archive (iarch))
1282 bfd_set_thin_archive (obfd, true);
1284 if (!bfd_set_archive_head (obfd, contents_head))
1285 bfd_fatal (old_name);
1287 tmpfd = dup (tmpfd);
1288 if (!bfd_close (obfd))
1289 bfd_fatal (old_name);
1291 output_filename = NULL;
1293 /* We don't care if this fails; we might be creating the archive. */
1294 bfd_close (iarch);
1296 if (smart_rename (new_name, old_name, tmpfd, NULL, false) != 0)
1297 xexit (1);
1298 free (old_name);
1299 free (new_name);
1302 /* Return a pointer to the pointer to the entry which should be rplacd'd
1303 into when altering. DEFAULT_POS should be how to interpret pos_default,
1304 and should be a pos value. */
1306 static bfd **
1307 get_pos_bfd (bfd **contents, enum pos default_pos, const char *default_posname)
1309 bfd **after_bfd = contents;
1310 enum pos realpos;
1311 const char *realposname;
1313 if (postype == pos_default)
1315 realpos = default_pos;
1316 realposname = default_posname;
1318 else
1320 realpos = postype;
1321 realposname = posname;
1324 if (realpos == pos_end)
1326 while (*after_bfd)
1327 after_bfd = &((*after_bfd)->archive_next);
1329 else
1331 for (; *after_bfd; after_bfd = &(*after_bfd)->archive_next)
1332 if (FILENAME_CMP (bfd_get_filename (*after_bfd), realposname) == 0)
1334 if (realpos == pos_after)
1335 after_bfd = &(*after_bfd)->archive_next;
1336 break;
1339 return after_bfd;
1342 static void
1343 delete_members (bfd *arch, char **files_to_delete)
1345 bfd **current_ptr_ptr;
1346 bool found;
1347 bool something_changed = false;
1348 int match_count;
1350 for (; *files_to_delete != NULL; ++files_to_delete)
1352 /* In a.out systems, the armap is optional. It's also called
1353 __.SYMDEF. So if the user asked to delete it, we should remember
1354 that fact. This isn't quite right for COFF systems (where
1355 __.SYMDEF might be regular member), but it's very unlikely
1356 to be a problem. FIXME */
1358 if (!strcmp (*files_to_delete, "__.SYMDEF"))
1360 arch->has_armap = false;
1361 write_armap = -1;
1362 continue;
1365 found = false;
1366 match_count = 0;
1367 current_ptr_ptr = &(arch->archive_next);
1368 while (*current_ptr_ptr)
1370 if (FILENAME_CMP (normalize (*files_to_delete, arch),
1371 bfd_get_filename (*current_ptr_ptr)) == 0)
1373 ++match_count;
1374 if (counted_name_mode
1375 && match_count != counted_name_counter)
1377 /* Counting, and didn't match on count; go on to the
1378 next one. */
1380 else
1382 found = true;
1383 something_changed = true;
1384 if (verbose)
1385 printf ("d - %s\n",
1386 *files_to_delete);
1387 *current_ptr_ptr = ((*current_ptr_ptr)->archive_next);
1388 goto next_file;
1392 current_ptr_ptr = &((*current_ptr_ptr)->archive_next);
1395 if (verbose && !found)
1397 /* xgettext:c-format */
1398 printf (_("No member named `%s'\n"), *files_to_delete);
1400 next_file:
1404 if (something_changed)
1405 write_archive (arch);
1406 else
1407 output_filename = NULL;
1411 /* Reposition existing members within an archive */
1413 static void
1414 move_members (bfd *arch, char **files_to_move)
1416 bfd **after_bfd; /* New entries go after this one */
1417 bfd **current_ptr_ptr; /* cdr pointer into contents */
1419 for (; *files_to_move; ++files_to_move)
1421 current_ptr_ptr = &(arch->archive_next);
1422 while (*current_ptr_ptr)
1424 bfd *current_ptr = *current_ptr_ptr;
1425 if (FILENAME_CMP (normalize (*files_to_move, arch),
1426 bfd_get_filename (current_ptr)) == 0)
1428 /* Move this file to the end of the list - first cut from
1429 where it is. */
1430 bfd *link_bfd;
1431 *current_ptr_ptr = current_ptr->archive_next;
1433 /* Now glue to end */
1434 after_bfd = get_pos_bfd (&arch->archive_next, pos_end, NULL);
1435 link_bfd = *after_bfd;
1436 *after_bfd = current_ptr;
1437 current_ptr->archive_next = link_bfd;
1439 if (verbose)
1440 printf ("m - %s\n", *files_to_move);
1442 goto next_file;
1445 current_ptr_ptr = &((*current_ptr_ptr)->archive_next);
1447 /* xgettext:c-format */
1448 fatal (_("no entry %s in archive %s!"), *files_to_move,
1449 bfd_get_filename (arch));
1451 next_file:;
1454 write_archive (arch);
1457 /* Ought to default to replacing in place, but this is existing practice! */
1459 static void
1460 replace_members (bfd *arch, char **files_to_move, bool quick)
1462 bool changed = false;
1463 bfd **after_bfd; /* New entries go after this one. */
1464 bfd *current;
1465 bfd **current_ptr;
1467 while (files_to_move && *files_to_move)
1469 if (! quick)
1471 current_ptr = &arch->archive_next;
1472 while (*current_ptr)
1474 current = *current_ptr;
1476 /* For compatibility with existing ar programs, we
1477 permit the same file to be added multiple times. */
1478 if (FILENAME_CMP (normalize (*files_to_move, arch),
1479 normalize (bfd_get_filename (current), arch)) == 0
1480 && current->arelt_data != NULL)
1482 bool replaced;
1483 if (newer_only)
1485 struct stat fsbuf, asbuf;
1487 if (stat (*files_to_move, &fsbuf) != 0)
1489 if (errno != ENOENT)
1490 bfd_fatal (*files_to_move);
1491 goto next_file;
1493 if (bfd_stat_arch_elt (current, &asbuf) != 0)
1494 /* xgettext:c-format */
1495 fatal (_("internal stat error on %s"),
1496 bfd_get_filename (current));
1498 if (fsbuf.st_mtime <= asbuf.st_mtime)
1499 goto next_file;
1502 after_bfd = get_pos_bfd (&arch->archive_next, pos_after,
1503 bfd_get_filename (current));
1504 if (libdeps_bfd != NULL
1505 && FILENAME_CMP (normalize (*files_to_move, arch),
1506 LIBDEPS) == 0)
1508 replaced = ar_emul_replace_bfd (after_bfd, libdeps_bfd,
1509 verbose);
1511 else
1513 replaced = ar_emul_replace (after_bfd, *files_to_move,
1514 target, verbose);
1516 if (replaced)
1518 /* Snip out this entry from the chain. */
1519 *current_ptr = (*current_ptr)->archive_next;
1520 changed = true;
1523 goto next_file;
1525 current_ptr = &(current->archive_next);
1529 /* Add to the end of the archive. */
1530 after_bfd = get_pos_bfd (&arch->archive_next, pos_end, NULL);
1532 if (libdeps_bfd != NULL
1533 && FILENAME_CMP (normalize (*files_to_move, arch), LIBDEPS) == 0)
1535 changed |= ar_emul_append_bfd (after_bfd, libdeps_bfd,
1536 verbose, make_thin_archive);
1538 else
1540 changed |= ar_emul_append (after_bfd, *files_to_move, target,
1541 verbose, make_thin_archive);
1544 next_file:;
1546 files_to_move++;
1549 if (changed)
1550 write_archive (arch);
1551 else
1552 output_filename = NULL;
1555 static int
1556 ranlib_only (const char *archname)
1558 bfd *arch;
1560 if (get_file_size (archname) < 1)
1561 return 1;
1562 write_armap = 1;
1563 arch = open_inarch (archname, (char *) NULL);
1564 if (arch == NULL)
1565 xexit (1);
1566 write_archive (arch);
1567 return 0;
1570 /* Update the timestamp of the symbol map of an archive. */
1572 static int
1573 ranlib_touch (const char *archname)
1575 #ifdef __GO32__
1576 /* I don't think updating works on go32. */
1577 ranlib_only (archname);
1578 #else
1579 int f;
1580 bfd *arch;
1581 char **matching;
1583 if (get_file_size (archname) < 1)
1584 return 1;
1585 f = open (archname, O_RDWR | O_BINARY, 0);
1586 if (f < 0)
1588 bfd_set_error (bfd_error_system_call);
1589 bfd_fatal (archname);
1592 arch = bfd_fdopenr (archname, (const char *) NULL, f);
1593 if (arch == NULL)
1594 bfd_fatal (archname);
1595 if (! bfd_check_format_matches (arch, bfd_archive, &matching))
1597 bfd_nonfatal (archname);
1598 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1599 list_matching_formats (matching);
1600 xexit (1);
1603 if (! bfd_has_map (arch))
1604 /* xgettext:c-format */
1605 fatal (_("%s: no archive map to update"), archname);
1607 if (deterministic)
1608 arch->flags |= BFD_DETERMINISTIC_OUTPUT;
1610 bfd_update_armap_timestamp (arch);
1612 if (! bfd_close (arch))
1613 bfd_fatal (archname);
1614 #endif
1615 return 0;
1618 /* Things which are interesting to map over all or some of the files: */
1620 static void
1621 print_descr (bfd *abfd)
1623 print_arelt_descr (stdout, abfd, verbose, display_offsets);