1 /* ar.c - Archive modify and extract.
2 Copyright (C) 1991-2021 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. */
28 #include "libiberty.h"
34 #include "filenames.h"
36 #include "plugin-api.h"
41 #define EXT_NAME_LEN 3 /* Bufflen of addition to name if it's MS-DOS. */
43 #define EXT_NAME_LEN 6 /* Ditto for *NIX. */
46 /* Static declarations. */
48 static void mri_emul (void);
49 static const char *normalize (const char *, bfd *);
50 static void remove_output (void);
51 static void map_over_members (bfd *, void (*)(bfd *), char **, int);
52 static void print_contents (bfd * member);
53 static void delete_members (bfd *, char **files_to_delete);
55 static void move_members (bfd *, char **files_to_move);
56 static void replace_members
57 (bfd *, char **files_to_replace, bool quick);
58 static void print_descr (bfd * abfd);
59 static void write_archive (bfd *);
60 static int ranlib_only (const char *archname);
61 static int ranlib_touch (const char *archname);
62 static void usage (int);
64 /** Globals and flags. */
68 /* This flag distinguishes between ar and ranlib:
69 1 means this is 'ranlib'; 0 means this is 'ar'.
70 -1 means if we should use argv[0] to decide. */
73 /* Nonzero means don't warn about creating the archive file if necessary. */
74 int silent_create = 0;
76 /* Nonzero means describe each action performed. */
79 /* Nonzero means display offsets of files in the archive. */
80 int display_offsets = 0;
82 /* Nonzero means preserve dates of members when extracting them. */
83 int preserve_dates = 0;
85 /* Nonzero means don't replace existing members whose dates are more recent
86 than the corresponding files. */
89 /* Controls the writing of an archive symbol table (in BSD: a __.SYMDEF
90 member). -1 means we've been explicitly asked to not write a symbol table;
91 +1 means we've been explicitly asked to write it;
93 Traditionally, the default in BSD has been to not write the table.
94 However, for POSIX.2 compliance the default is now to write a symbol table
95 if any of the members are object files. */
98 /* Operate in deterministic mode: write zero for timestamps, uids,
99 and gids for archive members and the archive symbol table, and write
100 consistent file modes. */
101 int deterministic = -1; /* Determinism indeterminate. */
103 /* Nonzero means it's the name of an existing member; position new or moved
104 files with respect to this one. */
105 char *posname = NULL;
107 /* Sez how to use `posname': pos_before means position before that member.
108 pos_after means position after that member. pos_end means always at end.
109 pos_default means default appropriately. For the latter two, `posname'
110 should also be zero. */
113 pos_default, pos_before, pos_after, pos_end
114 } postype = pos_default;
118 none = 0, del, replace, print_table,
119 print_files, extract, move, quick_append
123 get_pos_bfd (bfd **, enum pos, const char *);
125 /* For extract/delete only. If COUNTED_NAME_MODE is TRUE, we only
126 extract the COUNTED_NAME_COUNTER instance of that name. */
127 static bool counted_name_mode = 0;
128 static int counted_name_counter = 0;
130 /* Whether to truncate names of files stored in the archive. */
131 static bool ar_truncate = false;
133 /* Whether to use a full file name match when searching an archive.
134 This is convenient for archives created by the Microsoft lib
136 static bool full_pathname = false;
138 /* Whether to create a "thin" archive (symbol index only -- no files). */
139 static bool make_thin_archive = false;
141 #define LIBDEPS "__.LIBDEP"
142 /* Text to store in the __.LIBDEP archive element for the linker to use. */
143 static char * libdeps = NULL;
144 static bfd * libdeps_bfd = NULL;
146 static int show_version = 0;
148 static int show_help = 0;
150 #if BFD_SUPPORTS_PLUGINS
151 static const char *plugin_target = "plugin";
153 static const char *plugin_target = NULL;
156 static const char *target = NULL;
158 enum long_option_numbers
165 static const char * output_dir = NULL;
167 static struct option long_options[] =
169 {"help", no_argument, &show_help, 1},
170 {"plugin", required_argument, NULL, OPTION_PLUGIN},
171 {"target", required_argument, NULL, OPTION_TARGET},
172 {"version", no_argument, &show_version, 1},
173 {"output", required_argument, NULL, OPTION_OUTPUT},
174 {"record-libdeps", required_argument, NULL, 'l'},
175 {NULL, no_argument, NULL, 0}
183 interactive = isatty (fileno (stdin));
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. */
192 map_over_members (bfd *arch, void (*function)(bfd *), char **files, int count)
199 for (head = arch->archive_next; head; head = head->archive_next)
207 /* This may appear to be a baroque way of accomplishing what we want.
208 However we have to iterate over the filenames in order to notice where
209 a filename is requested but does not exist in the archive. Ditto
210 mapping over each file each time -- we want to hack multiple
213 for (head = arch->archive_next; head; head = head->archive_next)
214 head->archive_pass = 0;
216 for (; count > 0; files++, count--)
221 for (head = arch->archive_next; head; head = head->archive_next)
223 const char * filename;
226 /* PR binutils/15796: Once an archive element has been matched
227 do not match it again. If the user provides multiple same-named
228 parameters on the command line their intent is to match multiple
229 same-named entries in the archive, not the same entry multiple
231 if (head->archive_pass)
234 filename = bfd_get_filename (head);
235 if (filename == NULL)
237 /* Some archive formats don't get the filenames filled in
238 until the elements are opened. */
240 bfd_stat_arch_elt (head, &buf);
242 else if (bfd_is_thin_archive (arch))
244 /* Thin archives store full pathnames. Need to normalize. */
245 filename = normalize (filename, arch);
249 && !FILENAME_CMP (normalize (*files, arch), filename))
252 if (counted_name_mode
253 && match_count != counted_name_counter)
255 /* Counting, and didn't match on count; go on to the
262 head->archive_pass = 1;
263 /* PR binutils/15796: Once a file has been matched, do not
264 match any more same-named files in the archive. If the
265 user does want to match multiple same-name files in an
266 archive they should provide multiple same-name parameters
267 to the ar command. */
273 /* xgettext:c-format */
274 fprintf (stderr, _("no entry %s in archive\n"), *files);
278 bool operation_alters_arch = false;
285 #if BFD_SUPPORTS_PLUGINS
286 /* xgettext:c-format */
287 const char *command_line
288 = _("Usage: %s [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV]"
289 " [--plugin <name>] [member-name] [count] archive-file file...\n");
292 /* xgettext:c-format */
293 const char *command_line
294 = _("Usage: %s [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV]"
295 " [member-name] [count] archive-file file...\n");
297 s = help ? stdout : stderr;
299 fprintf (s, command_line, program_name);
301 /* xgettext:c-format */
302 fprintf (s, _(" %s -M [<mri-script]\n"), program_name);
303 fprintf (s, _(" commands:\n"));
304 fprintf (s, _(" d - delete file(s) from the archive\n"));
305 fprintf (s, _(" m[ab] - move file(s) in the archive\n"));
306 fprintf (s, _(" p - print file(s) found in the archive\n"));
307 fprintf (s, _(" q[f] - quick append file(s) to the archive\n"));
308 fprintf (s, _(" r[ab][f][u] - replace existing or insert new file(s) into the archive\n"));
309 fprintf (s, _(" s - act as ranlib\n"));
310 fprintf (s, _(" t[O][v] - display contents of the archive\n"));
311 fprintf (s, _(" x[o] - extract file(s) from the archive\n"));
312 fprintf (s, _(" command specific modifiers:\n"));
313 fprintf (s, _(" [a] - put file(s) after [member-name]\n"));
314 fprintf (s, _(" [b] - put file(s) before [member-name] (same as [i])\n"));
315 if (DEFAULT_AR_DETERMINISTIC)
318 [D] - use zero for timestamps and uids/gids (default)\n"));
320 [U] - use actual timestamps and uids/gids\n"));
325 [D] - use zero for timestamps and uids/gids\n"));
327 [U] - use actual timestamps and uids/gids (default)\n"));
329 fprintf (s, _(" [N] - use instance [count] of name\n"));
330 fprintf (s, _(" [f] - truncate inserted file names\n"));
331 fprintf (s, _(" [P] - use full path names when matching\n"));
332 fprintf (s, _(" [o] - preserve original dates\n"));
333 fprintf (s, _(" [O] - display offsets of files in the archive\n"));
334 fprintf (s, _(" [u] - only replace files that are newer than current archive contents\n"));
335 fprintf (s, _(" generic modifiers:\n"));
336 fprintf (s, _(" [c] - do not warn if the library had to be created\n"));
337 fprintf (s, _(" [s] - create an archive index (cf. ranlib)\n"));
338 fprintf (s, _(" [l <text> ] - specify the dependencies of this library\n"));
339 fprintf (s, _(" [S] - do not build a symbol table\n"));
340 fprintf (s, _(" [T] - make a thin archive\n"));
341 fprintf (s, _(" [v] - be verbose\n"));
342 fprintf (s, _(" [V] - display the version number\n"));
343 fprintf (s, _(" @<file> - read options from <file>\n"));
344 fprintf (s, _(" --target=BFDNAME - specify the target object format as BFDNAME\n"));
345 fprintf (s, _(" --output=DIRNAME - specify the output directory for extraction operations\n"));
346 fprintf (s, _(" --record-libdeps=<text> - specify the dependencies of this library\n"));
347 #if BFD_SUPPORTS_PLUGINS
348 fprintf (s, _(" optional:\n"));
349 fprintf (s, _(" --plugin <p> - load the specified plugin\n"));
354 list_supported_targets (program_name, s);
356 if (REPORT_BUGS_TO[0] && help)
357 fprintf (s, _("Report bugs to %s\n"), REPORT_BUGS_TO);
359 xexit (help ? 0 : 1);
363 ranlib_usage (int help)
367 s = help ? stdout : stderr;
369 /* xgettext:c-format */
370 fprintf (s, _("Usage: %s [options] archive\n"), program_name);
371 fprintf (s, _(" Generate an index to speed access to archives\n"));
372 fprintf (s, _(" The options are:\n\
373 @<file> Read options from <file>\n"));
374 #if BFD_SUPPORTS_PLUGINS
376 --plugin <name> Load the specified plugin\n"));
378 if (DEFAULT_AR_DETERMINISTIC)
380 -D Use zero for symbol map timestamp (default)\n\
381 -U Use an actual symbol map timestamp\n"));
384 -D Use zero for symbol map timestamp\n\
385 -U Use actual symbol map timestamp (default)\n"));
387 -t Update the archive's symbol map timestamp\n\
388 -h --help Print this help message\n\
389 -v --version Print version information\n"));
391 list_supported_targets (program_name, s);
393 if (REPORT_BUGS_TO[0] && help)
394 fprintf (s, _("Report bugs to %s\n"), REPORT_BUGS_TO);
396 xexit (help ? 0 : 1);
399 /* Normalize a file name specified on the command line into a file
400 name which we will use in an archive. */
403 normalize (const char *file, bfd *abfd)
405 const char *filename;
410 filename = lbasename (file);
414 && strlen (filename) > abfd->xvec->ar_max_namelen)
419 s = (char *) xmalloc (abfd->xvec->ar_max_namelen + 1);
420 memcpy (s, filename, abfd->xvec->ar_max_namelen);
421 s[abfd->xvec->ar_max_namelen] = '\0';
428 /* Remove any output file. This is only called via xatexit. */
430 static const char *output_filename = NULL;
431 static FILE *output_file = NULL;
432 static bfd *output_bfd = NULL;
437 if (output_filename != NULL)
439 if (output_bfd != NULL)
440 bfd_cache_close (output_bfd);
441 if (output_file != NULL)
442 fclose (output_file);
443 unlink_if_ordinary (output_filename);
448 decode_options (int argc, char **argv)
452 /* Convert old-style ar call by exploding option element and rearranging
453 options accordingly. */
456 if (argc > 1 && argv[1][0] != '-')
458 int new_argc; /* argc value for rearranged arguments */
459 char **new_argv; /* argv value for rearranged arguments */
460 char *const *in; /* cursor into original argv */
461 char **out; /* cursor into rearranged argv */
462 const char *letter; /* cursor into old option letters */
463 char buffer[3]; /* constructed option buffer */
465 /* Initialize a constructed option. */
470 /* Allocate a new argument array, and copy program name in it. */
472 new_argc = argc - 1 + strlen (argv[1]);
473 new_argv = xmalloc ((new_argc + 1) * sizeof (*argv));
478 /* Copy each old letter option as a separate option. */
480 for (letter = *in++; *letter; letter++)
483 *out++ = xstrdup (buffer);
486 /* Copy all remaining options. */
488 while (in < argv + argc)
492 /* Replace the old option list by the new one. */
498 while ((c = getopt_long (argc, argv, "hdmpqrtxl:coOVsSuvabiMNfPTDU",
499 long_options, NULL)) != EOF)
510 if (operation != none)
511 fatal (_("two different operation options specified"));
522 operation_alters_arch = true;
526 operation_alters_arch = true;
529 operation = print_files;
532 operation = quick_append;
533 operation_alters_arch = true;
537 operation_alters_arch = true;
540 operation = print_table;
547 fatal (_("libdeps specified more than once"));
578 postype = pos_before;
581 postype = pos_before;
587 counted_name_mode = true;
593 full_pathname = true;
596 make_thin_archive = true;
599 deterministic = true;
602 deterministic = false;
605 #if BFD_SUPPORTS_PLUGINS
606 bfd_plugin_set_plugin (optarg);
608 fprintf (stderr, _("sorry - this program has been built without plugin support\n"));
618 case 0: /* A long option that just sets a flag. */
625 /* PR 13256: Allow for the possibility that the first command line option
626 started with a dash (eg --plugin) but then the following option(s) are
627 old style, non-dash-prefixed versions. */
628 if (operation == none && write_armap != 1 && !mri_mode
629 && optind > 0 && optind < argc)
631 argv += (optind - 1);
632 argc -= (optind - 1);
637 return &argv[optind];
640 /* If neither -D nor -U was specified explicitly,
641 then use the configured default. */
643 default_deterministic (void)
645 if (deterministic < 0)
646 deterministic = DEFAULT_AR_DETERMINISTIC;
650 ranlib_main (int argc, char **argv)
652 int arg_index, status = 0;
656 while ((c = getopt_long (argc, argv, "DhHUvVt", long_options, NULL)) != EOF)
661 deterministic = true;
664 deterministic = false;
678 /* PR binutils/13493: Support plugins. */
680 #if BFD_SUPPORTS_PLUGINS
681 bfd_plugin_set_plugin (optarg);
683 fprintf (stderr, _("sorry - this program has been built without plugin support\n"));
697 print_version ("ranlib");
699 default_deterministic ();
703 while (arg_index < argc)
706 status |= ranlib_only (argv[arg_index]);
708 status |= ranlib_touch (argv[arg_index]);
715 int main (int, char **);
718 main (int argc, char **argv)
723 char *inarch_filename;
726 #ifdef HAVE_LC_MESSAGES
727 setlocale (LC_MESSAGES, "");
729 setlocale (LC_CTYPE, "");
730 bindtextdomain (PACKAGE, LOCALEDIR);
731 textdomain (PACKAGE);
733 program_name = argv[0];
734 xmalloc_set_program_name (program_name);
735 bfd_set_error_program_name (program_name);
736 #if BFD_SUPPORTS_PLUGINS
737 bfd_plugin_set_program_name (program_name);
740 expandargv (&argc, &argv);
744 const char *temp = lbasename (program_name);
746 if (strlen (temp) >= 6
747 && FILENAME_CMP (temp + strlen (temp) - 6, "ranlib") == 0)
753 START_PROGRESS (program_name, 0);
755 if (bfd_init () != BFD_INIT_MAGIC)
756 fatal (_("fatal error: libbfd ABI mismatch"));
757 set_default_bfd_target ();
759 xatexit (remove_output);
761 for (i = 1; i < argc; i++)
762 if (! ar_emul_parse_arg (argv[i]))
768 ranlib_main (argc, argv);
773 argv = decode_options (argc, argv);
779 print_version ("ar");
785 default_deterministic ();
792 /* Fail if no files are specified on the command line.
793 (But not for MRI mode which allows for reading arguments
794 and filenames from stdin). */
795 if (argv[arg_index] == NULL)
798 /* We don't use do_quick_append any more. Too many systems
799 expect ar to always rebuild the symbol table even when q is
802 /* We can't write an armap when using ar q, so just do ar r
804 if (operation == quick_append && write_armap)
807 if ((operation == none || operation == print_table)
809 xexit (ranlib_only (argv[arg_index]));
811 if (operation == none)
812 fatal (_("no operation specified"));
814 if (newer_only && operation != replace)
815 fatal (_("`u' is only meaningful with the `r' option."));
817 if (newer_only && deterministic > 0)
818 fatal (_("`u' is not meaningful with the `D' option."));
820 if (newer_only && deterministic < 0 && DEFAULT_AR_DETERMINISTIC)
822 `u' modifier ignored since `D' is the default (see `U')"));
824 default_deterministic ();
826 if (postype != pos_default)
828 posname = argv[arg_index++];
830 fatal (_("missing position arg."));
833 if (counted_name_mode)
835 if (operation != extract && operation != del)
836 fatal (_("`N' is only meaningful with the `x' and `d' options."));
837 if (argv[arg_index] == NULL)
838 fatal (_("`N' missing value."));
839 counted_name_counter = atoi (argv[arg_index++]);
840 if (counted_name_counter <= 0)
841 fatal (_("Value for `N' must be positive."));
844 inarch_filename = argv[arg_index++];
845 if (inarch_filename == NULL)
848 for (file_count = 0; argv[arg_index + file_count] != NULL; file_count++)
851 files = (file_count > 0) ? argv + arg_index : NULL;
853 arch = open_inarch (inarch_filename,
854 files == NULL ? (char *) NULL : files[0]);
856 if (operation == extract && bfd_is_thin_archive (arch))
857 fatal (_("`x' cannot be used on thin archives."));
862 bfd_size_type reclen = strlen (libdeps) + 1;
864 /* Create a bfd to contain the dependencies.
865 It inherits its type from arch, but we must set the type to
866 "binary" otherwise bfd_bwrite() will fail. After writing, we
867 must set the type back to default otherwise adding it to the
868 archive will fail. */
869 libdeps_bfd = bfd_create (LIBDEPS, arch);
870 if (libdeps_bfd == NULL)
871 fatal (_("Cannot create libdeps record."));
873 if (bfd_find_target ("binary", libdeps_bfd) == NULL)
874 fatal (_("Cannot set libdeps record type to binary."));
876 if (! bfd_set_format (libdeps_bfd, bfd_object))
877 fatal (_("Cannot set libdeps object format."));
879 if (! bfd_make_writable (libdeps_bfd))
880 fatal (_("Cannot make libdeps object writable."));
882 if (bfd_bwrite (libdeps, reclen, libdeps_bfd) != reclen)
883 fatal (_("Cannot write libdeps record."));
885 if (! bfd_make_readable (libdeps_bfd))
886 fatal (_("Cannot make libdeps object readable."));
888 if (bfd_find_target (plugin_target, libdeps_bfd) == NULL)
889 fatal (_("Cannot reset libdeps record type."));
891 /* Insert our libdeps record in 2nd slot of the list of files
892 being operated on. We shouldn't use 1st slot, but we want
893 to avoid having to search all the way to the end of an
894 archive with a large number of members at link time. */
895 new_files = xmalloc ((file_count + 2) * sizeof (char *));
896 new_files[0] = files[0];
897 new_files[1] = LIBDEPS;
898 for (i = 1; i < file_count; i++)
899 new_files[i+1] = files[i];
908 map_over_members (arch, print_descr, files, file_count);
912 map_over_members (arch, print_contents, files, file_count);
916 map_over_members (arch, extract_file, files, file_count);
921 delete_members (arch, files);
923 output_filename = NULL;
927 /* PR 12558: Creating and moving at the same time does
928 not make sense. Just create the archive instead. */
932 move_members (arch, files);
934 output_filename = NULL;
941 if (files != NULL || write_armap > 0)
942 replace_members (arch, files, operation == quick_append);
944 output_filename = NULL;
947 /* Shouldn't happen! */
949 /* xgettext:c-format */
950 fatal (_("internal error -- this option not implemented"));
954 END_PROGRESS (program_name);
961 open_inarch (const char *archive_filename, const char *file)
969 bfd_set_error (bfd_error_no_error);
972 target = plugin_target;
974 if (stat (archive_filename, &sbuf) != 0)
976 #if !defined(__GO32__) || defined(__DJGPP__)
978 /* FIXME: I don't understand why this fragment was ifndef'ed
979 away for __GO32__; perhaps it was in the days of DJGPP v1.x.
980 stat() works just fine in v2.x, so I think this should be
981 removed. For now, I enable it for DJGPP v2. -- EZ. */
983 /* KLUDGE ALERT! Temporary fix until I figger why
984 stat() is wrong ... think it's buried in GO32's IDT - Jax */
986 bfd_fatal (archive_filename);
989 if (!operation_alters_arch)
991 fprintf (stderr, "%s: ", program_name);
992 perror (archive_filename);
997 /* If the target isn't set, try to figure out the target to use
998 for the archive from the first object on the list. */
999 if (target == NULL && file != NULL)
1003 obj = bfd_openr (file, target);
1006 if (bfd_check_format (obj, bfd_object))
1007 target = bfd_get_target (obj);
1008 (void) bfd_close (obj);
1012 /* Create an empty archive. */
1013 arch = bfd_openw (archive_filename, target);
1015 || ! bfd_set_format (arch, bfd_archive)
1016 || ! bfd_close (arch))
1017 bfd_fatal (archive_filename);
1018 else if (!silent_create)
1019 non_fatal (_("creating %s"), archive_filename);
1021 /* If we die creating a new archive, don't leave it around. */
1022 output_filename = archive_filename;
1025 arch = bfd_openr (archive_filename, target);
1029 bfd_fatal (archive_filename);
1032 if (! bfd_check_format_matches (arch, bfd_archive, &matching))
1034 bfd_nonfatal (archive_filename);
1035 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1037 list_matching_formats (matching);
1043 if ((operation == replace || operation == quick_append)
1044 && bfd_openr_next_archived_file (arch, NULL) != NULL)
1046 /* PR 15140: Catch attempts to convert a normal
1047 archive into a thin archive or vice versa. */
1048 if (make_thin_archive && ! bfd_is_thin_archive (arch))
1050 fatal (_("Cannot convert existing library %s to thin format"),
1051 bfd_get_filename (arch));
1054 else if (! make_thin_archive && bfd_is_thin_archive (arch))
1056 fatal (_("Cannot convert existing thin library %s to normal format"),
1057 bfd_get_filename (arch));
1062 last_one = &(arch->archive_next);
1063 /* Read all the contents right away, regardless. */
1064 for (next_one = bfd_openr_next_archived_file (arch, NULL);
1066 next_one = bfd_openr_next_archived_file (arch, next_one))
1069 *last_one = next_one;
1070 last_one = &next_one->archive_next;
1072 *last_one = (bfd *) NULL;
1073 if (bfd_get_error () != bfd_error_no_more_archived_files)
1079 print_contents (bfd *abfd)
1081 bfd_size_type ncopied = 0;
1083 char *cbuf = (char *) xmalloc (BUFSIZE);
1086 if (bfd_stat_arch_elt (abfd, &buf) != 0)
1087 /* xgettext:c-format */
1088 fatal (_("internal stat error on %s"), bfd_get_filename (abfd));
1091 printf ("\n<%s>\n\n", bfd_get_filename (abfd));
1093 bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
1096 while (ncopied < size)
1098 bfd_size_type nread;
1099 bfd_size_type tocopy = size - ncopied;
1101 if (tocopy > BUFSIZE)
1104 nread = bfd_bread (cbuf, tocopy, abfd);
1105 if (nread != tocopy)
1106 /* xgettext:c-format */
1107 fatal (_("%s is not a valid archive"),
1108 bfd_get_filename (abfd->my_archive));
1110 /* fwrite in mingw32 may return int instead of bfd_size_type. Cast the
1111 return value to bfd_size_type to avoid comparison between signed and
1113 if ((bfd_size_type) fwrite (cbuf, 1, nread, stdout) != nread)
1114 fatal ("stdout: %s", strerror (errno));
1121 static FILE * open_output_file (bfd *) ATTRIBUTE_RETURNS_NONNULL;
1124 open_output_file (bfd * abfd)
1126 output_filename = bfd_get_filename (abfd);
1128 /* PR binutils/17533: Do not allow directory traversal
1129 outside of the current directory tree - unless the
1130 user has explicitly specified an output directory. */
1131 if (! is_valid_archive_path (output_filename))
1133 char * base = (char *) lbasename (output_filename);
1135 non_fatal (_("illegal output pathname for archive member: %s, using '%s' instead"),
1136 output_filename, base);
1137 output_filename = base;
1142 size_t len = strlen (output_dir);
1146 /* FIXME: There is a memory leak here, but it is not serious. */
1147 if (IS_DIR_SEPARATOR (output_dir [len - 1]))
1148 output_filename = concat (output_dir, output_filename, NULL);
1150 output_filename = concat (output_dir, "/", output_filename, NULL);
1155 printf ("x - %s\n", output_filename);
1157 FILE * ostream = fopen (output_filename, FOPEN_WB);
1158 if (ostream == NULL)
1160 perror (output_filename);
1167 /* Extract a member of the archive into its own file.
1169 We defer opening the new file until after we have read a BUFSIZ chunk of the
1170 old one, since we know we have just read the archive header for the old
1171 one. Since most members are shorter than BUFSIZ, this means we will read
1172 the old header, read the old data, write a new inode for the new file, and
1173 write the new data, and be done. This 'optimization' is what comes from
1174 sitting next to a bare disk and hearing it every time it seeks. -- Gnu
1178 extract_file (bfd *abfd)
1184 memset (&buf, 0, sizeof (buf));
1186 if (bfd_stat_arch_elt (abfd, &buf) != 0)
1187 /* xgettext:c-format */
1188 fatal (_("internal stat error on %s"), bfd_get_filename (abfd));
1191 bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
1196 output_file = open_output_file (abfd);
1200 bfd_size_type ncopied = 0;
1201 char *cbuf = (char *) xmalloc (BUFSIZE);
1203 while (ncopied < size)
1205 bfd_size_type nread, tocopy;
1207 tocopy = size - ncopied;
1208 if (tocopy > BUFSIZE)
1211 nread = bfd_bread (cbuf, tocopy, abfd);
1212 if (nread != tocopy)
1213 /* xgettext:c-format */
1214 fatal (_("%s is not a valid archive"),
1215 bfd_get_filename (abfd->my_archive));
1217 /* See comment above; this saves disk arm motion. */
1218 if (output_file == NULL)
1219 output_file = open_output_file (abfd);
1221 /* fwrite in mingw32 may return int instead of bfd_size_type. Cast
1222 the return value to bfd_size_type to avoid comparison between
1223 signed and unsigned values. */
1224 if ((bfd_size_type) fwrite (cbuf, 1, nread, output_file) != nread)
1225 fatal ("%s: %s", output_filename, strerror (errno));
1233 fclose (output_file);
1237 chmod (output_filename, buf.st_mode);
1241 /* Set access time to modification time. Only st_mtime is
1242 initialized by bfd_stat_arch_elt. */
1243 buf.st_atime = buf.st_mtime;
1244 set_times (output_filename, &buf);
1247 output_filename = NULL;
1251 write_archive (bfd *iarch)
1254 char *old_name, *new_name;
1255 bfd *contents_head = iarch->archive_next;
1258 old_name = xstrdup (bfd_get_filename (iarch));
1259 new_name = make_tempname (old_name, &tmpfd);
1261 if (new_name == NULL)
1262 bfd_fatal (_("could not create temporary file whilst writing archive"));
1264 output_filename = new_name;
1266 obfd = bfd_fdopenw (new_name, bfd_get_target (iarch), tmpfd);
1271 bfd_fatal (old_name);
1276 bfd_set_format (obfd, bfd_archive);
1278 /* Request writing the archive symbol table unless we've
1279 been explicitly requested not to. */
1280 obfd->has_armap = write_armap >= 0;
1284 /* This should really use bfd_set_file_flags, but that rejects
1286 obfd->flags |= BFD_TRADITIONAL_FORMAT;
1290 obfd->flags |= BFD_DETERMINISTIC_OUTPUT;
1293 obfd->flags |= BFD_ARCHIVE_FULL_PATH;
1295 if (make_thin_archive || bfd_is_thin_archive (iarch))
1296 bfd_set_thin_archive (obfd, true);
1298 if (!bfd_set_archive_head (obfd, contents_head))
1299 bfd_fatal (old_name);
1301 tmpfd = dup (tmpfd);
1302 if (!bfd_close (obfd))
1303 bfd_fatal (old_name);
1306 output_filename = NULL;
1308 /* We don't care if this fails; we might be creating the archive. */
1311 if (smart_rename (new_name, old_name, tmpfd, NULL, false) != 0)
1317 /* Return a pointer to the pointer to the entry which should be rplacd'd
1318 into when altering. DEFAULT_POS should be how to interpret pos_default,
1319 and should be a pos value. */
1322 get_pos_bfd (bfd **contents, enum pos default_pos, const char *default_posname)
1324 bfd **after_bfd = contents;
1326 const char *realposname;
1328 if (postype == pos_default)
1330 realpos = default_pos;
1331 realposname = default_posname;
1336 realposname = posname;
1339 if (realpos == pos_end)
1342 after_bfd = &((*after_bfd)->archive_next);
1346 for (; *after_bfd; after_bfd = &(*after_bfd)->archive_next)
1347 if (FILENAME_CMP (bfd_get_filename (*after_bfd), realposname) == 0)
1349 if (realpos == pos_after)
1350 after_bfd = &(*after_bfd)->archive_next;
1358 delete_members (bfd *arch, char **files_to_delete)
1360 bfd **current_ptr_ptr;
1362 bool something_changed = false;
1365 for (; *files_to_delete != NULL; ++files_to_delete)
1367 /* In a.out systems, the armap is optional. It's also called
1368 __.SYMDEF. So if the user asked to delete it, we should remember
1369 that fact. This isn't quite right for COFF systems (where
1370 __.SYMDEF might be regular member), but it's very unlikely
1371 to be a problem. FIXME */
1373 if (!strcmp (*files_to_delete, "__.SYMDEF"))
1375 arch->has_armap = false;
1382 current_ptr_ptr = &(arch->archive_next);
1383 while (*current_ptr_ptr)
1385 if (FILENAME_CMP (normalize (*files_to_delete, arch),
1386 bfd_get_filename (*current_ptr_ptr)) == 0)
1389 if (counted_name_mode
1390 && match_count != counted_name_counter)
1392 /* Counting, and didn't match on count; go on to the
1398 something_changed = true;
1402 *current_ptr_ptr = ((*current_ptr_ptr)->archive_next);
1407 current_ptr_ptr = &((*current_ptr_ptr)->archive_next);
1410 if (verbose && !found)
1412 /* xgettext:c-format */
1413 printf (_("No member named `%s'\n"), *files_to_delete);
1419 if (something_changed)
1420 write_archive (arch);
1422 output_filename = NULL;
1426 /* Reposition existing members within an archive */
1429 move_members (bfd *arch, char **files_to_move)
1431 bfd **after_bfd; /* New entries go after this one */
1432 bfd **current_ptr_ptr; /* cdr pointer into contents */
1434 for (; *files_to_move; ++files_to_move)
1436 current_ptr_ptr = &(arch->archive_next);
1437 while (*current_ptr_ptr)
1439 bfd *current_ptr = *current_ptr_ptr;
1440 if (FILENAME_CMP (normalize (*files_to_move, arch),
1441 bfd_get_filename (current_ptr)) == 0)
1443 /* Move this file to the end of the list - first cut from
1446 *current_ptr_ptr = current_ptr->archive_next;
1448 /* Now glue to end */
1449 after_bfd = get_pos_bfd (&arch->archive_next, pos_end, NULL);
1450 link_bfd = *after_bfd;
1451 *after_bfd = current_ptr;
1452 current_ptr->archive_next = link_bfd;
1455 printf ("m - %s\n", *files_to_move);
1460 current_ptr_ptr = &((*current_ptr_ptr)->archive_next);
1462 /* xgettext:c-format */
1463 fatal (_("no entry %s in archive %s!"), *files_to_move,
1464 bfd_get_filename (arch));
1469 write_archive (arch);
1472 /* Ought to default to replacing in place, but this is existing practice! */
1475 replace_members (bfd *arch, char **files_to_move, bool quick)
1477 bool changed = false;
1478 bfd **after_bfd; /* New entries go after this one. */
1482 while (files_to_move && *files_to_move)
1486 current_ptr = &arch->archive_next;
1487 while (*current_ptr)
1489 current = *current_ptr;
1491 /* For compatibility with existing ar programs, we
1492 permit the same file to be added multiple times. */
1493 if (FILENAME_CMP (normalize (*files_to_move, arch),
1494 normalize (bfd_get_filename (current), arch)) == 0
1495 && current->arelt_data != NULL)
1500 struct stat fsbuf, asbuf;
1502 if (stat (*files_to_move, &fsbuf) != 0)
1504 if (errno != ENOENT)
1505 bfd_fatal (*files_to_move);
1508 if (bfd_stat_arch_elt (current, &asbuf) != 0)
1509 /* xgettext:c-format */
1510 fatal (_("internal stat error on %s"),
1511 bfd_get_filename (current));
1513 if (fsbuf.st_mtime <= asbuf.st_mtime)
1517 after_bfd = get_pos_bfd (&arch->archive_next, pos_after,
1518 bfd_get_filename (current));
1519 if (libdeps_bfd != NULL
1520 && FILENAME_CMP (normalize (*files_to_move, arch),
1523 replaced = ar_emul_replace_bfd (after_bfd, libdeps_bfd,
1528 replaced = ar_emul_replace (after_bfd, *files_to_move,
1533 /* Snip out this entry from the chain. */
1534 *current_ptr = (*current_ptr)->archive_next;
1540 current_ptr = &(current->archive_next);
1544 /* Add to the end of the archive. */
1545 after_bfd = get_pos_bfd (&arch->archive_next, pos_end, NULL);
1547 if (libdeps_bfd != NULL
1548 && FILENAME_CMP (normalize (*files_to_move, arch), LIBDEPS) == 0)
1550 changed |= ar_emul_append_bfd (after_bfd, libdeps_bfd,
1551 verbose, make_thin_archive);
1555 changed |= ar_emul_append (after_bfd, *files_to_move, target,
1556 verbose, make_thin_archive);
1565 write_archive (arch);
1567 output_filename = NULL;
1571 ranlib_only (const char *archname)
1575 if (get_file_size (archname) < 1)
1578 arch = open_inarch (archname, (char *) NULL);
1581 write_archive (arch);
1585 /* Update the timestamp of the symbol map of an archive. */
1588 ranlib_touch (const char *archname)
1591 /* I don't think updating works on go32. */
1592 ranlib_only (archname);
1598 if (get_file_size (archname) < 1)
1600 f = open (archname, O_RDWR | O_BINARY, 0);
1603 bfd_set_error (bfd_error_system_call);
1604 bfd_fatal (archname);
1607 arch = bfd_fdopenr (archname, (const char *) NULL, f);
1609 bfd_fatal (archname);
1610 if (! bfd_check_format_matches (arch, bfd_archive, &matching))
1612 bfd_nonfatal (archname);
1613 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1615 list_matching_formats (matching);
1621 if (! bfd_has_map (arch))
1622 /* xgettext:c-format */
1623 fatal (_("%s: no archive map to update"), archname);
1626 arch->flags |= BFD_DETERMINISTIC_OUTPUT;
1628 bfd_update_armap_timestamp (arch);
1630 if (! bfd_close (arch))
1631 bfd_fatal (archname);
1636 /* Things which are interesting to map over all or some of the files: */
1639 print_descr (bfd *abfd)
1641 print_arelt_descr (stdout, abfd, verbose, display_offsets);