1 /* ar.c - Archive modify and extract.
2 Copyright (C) 1991-2024 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"
33 #include "filenames.h"
35 #include "plugin-api.h"
40 #define EXT_NAME_LEN 3 /* Bufflen of addition to name if it's MS-DOS. */
42 #define EXT_NAME_LEN 6 /* Ditto for *NIX. */
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. */
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. */
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. */
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. */
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;
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. */
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. */
112 pos_default
, pos_before
, pos_after
, pos_end
113 } postype
= pos_default
;
117 none
= 0, del
, replace
, print_table
,
118 print_files
, extract
, move
, quick_append
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
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";
152 static const char *plugin_target
= NULL
;
155 static const char *target
= NULL
;
157 enum long_option_numbers
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}
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
)
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
210 for (head
= arch
->archive_next
; head
; head
= head
->archive_next
)
211 head
->archive_pass
= 0;
213 for (; count
> 0; files
++, count
--)
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
227 if (head
->archive_pass
)
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. */
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
);
245 && !FILENAME_CMP (normalize (*files
, arch
), filename
))
248 if (counted_name_mode
249 && match_count
!= counted_name_counter
)
251 /* Counting, and didn't match on count; go on to the
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. */
269 /* xgettext:c-format */
270 fprintf (stderr
, _("no entry %s in archive\n"), *files
);
274 bool operation_alters_arch
= false;
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");
288 /* xgettext:c-format */
289 const char *command_line
290 = _("Usage: %s [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV]"
291 " [member-name] [count] archive-file file...\n");
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
)
314 [D] - use zero for timestamps and uids/gids (default)\n"));
316 [U] - use actual timestamps and uids/gids\n"));
321 [D] - use zero for timestamps and uids/gids\n"));
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"));
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);
360 ranlib_usage (int help
)
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
373 --plugin <name> Load the specified plugin\n"));
375 if (DEFAULT_AR_DETERMINISTIC
)
377 -D Use zero for symbol map timestamp (default)\n\
378 -U Use an actual symbol map timestamp\n"));
381 -D Use zero for symbol map timestamp\n\
382 -U Use actual symbol map timestamp (default)\n"));
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. */
400 normalize (const char *file
, bfd
*abfd
)
402 const char *filename
;
407 filename
= lbasename (file
);
411 && strlen (filename
) > abfd
->xvec
->ar_max_namelen
)
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';
425 /* Remove any output file. This is only called via xatexit. */
427 static const char *output_filename
= NULL
;
428 static FILE *output_file
= NULL
;
433 if (output_filename
!= NULL
)
435 if (output_file
!= NULL
)
436 fclose (output_file
);
437 unlink_if_ordinary (output_filename
);
442 decode_options (int argc
, char **argv
)
446 /* Convert old-style ar call by exploding option element and rearranging
447 options accordingly. */
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. */
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
));
472 /* Copy each old letter option as a separate option. */
474 for (letter
= *in
++; *letter
; letter
++)
477 *out
++ = xstrdup (buffer
);
480 /* Copy all remaining options. */
482 while (in
< argv
+ argc
)
486 /* Replace the old option list by the new one. */
492 while ((c
= getopt_long (argc
, argv
, "hdmpqrtxl:coOVsSuvabiMNfPTDU",
493 long_options
, NULL
)) != EOF
)
504 if (operation
!= none
)
505 fatal (_("two different operation options specified"));
516 operation_alters_arch
= true;
520 operation_alters_arch
= true;
523 operation
= print_files
;
526 operation
= quick_append
;
527 operation_alters_arch
= true;
531 operation_alters_arch
= true;
534 operation
= print_table
;
541 fatal (_("libdeps specified more than once"));
572 postype
= pos_before
;
575 postype
= pos_before
;
581 counted_name_mode
= true;
587 full_pathname
= true;
590 make_thin_archive
= true;
593 deterministic
= true;
596 deterministic
= false;
599 #if BFD_SUPPORTS_PLUGINS
600 bfd_plugin_set_plugin (optarg
);
602 fprintf (stderr
, _("sorry - this program has been built without plugin support\n"));
612 case 0: /* A long option that just sets a flag. */
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);
631 return &argv
[optind
];
634 /* If neither -D nor -U was specified explicitly,
635 then use the configured default. */
637 default_deterministic (void)
639 if (deterministic
< 0)
640 deterministic
= DEFAULT_AR_DETERMINISTIC
;
644 ranlib_main (int argc
, char **argv
)
646 int arg_index
, status
= 0;
650 while ((c
= getopt_long (argc
, argv
, "DhHUvVt", long_options
, NULL
)) != EOF
)
655 deterministic
= true;
658 deterministic
= false;
672 /* PR binutils/13493: Support plugins. */
674 #if BFD_SUPPORTS_PLUGINS
675 bfd_plugin_set_plugin (optarg
);
677 fprintf (stderr
, _("sorry - this program has been built without plugin support\n"));
691 print_version ("ranlib");
693 default_deterministic ();
697 while (arg_index
< argc
)
700 status
|= ranlib_only (argv
[arg_index
]);
702 status
|= ranlib_touch (argv
[arg_index
]);
709 int main (int, char **);
712 main (int argc
, char **argv
)
717 char *inarch_filename
;
720 #ifdef HAVE_LC_MESSAGES
721 setlocale (LC_MESSAGES
, "");
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
);
734 expandargv (&argc
, &argv
);
738 const char *temp
= lbasename (program_name
);
740 if (strlen (temp
) >= 6
741 && FILENAME_CMP (temp
+ strlen (temp
) - 6, "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
]))
760 ranlib_main (argc
, argv
);
765 argv
= decode_options (argc
, argv
);
771 print_version ("ar");
777 default_deterministic ();
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
)
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
794 /* We can't write an armap when using ar q, so just do ar r
796 if (operation
== quick_append
&& write_armap
)
799 if ((operation
== none
|| operation
== print_table
)
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 non_fatal (_("`u' is not meaningful with the `D' option - replacement will always happen."));
812 if (newer_only
&& deterministic
< 0 && DEFAULT_AR_DETERMINISTIC
)
814 `u' modifier ignored since `D' is the default (see `U')"));
816 default_deterministic ();
818 if (postype
!= pos_default
)
820 posname
= argv
[arg_index
++];
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
)
840 for (file_count
= 0; argv
[arg_index
+ file_count
] != NULL
; file_count
++)
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."));
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_write() 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_write (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
));
890 new_files
[0] = files
[0];
891 memcpy (new_files
+ 1, files
, file_count
* sizeof (*files
));
893 new_files
[file_count
!= 0] = LIBDEPS
;
895 new_files
[file_count
] = NULL
;
902 map_over_members (arch
, print_descr
, files
, file_count
);
906 map_over_members (arch
, print_contents
, files
, file_count
);
910 map_over_members (arch
, extract_file
, files
, file_count
);
915 delete_members (arch
, files
);
917 output_filename
= NULL
;
921 /* PR 12558: Creating and moving at the same time does
922 not make sense. Just create the archive instead. */
926 move_members (arch
, files
);
928 output_filename
= NULL
;
935 if (files
!= NULL
|| write_armap
> 0)
936 replace_members (arch
, files
, operation
== quick_append
);
938 output_filename
= NULL
;
941 /* Shouldn't happen! */
943 /* xgettext:c-format */
944 fatal (_("internal error -- this option not implemented"));
953 open_inarch (const char *archive_filename
, const char *file
)
961 bfd_set_error (bfd_error_no_error
);
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 */
978 bfd_fatal (archive_filename
);
981 if (!operation_alters_arch
)
983 fprintf (stderr
, "%s: ", program_name
);
984 perror (archive_filename
);
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
)
995 obj
= bfd_openr (file
, target
);
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
);
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
);
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
);
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
));
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
));
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
);
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
)
1067 print_contents (bfd
*abfd
)
1069 bfd_size_type ncopied
= 0;
1071 char *cbuf
= (char *) xmalloc (BUFSIZE
);
1074 if (bfd_stat_arch_elt (abfd
, &buf
) != 0)
1075 /* xgettext:c-format */
1076 fatal (_("internal stat error on %s"), bfd_get_filename (abfd
));
1079 printf ("\n<%s>\n\n", bfd_get_filename (abfd
));
1081 if (bfd_seek (abfd
, 0, SEEK_SET
) != 0)
1082 bfd_fatal (bfd_get_filename (abfd
));
1085 while (ncopied
< size
)
1087 bfd_size_type nread
;
1088 bfd_size_type tocopy
= size
- ncopied
;
1090 if (tocopy
> BUFSIZE
)
1093 nread
= bfd_read (cbuf
, tocopy
, abfd
);
1094 if (nread
!= tocopy
)
1095 /* xgettext:c-format */
1096 fatal (_("%s is not a valid archive"),
1097 bfd_get_filename (abfd
->my_archive
));
1099 /* fwrite in mingw32 may return int instead of bfd_size_type. Cast the
1100 return value to bfd_size_type to avoid comparison between signed and
1102 if ((bfd_size_type
) fwrite (cbuf
, 1, nread
, stdout
) != nread
)
1103 fatal ("stdout: %s", strerror (errno
));
1110 static FILE * open_output_file (bfd
*) ATTRIBUTE_RETURNS_NONNULL
;
1113 open_output_file (bfd
* abfd
)
1115 output_filename
= bfd_get_filename (abfd
);
1117 /* PR binutils/17533: Do not allow directory traversal
1118 outside of the current directory tree - unless the
1119 user has explicitly specified an output directory. */
1120 if (! is_valid_archive_path (output_filename
))
1122 char * base
= (char *) lbasename (output_filename
);
1124 non_fatal (_("illegal output pathname for archive member: %s, using '%s' instead"),
1125 output_filename
, base
);
1126 output_filename
= base
;
1131 size_t len
= strlen (output_dir
);
1135 /* FIXME: There is a memory leak here, but it is not serious. */
1136 if (IS_DIR_SEPARATOR (output_dir
[len
- 1]))
1137 output_filename
= concat (output_dir
, output_filename
, NULL
);
1139 output_filename
= concat (output_dir
, "/", output_filename
, NULL
);
1144 printf ("x - %s\n", output_filename
);
1146 FILE * ostream
= fopen (output_filename
, FOPEN_WB
);
1147 if (ostream
== NULL
)
1149 perror (output_filename
);
1156 /* Extract a member of the archive into its own file.
1158 We defer opening the new file until after we have read a BUFSIZ chunk of the
1159 old one, since we know we have just read the archive header for the old
1160 one. Since most members are shorter than BUFSIZ, this means we will read
1161 the old header, read the old data, write a new inode for the new file, and
1162 write the new data, and be done. This 'optimization' is what comes from
1163 sitting next to a bare disk and hearing it every time it seeks. -- Gnu
1167 extract_file (bfd
*abfd
)
1173 memset (&buf
, 0, sizeof (buf
));
1175 if (bfd_stat_arch_elt (abfd
, &buf
) != 0)
1176 /* xgettext:c-format */
1177 fatal (_("internal stat error on %s"), bfd_get_filename (abfd
));
1180 if (bfd_seek (abfd
, 0, SEEK_SET
) != 0)
1181 bfd_fatal (bfd_get_filename (abfd
));
1186 output_file
= open_output_file (abfd
);
1190 bfd_size_type ncopied
= 0;
1191 char *cbuf
= (char *) xmalloc (BUFSIZE
);
1193 while (ncopied
< size
)
1195 bfd_size_type nread
, tocopy
;
1197 tocopy
= size
- ncopied
;
1198 if (tocopy
> BUFSIZE
)
1201 nread
= bfd_read (cbuf
, tocopy
, abfd
);
1202 if (nread
!= tocopy
)
1203 /* xgettext:c-format */
1204 fatal (_("%s is not a valid archive"),
1205 bfd_get_filename (abfd
->my_archive
));
1207 /* See comment above; this saves disk arm motion. */
1208 if (output_file
== NULL
)
1209 output_file
= open_output_file (abfd
);
1211 /* fwrite in mingw32 may return int instead of bfd_size_type. Cast
1212 the return value to bfd_size_type to avoid comparison between
1213 signed and unsigned values. */
1214 if ((bfd_size_type
) fwrite (cbuf
, 1, nread
, output_file
) != nread
)
1215 fatal ("%s: %s", output_filename
, strerror (errno
));
1223 fclose (output_file
);
1227 chmod (output_filename
, buf
.st_mode
);
1231 /* Set access time to modification time. Only st_mtime is
1232 initialized by bfd_stat_arch_elt. */
1233 buf
.st_atime
= buf
.st_mtime
;
1234 set_times (output_filename
, &buf
);
1237 output_filename
= NULL
;
1241 write_archive (bfd
*iarch
)
1244 char *old_name
, *new_name
;
1245 bfd
*contents_head
= iarch
->archive_next
;
1248 old_name
= xstrdup (bfd_get_filename (iarch
));
1249 new_name
= make_tempname (old_name
, &tmpfd
);
1251 if (new_name
== NULL
)
1252 bfd_fatal (_("could not create temporary file whilst writing archive"));
1254 output_filename
= new_name
;
1256 obfd
= bfd_fdopenw (new_name
, bfd_get_target (iarch
), tmpfd
);
1261 bfd_fatal (old_name
);
1264 bfd_set_format (obfd
, bfd_archive
);
1266 /* Request writing the archive symbol table unless we've
1267 been explicitly requested not to. */
1268 obfd
->has_armap
= write_armap
>= 0;
1272 /* This should really use bfd_set_file_flags, but that rejects
1274 obfd
->flags
|= BFD_TRADITIONAL_FORMAT
;
1278 obfd
->flags
|= BFD_DETERMINISTIC_OUTPUT
;
1281 obfd
->flags
|= BFD_ARCHIVE_FULL_PATH
;
1283 if (make_thin_archive
|| bfd_is_thin_archive (iarch
))
1284 bfd_set_thin_archive (obfd
, true);
1286 if (!bfd_set_archive_head (obfd
, contents_head
))
1287 bfd_fatal (old_name
);
1289 tmpfd
= dup (tmpfd
);
1290 if (!bfd_close (obfd
))
1291 bfd_fatal (old_name
);
1293 output_filename
= NULL
;
1295 /* We don't care if this fails; we might be creating the archive. */
1298 if (smart_rename (new_name
, old_name
, tmpfd
, NULL
, false) != 0)
1304 /* Return a pointer to the pointer to the entry which should be rplacd'd
1305 into when altering. DEFAULT_POS should be how to interpret pos_default,
1306 and should be a pos value. */
1309 get_pos_bfd (bfd
**contents
, enum pos default_pos
, const char *default_posname
)
1311 bfd
**after_bfd
= contents
;
1313 const char *realposname
;
1315 if (postype
== pos_default
)
1317 realpos
= default_pos
;
1318 realposname
= default_posname
;
1323 realposname
= posname
;
1326 if (realpos
== pos_end
)
1329 after_bfd
= &((*after_bfd
)->archive_next
);
1333 for (; *after_bfd
; after_bfd
= &(*after_bfd
)->archive_next
)
1334 if (FILENAME_CMP (bfd_get_filename (*after_bfd
), realposname
) == 0)
1336 if (realpos
== pos_after
)
1337 after_bfd
= &(*after_bfd
)->archive_next
;
1345 delete_members (bfd
*arch
, char **files_to_delete
)
1347 bfd
**current_ptr_ptr
;
1349 bool something_changed
= false;
1352 for (; *files_to_delete
!= NULL
; ++files_to_delete
)
1354 /* In a.out systems, the armap is optional. It's also called
1355 __.SYMDEF. So if the user asked to delete it, we should remember
1356 that fact. This isn't quite right for COFF systems (where
1357 __.SYMDEF might be regular member), but it's very unlikely
1358 to be a problem. FIXME */
1360 if (!strcmp (*files_to_delete
, "__.SYMDEF"))
1362 arch
->has_armap
= false;
1369 current_ptr_ptr
= &(arch
->archive_next
);
1370 while (*current_ptr_ptr
)
1372 if (FILENAME_CMP (normalize (*files_to_delete
, arch
),
1373 bfd_get_filename (*current_ptr_ptr
)) == 0)
1376 if (counted_name_mode
1377 && match_count
!= counted_name_counter
)
1379 /* Counting, and didn't match on count; go on to the
1385 something_changed
= true;
1389 *current_ptr_ptr
= ((*current_ptr_ptr
)->archive_next
);
1394 current_ptr_ptr
= &((*current_ptr_ptr
)->archive_next
);
1397 if (verbose
&& !found
)
1399 /* xgettext:c-format */
1400 printf (_("No member named `%s'\n"), *files_to_delete
);
1406 if (something_changed
)
1407 write_archive (arch
);
1409 output_filename
= NULL
;
1413 /* Reposition existing members within an archive */
1416 move_members (bfd
*arch
, char **files_to_move
)
1418 bfd
**after_bfd
; /* New entries go after this one */
1419 bfd
**current_ptr_ptr
; /* cdr pointer into contents */
1421 for (; *files_to_move
; ++files_to_move
)
1423 current_ptr_ptr
= &(arch
->archive_next
);
1424 while (*current_ptr_ptr
)
1426 bfd
*current_ptr
= *current_ptr_ptr
;
1427 if (FILENAME_CMP (normalize (*files_to_move
, arch
),
1428 bfd_get_filename (current_ptr
)) == 0)
1430 /* Move this file to the end of the list - first cut from
1433 *current_ptr_ptr
= current_ptr
->archive_next
;
1435 /* Now glue to end */
1436 after_bfd
= get_pos_bfd (&arch
->archive_next
, pos_end
, NULL
);
1437 link_bfd
= *after_bfd
;
1438 *after_bfd
= current_ptr
;
1439 current_ptr
->archive_next
= link_bfd
;
1442 printf ("m - %s\n", *files_to_move
);
1447 current_ptr_ptr
= &((*current_ptr_ptr
)->archive_next
);
1449 /* xgettext:c-format */
1450 fatal (_("no entry %s in archive %s!"), *files_to_move
,
1451 bfd_get_filename (arch
));
1456 write_archive (arch
);
1459 /* Ought to default to replacing in place, but this is existing practice! */
1462 replace_members (bfd
*arch
, char **files_to_move
, bool quick
)
1464 bool changed
= false;
1465 bfd
**after_bfd
; /* New entries go after this one. */
1469 while (files_to_move
&& *files_to_move
)
1473 current_ptr
= &arch
->archive_next
;
1474 while (*current_ptr
)
1476 current
= *current_ptr
;
1478 /* For compatibility with existing ar programs, we
1479 permit the same file to be added multiple times. */
1480 if (FILENAME_CMP (normalize (*files_to_move
, arch
),
1481 normalize (bfd_get_filename (current
), arch
)) == 0
1482 && current
->arelt_data
!= NULL
)
1488 struct stat fsbuf
, asbuf
;
1490 if (stat (*files_to_move
, &fsbuf
) != 0)
1492 if (errno
!= ENOENT
)
1493 bfd_fatal (*files_to_move
);
1497 if (bfd_stat_arch_elt (current
, &asbuf
) != 0)
1498 /* xgettext:c-format */
1499 fatal (_("internal stat error on %s"),
1500 bfd_get_filename (current
));
1502 if (fsbuf
.st_mtime
<= asbuf
.st_mtime
)
1503 /* A note about deterministic timestamps: In an
1504 archive created in a determistic manner the
1505 individual elements will either have a timestamp
1506 of 0 or SOURCE_DATE_EPOCH, depending upon the
1507 method used. This will be the value retrieved
1508 by bfd_stat_arch_elt().
1510 The timestamp in fsbuf.st_mtime however will
1511 definitely be greater than 0, and it is unlikely
1512 to be less than SOURCE_DATE_EPOCH. (FIXME:
1513 should we test for this case case and issue an
1516 So in either case fsbuf.st_mtime > asbuf.st_time
1517 and hence the incoming file will replace the
1518 current file. Which is what should be expected to
1519 happen. Deterministic archives have no real sense
1520 of the time/date when their elements were created,
1521 and so any updates to the archive should always
1522 result in replaced files. */
1526 after_bfd
= get_pos_bfd (&arch
->archive_next
, pos_after
,
1527 bfd_get_filename (current
));
1528 if (libdeps_bfd
!= NULL
1529 && FILENAME_CMP (normalize (*files_to_move
, arch
),
1532 replaced
= ar_emul_replace_bfd (after_bfd
, libdeps_bfd
,
1537 replaced
= ar_emul_replace (after_bfd
, *files_to_move
,
1542 /* Snip out this entry from the chain. */
1543 *current_ptr
= (*current_ptr
)->archive_next
;
1549 current_ptr
= &(current
->archive_next
);
1553 /* Add to the end of the archive. */
1554 after_bfd
= get_pos_bfd (&arch
->archive_next
, pos_end
, NULL
);
1556 if (libdeps_bfd
!= NULL
1557 && FILENAME_CMP (normalize (*files_to_move
, arch
), LIBDEPS
) == 0)
1559 changed
|= ar_emul_append_bfd (after_bfd
, libdeps_bfd
,
1560 verbose
, make_thin_archive
);
1564 changed
|= ar_emul_append (after_bfd
, *files_to_move
, target
,
1565 verbose
, make_thin_archive
);
1574 write_archive (arch
);
1576 output_filename
= NULL
;
1580 ranlib_only (const char *archname
)
1584 if (get_file_size (archname
) < 1)
1587 arch
= open_inarch (archname
, (char *) NULL
);
1590 write_archive (arch
);
1594 /* Update the timestamp of the symbol map of an archive. */
1597 ranlib_touch (const char *archname
)
1600 /* I don't think updating works on go32. */
1601 ranlib_only (archname
);
1607 if (get_file_size (archname
) < 1)
1609 f
= open (archname
, O_RDWR
| O_BINARY
, 0);
1612 bfd_set_error (bfd_error_system_call
);
1613 bfd_fatal (archname
);
1616 arch
= bfd_fdopenr (archname
, (const char *) NULL
, f
);
1618 bfd_fatal (archname
);
1619 if (! bfd_check_format_matches (arch
, bfd_archive
, &matching
))
1621 bfd_nonfatal (archname
);
1622 if (bfd_get_error () == bfd_error_file_ambiguously_recognized
)
1623 list_matching_formats (matching
);
1627 if (! bfd_has_map (arch
))
1628 /* xgettext:c-format */
1629 fatal (_("%s: no archive map to update"), archname
);
1632 arch
->flags
|= BFD_DETERMINISTIC_OUTPUT
;
1634 bfd_update_armap_timestamp (arch
);
1636 if (! bfd_close (arch
))
1637 bfd_fatal (archname
);
1642 /* Things which are interesting to map over all or some of the files: */
1645 print_descr (bfd
*abfd
)
1647 print_arelt_descr (stdout
, abfd
, verbose
, display_offsets
);