2010-01-13 Tristan Gingold <gingold@adacore.com>
[external/binutils.git] / binutils / ar.c
1 /* ar.c - Archive modify and extract.
2    Copyright 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5
6    This file is part of GNU Binutils.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21    MA 02110-1301, USA.  */
22 \f
23 /*
24    Bugs: should use getopt the way tar does (complete w/optional -) and
25    should have long options too. GNU ar used to check file against filesystem
26    in quick_update and replace operations (would check mtime). Doesn't warn
27    when name truncated. No way to specify pos_end. Error messages should be
28    more consistent.  */
29
30 #include "sysdep.h"
31 #include "bfd.h"
32 #include "libiberty.h"
33 #include "progress.h"
34 #include "aout/ar.h"
35 #include "libbfd.h"
36 #include "bucomm.h"
37 #include "arsup.h"
38 #include "filenames.h"
39 #include "binemul.h"
40 #include "plugin.h"
41 #include <sys/stat.h>
42
43 #ifdef __GO32___
44 #define EXT_NAME_LEN 3          /* Bufflen of addition to name if it's MS-DOS.  */
45 #else
46 #define EXT_NAME_LEN 6          /* Ditto for *NIX.  */
47 #endif
48
49 /* Static declarations.  */
50
51 static void mri_emul (void);
52 static const char *normalize (const char *, bfd *);
53 static void remove_output (void);
54 static void map_over_members (bfd *, void (*)(bfd *), char **, int);
55 static void print_contents (bfd * member);
56 static void delete_members (bfd *, char **files_to_delete);
57
58 static void move_members (bfd *, char **files_to_move);
59 static void replace_members
60   (bfd *, char **files_to_replace, bfd_boolean quick);
61 static void print_descr (bfd * abfd);
62 static void write_archive (bfd *);
63 static int  ranlib_only (const char *archname);
64 static int  ranlib_touch (const char *archname);
65 static void usage (int);
66 \f
67 /** Globals and flags.  */
68
69 static int mri_mode;
70
71 /* This flag distinguishes between ar and ranlib:
72    1 means this is 'ranlib'; 0 means this is 'ar'.
73    -1 means if we should use argv[0] to decide.  */
74 extern int is_ranlib;
75
76 /* Nonzero means don't warn about creating the archive file if necessary.  */
77 int silent_create = 0;
78
79 /* Nonzero means describe each action performed.  */
80 int verbose = 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 = 0;
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 static bfd **
117 get_pos_bfd (bfd **, enum pos, const char *);
118
119 /* For extract/delete only.  If COUNTED_NAME_MODE is TRUE, we only
120    extract the COUNTED_NAME_COUNTER instance of that name.  */
121 static bfd_boolean counted_name_mode = 0;
122 static int counted_name_counter = 0;
123
124 /* Whether to truncate names of files stored in the archive.  */
125 static bfd_boolean ar_truncate = FALSE;
126
127 /* Whether to use a full file name match when searching an archive.
128    This is convenient for archives created by the Microsoft lib
129    program.  */
130 static bfd_boolean full_pathname = FALSE;
131
132 /* Whether to create a "thin" archive (symbol index only -- no files).  */
133 static bfd_boolean make_thin_archive = FALSE;
134
135 int interactive = 0;
136
137 static void
138 mri_emul (void)
139 {
140   interactive = isatty (fileno (stdin));
141   yyparse ();
142 }
143
144 /* If COUNT is 0, then FUNCTION is called once on each entry.  If nonzero,
145    COUNT is the length of the FILES chain; FUNCTION is called on each entry
146    whose name matches one in FILES.  */
147
148 static void
149 map_over_members (bfd *arch, void (*function)(bfd *), char **files, int count)
150 {
151   bfd *head;
152   int match_count;
153
154   if (count == 0)
155     {
156       for (head = arch->archive_next; head; head = head->archive_next)
157         {
158           PROGRESS (1);
159           function (head);
160         }
161       return;
162     }
163
164   /* This may appear to be a baroque way of accomplishing what we want.
165      However we have to iterate over the filenames in order to notice where
166      a filename is requested but does not exist in the archive.  Ditto
167      mapping over each file each time -- we want to hack multiple
168      references.  */
169
170   for (; count > 0; files++, count--)
171     {
172       bfd_boolean found = FALSE;
173
174       match_count = 0;
175       for (head = arch->archive_next; head; head = head->archive_next)
176         {
177           const char * filename;
178
179           PROGRESS (1);
180           filename = head->filename;
181           if (filename == NULL)
182             {
183               /* Some archive formats don't get the filenames filled in
184                  until the elements are opened.  */
185               struct stat buf;
186               bfd_stat_arch_elt (head, &buf);
187             }
188           else if (bfd_is_thin_archive (arch))
189             {
190               /* Thin archives store full pathnames.  Need to normalize.  */
191               filename = normalize (filename, arch);
192             }
193
194           if ((filename != NULL) &&
195               (!FILENAME_CMP (normalize (*files, arch), filename)))
196             {
197               ++match_count;
198               if (counted_name_mode
199                   && match_count != counted_name_counter)
200                 {
201                   /* Counting, and didn't match on count; go on to the
202                      next one.  */
203                   continue;
204                 }
205
206               found = TRUE;
207               function (head);
208             }
209         }
210
211       if (!found)
212         /* xgettext:c-format */
213         fprintf (stderr, _("no entry %s in archive\n"), *files);
214     }
215 }
216 \f
217 bfd_boolean operation_alters_arch = FALSE;
218
219 static void
220 usage (int help)
221 {
222   FILE *s;
223
224   s = help ? stdout : stderr;
225
226   if (! is_ranlib)
227     {
228       /* xgettext:c-format */
229       const char * command_line =
230 #if BFD_SUPPORTS_PLUGINS
231         _("Usage: %s [emulation options] [--plugin <name>] [-]{dmpqrstx}[abcfilNoPsSuvV] [member-name] [count] archive-file file...\n");
232 #else
233         _("Usage: %s [emulation options] [-]{dmpqrstx}[abcfilNoPsSuvV] [member-name] [count] archive-file file...\n");
234 #endif
235       fprintf (s, command_line, program_name);
236
237       /* xgettext:c-format */
238       fprintf (s, _("       %s -M [<mri-script]\n"), program_name);
239       fprintf (s, _(" commands:\n"));
240       fprintf (s, _("  d            - delete file(s) from the archive\n"));
241       fprintf (s, _("  m[ab]        - move file(s) in the archive\n"));
242       fprintf (s, _("  p            - print file(s) found in the archive\n"));
243       fprintf (s, _("  q[f]         - quick append file(s) to the archive\n"));
244       fprintf (s, _("  r[ab][f][u]  - replace existing or insert new file(s) into the archive\n"));
245       fprintf (s, _("  t            - display contents of archive\n"));
246       fprintf (s, _("  x[o]         - extract file(s) from the archive\n"));
247       fprintf (s, _(" command specific modifiers:\n"));
248       fprintf (s, _("  [a]          - put file(s) after [member-name]\n"));
249       fprintf (s, _("  [b]          - put file(s) before [member-name] (same as [i])\n"));
250       fprintf (s, _("  [D]          - use zero for timestamps and uids/gids\n"));
251       fprintf (s, _("  [N]          - use instance [count] of name\n"));
252       fprintf (s, _("  [f]          - truncate inserted file names\n"));
253       fprintf (s, _("  [P]          - use full path names when matching\n"));
254       fprintf (s, _("  [o]          - preserve original dates\n"));
255       fprintf (s, _("  [u]          - only replace files that are newer than current archive contents\n"));
256       fprintf (s, _(" generic modifiers:\n"));
257       fprintf (s, _("  [c]          - do not warn if the library had to be created\n"));
258       fprintf (s, _("  [s]          - create an archive index (cf. ranlib)\n"));
259       fprintf (s, _("  [S]          - do not build a symbol table\n"));
260       fprintf (s, _("  [T]          - make a thin archive\n"));
261       fprintf (s, _("  [v]          - be verbose\n"));
262       fprintf (s, _("  [V]          - display the version number\n"));
263       fprintf (s, _("  @<file>      - read options from <file>\n"));
264 #if BFD_SUPPORTS_PLUGINS
265       fprintf (s, _(" optional:\n"));
266       fprintf (s, _("  --plugin <p> - load the specified plugin\n"));
267 #endif
268       ar_emul_usage (s);
269     }
270   else
271     {
272       /* xgettext:c-format */
273       fprintf (s, _("Usage: %s [options] archive\n"), program_name);
274       fprintf (s, _(" Generate an index to speed access to archives\n"));
275       fprintf (s, _(" The options are:\n\
276   @<file>                      Read options from <file>\n"));
277 #if BFD_SUPPORTS_PLUGINS
278       fprintf (s, _("\
279   --plugin <name>              Load the specified plugin\n"));
280 #endif
281       fprintf (s, _("\
282   -t                           Update the archive's symbol map timestamp\n\
283   -h --help                    Print this help message\n\
284   -v --version                 Print version information\n"));
285     }
286
287   list_supported_targets (program_name, s);
288
289   if (REPORT_BUGS_TO[0] && help)
290     fprintf (s, _("Report bugs to %s\n"), REPORT_BUGS_TO);
291
292   xexit (help ? 0 : 1);
293 }
294
295 /* Normalize a file name specified on the command line into a file
296    name which we will use in an archive.  */
297
298 static const char *
299 normalize (const char *file, bfd *abfd)
300 {
301   const char *filename;
302
303   if (full_pathname)
304     return file;
305
306   filename = lbasename (file);
307
308   if (ar_truncate
309       && abfd != NULL
310       && strlen (filename) > abfd->xvec->ar_max_namelen)
311     {
312       char *s;
313
314       /* Space leak.  */
315       s = (char *) xmalloc (abfd->xvec->ar_max_namelen + 1);
316       memcpy (s, filename, abfd->xvec->ar_max_namelen);
317       s[abfd->xvec->ar_max_namelen] = '\0';
318       filename = s;
319     }
320
321   return filename;
322 }
323
324 /* Remove any output file.  This is only called via xatexit.  */
325
326 static const char *output_filename = NULL;
327 static FILE *output_file = NULL;
328 static bfd *output_bfd = NULL;
329
330 static void
331 remove_output (void)
332 {
333   if (output_filename != NULL)
334     {
335       if (output_bfd != NULL)
336         bfd_cache_close (output_bfd);
337       if (output_file != NULL)
338         fclose (output_file);
339       unlink_if_ordinary (output_filename);
340     }
341 }
342
343 /* The option parsing should be in its own function.
344    It will be when I have getopt working.  */
345
346 int main (int, char **);
347
348 int
349 main (int argc, char **argv)
350 {
351   char *arg_ptr;
352   char c;
353   enum
354     {
355       none = 0, del, replace, print_table,
356       print_files, extract, move, quick_append
357     } operation = none;
358   int arg_index;
359   char **files;
360   int file_count;
361   char *inarch_filename;
362   int show_version;
363   int i;
364   int do_posix = 0;
365
366 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
367   setlocale (LC_MESSAGES, "");
368 #endif
369 #if defined (HAVE_SETLOCALE)
370   setlocale (LC_CTYPE, "");
371 #endif
372   bindtextdomain (PACKAGE, LOCALEDIR);
373   textdomain (PACKAGE);
374
375   program_name = argv[0];
376   xmalloc_set_program_name (program_name);
377 #if BFD_SUPPORTS_PLUGINS
378   bfd_plugin_set_program_name (program_name);
379 #endif
380
381   expandargv (&argc, &argv);
382
383   if (is_ranlib < 0)
384     {
385       const char *temp = lbasename (program_name);
386
387       if (strlen (temp) >= 6
388           && FILENAME_CMP (temp + strlen (temp) - 6, "ranlib") == 0)
389         is_ranlib = 1;
390       else
391         is_ranlib = 0;
392     }
393
394   if (argc > 1 && argv[1][0] == '-')
395     {
396       if (strcmp (argv[1], "--help") == 0)
397         usage (1);
398       else if (strcmp (argv[1], "--version") == 0)
399         {
400           if (is_ranlib)
401             print_version ("ranlib");
402           else
403             print_version ("ar");
404         }
405     }
406
407   START_PROGRESS (program_name, 0);
408
409   bfd_init ();
410   set_default_bfd_target ();
411
412   show_version = 0;
413
414   xatexit (remove_output);
415
416   for (i = 1; i < argc; i++)
417     if (! ar_emul_parse_arg (argv[i]))
418       break;
419   argv += (i - 1);
420   argc -= (i - 1);
421
422   if (is_ranlib)
423     {
424       int status = 0;
425       bfd_boolean touch = FALSE;
426
427       if (argc < 2
428           || strcmp (argv[1], "--help") == 0
429           || strcmp (argv[1], "-h") == 0
430           || strcmp (argv[1], "-H") == 0)
431         usage (0);
432       if (strcmp (argv[1], "-V") == 0
433           || strcmp (argv[1], "-v") == 0
434           || CONST_STRNEQ (argv[1], "--v"))
435         print_version ("ranlib");
436       arg_index = 1;
437       if (strcmp (argv[1], "-t") == 0)
438         {
439           ++arg_index;
440           touch = TRUE;
441         }
442       while (arg_index < argc)
443         {
444           if (! touch)
445             status |= ranlib_only (argv[arg_index]);
446           else
447             status |= ranlib_touch (argv[arg_index]);
448           ++arg_index;
449         }
450       xexit (status);
451     }
452
453   if (argc == 2 && strcmp (argv[1], "-M") == 0)
454     {
455       mri_emul ();
456       xexit (0);
457     }
458
459   if (argc < 2)
460     usage (0);
461
462   arg_index = 1;
463   arg_ptr = argv[arg_index];
464
465   if (strcmp (arg_ptr, "--plugin") == 0)
466     {
467 #if BFD_SUPPORTS_PLUGINS
468       if (argc < 4)
469         usage (1);
470
471       bfd_plugin_set_plugin (argv[2]);
472
473       arg_index += 2;
474       arg_ptr = argv[arg_index];
475 #else
476       fprintf (stderr, _("sorry - this program has been built without plugin support\n"));
477       xexit (1);
478 #endif
479     }
480
481   if (*arg_ptr == '-')
482     {
483       /* When the first option starts with '-' we support POSIX-compatible
484          option parsing.  */
485       do_posix = 1;
486       ++arg_ptr;                        /* compatibility */
487     }
488
489   do
490     {
491       while ((c = *arg_ptr++) != '\0')
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               switch (c)
505                 {
506                 case 'd':
507                   operation = del;
508                   operation_alters_arch = TRUE;
509                   break;
510                 case 'm':
511                   operation = move;
512                   operation_alters_arch = TRUE;
513                   break;
514                 case 'p':
515                   operation = print_files;
516                   break;
517                 case 'q':
518                   operation = quick_append;
519                   operation_alters_arch = TRUE;
520                   break;
521                 case 'r':
522                   operation = replace;
523                   operation_alters_arch = TRUE;
524                   break;
525                 case 't':
526                   operation = print_table;
527                   break;
528                 case 'x':
529                   operation = extract;
530                   break;
531                 }
532             case 'l':
533               break;
534             case 'c':
535               silent_create = 1;
536               break;
537             case 'o':
538               preserve_dates = 1;
539               break;
540             case 'V':
541               show_version = TRUE;
542               break;
543             case 's':
544               write_armap = 1;
545               break;
546             case 'S':
547               write_armap = -1;
548               break;
549             case 'u':
550               newer_only = 1;
551               break;
552             case 'v':
553               verbose = 1;
554               break;
555             case 'a':
556               postype = pos_after;
557               break;
558             case 'b':
559               postype = pos_before;
560               break;
561             case 'i':
562               postype = pos_before;
563               break;
564             case 'M':
565               mri_mode = 1;
566               break;
567             case 'N':
568               counted_name_mode = TRUE;
569               break;
570             case 'f':
571               ar_truncate = TRUE;
572               break;
573             case 'P':
574               full_pathname = TRUE;
575               break;
576             case 'T':
577               make_thin_archive = TRUE;
578               break;
579             case 'D':
580               deterministic = TRUE;
581               break;
582             default:
583               /* xgettext:c-format */
584               non_fatal (_("illegal option -- %c"), c);
585               usage (0);
586             }
587         }
588
589       /* With POSIX-compatible option parsing continue with the next
590          argument if it starts with '-'.  */
591       if (do_posix && arg_index + 1 < argc && argv[arg_index + 1][0] == '-')
592         arg_ptr = argv[++arg_index] + 1;
593       else
594         do_posix = 0;
595     }
596   while (do_posix);
597
598   if (show_version)
599     print_version ("ar");
600
601   ++arg_index;
602   if (arg_index >= argc)
603     usage (0);
604
605   if (mri_mode)
606     {
607       mri_emul ();
608     }
609   else
610     {
611       bfd *arch;
612
613       /* We don't use do_quick_append any more.  Too many systems
614          expect ar to always rebuild the symbol table even when q is
615          used.  */
616
617       /* We can't write an armap when using ar q, so just do ar r
618          instead.  */
619       if (operation == quick_append && write_armap)
620         operation = replace;
621
622       if ((operation == none || operation == print_table)
623           && write_armap == 1)
624         xexit (ranlib_only (argv[arg_index]));
625
626       if (operation == none)
627         fatal (_("no operation specified"));
628
629       if (newer_only && operation != replace)
630         fatal (_("`u' is only meaningful with the `r' option."));
631
632       if (newer_only && deterministic)
633         fatal (_("`u' is not meaningful with the `D' option."));
634
635       if (postype != pos_default)
636         posname = argv[arg_index++];
637
638       if (counted_name_mode)
639         {
640           if (operation != extract && operation != del)
641              fatal (_("`N' is only meaningful with the `x' and `d' options."));
642           counted_name_counter = atoi (argv[arg_index++]);
643           if (counted_name_counter <= 0)
644             fatal (_("Value for `N' must be positive."));
645         }
646
647       inarch_filename = argv[arg_index++];
648
649       files = arg_index < argc ? argv + arg_index : NULL;
650       file_count = argc - arg_index;
651
652       arch = open_inarch (inarch_filename,
653                           files == NULL ? (char *) NULL : files[0]);
654
655       if (operation == extract && bfd_is_thin_archive (arch))
656         fatal (_("`x' cannot be used on thin archives."));
657
658       switch (operation)
659         {
660         case print_table:
661           map_over_members (arch, print_descr, files, file_count);
662           break;
663
664         case print_files:
665           map_over_members (arch, print_contents, files, file_count);
666           break;
667
668         case extract:
669           map_over_members (arch, extract_file, files, file_count);
670           break;
671
672         case del:
673           if (files != NULL)
674             delete_members (arch, files);
675           else
676             output_filename = NULL;
677           break;
678
679         case move:
680           if (files != NULL)
681             move_members (arch, files);
682           else
683             output_filename = NULL;
684           break;
685
686         case replace:
687         case quick_append:
688           if (files != NULL || write_armap > 0)
689             replace_members (arch, files, operation == quick_append);
690           else
691             output_filename = NULL;
692           break;
693
694           /* Shouldn't happen! */
695         default:
696           /* xgettext:c-format */
697           fatal (_("internal error -- this option not implemented"));
698         }
699     }
700
701   END_PROGRESS (program_name);
702
703   xexit (0);
704   return 0;
705 }
706
707 bfd *
708 open_inarch (const char *archive_filename, const char *file)
709 {
710   const char *target;
711   bfd **last_one;
712   bfd *next_one;
713   struct stat sbuf;
714   bfd *arch;
715   char **matching;
716
717   bfd_set_error (bfd_error_no_error);
718
719   target = NULL;
720
721   if (stat (archive_filename, &sbuf) != 0)
722     {
723 #if !defined(__GO32__) || defined(__DJGPP__)
724
725       /* FIXME: I don't understand why this fragment was ifndef'ed
726          away for __GO32__; perhaps it was in the days of DJGPP v1.x.
727          stat() works just fine in v2.x, so I think this should be
728          removed.  For now, I enable it for DJGPP v2. -- EZ.  */
729
730 /* KLUDGE ALERT! Temporary fix until I figger why
731    stat() is wrong ... think it's buried in GO32's IDT - Jax */
732       if (errno != ENOENT)
733         bfd_fatal (archive_filename);
734 #endif
735
736       if (!operation_alters_arch)
737         {
738           fprintf (stderr, "%s: ", program_name);
739           perror (archive_filename);
740           maybequit ();
741           return NULL;
742         }
743
744       /* Try to figure out the target to use for the archive from the
745          first object on the list.  */
746       if (file != NULL)
747         {
748           bfd *obj;
749
750           obj = bfd_openr (file, NULL);
751           if (obj != NULL)
752             {
753               if (bfd_check_format (obj, bfd_object))
754                 target = bfd_get_target (obj);
755               (void) bfd_close (obj);
756             }
757         }
758
759       /* Create an empty archive.  */
760       arch = bfd_openw (archive_filename, target);
761       if (arch == NULL
762           || ! bfd_set_format (arch, bfd_archive)
763           || ! bfd_close (arch))
764         bfd_fatal (archive_filename);
765       else if (!silent_create)
766         non_fatal (_("creating %s"), archive_filename);
767
768       /* If we die creating a new archive, don't leave it around.  */
769       output_filename = archive_filename;
770     }
771
772   arch = bfd_openr (archive_filename, target);
773   if (arch == NULL)
774     {
775     bloser:
776       bfd_fatal (archive_filename);
777     }
778
779   if (! bfd_check_format_matches (arch, bfd_archive, &matching))
780     {
781       bfd_nonfatal (archive_filename);
782       if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
783         {
784           list_matching_formats (matching);
785           free (matching);
786         }
787       xexit (1);
788     }
789
790   last_one = &(arch->archive_next);
791   /* Read all the contents right away, regardless.  */
792   for (next_one = bfd_openr_next_archived_file (arch, NULL);
793        next_one;
794        next_one = bfd_openr_next_archived_file (arch, next_one))
795     {
796       PROGRESS (1);
797       *last_one = next_one;
798       last_one = &next_one->archive_next;
799     }
800   *last_one = (bfd *) NULL;
801   if (bfd_get_error () != bfd_error_no_more_archived_files)
802     goto bloser;
803   return arch;
804 }
805
806 static void
807 print_contents (bfd *abfd)
808 {
809   size_t ncopied = 0;
810   char *cbuf = (char *) xmalloc (BUFSIZE);
811   struct stat buf;
812   size_t size;
813   if (bfd_stat_arch_elt (abfd, &buf) != 0)
814     /* xgettext:c-format */
815     fatal (_("internal stat error on %s"), bfd_get_filename (abfd));
816
817   if (verbose)
818     /* xgettext:c-format */
819     printf (_("\n<%s>\n\n"), bfd_get_filename (abfd));
820
821   bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
822
823   size = buf.st_size;
824   while (ncopied < size)
825     {
826
827       size_t nread;
828       size_t tocopy = size - ncopied;
829       if (tocopy > BUFSIZE)
830         tocopy = BUFSIZE;
831
832       nread = bfd_bread (cbuf, (bfd_size_type) tocopy, abfd);
833       if (nread != tocopy)
834         /* xgettext:c-format */
835         fatal (_("%s is not a valid archive"),
836                bfd_get_filename (bfd_my_archive (abfd)));
837
838       /* fwrite in mingw32 may return int instead of size_t. Cast the
839          return value to size_t to avoid comparison between signed and
840          unsigned values.  */
841       if ((size_t) fwrite (cbuf, 1, nread, stdout) != nread)
842         fatal ("stdout: %s", strerror (errno));
843       ncopied += tocopy;
844     }
845   free (cbuf);
846 }
847
848 /* Extract a member of the archive into its own file.
849
850    We defer opening the new file until after we have read a BUFSIZ chunk of the
851    old one, since we know we have just read the archive header for the old
852    one.  Since most members are shorter than BUFSIZ, this means we will read
853    the old header, read the old data, write a new inode for the new file, and
854    write the new data, and be done. This 'optimization' is what comes from
855    sitting next to a bare disk and hearing it every time it seeks.  -- Gnu
856    Gilmore  */
857
858 void
859 extract_file (bfd *abfd)
860 {
861   FILE *ostream;
862   char *cbuf = (char *) xmalloc (BUFSIZE);
863   size_t nread, tocopy;
864   size_t ncopied = 0;
865   size_t size;
866   struct stat buf;
867
868   if (bfd_stat_arch_elt (abfd, &buf) != 0)
869     /* xgettext:c-format */
870     fatal (_("internal stat error on %s"), bfd_get_filename (abfd));
871   size = buf.st_size;
872
873   if (verbose)
874     printf ("x - %s\n", bfd_get_filename (abfd));
875
876   bfd_seek (abfd, (file_ptr) 0, SEEK_SET);
877
878   ostream = NULL;
879   if (size == 0)
880     {
881       /* Seems like an abstraction violation, eh?  Well it's OK! */
882       output_filename = bfd_get_filename (abfd);
883
884       ostream = fopen (bfd_get_filename (abfd), FOPEN_WB);
885       if (ostream == NULL)
886         {
887           perror (bfd_get_filename (abfd));
888           xexit (1);
889         }
890
891       output_file = ostream;
892     }
893   else
894     while (ncopied < size)
895       {
896         tocopy = size - ncopied;
897         if (tocopy > BUFSIZE)
898           tocopy = BUFSIZE;
899
900         nread = bfd_bread (cbuf, (bfd_size_type) tocopy, abfd);
901         if (nread != tocopy)
902           /* xgettext:c-format */
903           fatal (_("%s is not a valid archive"),
904                  bfd_get_filename (bfd_my_archive (abfd)));
905
906         /* See comment above; this saves disk arm motion */
907         if (ostream == NULL)
908           {
909             /* Seems like an abstraction violation, eh?  Well it's OK! */
910             output_filename = bfd_get_filename (abfd);
911
912             ostream = fopen (bfd_get_filename (abfd), FOPEN_WB);
913             if (ostream == NULL)
914               {
915                 perror (bfd_get_filename (abfd));
916                 xexit (1);
917               }
918
919             output_file = ostream;
920           }
921
922         /* fwrite in mingw32 may return int instead of size_t. Cast
923            the return value to size_t to avoid comparison between
924            signed and unsigned values.  */
925         if ((size_t) fwrite (cbuf, 1, nread, ostream) != nread)
926           fatal ("%s: %s", output_filename, strerror (errno));
927         ncopied += tocopy;
928       }
929
930   if (ostream != NULL)
931     fclose (ostream);
932
933   output_file = NULL;
934   output_filename = NULL;
935
936   chmod (bfd_get_filename (abfd), buf.st_mode);
937
938   if (preserve_dates)
939     {
940       /* Set access time to modification time.  Only st_mtime is
941          initialized by bfd_stat_arch_elt.  */
942       buf.st_atime = buf.st_mtime;
943       set_times (bfd_get_filename (abfd), &buf);
944     }
945
946   free (cbuf);
947 }
948
949 static void
950 write_archive (bfd *iarch)
951 {
952   bfd *obfd;
953   char *old_name, *new_name;
954   bfd *contents_head = iarch->archive_next;
955
956   old_name = (char *) xmalloc (strlen (bfd_get_filename (iarch)) + 1);
957   strcpy (old_name, bfd_get_filename (iarch));
958   new_name = make_tempname (old_name);
959
960   if (new_name == NULL)
961     bfd_fatal ("could not create temporary file whilst writing archive");
962
963   output_filename = new_name;
964
965   obfd = bfd_openw (new_name, bfd_get_target (iarch));
966
967   if (obfd == NULL)
968     bfd_fatal (old_name);
969
970   output_bfd = obfd;
971
972   bfd_set_format (obfd, bfd_archive);
973
974   /* Request writing the archive symbol table unless we've
975      been explicitly requested not to.  */
976   obfd->has_armap = write_armap >= 0;
977
978   if (ar_truncate)
979     {
980       /* This should really use bfd_set_file_flags, but that rejects
981          archives.  */
982       obfd->flags |= BFD_TRADITIONAL_FORMAT;
983     }
984
985   if (deterministic)
986     obfd->flags |= BFD_DETERMINISTIC_OUTPUT;
987
988   if (make_thin_archive || bfd_is_thin_archive (iarch))
989     bfd_is_thin_archive (obfd) = 1;
990
991   if (!bfd_set_archive_head (obfd, contents_head))
992     bfd_fatal (old_name);
993
994   if (!bfd_close (obfd))
995     bfd_fatal (old_name);
996
997   output_bfd = NULL;
998   output_filename = NULL;
999
1000   /* We don't care if this fails; we might be creating the archive.  */
1001   bfd_close (iarch);
1002
1003   if (smart_rename (new_name, old_name, 0) != 0)
1004     xexit (1);
1005 }
1006
1007 /* Return a pointer to the pointer to the entry which should be rplacd'd
1008    into when altering.  DEFAULT_POS should be how to interpret pos_default,
1009    and should be a pos value.  */
1010
1011 static bfd **
1012 get_pos_bfd (bfd **contents, enum pos default_pos, const char *default_posname)
1013 {
1014   bfd **after_bfd = contents;
1015   enum pos realpos;
1016   const char *realposname;
1017
1018   if (postype == pos_default)
1019     {
1020       realpos = default_pos;
1021       realposname = default_posname;
1022     }
1023   else
1024     {
1025       realpos = postype;
1026       realposname = posname;
1027     }
1028
1029   if (realpos == pos_end)
1030     {
1031       while (*after_bfd)
1032         after_bfd = &((*after_bfd)->archive_next);
1033     }
1034   else
1035     {
1036       for (; *after_bfd; after_bfd = &(*after_bfd)->archive_next)
1037         if (FILENAME_CMP ((*after_bfd)->filename, realposname) == 0)
1038           {
1039             if (realpos == pos_after)
1040               after_bfd = &(*after_bfd)->archive_next;
1041             break;
1042           }
1043     }
1044   return after_bfd;
1045 }
1046
1047 static void
1048 delete_members (bfd *arch, char **files_to_delete)
1049 {
1050   bfd **current_ptr_ptr;
1051   bfd_boolean found;
1052   bfd_boolean something_changed = FALSE;
1053   int match_count;
1054
1055   for (; *files_to_delete != NULL; ++files_to_delete)
1056     {
1057       /* In a.out systems, the armap is optional.  It's also called
1058          __.SYMDEF.  So if the user asked to delete it, we should remember
1059          that fact. This isn't quite right for COFF systems (where
1060          __.SYMDEF might be regular member), but it's very unlikely
1061          to be a problem.  FIXME */
1062
1063       if (!strcmp (*files_to_delete, "__.SYMDEF"))
1064         {
1065           arch->has_armap = FALSE;
1066           write_armap = -1;
1067           continue;
1068         }
1069
1070       found = FALSE;
1071       match_count = 0;
1072       current_ptr_ptr = &(arch->archive_next);
1073       while (*current_ptr_ptr)
1074         {
1075           if (FILENAME_CMP (normalize (*files_to_delete, arch),
1076                             (*current_ptr_ptr)->filename) == 0)
1077             {
1078               ++match_count;
1079               if (counted_name_mode
1080                   && match_count != counted_name_counter)
1081                 {
1082                   /* Counting, and didn't match on count; go on to the
1083                      next one.  */
1084                 }
1085               else
1086                 {
1087                   found = TRUE;
1088                   something_changed = TRUE;
1089                   if (verbose)
1090                     printf ("d - %s\n",
1091                             *files_to_delete);
1092                   *current_ptr_ptr = ((*current_ptr_ptr)->archive_next);
1093                   goto next_file;
1094                 }
1095             }
1096
1097           current_ptr_ptr = &((*current_ptr_ptr)->archive_next);
1098         }
1099
1100       if (verbose && !found)
1101         {
1102           /* xgettext:c-format */
1103           printf (_("No member named `%s'\n"), *files_to_delete);
1104         }
1105     next_file:
1106       ;
1107     }
1108
1109   if (something_changed)
1110     write_archive (arch);
1111   else
1112     output_filename = NULL;
1113 }
1114
1115
1116 /* Reposition existing members within an archive */
1117
1118 static void
1119 move_members (bfd *arch, char **files_to_move)
1120 {
1121   bfd **after_bfd;              /* New entries go after this one */
1122   bfd **current_ptr_ptr;        /* cdr pointer into contents */
1123
1124   for (; *files_to_move; ++files_to_move)
1125     {
1126       current_ptr_ptr = &(arch->archive_next);
1127       while (*current_ptr_ptr)
1128         {
1129           bfd *current_ptr = *current_ptr_ptr;
1130           if (FILENAME_CMP (normalize (*files_to_move, arch),
1131                             current_ptr->filename) == 0)
1132             {
1133               /* Move this file to the end of the list - first cut from
1134                  where it is.  */
1135               bfd *link_bfd;
1136               *current_ptr_ptr = current_ptr->archive_next;
1137
1138               /* Now glue to end */
1139               after_bfd = get_pos_bfd (&arch->archive_next, pos_end, NULL);
1140               link_bfd = *after_bfd;
1141               *after_bfd = current_ptr;
1142               current_ptr->archive_next = link_bfd;
1143
1144               if (verbose)
1145                 printf ("m - %s\n", *files_to_move);
1146
1147               goto next_file;
1148             }
1149
1150           current_ptr_ptr = &((*current_ptr_ptr)->archive_next);
1151         }
1152       /* xgettext:c-format */
1153       fatal (_("no entry %s in archive %s!"), *files_to_move, arch->filename);
1154
1155     next_file:;
1156     }
1157
1158   write_archive (arch);
1159 }
1160
1161 /* Ought to default to replacing in place, but this is existing practice!  */
1162
1163 static void
1164 replace_members (bfd *arch, char **files_to_move, bfd_boolean quick)
1165 {
1166   bfd_boolean changed = FALSE;
1167   bfd **after_bfd;              /* New entries go after this one.  */
1168   bfd *current;
1169   bfd **current_ptr;
1170
1171   while (files_to_move && *files_to_move)
1172     {
1173       if (! quick)
1174         {
1175           current_ptr = &arch->archive_next;
1176           while (*current_ptr)
1177             {
1178               current = *current_ptr;
1179
1180               /* For compatibility with existing ar programs, we
1181                  permit the same file to be added multiple times.  */
1182               if (FILENAME_CMP (normalize (*files_to_move, arch),
1183                                 normalize (current->filename, arch)) == 0
1184                   && current->arelt_data != NULL)
1185                 {
1186                   if (newer_only)
1187                     {
1188                       struct stat fsbuf, asbuf;
1189
1190                       if (stat (*files_to_move, &fsbuf) != 0)
1191                         {
1192                           if (errno != ENOENT)
1193                             bfd_fatal (*files_to_move);
1194                           goto next_file;
1195                         }
1196                       if (bfd_stat_arch_elt (current, &asbuf) != 0)
1197                         /* xgettext:c-format */
1198                         fatal (_("internal stat error on %s"),
1199                                current->filename);
1200
1201                       if (fsbuf.st_mtime <= asbuf.st_mtime)
1202                         goto next_file;
1203                     }
1204
1205                   after_bfd = get_pos_bfd (&arch->archive_next, pos_after,
1206                                            current->filename);
1207                   if (ar_emul_replace (after_bfd, *files_to_move,
1208                                        verbose))
1209                     {
1210                       /* Snip out this entry from the chain.  */
1211                       *current_ptr = (*current_ptr)->archive_next;
1212                       changed = TRUE;
1213                     }
1214
1215                   goto next_file;
1216                 }
1217               current_ptr = &(current->archive_next);
1218             }
1219         }
1220
1221       /* Add to the end of the archive.  */
1222       after_bfd = get_pos_bfd (&arch->archive_next, pos_end, NULL);
1223
1224       if (ar_emul_append (after_bfd, *files_to_move, verbose,
1225                           make_thin_archive))
1226         changed = TRUE;
1227
1228     next_file:;
1229
1230       files_to_move++;
1231     }
1232
1233   if (changed)
1234     write_archive (arch);
1235   else
1236     output_filename = NULL;
1237 }
1238
1239 static int
1240 ranlib_only (const char *archname)
1241 {
1242   bfd *arch;
1243
1244   if (get_file_size (archname) < 1)
1245     return 1;
1246   write_armap = 1;
1247   arch = open_inarch (archname, (char *) NULL);
1248   if (arch == NULL)
1249     xexit (1);
1250   write_archive (arch);
1251   return 0;
1252 }
1253
1254 /* Update the timestamp of the symbol map of an archive.  */
1255
1256 static int
1257 ranlib_touch (const char *archname)
1258 {
1259 #ifdef __GO32__
1260   /* I don't think updating works on go32.  */
1261   ranlib_only (archname);
1262 #else
1263   int f;
1264   bfd *arch;
1265   char **matching;
1266
1267   if (get_file_size (archname) < 1)
1268     return 1;
1269   f = open (archname, O_RDWR | O_BINARY, 0);
1270   if (f < 0)
1271     {
1272       bfd_set_error (bfd_error_system_call);
1273       bfd_fatal (archname);
1274     }
1275
1276   arch = bfd_fdopenr (archname, (const char *) NULL, f);
1277   if (arch == NULL)
1278     bfd_fatal (archname);
1279   if (! bfd_check_format_matches (arch, bfd_archive, &matching))
1280     {
1281       bfd_nonfatal (archname);
1282       if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1283         {
1284           list_matching_formats (matching);
1285           free (matching);
1286         }
1287       xexit (1);
1288     }
1289
1290   if (! bfd_has_map (arch))
1291     /* xgettext:c-format */
1292     fatal (_("%s: no archive map to update"), archname);
1293
1294   bfd_update_armap_timestamp (arch);
1295
1296   if (! bfd_close (arch))
1297     bfd_fatal (archname);
1298 #endif
1299   return 0;
1300 }
1301
1302 /* Things which are interesting to map over all or some of the files: */
1303
1304 static void
1305 print_descr (bfd *abfd)
1306 {
1307   print_arelt_descr (stdout, abfd, verbose);
1308 }