Update email address for Palmer Dabbelt.
[deliverable/binutils-gdb.git] / binutils / ar.c
1 /* ar.c - Archive modify and extract.
2 Copyright (C) 1991-2019 Free Software Foundation, Inc.
3
4 This file is part of GNU Binutils.
5
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.
10
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.
15
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. */
20 \f
21 /*
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. */
25
26 #include "sysdep.h"
27 #include "bfd.h"
28 #include "libiberty.h"
29 #include "progress.h"
30 #include "getopt.h"
31 #include "aout/ar.h"
32 #include "bucomm.h"
33 #include "arsup.h"
34 #include "filenames.h"
35 #include "binemul.h"
36 #include "plugin-api.h"
37 #include "plugin.h"
38 #include "ansidecl.h"
39
40 #ifdef __GO32___
41 #define EXT_NAME_LEN 3 /* Bufflen of addition to name if it's MS-DOS. */
42 #else
43 #define EXT_NAME_LEN 6 /* Ditto for *NIX. */
44 #endif
45
46 /* Static declarations. */
47
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);
54
55 static void move_members (bfd *, char **files_to_move);
56 static void replace_members
57 (bfd *, char **files_to_replace, bfd_boolean 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);
63 \f
64 /** Globals and flags. */
65
66 static int mri_mode;
67
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. */
71 extern int is_ranlib;
72
73 /* Nonzero means don't warn about creating the archive file if necessary. */
74 int silent_create = 0;
75
76 /* Nonzero means describe each action performed. */
77 int verbose = 0;
78
79 /* Nonzero means display offsets of files in the archive. */
80 int display_offsets = 0;
81
82 /* Nonzero means preserve dates of members when extracting them. */
83 int preserve_dates = 0;
84
85 /* Nonzero means don't replace existing members whose dates are more recent
86 than the corresponding files. */
87 int newer_only = 0;
88
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;
92 0 is the default.
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. */
96 int write_armap = 0;
97
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. */
102
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;
106
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. */
111 enum pos
112 {
113 pos_default, pos_before, pos_after, pos_end
114 } postype = pos_default;
115
116 enum operations
117 {
118 none = 0, del, replace, print_table,
119 print_files, extract, move, quick_append
120 } operation = none;
121
122 static bfd **
123 get_pos_bfd (bfd **, enum pos, const char *);
124
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 bfd_boolean counted_name_mode = 0;
128 static int counted_name_counter = 0;
129
130 /* Whether to truncate names of files stored in the archive. */
131 static bfd_boolean ar_truncate = FALSE;
132
133 /* Whether to use a full file name match when searching an archive.
134 This is convenient for archives created by the Microsoft lib
135 program. */
136 static bfd_boolean full_pathname = FALSE;
137
138 /* Whether to create a "thin" archive (symbol index only -- no files). */
139 static bfd_boolean make_thin_archive = FALSE;
140
141 static int show_version = 0;
142
143 static int show_help = 0;
144
145 #if BFD_SUPPORTS_PLUGINS
146 static const char *plugin_target = "plugin";
147 #else
148 static const char *plugin_target = NULL;
149 #endif
150
151 static const char *target = NULL;
152
153 enum long_option_numbers
154 {
155 OPTION_PLUGIN = 201,
156 OPTION_TARGET,
157 OPTION_OUTPUT
158 };
159
160 static const char * output_dir = NULL;
161
162 static struct option long_options[] =
163 {
164 {"help", no_argument, &show_help, 1},
165 {"plugin", required_argument, NULL, OPTION_PLUGIN},
166 {"target", required_argument, NULL, OPTION_TARGET},
167 {"version", no_argument, &show_version, 1},
168 {"output", required_argument, NULL, OPTION_OUTPUT},
169 {NULL, no_argument, NULL, 0}
170 };
171
172 int interactive = 0;
173
174 static void
175 mri_emul (void)
176 {
177 interactive = isatty (fileno (stdin));
178 yyparse ();
179 }
180
181 /* If COUNT is 0, then FUNCTION is called once on each entry. If nonzero,
182 COUNT is the length of the FILES chain; FUNCTION is called on each entry
183 whose name matches one in FILES. */
184
185 static void
186 map_over_members (bfd *arch, void (*function)(bfd *), char **files, int count)
187 {
188 bfd *head;
189 int match_count;
190
191 if (count == 0)
192 {
193 for (head = arch->archive_next; head; head = head->archive_next)
194 {
195 PROGRESS (1);
196 function (head);
197 }
198 return;
199 }
200
201 /* This may appear to be a baroque way of accomplishing what we want.
202 However we have to iterate over the filenames in order to notice where
203 a filename is requested but does not exist in the archive. Ditto
204 mapping over each file each time -- we want to hack multiple
205 references. */
206
207 for (head = arch->archive_next; head; head = head->archive_next)
208 head->archive_pass = 0;
209
210 for (; count > 0; files++, count--)
211 {
212 bfd_boolean found = FALSE;
213
214 match_count = 0;
215 for (head = arch->archive_next; head; head = head->archive_next)
216 {
217 const char * filename;
218
219 PROGRESS (1);
220 /* PR binutils/15796: Once an archive element has been matched
221 do not match it again. If the user provides multiple same-named
222 parameters on the command line their intent is to match multiple
223 same-named entries in the archive, not the same entry multiple
224 times. */
225 if (head->archive_pass)
226 continue;
227
228 filename = head->filename;
229 if (filename == NULL)
230 {
231 /* Some archive formats don't get the filenames filled in
232 until the elements are opened. */
233 struct stat buf;
234 bfd_stat_arch_elt (head, &buf);
235 }
236 else if (bfd_is_thin_archive (arch))
237 {
238 /* Thin archives store full pathnames. Need to normalize. */
239 filename = normalize (filename, arch);
240 }
241
242 if (filename != NULL
243 && !FILENAME_CMP (normalize (*files, arch), filename))
244 {
245 ++match_count;
246 if (counted_name_mode
247 && match_count != counted_name_counter)
248 {
249 /* Counting, and didn't match on count; go on to the
250 next one. */
251 continue;
252 }
253
254 found = TRUE;
255 function (head);
256 head->archive_pass = 1;
257 /* PR binutils/15796: Once a file has been matched, do not
258 match any more same-named files in the archive. If the
259 user does want to match multiple same-name files in an
260 archive they should provide multiple same-name parameters
261 to the ar command. */
262 break;
263 }
264 }
265
266 if (!found)
267 /* xgettext:c-format */
268 fprintf (stderr, _("no entry %s in archive\n"), *files);
269 }
270 }
271 \f
272 bfd_boolean operation_alters_arch = FALSE;
273
274 static void
275 usage (int help)
276 {
277 FILE *s;
278
279 #if BFD_SUPPORTS_PLUGINS
280 /* xgettext:c-format */
281 const char *command_line
282 = _("Usage: %s [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV]"
283 " [--plugin <name>] [member-name] [count] archive-file file...\n");
284
285 #else
286 /* xgettext:c-format */
287 const char *command_line
288 = _("Usage: %s [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV]"
289 " [member-name] [count] archive-file file...\n");
290 #endif
291 s = help ? stdout : stderr;
292
293 fprintf (s, command_line, program_name);
294
295 /* xgettext:c-format */
296 fprintf (s, _(" %s -M [<mri-script]\n"), program_name);
297 fprintf (s, _(" commands:\n"));
298 fprintf (s, _(" d - delete file(s) from the archive\n"));
299 fprintf (s, _(" m[ab] - move file(s) in the archive\n"));
300 fprintf (s, _(" p - print file(s) found in the archive\n"));
301 fprintf (s, _(" q[f] - quick append file(s) to the archive\n"));
302 fprintf (s, _(" r[ab][f][u] - replace existing or insert new file(s) into the archive\n"));
303 fprintf (s, _(" s - act as ranlib\n"));
304 fprintf (s, _(" t[O][v] - display contents of the archive\n"));
305 fprintf (s, _(" x[o] - extract file(s) from the archive\n"));
306 fprintf (s, _(" command specific modifiers:\n"));
307 fprintf (s, _(" [a] - put file(s) after [member-name]\n"));
308 fprintf (s, _(" [b] - put file(s) before [member-name] (same as [i])\n"));
309 if (DEFAULT_AR_DETERMINISTIC)
310 {
311 fprintf (s, _("\
312 [D] - use zero for timestamps and uids/gids (default)\n"));
313 fprintf (s, _("\
314 [U] - use actual timestamps and uids/gids\n"));
315 }
316 else
317 {
318 fprintf (s, _("\
319 [D] - use zero for timestamps and uids/gids\n"));
320 fprintf (s, _("\
321 [U] - use actual timestamps and uids/gids (default)\n"));
322 }
323 fprintf (s, _(" [N] - use instance [count] of name\n"));
324 fprintf (s, _(" [f] - truncate inserted file names\n"));
325 fprintf (s, _(" [P] - use full path names when matching\n"));
326 fprintf (s, _(" [o] - preserve original dates\n"));
327 fprintf (s, _(" [O] - display offsets of files in the archive\n"));
328 fprintf (s, _(" [u] - only replace files that are newer than current archive contents\n"));
329 fprintf (s, _(" generic modifiers:\n"));
330 fprintf (s, _(" [c] - do not warn if the library had to be created\n"));
331 fprintf (s, _(" [s] - create an archive index (cf. ranlib)\n"));
332 fprintf (s, _(" [S] - do not build a symbol table\n"));
333 fprintf (s, _(" [T] - make a thin archive\n"));
334 fprintf (s, _(" [v] - be verbose\n"));
335 fprintf (s, _(" [V] - display the version number\n"));
336 fprintf (s, _(" @<file> - read options from <file>\n"));
337 fprintf (s, _(" --target=BFDNAME - specify the target object format as BFDNAME\n"));
338 fprintf (s, _(" --output=DIRNAME - specify the output directory for extraction operations\n"));
339 #if BFD_SUPPORTS_PLUGINS
340 fprintf (s, _(" optional:\n"));
341 fprintf (s, _(" --plugin <p> - load the specified plugin\n"));
342 #endif
343
344 ar_emul_usage (s);
345
346 list_supported_targets (program_name, s);
347
348 if (REPORT_BUGS_TO[0] && help)
349 fprintf (s, _("Report bugs to %s\n"), REPORT_BUGS_TO);
350
351 xexit (help ? 0 : 1);
352 }
353
354 static void
355 ranlib_usage (int help)
356 {
357 FILE *s;
358
359 s = help ? stdout : stderr;
360
361 /* xgettext:c-format */
362 fprintf (s, _("Usage: %s [options] archive\n"), program_name);
363 fprintf (s, _(" Generate an index to speed access to archives\n"));
364 fprintf (s, _(" The options are:\n\
365 @<file> Read options from <file>\n"));
366 #if BFD_SUPPORTS_PLUGINS
367 fprintf (s, _("\
368 --plugin <name> Load the specified plugin\n"));
369 #endif
370 if (DEFAULT_AR_DETERMINISTIC)
371 fprintf (s, _("\
372 -D Use zero for symbol map timestamp (default)\n\
373 -U Use an actual symbol map timestamp\n"));
374 else
375 fprintf (s, _("\
376 -D Use zero for symbol map timestamp\n\
377 -U Use actual symbol map timestamp (default)\n"));
378 fprintf (s, _("\
379 -t Update the archive's symbol map timestamp\n\
380 -h --help Print this help message\n\
381 -v --version Print version information\n"));
382
383 list_supported_targets (program_name, s);
384
385 if (REPORT_BUGS_TO[0] && help)
386 fprintf (s, _("Report bugs to %s\n"), REPORT_BUGS_TO);
387
388 xexit (help ? 0 : 1);
389 }
390
391 /* Normalize a file name specified on the command line into a file
392 name which we will use in an archive. */
393
394 static const char *
395 normalize (const char *file, bfd *abfd)
396 {
397 const char *filename;
398
399 if (full_pathname)
400 return file;
401
402 filename = lbasename (file);
403
404 if (ar_truncate
405 && abfd != NULL
406 && strlen (filename) > abfd->xvec->ar_max_namelen)
407 {
408 char *s;
409
410 /* Space leak. */
411 s = (char *) xmalloc (abfd->xvec->ar_max_namelen + 1);
412 memcpy (s, filename, abfd->xvec->ar_max_namelen);
413 s[abfd->xvec->ar_max_namelen] = '\0';
414 filename = s;
415 }
416
417 return filename;
418 }
419
420 /* Remove any output file. This is only called via xatexit. */
421
422 static const char *output_filename = NULL;
423 static FILE *output_file = NULL;
424 static bfd *output_bfd = NULL;
425
426 static void
427 remove_output (void)
428 {
429 if (output_filename != NULL)
430 {
431 if (output_bfd != NULL)
432 bfd_cache_close (output_bfd);
433 if (output_file != NULL)
434 fclose (output_file);
435 unlink_if_ordinary (output_filename);
436 }
437 }
438
439 static char **
440 decode_options (int argc, char **argv)
441 {
442 int c;
443
444 /* Convert old-style ar call by exploding option element and rearranging
445 options accordingly. */
446
447 restart:
448 if (argc > 1 && argv[1][0] != '-')
449 {
450 int new_argc; /* argc value for rearranged arguments */
451 char **new_argv; /* argv value for rearranged arguments */
452 char *const *in; /* cursor into original argv */
453 char **out; /* cursor into rearranged argv */
454 const char *letter; /* cursor into old option letters */
455 char buffer[3]; /* constructed option buffer */
456
457 /* Initialize a constructed option. */
458
459 buffer[0] = '-';
460 buffer[2] = '\0';
461
462 /* Allocate a new argument array, and copy program name in it. */
463
464 new_argc = argc - 1 + strlen (argv[1]);
465 new_argv = xmalloc ((new_argc + 1) * sizeof (*argv));
466 in = argv;
467 out = new_argv;
468 *out++ = *in++;
469
470 /* Copy each old letter option as a separate option. */
471
472 for (letter = *in++; *letter; letter++)
473 {
474 buffer[1] = *letter;
475 *out++ = xstrdup (buffer);
476 }
477
478 /* Copy all remaining options. */
479
480 while (in < argv + argc)
481 *out++ = *in++;
482 *out = NULL;
483
484 /* Replace the old option list by the new one. */
485
486 argc = new_argc;
487 argv = new_argv;
488 }
489
490 while ((c = getopt_long (argc, argv, "hdmpqrtxlcoOVsSuvabiMNfPTDU",
491 long_options, NULL)) != EOF)
492 {
493 switch (c)
494 {
495 case 'd':
496 case 'm':
497 case 'p':
498 case 'q':
499 case 'r':
500 case 't':
501 case 'x':
502 if (operation != none)
503 fatal (_("two different operation options specified"));
504 break;
505 }
506
507 switch (c)
508 {
509 case 'h':
510 show_help = 1;
511 break;
512 case 'd':
513 operation = del;
514 operation_alters_arch = TRUE;
515 break;
516 case 'm':
517 operation = move;
518 operation_alters_arch = TRUE;
519 break;
520 case 'p':
521 operation = print_files;
522 break;
523 case 'q':
524 operation = quick_append;
525 operation_alters_arch = TRUE;
526 break;
527 case 'r':
528 operation = replace;
529 operation_alters_arch = TRUE;
530 break;
531 case 't':
532 operation = print_table;
533 break;
534 case 'x':
535 operation = extract;
536 break;
537 case 'l':
538 break;
539 case 'c':
540 silent_create = 1;
541 break;
542 case 'o':
543 preserve_dates = 1;
544 break;
545 case 'O':
546 display_offsets = 1;
547 break;
548 case 'V':
549 show_version = TRUE;
550 break;
551 case 's':
552 write_armap = 1;
553 break;
554 case 'S':
555 write_armap = -1;
556 break;
557 case 'u':
558 newer_only = 1;
559 break;
560 case 'v':
561 verbose = 1;
562 break;
563 case 'a':
564 postype = pos_after;
565 break;
566 case 'b':
567 postype = pos_before;
568 break;
569 case 'i':
570 postype = pos_before;
571 break;
572 case 'M':
573 mri_mode = 1;
574 break;
575 case 'N':
576 counted_name_mode = TRUE;
577 break;
578 case 'f':
579 ar_truncate = TRUE;
580 break;
581 case 'P':
582 full_pathname = TRUE;
583 break;
584 case 'T':
585 make_thin_archive = TRUE;
586 break;
587 case 'D':
588 deterministic = TRUE;
589 break;
590 case 'U':
591 deterministic = FALSE;
592 break;
593 case OPTION_PLUGIN:
594 #if BFD_SUPPORTS_PLUGINS
595 bfd_plugin_set_plugin (optarg);
596 #else
597 fprintf (stderr, _("sorry - this program has been built without plugin support\n"));
598 xexit (1);
599 #endif
600 break;
601 case OPTION_TARGET:
602 target = optarg;
603 break;
604 case OPTION_OUTPUT:
605 output_dir = optarg;
606 break;
607 case 0: /* A long option that just sets a flag. */
608 break;
609 default:
610 usage (0);
611 }
612 }
613
614 /* PR 13256: Allow for the possibility that the first command line option
615 started with a dash (eg --plugin) but then the following option(s) are
616 old style, non-dash-prefixed versions. */
617 if (operation == none && write_armap != 1 && !mri_mode
618 && optind > 0 && optind < argc)
619 {
620 argv += (optind - 1);
621 argc -= (optind - 1);
622 optind = 0;
623 goto restart;
624 }
625
626 return &argv[optind];
627 }
628
629 /* If neither -D nor -U was specified explicitly,
630 then use the configured default. */
631 static void
632 default_deterministic (void)
633 {
634 if (deterministic < 0)
635 deterministic = DEFAULT_AR_DETERMINISTIC;
636 }
637
638 static void
639 ranlib_main (int argc, char **argv)
640 {
641 int arg_index, status = 0;
642 bfd_boolean touch = FALSE;
643 int c;
644
645 while ((c = getopt_long (argc, argv, "DhHUvVt", long_options, NULL)) != EOF)
646 {
647 switch (c)
648 {
649 case 'D':
650 deterministic = TRUE;
651 break;
652 case 'U':
653 deterministic = FALSE;
654 break;
655 case 'h':
656 case 'H':
657 show_help = 1;
658 break;
659 case 't':
660 touch = TRUE;
661 break;
662 case 'v':
663 case 'V':
664 show_version = 1;
665 break;
666
667 /* PR binutils/13493: Support plugins. */
668 case OPTION_PLUGIN:
669 #if BFD_SUPPORTS_PLUGINS
670 bfd_plugin_set_plugin (optarg);
671 #else
672 fprintf (stderr, _("sorry - this program has been built without plugin support\n"));
673 xexit (1);
674 #endif
675 break;
676 }
677 }
678
679 if (argc < 2)
680 ranlib_usage (0);
681
682 if (show_help)
683 ranlib_usage (1);
684
685 if (show_version)
686 print_version ("ranlib");
687
688 default_deterministic ();
689
690 arg_index = optind;
691
692 while (arg_index < argc)
693 {
694 if (! touch)
695 status |= ranlib_only (argv[arg_index]);
696 else
697 status |= ranlib_touch (argv[arg_index]);
698 ++arg_index;
699 }
700
701 xexit (status);
702 }
703
704 int main (int, char **);
705
706 int
707 main (int argc, char **argv)
708 {
709 int arg_index;
710 char **files;
711 int file_count;
712 char *inarch_filename;
713 int i;
714
715 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
716 setlocale (LC_MESSAGES, "");
717 #endif
718 #if defined (HAVE_SETLOCALE)
719 setlocale (LC_CTYPE, "");
720 #endif
721 bindtextdomain (PACKAGE, LOCALEDIR);
722 textdomain (PACKAGE);
723
724 program_name = argv[0];
725 xmalloc_set_program_name (program_name);
726 bfd_set_error_program_name (program_name);
727 #if BFD_SUPPORTS_PLUGINS
728 bfd_plugin_set_program_name (program_name);
729 #endif
730
731 expandargv (&argc, &argv);
732
733 if (is_ranlib < 0)
734 {
735 const char *temp = lbasename (program_name);
736
737 if (strlen (temp) >= 6
738 && FILENAME_CMP (temp + strlen (temp) - 6, "ranlib") == 0)
739 is_ranlib = 1;
740 else
741 is_ranlib = 0;
742 }
743
744 START_PROGRESS (program_name, 0);
745
746 if (bfd_init () != BFD_INIT_MAGIC)
747 fatal (_("fatal error: libbfd ABI mismatch"));
748 set_default_bfd_target ();
749
750 xatexit (remove_output);
751
752 for (i = 1; i < argc; i++)
753 if (! ar_emul_parse_arg (argv[i]))
754 break;
755 argv += (i - 1);
756 argc -= (i - 1);
757
758 if (is_ranlib)
759 ranlib_main (argc, argv);
760
761 if (argc < 2)
762 usage (0);
763
764 argv = decode_options (argc, argv);
765
766 if (show_help)
767 usage (1);
768
769 if (show_version)
770 print_version ("ar");
771
772 arg_index = 0;
773
774 if (mri_mode)
775 {
776 default_deterministic ();
777 mri_emul ();
778 }
779 else
780 {
781 bfd *arch;
782
783 /* Fail if no files are specified on the command line.
784 (But not for MRI mode which allows for reading arguments
785 and filenames from stdin). */
786 if (argv[arg_index] == NULL)
787 usage (0);
788
789 /* We don't use do_quick_append any more. Too many systems
790 expect ar to always rebuild the symbol table even when q is
791 used. */
792
793 /* We can't write an armap when using ar q, so just do ar r
794 instead. */
795 if (operation == quick_append && write_armap)
796 operation = replace;
797
798 if ((operation == none || operation == print_table)
799 && write_armap == 1)
800 xexit (ranlib_only (argv[arg_index]));
801
802 if (operation == none)
803 fatal (_("no operation specified"));
804
805 if (newer_only && operation != replace)
806 fatal (_("`u' is only meaningful with the `r' option."));
807
808 if (newer_only && deterministic > 0)
809 fatal (_("`u' is not meaningful with the `D' option."));
810
811 if (newer_only && deterministic < 0 && DEFAULT_AR_DETERMINISTIC)
812 non_fatal (_("\
813 `u' modifier ignored since `D' is the default (see `U')"));
814
815 default_deterministic ();
816
817 if (postype != pos_default)
818 {
819 posname = argv[arg_index++];
820 if (posname == NULL)
821 fatal (_("missing position arg."));
822 }
823
824 if (counted_name_mode)
825 {
826 if (operation != extract && operation != del)
827 fatal (_("`N' is only meaningful with the `x' and `d' options."));
828 if (argv[arg_index] == NULL)
829 fatal (_("`N' missing value."));
830 counted_name_counter = atoi (argv[arg_index++]);
831 if (counted_name_counter <= 0)
832 fatal (_("Value for `N' must be positive."));
833 }
834
835 inarch_filename = argv[arg_index++];
836 if (inarch_filename == NULL)
837 usage (0);
838
839 for (file_count = 0; argv[arg_index + file_count] != NULL; file_count++)
840 continue;
841
842 files = (file_count > 0) ? argv + arg_index : NULL;
843
844 arch = open_inarch (inarch_filename,
845 files == NULL ? (char *) NULL : files[0]);
846
847 if (operation == extract && bfd_is_thin_archive (arch))
848 fatal (_("`x' cannot be used on thin archives."));
849
850 switch (operation)
851 {
852 case print_table:
853 map_over_members (arch, print_descr, files, file_count);
854 break;
855
856 case print_files:
857 map_over_members (arch, print_contents, files, file_count);
858 break;
859
860 case extract:
861 map_over_members (arch, extract_file, files, file_count);
862 break;
863
864 case del:
865 if (files != NULL)
866 delete_members (arch, files);
867 else
868 output_filename = NULL;
869 break;
870
871 case move:
872 /* PR 12558: Creating and moving at the same time does
873 not make sense. Just create the archive instead. */
874 if (! silent_create)
875 {
876 if (files != NULL)
877 move_members (arch, files);
878 else
879 output_filename = NULL;
880 break;
881 }
882 /* Fall through. */
883
884 case replace:
885 case quick_append:
886 if (files != NULL || write_armap > 0)
887 replace_members (arch, files, operation == quick_append);
888 else
889 output_filename = NULL;
890 break;
891
892 /* Shouldn't happen! */
893 default:
894 /* xgettext:c-format */
895 fatal (_("internal error -- this option not implemented"));
896 }
897 }
898
899 END_PROGRESS (program_name);
900
901 xexit (0);
902 return 0;
903 }
904
905 bfd *
906 open_inarch (const char *archive_filename, const char *file)
907 {
908 bfd **last_one;
909 bfd *next_one;
910 struct stat sbuf;
911 bfd *arch;
912 char **matching;
913
914 bfd_set_error (bfd_error_no_error);
915
916 if (target == NULL)
917 target = plugin_target;
918
919 if (stat (archive_filename, &sbuf) != 0)
920 {
921 #if !defined(__GO32__) || defined(__DJGPP__)
922
923 /* FIXME: I don't understand why this fragment was ifndef'ed
924 away for __GO32__; perhaps it was in the days of DJGPP v1.x.
925 stat() works just fine in v2.x, so I think this should be
926 removed. For now, I enable it for DJGPP v2. -- EZ. */
927
928 /* KLUDGE ALERT! Temporary fix until I figger why
929 stat() is wrong ... think it's buried in GO32's IDT - Jax */
930 if (errno != ENOENT)
931 bfd_fatal (archive_filename);
932 #endif
933
934 if (!operation_alters_arch)
935 {
936 fprintf (stderr, "%s: ", program_name);
937 perror (archive_filename);
938 maybequit ();
939 return NULL;
940 }
941
942 /* If the target isn't set, try to figure out the target to use
943 for the archive from the first object on the list. */
944 if (target == NULL && file != NULL)
945 {
946 bfd *obj;
947
948 obj = bfd_openr (file, target);
949 if (obj != NULL)
950 {
951 if (bfd_check_format (obj, bfd_object))
952 target = bfd_get_target (obj);
953 (void) bfd_close (obj);
954 }
955 }
956
957 /* Create an empty archive. */
958 arch = bfd_openw (archive_filename, target);
959 if (arch == NULL
960 || ! bfd_set_format (arch, bfd_archive)
961 || ! bfd_close (arch))
962 bfd_fatal (archive_filename);
963 else if (!silent_create)
964 non_fatal (_("creating %s"), archive_filename);
965
966 /* If we die creating a new archive, don't leave it around. */
967 output_filename = archive_filename;
968 }
969
970 arch = bfd_openr (archive_filename, target);
971 if (arch == NULL)
972 {
973 bloser:
974 bfd_fatal (archive_filename);
975 }
976
977 if (! bfd_check_format_matches (arch, bfd_archive, &matching))
978 {
979 bfd_nonfatal (archive_filename);
980 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
981 {
982 list_matching_formats (matching);
983 free (matching);
984 }
985 xexit (1);
986 }
987
988 if ((operation == replace || operation == quick_append)
989 && bfd_openr_next_archived_file (arch, NULL) != NULL)
990 {
991 /* PR 15140: Catch attempts to convert a normal
992 archive into a thin archive or vice versa. */
993 if (make_thin_archive && ! bfd_is_thin_archive (arch))
994 {
995 fatal (_("Cannot convert existing library %s to thin format"),
996 bfd_get_filename (arch));
997 goto bloser;
998 }
999 else if (! make_thin_archive && bfd_is_thin_archive (arch))
1000 {
1001 fatal (_("Cannot convert existing thin library %s to normal format"),
1002 bfd_get_filename (arch));
1003 goto bloser;
1004 }
1005 }
1006
1007 last_one = &(arch->archive_next);
1008 /* Read all the contents right away, regardless. */
1009 for (next_one = bfd_openr_next_archived_file (arch, NULL);
1010 next_one;
1011 next_one = bfd_openr_next_archived_file (arch, next_one))
1012 {
1013 PROGRESS (1);
1014 *last_one = next_one;
1015 last_one = &next_one->archive_next;
1016 }
1017 *last_one = (bfd *) NULL;
1018 if (bfd_get_error () != bfd_error_no_more_archived_files)
1019 goto bloser;
1020 return arch;
1021 }
1022
1023 static void
1024 print_contents (bfd *abfd)
1025 {
1026 bfd_size_type ncopied = 0;
1027 bfd_size_type size;
1028 char *cbuf = (char *) xmalloc (BUFSIZE);
1029 struct stat buf;
1030
1031 if (bfd_stat_arch_elt (abfd, &buf) != 0)
1032 /* xgettext:c-format */
1033 fatal (_("internal stat error on %s"), bfd_get_filename (abfd));
1034
1035 if (verbose)
1036 printf ("\n<%s>\n\n", bfd_get_filename (abfd));
1037
1038 bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
1039
1040 size = buf.st_size;
1041 while (ncopied < size)
1042 {
1043 bfd_size_type nread;
1044 bfd_size_type tocopy = size - ncopied;
1045
1046 if (tocopy > BUFSIZE)
1047 tocopy = BUFSIZE;
1048
1049 nread = bfd_bread (cbuf, tocopy, abfd);
1050 if (nread != tocopy)
1051 /* xgettext:c-format */
1052 fatal (_("%s is not a valid archive"),
1053 bfd_get_filename (abfd->my_archive));
1054
1055 /* fwrite in mingw32 may return int instead of bfd_size_type. Cast the
1056 return value to bfd_size_type to avoid comparison between signed and
1057 unsigned values. */
1058 if ((bfd_size_type) fwrite (cbuf, 1, nread, stdout) != nread)
1059 fatal ("stdout: %s", strerror (errno));
1060 ncopied += tocopy;
1061 }
1062 free (cbuf);
1063 }
1064
1065
1066 static FILE * open_output_file (bfd *) ATTRIBUTE_RETURNS_NONNULL;
1067
1068 static FILE *
1069 open_output_file (bfd * abfd)
1070 {
1071 output_filename = bfd_get_filename (abfd);
1072
1073 if (output_dir)
1074 {
1075 size_t len = strlen (output_dir);
1076
1077 if (len > 0)
1078 {
1079 /* FIXME: There is a memory leak here, but it is not serious. */
1080 if (IS_DIR_SEPARATOR (output_dir [len - 1]))
1081 output_filename = concat (output_dir, output_filename, NULL);
1082 else
1083 output_filename = concat (output_dir, "/", output_filename, NULL);
1084 }
1085 }
1086
1087 /* PR binutils/17533: Do not allow directory traversal
1088 outside of the current directory tree. */
1089 if (! is_valid_archive_path (output_filename))
1090 {
1091 char * base = (char *) lbasename (output_filename);
1092
1093 non_fatal (_("illegal output pathname for archive member: %s, using '%s' instead"),
1094 output_filename, base);
1095 output_filename = base;
1096 }
1097
1098 FILE * ostream = fopen (output_filename, FOPEN_WB);
1099 if (ostream == NULL)
1100 {
1101 perror (output_filename);
1102 xexit (1);
1103 }
1104
1105 return ostream;
1106 }
1107
1108 /* Extract a member of the archive into its own file.
1109
1110 We defer opening the new file until after we have read a BUFSIZ chunk of the
1111 old one, since we know we have just read the archive header for the old
1112 one. Since most members are shorter than BUFSIZ, this means we will read
1113 the old header, read the old data, write a new inode for the new file, and
1114 write the new data, and be done. This 'optimization' is what comes from
1115 sitting next to a bare disk and hearing it every time it seeks. -- Gnu
1116 Gilmore */
1117
1118 void
1119 extract_file (bfd *abfd)
1120 {
1121 bfd_size_type size;
1122 struct stat buf;
1123
1124 if (bfd_stat_arch_elt (abfd, &buf) != 0)
1125 /* xgettext:c-format */
1126 fatal (_("internal stat error on %s"), bfd_get_filename (abfd));
1127 size = buf.st_size;
1128
1129 if (verbose)
1130 printf ("x - %s\n", bfd_get_filename (abfd));
1131
1132 bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
1133
1134 output_file = NULL;
1135 if (size == 0)
1136 {
1137 output_file = open_output_file (abfd);
1138 }
1139 else
1140 {
1141 bfd_size_type ncopied = 0;
1142 char *cbuf = (char *) xmalloc (BUFSIZE);
1143
1144 while (ncopied < size)
1145 {
1146 bfd_size_type nread, tocopy;
1147
1148 tocopy = size - ncopied;
1149 if (tocopy > BUFSIZE)
1150 tocopy = BUFSIZE;
1151
1152 nread = bfd_bread (cbuf, tocopy, abfd);
1153 if (nread != tocopy)
1154 /* xgettext:c-format */
1155 fatal (_("%s is not a valid archive"),
1156 bfd_get_filename (abfd->my_archive));
1157
1158 /* See comment above; this saves disk arm motion. */
1159 if (output_file == NULL)
1160 output_file = open_output_file (abfd);
1161
1162 /* fwrite in mingw32 may return int instead of bfd_size_type. Cast
1163 the return value to bfd_size_type to avoid comparison between
1164 signed and unsigned values. */
1165 if ((bfd_size_type) fwrite (cbuf, 1, nread, output_file) != nread)
1166 fatal ("%s: %s", output_filename, strerror (errno));
1167
1168 ncopied += tocopy;
1169 }
1170
1171 free (cbuf);
1172 }
1173
1174 fclose (output_file);
1175
1176 output_file = NULL;
1177
1178 chmod (output_filename, buf.st_mode);
1179
1180 if (preserve_dates)
1181 {
1182 /* Set access time to modification time. Only st_mtime is
1183 initialized by bfd_stat_arch_elt. */
1184 buf.st_atime = buf.st_mtime;
1185 set_times (output_filename, &buf);
1186 }
1187
1188 output_filename = NULL;
1189 }
1190
1191 static void
1192 write_archive (bfd *iarch)
1193 {
1194 bfd *obfd;
1195 char *old_name, *new_name;
1196 bfd *contents_head = iarch->archive_next;
1197
1198 old_name = (char *) xmalloc (strlen (bfd_get_filename (iarch)) + 1);
1199 strcpy (old_name, bfd_get_filename (iarch));
1200 new_name = make_tempname (old_name);
1201
1202 if (new_name == NULL)
1203 bfd_fatal (_("could not create temporary file whilst writing archive"));
1204
1205 output_filename = new_name;
1206
1207 obfd = bfd_openw (new_name, bfd_get_target (iarch));
1208
1209 if (obfd == NULL)
1210 bfd_fatal (old_name);
1211
1212 output_bfd = obfd;
1213
1214 bfd_set_format (obfd, bfd_archive);
1215
1216 /* Request writing the archive symbol table unless we've
1217 been explicitly requested not to. */
1218 obfd->has_armap = write_armap >= 0;
1219
1220 if (ar_truncate)
1221 {
1222 /* This should really use bfd_set_file_flags, but that rejects
1223 archives. */
1224 obfd->flags |= BFD_TRADITIONAL_FORMAT;
1225 }
1226
1227 if (deterministic)
1228 obfd->flags |= BFD_DETERMINISTIC_OUTPUT;
1229
1230 if (full_pathname)
1231 obfd->flags |= BFD_ARCHIVE_FULL_PATH;
1232
1233 if (make_thin_archive || bfd_is_thin_archive (iarch))
1234 bfd_set_thin_archive (obfd, TRUE);
1235
1236 if (!bfd_set_archive_head (obfd, contents_head))
1237 bfd_fatal (old_name);
1238
1239 if (!bfd_close (obfd))
1240 bfd_fatal (old_name);
1241
1242 output_bfd = NULL;
1243 output_filename = NULL;
1244
1245 /* We don't care if this fails; we might be creating the archive. */
1246 bfd_close (iarch);
1247
1248 if (smart_rename (new_name, old_name, 0) != 0)
1249 xexit (1);
1250 free (old_name);
1251 free (new_name);
1252 }
1253
1254 /* Return a pointer to the pointer to the entry which should be rplacd'd
1255 into when altering. DEFAULT_POS should be how to interpret pos_default,
1256 and should be a pos value. */
1257
1258 static bfd **
1259 get_pos_bfd (bfd **contents, enum pos default_pos, const char *default_posname)
1260 {
1261 bfd **after_bfd = contents;
1262 enum pos realpos;
1263 const char *realposname;
1264
1265 if (postype == pos_default)
1266 {
1267 realpos = default_pos;
1268 realposname = default_posname;
1269 }
1270 else
1271 {
1272 realpos = postype;
1273 realposname = posname;
1274 }
1275
1276 if (realpos == pos_end)
1277 {
1278 while (*after_bfd)
1279 after_bfd = &((*after_bfd)->archive_next);
1280 }
1281 else
1282 {
1283 for (; *after_bfd; after_bfd = &(*after_bfd)->archive_next)
1284 if (FILENAME_CMP ((*after_bfd)->filename, realposname) == 0)
1285 {
1286 if (realpos == pos_after)
1287 after_bfd = &(*after_bfd)->archive_next;
1288 break;
1289 }
1290 }
1291 return after_bfd;
1292 }
1293
1294 static void
1295 delete_members (bfd *arch, char **files_to_delete)
1296 {
1297 bfd **current_ptr_ptr;
1298 bfd_boolean found;
1299 bfd_boolean something_changed = FALSE;
1300 int match_count;
1301
1302 for (; *files_to_delete != NULL; ++files_to_delete)
1303 {
1304 /* In a.out systems, the armap is optional. It's also called
1305 __.SYMDEF. So if the user asked to delete it, we should remember
1306 that fact. This isn't quite right for COFF systems (where
1307 __.SYMDEF might be regular member), but it's very unlikely
1308 to be a problem. FIXME */
1309
1310 if (!strcmp (*files_to_delete, "__.SYMDEF"))
1311 {
1312 arch->has_armap = FALSE;
1313 write_armap = -1;
1314 continue;
1315 }
1316
1317 found = FALSE;
1318 match_count = 0;
1319 current_ptr_ptr = &(arch->archive_next);
1320 while (*current_ptr_ptr)
1321 {
1322 if (FILENAME_CMP (normalize (*files_to_delete, arch),
1323 (*current_ptr_ptr)->filename) == 0)
1324 {
1325 ++match_count;
1326 if (counted_name_mode
1327 && match_count != counted_name_counter)
1328 {
1329 /* Counting, and didn't match on count; go on to the
1330 next one. */
1331 }
1332 else
1333 {
1334 found = TRUE;
1335 something_changed = TRUE;
1336 if (verbose)
1337 printf ("d - %s\n",
1338 *files_to_delete);
1339 *current_ptr_ptr = ((*current_ptr_ptr)->archive_next);
1340 goto next_file;
1341 }
1342 }
1343
1344 current_ptr_ptr = &((*current_ptr_ptr)->archive_next);
1345 }
1346
1347 if (verbose && !found)
1348 {
1349 /* xgettext:c-format */
1350 printf (_("No member named `%s'\n"), *files_to_delete);
1351 }
1352 next_file:
1353 ;
1354 }
1355
1356 if (something_changed)
1357 write_archive (arch);
1358 else
1359 output_filename = NULL;
1360 }
1361
1362
1363 /* Reposition existing members within an archive */
1364
1365 static void
1366 move_members (bfd *arch, char **files_to_move)
1367 {
1368 bfd **after_bfd; /* New entries go after this one */
1369 bfd **current_ptr_ptr; /* cdr pointer into contents */
1370
1371 for (; *files_to_move; ++files_to_move)
1372 {
1373 current_ptr_ptr = &(arch->archive_next);
1374 while (*current_ptr_ptr)
1375 {
1376 bfd *current_ptr = *current_ptr_ptr;
1377 if (FILENAME_CMP (normalize (*files_to_move, arch),
1378 current_ptr->filename) == 0)
1379 {
1380 /* Move this file to the end of the list - first cut from
1381 where it is. */
1382 bfd *link_bfd;
1383 *current_ptr_ptr = current_ptr->archive_next;
1384
1385 /* Now glue to end */
1386 after_bfd = get_pos_bfd (&arch->archive_next, pos_end, NULL);
1387 link_bfd = *after_bfd;
1388 *after_bfd = current_ptr;
1389 current_ptr->archive_next = link_bfd;
1390
1391 if (verbose)
1392 printf ("m - %s\n", *files_to_move);
1393
1394 goto next_file;
1395 }
1396
1397 current_ptr_ptr = &((*current_ptr_ptr)->archive_next);
1398 }
1399 /* xgettext:c-format */
1400 fatal (_("no entry %s in archive %s!"), *files_to_move, arch->filename);
1401
1402 next_file:;
1403 }
1404
1405 write_archive (arch);
1406 }
1407
1408 /* Ought to default to replacing in place, but this is existing practice! */
1409
1410 static void
1411 replace_members (bfd *arch, char **files_to_move, bfd_boolean quick)
1412 {
1413 bfd_boolean changed = FALSE;
1414 bfd **after_bfd; /* New entries go after this one. */
1415 bfd *current;
1416 bfd **current_ptr;
1417
1418 while (files_to_move && *files_to_move)
1419 {
1420 if (! quick)
1421 {
1422 current_ptr = &arch->archive_next;
1423 while (*current_ptr)
1424 {
1425 current = *current_ptr;
1426
1427 /* For compatibility with existing ar programs, we
1428 permit the same file to be added multiple times. */
1429 if (FILENAME_CMP (normalize (*files_to_move, arch),
1430 normalize (current->filename, arch)) == 0
1431 && current->arelt_data != NULL)
1432 {
1433 if (newer_only)
1434 {
1435 struct stat fsbuf, asbuf;
1436
1437 if (stat (*files_to_move, &fsbuf) != 0)
1438 {
1439 if (errno != ENOENT)
1440 bfd_fatal (*files_to_move);
1441 goto next_file;
1442 }
1443 if (bfd_stat_arch_elt (current, &asbuf) != 0)
1444 /* xgettext:c-format */
1445 fatal (_("internal stat error on %s"),
1446 current->filename);
1447
1448 if (fsbuf.st_mtime <= asbuf.st_mtime)
1449 goto next_file;
1450 }
1451
1452 after_bfd = get_pos_bfd (&arch->archive_next, pos_after,
1453 current->filename);
1454 if (ar_emul_replace (after_bfd, *files_to_move,
1455 target, verbose))
1456 {
1457 /* Snip out this entry from the chain. */
1458 *current_ptr = (*current_ptr)->archive_next;
1459 changed = TRUE;
1460 }
1461
1462 goto next_file;
1463 }
1464 current_ptr = &(current->archive_next);
1465 }
1466 }
1467
1468 /* Add to the end of the archive. */
1469 after_bfd = get_pos_bfd (&arch->archive_next, pos_end, NULL);
1470
1471 if (ar_emul_append (after_bfd, *files_to_move, target,
1472 verbose, make_thin_archive))
1473 changed = TRUE;
1474
1475 next_file:;
1476
1477 files_to_move++;
1478 }
1479
1480 if (changed)
1481 write_archive (arch);
1482 else
1483 output_filename = NULL;
1484 }
1485
1486 static int
1487 ranlib_only (const char *archname)
1488 {
1489 bfd *arch;
1490
1491 if (get_file_size (archname) < 1)
1492 return 1;
1493 write_armap = 1;
1494 arch = open_inarch (archname, (char *) NULL);
1495 if (arch == NULL)
1496 xexit (1);
1497 write_archive (arch);
1498 return 0;
1499 }
1500
1501 /* Update the timestamp of the symbol map of an archive. */
1502
1503 static int
1504 ranlib_touch (const char *archname)
1505 {
1506 #ifdef __GO32__
1507 /* I don't think updating works on go32. */
1508 ranlib_only (archname);
1509 #else
1510 int f;
1511 bfd *arch;
1512 char **matching;
1513
1514 if (get_file_size (archname) < 1)
1515 return 1;
1516 f = open (archname, O_RDWR | O_BINARY, 0);
1517 if (f < 0)
1518 {
1519 bfd_set_error (bfd_error_system_call);
1520 bfd_fatal (archname);
1521 }
1522
1523 arch = bfd_fdopenr (archname, (const char *) NULL, f);
1524 if (arch == NULL)
1525 bfd_fatal (archname);
1526 if (! bfd_check_format_matches (arch, bfd_archive, &matching))
1527 {
1528 bfd_nonfatal (archname);
1529 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1530 {
1531 list_matching_formats (matching);
1532 free (matching);
1533 }
1534 xexit (1);
1535 }
1536
1537 if (! bfd_has_map (arch))
1538 /* xgettext:c-format */
1539 fatal (_("%s: no archive map to update"), archname);
1540
1541 if (deterministic)
1542 arch->flags |= BFD_DETERMINISTIC_OUTPUT;
1543
1544 bfd_update_armap_timestamp (arch);
1545
1546 if (! bfd_close (arch))
1547 bfd_fatal (archname);
1548 #endif
1549 return 0;
1550 }
1551
1552 /* Things which are interesting to map over all or some of the files: */
1553
1554 static void
1555 print_descr (bfd *abfd)
1556 {
1557 print_arelt_descr (stdout, abfd, verbose, display_offsets);
1558 }
This page took 0.07671 seconds and 4 git commands to generate.