1 /* Create, modify, and extract from archives.
2 Copyright (C) 2005-2012 Red Hat, Inc.
3 This file is part of elfutils.
4 Written by Ulrich Drepper <drepper@redhat.com>, 2005.
6 This file 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 elfutils is distributed in the hope that it will be useful, but
12 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, see <http://www.gnu.org/licenses/>. */
35 #include <stdio_ext.h>
48 /* Name and version of program. */
49 static void print_version (FILE *stream, struct argp_state *state);
50 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
52 /* Prototypes for local functions. */
53 static int do_oper_extract (int oper, const char *arfname, char **argv,
54 int argc, long int instance);
55 static int do_oper_delete (const char *arfname, char **argv, int argc,
57 static int do_oper_insert (int oper, const char *arfname, char **argv,
58 int argc, const char *member);
61 /* Bug report address. */
62 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
65 /* Definitions of arguments for argp functions. */
66 static const struct argp_option options[] =
68 { NULL, 0, NULL, 0, N_("Commands:"), 1 },
69 { NULL, 'd', NULL, 0, N_("Delete files from archive."), 0 },
70 { NULL, 'm', NULL, 0, N_("Move files in archive."), 0 },
71 { NULL, 'p', NULL, 0, N_("Print files in archive."), 0 },
72 { NULL, 'q', NULL, 0, N_("Quick append files to archive."), 0 },
74 N_("Replace existing or insert new file into archive."), 0 },
75 { NULL, 't', NULL, 0, N_("Display content of archive."), 0 },
76 { NULL, 'x', NULL, 0, N_("Extract files from archive."), 0 },
78 { NULL, 0, NULL, 0, N_("Command Modifiers:"), 2 },
79 { NULL, 'o', NULL, 0, N_("Preserve original dates."), 0 },
80 { NULL, 'N', NULL, 0, N_("Use instance [COUNT] of name."), 0 },
82 N_("Do not replace existing files with extracted files."), 0 },
83 { NULL, 'T', NULL, 0, N_("Allow filename to be truncated if necessary."),
85 { NULL, 'v', NULL, 0, N_("Provide verbose output."), 0 },
86 { NULL, 's', NULL, 0, N_("Force regeneration of symbol table."), 0 },
87 { NULL, 'a', NULL, 0, N_("Insert file after [MEMBER]."), 0 },
88 { NULL, 'b', NULL, 0, N_("Insert file before [MEMBER]."), 0 },
89 { NULL, 'i', NULL, 0, N_("Same as -b."), 0 },
90 { NULL, 'c', NULL, 0, N_("Suppress message when library has to be created."),
92 { NULL, 'P', NULL, 0, N_("Use full path for file matching."), 0 },
93 { NULL, 'u', NULL, 0, N_("Update only older files in archive."), 0 },
95 { NULL, 0, NULL, 0, NULL, 0 }
98 /* Short description of program. */
99 static const char doc[] = N_("Create, modify, and extract from archives.");
101 /* Strings for arguments in help texts. */
102 static const char args_doc[] = N_("[MEMBER] [COUNT] ARCHIVE [FILE...]");
104 /* Prototype for option handler. */
105 static error_t parse_opt (int key, char *arg, struct argp_state *state);
107 /* Data structure to communicate with argp functions. */
108 static struct argp argp =
110 options, parse_opt, args_doc, doc, arlib_argp_children, NULL, NULL
114 /* What operation to perform. */
129 static bool preserve_dates;
130 static bool instance_specifed;
131 static bool dont_replace_existing;
132 static bool allow_truncate_fname;
133 static bool force_symtab;
134 static bool suppress_create_msg;
135 static bool full_path;
136 static bool update_newer;
137 static enum { ipos_none, ipos_before, ipos_after } ipos;
141 main (int argc, char *argv[])
143 /* We use no threads here which can interfere with handling a stream. */
144 (void) __fsetlocking (stdin, FSETLOCKING_BYCALLER);
145 (void) __fsetlocking (stdout, FSETLOCKING_BYCALLER);
146 (void) __fsetlocking (stderr, FSETLOCKING_BYCALLER);
149 (void) setlocale (LC_ALL, "");
151 /* Make sure the message catalog can be found. */
152 (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
154 /* Initialize the message catalog. */
155 (void) textdomain (PACKAGE_TARNAME);
157 /* For historical reasons the options in the first parameter need
158 not be preceded by a dash. Add it now if necessary. */
159 if (argc > 1 && argv[1][0] != '-')
161 size_t len = strlen (argv[1]) + 1;
162 char *newp = alloca (len + 1);
164 memcpy (&newp[1], argv[1], len);
168 /* Parse and process arguments. */
170 (void) argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
172 /* Tell the library which version we are expecting. */
173 (void) elf_version (EV_CURRENT);
175 /* Handle the [MEMBER] parameter. */
176 const char *member = NULL;
177 if (ipos != ipos_none)
179 /* Only valid for certain operations. */
180 if (operation != oper_move && operation != oper_replace)
181 error (1, 0, gettext ("\
182 'a', 'b', and 'i' are only allowed with the 'm' and 'r' options"));
184 if (remaining == argc)
186 error (0, 0, gettext ("\
187 MEMBER parameter required for 'a', 'b', and 'i' modifiers"));
188 argp_help (&argp, stderr, ARGP_HELP_USAGE | ARGP_HELP_SEE,
189 program_invocation_short_name);
193 member = argv[remaining++];
196 /* Handle the [COUNT] parameter. */
197 long int instance = -1;
198 if (instance_specifed)
200 /* Only valid for certain operations. */
201 if (operation != oper_extract && operation != oper_delete)
202 error (1, 0, gettext ("\
203 'N' is only meaningful with the 'x' and 'd' options"));
205 if (remaining == argc)
207 error (0, 0, gettext ("COUNT parameter required"));
208 argp_help (&argp, stderr, ARGP_HELP_SEE,
209 program_invocation_short_name);
215 if (((instance = strtol (argv[remaining], &endp, 10)) == LONG_MAX
219 error (1, 0, gettext ("invalid COUNT parameter %s"), argv[remaining]);
224 if ((dont_replace_existing || allow_truncate_fname)
225 && unlikely (operation != oper_extract))
226 error (1, 0, gettext ("'%c' is only meaningful with the 'x' option"),
227 dont_replace_existing ? 'C' : 'T');
229 /* There must at least be one more parameter specifying the archive. */
230 if (remaining == argc)
232 error (0, 0, gettext ("archive name required"));
233 argp_help (&argp, stderr, ARGP_HELP_SEE, program_invocation_short_name);
237 const char *arfname = argv[remaining++];
245 error (0, 0, gettext ("command option required"));
246 argp_help (&argp, stderr, ARGP_HELP_STD_ERR,
247 program_invocation_short_name);
253 status = do_oper_extract (operation, arfname, argv, argc, -1);
257 status = do_oper_extract (operation, arfname, argv, argc, instance);
261 status = do_oper_delete (arfname, argv, argc, instance);
267 status = do_oper_insert (operation, arfname, argv, argc, member);
271 assert (! "should not happen");
280 /* Print the version information. */
282 print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
284 fprintf (stream, "ar (%s) %s\n", PACKAGE_NAME, PACKAGE_VERSION);
285 fprintf (stream, gettext ("\
286 Copyright (C) %s Red Hat, Inc.\n\
287 This is free software; see the source for copying conditions. There is NO\n\
288 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
290 fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
294 /* Handle program arguments. */
296 parse_opt (int key, char *arg __attribute__ ((unused)),
297 struct argp_state *state __attribute__ ((unused)))
308 if (operation != oper_none)
310 error (0, 0, gettext ("More than one operation specified"));
311 argp_help (&argp, stderr, ARGP_HELP_SEE,
312 program_invocation_short_name);
319 operation = oper_delete;
322 operation = oper_move;
325 operation = oper_print;
328 operation = oper_qappend;
331 operation = oper_replace;
334 operation = oper_list;
337 operation = oper_extract;
352 suppress_create_msg = true;
356 dont_replace_existing = true;
360 instance_specifed = true;
364 preserve_dates = true;
376 allow_truncate_fname = true;
388 return ARGP_ERR_UNKNOWN;
395 open_archive (const char *arfname, int flags, int mode, Elf **elf,
396 struct stat *st, bool miss_allowed)
398 int fd = open (arfname, flags, mode);
404 error (EXIT_FAILURE, errno, gettext ("cannot open archive '%s'"),
410 Elf_Cmd cmd = flags == O_RDONLY ? ELF_C_READ_MMAP : ELF_C_RDWR_MMAP;
412 *elf = elf_begin (fd, cmd, NULL);
414 error (EXIT_FAILURE, 0, gettext ("cannot open archive '%s': %s"),
415 arfname, elf_errmsg (-1));
417 if (flags == O_RDONLY && elf_kind (*elf) != ELF_K_AR)
418 error (EXIT_FAILURE, 0, gettext ("%s: not an archive file"), arfname);
421 if (st != NULL && fstat (fd, st) != 0)
422 error (EXIT_FAILURE, errno, gettext ("cannot stat archive '%s'"),
430 not_found (int argc, char *argv[argc], bool found[argc])
432 for (int i = 0; i < argc; ++i)
434 printf (gettext ("no entry %s in archive\n"), argv[i]);
439 copy_content (Elf *elf, int newfd, off_t off, size_t n)
442 char *rawfile = elf_rawfile (elf, &len);
444 assert (off + n <= len);
446 /* Tell the kernel we will read all the pages sequentially. */
447 size_t ps = sysconf (_SC_PAGESIZE);
449 posix_madvise (rawfile + (off & ~(ps - 1)), n, POSIX_MADV_SEQUENTIAL);
451 return write_retry (newfd, rawfile + off, n) != (ssize_t) n;
456 do_oper_extract (int oper, const char *arfname, char **argv, int argc,
460 memset (found, '\0', sizeof (found));
463 inline bool should_truncate_fname (void)
465 if (errno == ENAMETOOLONG && allow_truncate_fname)
469 long int len = pathconf (".", _PC_NAME_MAX);
473 return name_max != 0;
478 off_t index_off = -1;
479 size_t index_size = 0;
480 off_t cur_off = SARMAG;
484 int fd = open_archive (arfname, O_RDONLY, 0, &elf, NULL, false);
486 if (hcreate (2 * argc) == 0)
487 error (EXIT_FAILURE, errno, gettext ("cannot create hash table"));
489 for (int cnt = 0; cnt < argc; ++cnt)
491 ENTRY entry = { .key = argv[cnt], .data = &argv[cnt] };
492 if (hsearch (entry, ENTER) == NULL)
493 error (EXIT_FAILURE, errno,
494 gettext ("cannot insert into hash table"));
500 if (fstat (fd, &st) != 0)
502 error (0, errno, gettext ("cannot stat '%s'"), arfname);
509 Elf_Cmd cmd = ELF_C_READ_MMAP;
511 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
513 Elf_Arhdr *arhdr = elf_getarhdr (subelf);
515 if (strcmp (arhdr->ar_name, "/") == 0)
517 index_off = elf_getaroff (subelf);
518 index_size = arhdr->ar_size;
521 if (strcmp (arhdr->ar_name, "//") == 0)
526 arlib_add_symbols (elf, arfname, arhdr->ar_name, cur_off);
527 cur_off += (((arhdr->ar_size + 1) & ~((off_t) 1))
528 + sizeof (struct ar_hdr));
531 bool do_extract = argc <= 0;
535 entry.key = arhdr->ar_name;
536 ENTRY *res = hsearch (entry, FIND);
537 if (res != NULL && (instance < 0 || instance-- == 0)
538 && !found[(char **) res->data - argv])
539 found[(char **) res->data - argv] = do_extract = true;
546 if (oper == oper_print)
548 printf ("\n<%s>\n\n", arhdr->ar_name);
550 /* We have to flush now because now we use the descriptor
554 else if (oper == oper_list)
557 strftime (datestr, sizeof (datestr), "%b %e %H:%M %Y",
558 localtime (&arhdr->ar_date));
560 printf ("%c%c%c%c%c%c%c%c%c %u/%u %6ju %s %s\n",
561 (arhdr->ar_mode & S_IRUSR) ? 'r' : '-',
562 (arhdr->ar_mode & S_IWUSR) ? 'w' : '-',
563 (arhdr->ar_mode & S_IXUSR)
564 ? ((arhdr->ar_mode & S_ISUID) ? 's' : 'x')
565 : ((arhdr->ar_mode & S_ISUID) ? 'S' : '-'),
566 (arhdr->ar_mode & S_IRGRP) ? 'r' : '-',
567 (arhdr->ar_mode & S_IWGRP) ? 'w' : '-',
568 (arhdr->ar_mode & S_IXGRP)
569 ? ((arhdr->ar_mode & S_ISGID) ? 's' : 'x')
570 : ((arhdr->ar_mode & S_ISGID) ? 'S' : '-'),
571 (arhdr->ar_mode & S_IROTH) ? 'r' : '-',
572 (arhdr->ar_mode & S_IWOTH) ? 'w' : '-',
573 (arhdr->ar_mode & S_IXOTH)
574 ? ((arhdr->ar_mode & S_ISVTX) ? 't' : 'x')
575 : ((arhdr->ar_mode & S_ISVTX) ? 'T' : '-'),
578 (uintmax_t) arhdr->ar_size,
583 printf ("x - %s\n", arhdr->ar_name);
586 if (oper == oper_list)
589 puts (arhdr->ar_name);
595 char *data = elf_rawfile (subelf, &nleft);
598 error (0, 0, gettext ("cannot read content of %s: %s"),
599 arhdr->ar_name, elf_errmsg (-1));
605 char tempfname[] = "XXXXXX";
606 bool use_mkstemp = true;
608 if (oper == oper_print)
612 xfd = mkstemp (tempfname);
613 if (unlikely (xfd == -1))
615 /* We cannot create a temporary file. Try to overwrite
616 the file or create it if it does not exist. */
617 int flags = O_WRONLY | O_CREAT;
618 if (dont_replace_existing)
622 xfd = open (arhdr->ar_name, flags, 0600);
623 if (unlikely (xfd == -1))
625 int printlen = INT_MAX;
627 if (should_truncate_fname ())
629 /* Try to truncate the name. First find out by how
632 char truncfname[name_max + 1];
633 *((char *) mempcpy (truncfname, arhdr->ar_name,
636 xfd = open (truncfname, flags, 0600);
641 error (0, errno, gettext ("cannot open %.*s"),
642 (int) printlen, arhdr->ar_name);
653 while ((n = TEMP_FAILURE_RETRY (write (xfd, data, nleft))) != -1)
661 if (unlikely (n == -1))
663 error (0, errno, gettext ("failed to write %s"), arhdr->ar_name);
670 if (oper != oper_print)
672 /* Fix up the mode. */
673 if (unlikely (fchmod (xfd, arhdr->ar_mode) != 0))
675 error (0, errno, gettext ("cannot change mode of %s"),
682 struct timespec tv[2];
683 tv[0].tv_sec = arhdr->ar_date;
685 tv[1].tv_sec = arhdr->ar_date;
688 if (unlikely (futimens (xfd, tv) != 0))
691 gettext ("cannot change modification time of %s"),
697 /* If we used a temporary file, move it do the right
703 if (dont_replace_existing)
705 r = link (tempfname, arhdr->ar_name);
710 r = rename (tempfname, arhdr->ar_name);
712 if (unlikely (r) != 0)
714 int printlen = INT_MAX;
716 if (should_truncate_fname ())
718 /* Try to truncate the name. First find out by how
721 char truncfname[name_max + 1];
722 *((char *) mempcpy (truncfname, arhdr->ar_name,
725 if (dont_replace_existing)
727 r = link (tempfname, truncfname);
732 r = rename (tempfname, truncfname);
737 error (0, errno, gettext ("\
738 cannot rename temporary file to %.*s"),
739 printlen, arhdr->ar_name);
751 cmd = elf_next (subelf);
752 if (elf_end (subelf) != 0)
753 error (1, 0, "%s: %s", arfname, elf_errmsg (-1));
762 if (symtab.symsnamelen != 0
763 /* We have to rewrite the file also if it initially had an index
764 but now does not need one anymore. */
765 || (symtab.symsnamelen == 0 && index_size != 0))
767 char tmpfname[strlen (arfname) + 7];
768 strcpy (stpcpy (tmpfname, arfname), "XXXXXX");
769 int newfd = mkstemp (tmpfname);
770 if (unlikely (newfd == -1))
773 error (0, errno, gettext ("cannot create new file"));
778 /* Create the header. */
779 if (unlikely (write_retry (newfd, ARMAG, SARMAG) != SARMAG))
781 // XXX Use /prof/self/fd/%d ???
789 /* Create the new file. There are three parts as far we are
790 concerned: 1. original context before the index, 2. the
791 new index, 3. everything after the new index. */
794 rest_off = (index_off + sizeof (struct ar_hdr)
795 + ((index_size + 1) & ~1ul));
799 if ((symtab.symsnamelen != 0
800 && ((write_retry (newfd, symtab.symsoff,
802 != (ssize_t) symtab.symsofflen)
803 || (write_retry (newfd, symtab.symsname,
805 != (ssize_t) symtab.symsnamelen)))
806 /* Even if the original file had content before the
807 symbol table, we write it in the correct order. */
808 || (index_off != SARMAG
809 && copy_content (elf, newfd, SARMAG, index_off - SARMAG))
810 || copy_content (elf, newfd, rest_off, st.st_size - rest_off)
811 /* Set the mode of the new file to the same values the
812 original file has. */
813 || fchmod (newfd, st.st_mode & ALLPERMS) != 0
814 /* Never complain about fchown failing. */
815 || (({asm ("" :: "r" (fchown (newfd, st.st_uid,
818 || (newfd = -1, rename (tmpfname, arfname) != 0))
828 not_found (argc, argv, found);
839 long int long_name_off;
852 write_member (struct armem *memb, off_t *startp, off_t *lenp, Elf *elf,
853 off_t end_off, int newfd)
856 char tmpbuf[sizeof (arhdr.ar_name) + 1];
858 bool changed_header = memb->long_name_off != -1;
861 /* In case of a long file name we assume the archive header
862 changed and we write it here. */
863 memcpy (&arhdr, elf_rawfile (elf, NULL) + *startp, sizeof (arhdr));
865 snprintf (tmpbuf, sizeof (tmpbuf), "/%-*ld",
866 (int) sizeof (arhdr.ar_name), memb->long_name_off);
867 changed_header = memcmp (arhdr.ar_name, tmpbuf,
868 sizeof (arhdr.ar_name)) != 0;
871 /* If the files are adjacent in the old file extend the range. */
872 if (*startp != -1 && !changed_header && *startp + *lenp == memb->old_off)
874 /* Extend the current range. */
875 *lenp += (memb->next != NULL
876 ? memb->next->off : end_off) - memb->off;
880 /* Write out the old range. */
881 if (*startp != -1 && copy_content (elf, newfd, *startp, *lenp))
884 *startp = memb->old_off;
885 *lenp = (memb->next != NULL ? memb->next->off : end_off) - memb->off;
889 memcpy (arhdr.ar_name, tmpbuf, sizeof (arhdr.ar_name));
891 if (unlikely (write_retry (newfd, &arhdr, sizeof (arhdr))
895 *startp += sizeof (struct ar_hdr);
896 assert ((size_t) *lenp >= sizeof (struct ar_hdr));
897 *lenp -= sizeof (struct ar_hdr);
903 /* Store the name in the long name table if necessary.
904 Record its offset or -1 if we did not need to use the table. */
906 remember_long_name (struct armem *mem, const char *name, size_t namelen)
908 mem->long_name_off = (namelen > MAX_AR_NAME_LEN
909 ? arlib_add_long_name (name, namelen)
914 do_oper_delete (const char *arfname, char **argv, int argc,
917 bool *found = alloca (sizeof (bool) * argc);
918 memset (found, '\0', sizeof (bool) * argc);
920 /* List of the files we keep. */
921 struct armem *to_copy = NULL;
926 int fd = open_archive (arfname, O_RDONLY, 0, &elf, &st, false);
928 if (hcreate (2 * argc) == 0)
929 error (EXIT_FAILURE, errno, gettext ("cannot create hash table"));
931 for (int cnt = 0; cnt < argc; ++cnt)
933 ENTRY entry = { .key = argv[cnt], .data = &argv[cnt] };
934 if (hsearch (entry, ENTER) == NULL)
935 error (EXIT_FAILURE, errno,
936 gettext ("cannot insert into hash table"));
941 off_t cur_off = SARMAG;
942 Elf_Cmd cmd = ELF_C_READ_MMAP;
944 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
946 Elf_Arhdr *arhdr = elf_getarhdr (subelf);
948 /* Ignore the symbol table and the long file name table here. */
949 if (strcmp (arhdr->ar_name, "/") == 0
950 || strcmp (arhdr->ar_name, "//") == 0)
953 bool do_delete = argc <= 0;
957 entry.key = arhdr->ar_name;
958 ENTRY *res = hsearch (entry, FIND);
959 if (res != NULL && (instance < 0 || instance-- == 0)
960 && !found[(char **) res->data - argv])
961 found[(char **) res->data - argv] = do_delete = true;
967 printf ("d - %s\n", arhdr->ar_name);
971 struct armem *newp = alloca (sizeof (struct armem));
972 newp->old_off = elf_getaroff (subelf);
975 cur_off += (((arhdr->ar_size + 1) & ~((off_t) 1))
976 + sizeof (struct ar_hdr));
979 to_copy = newp->next = newp;
982 newp->next = to_copy->next;
983 to_copy = to_copy->next = newp;
986 /* If we recreate the symbol table read the file's symbol
988 arlib_add_symbols (subelf, arfname, arhdr->ar_name, newp->off);
990 /* Remember long file names. */
991 remember_long_name (newp, arhdr->ar_name, strlen (arhdr->ar_name));
995 cmd = elf_next (subelf);
996 if (elf_end (subelf) != 0)
997 error (1, 0, "%s: %s", arfname, elf_errmsg (-1));
1004 /* Create a new, temporary file in the same directory as the
1006 char tmpfname[strlen (arfname) + 7];
1007 strcpy (stpcpy (tmpfname, arfname), "XXXXXX");
1008 int newfd = mkstemp (tmpfname);
1009 if (unlikely (newfd == -1))
1012 /* Create the header. */
1013 if (unlikely (write_retry (newfd, ARMAG, SARMAG) != SARMAG))
1015 // XXX Use /prof/self/fd/%d ???
1021 error (0, errno, gettext ("cannot create new file"));
1026 /* If the archive is empty that is all we have to do. */
1027 if (likely (to_copy != NULL))
1029 /* Write the symbol table or the long file name table or both. */
1030 if (symtab.symsnamelen != 0
1031 && ((write_retry (newfd, symtab.symsoff, symtab.symsofflen)
1032 != (ssize_t) symtab.symsofflen)
1033 || (write_retry (newfd, symtab.symsname, symtab.symsnamelen)
1034 != (ssize_t) symtab.symsnamelen)))
1037 if (symtab.longnameslen > sizeof (struct ar_hdr)
1038 && (write_retry (newfd, symtab.longnames, symtab.longnameslen)
1039 != (ssize_t) symtab.longnameslen))
1042 /* NULL-terminate the list of files to copy. */
1043 struct armem *last = to_copy;
1044 to_copy = to_copy->next;
1051 if (write_member (to_copy, &start, &len, elf, cur_off, newfd) != 0)
1053 while ((to_copy = to_copy->next) != NULL);
1055 /* Write the last part. */
1056 if (copy_content (elf, newfd, start, len))
1060 /* Set the mode of the new file to the same values the original file
1062 if (fchmod (newfd, st.st_mode & ALLPERMS) != 0
1063 /* Never complain about fchown failing. */
1064 || (({asm ("" :: "r" (fchown (newfd, st.st_uid, st.st_gid))); }),
1066 || (newfd = -1, rename (tmpfname, arfname) != 0))
1078 not_found (argc, argv, found);
1085 no0print (bool ofmt, char *buf, int bufsize, long int val)
1087 char tmpbuf[bufsize + 1];
1088 snprintf (tmpbuf, sizeof (tmpbuf), ofmt ? "%-*lo" : "%-*ld", bufsize, val);
1089 memcpy (buf, tmpbuf, bufsize);
1094 do_oper_insert (int oper, const char *arfname, char **argv, int argc,
1100 int fd = open_archive (arfname, O_RDONLY, 0, &elf, &st, oper != oper_move);
1102 /* List of the files we keep. */
1103 struct armem *all = NULL;
1104 struct armem *after_memberelem = NULL;
1105 struct armem **found = alloca (sizeof (*found) * argc);
1106 memset (found, '\0', sizeof (*found) * argc);
1110 /* Initialize early for no_old case. */
1111 off_t cur_off = SARMAG;
1115 if (!suppress_create_msg)
1116 fprintf (stderr, "%s: creating %s\n",
1117 program_invocation_short_name, arfname);
1122 /* Store the names of all files from the command line in a hash
1123 table so that we can match it. Note that when no file name is
1124 given we are basically doing nothing except recreating the
1126 if (oper != oper_qappend)
1128 if (hcreate (2 * argc) == 0)
1129 error (EXIT_FAILURE, errno, gettext ("cannot create hash table"));
1131 for (int cnt = 0; cnt < argc; ++cnt)
1134 entry.key = full_path ? argv[cnt] : basename (argv[cnt]);
1135 entry.data = &argv[cnt];
1136 if (hsearch (entry, ENTER) == NULL)
1137 error (EXIT_FAILURE, errno,
1138 gettext ("cannot insert into hash table"));
1142 /* While iterating over the current content of the archive we must
1143 determine a number of things: which archive members to keep,
1144 which are replaced, and where to insert the new members. */
1145 Elf_Cmd cmd = ELF_C_READ_MMAP;
1147 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
1149 Elf_Arhdr *arhdr = elf_getarhdr (subelf);
1151 /* Ignore the symbol table and the long file name table here. */
1152 if (strcmp (arhdr->ar_name, "/") == 0
1153 || strcmp (arhdr->ar_name, "//") == 0)
1156 struct armem *newp = alloca (sizeof (struct armem));
1157 newp->old_off = elf_getaroff (subelf);
1158 newp->size = arhdr->ar_size;
1159 newp->sec = arhdr->ar_date;
1162 /* Remember long file names. */
1163 remember_long_name (newp, arhdr->ar_name, strlen (arhdr->ar_name));
1165 /* Check whether this is a file we are looking for. */
1166 if (oper != oper_qappend)
1168 /* Check whether this is the member used as the insert point. */
1169 if (member != NULL && strcmp (arhdr->ar_name, member) == 0)
1171 /* Note that all == NULL means insert at the beginning. */
1172 if (ipos == ipos_before)
1173 after_memberelem = all;
1175 after_memberelem = newp;
1180 entry.key = arhdr->ar_name;
1181 ENTRY *res = hsearch (entry, FIND);
1182 if (res != NULL && found[(char **) res->data - argv] == NULL)
1184 found[(char **) res->data - argv] = newp;
1186 /* If we insert before or after a certain element move
1187 all files to a special list. */
1188 if (unlikely (ipos != ipos_none || oper == oper_move))
1190 if (after_memberelem == newp)
1191 /* Since we remove this element even though we should
1192 insert everything after it, we in fact insert
1193 everything after the previous element. */
1194 after_memberelem = all;
1202 all = newp->next = newp;
1205 newp->next = all->next;
1206 all = all->next = newp;
1210 cmd = elf_next (subelf);
1211 if (elf_end (subelf) != 0)
1212 error (EXIT_FAILURE, 0, "%s: %s", arfname, elf_errmsg (-1));
1215 if (oper != oper_qappend)
1220 error (EXIT_FAILURE, 0, gettext ("position member %s not found"),
1223 if (oper == oper_move)
1225 /* Make sure all requested elements are found in the archive. */
1226 for (int cnt = 0; cnt < argc; ++cnt)
1228 if (found[cnt] == NULL)
1230 fprintf (stderr, gettext ("%s: no entry %s in archive!\n"),
1231 program_invocation_short_name, argv[cnt]);
1236 printf ("m - %s\n", argv[cnt]);
1241 /* Open all the new files, get their sizes and add all symbols. */
1242 for (int cnt = 0; cnt < argc; ++cnt)
1244 const char *bname = basename (argv[cnt]);
1245 size_t bnamelen = strlen (bname);
1246 if (found[cnt] == NULL)
1248 found[cnt] = alloca (sizeof (struct armem));
1249 found[cnt]->old_off = -1;
1251 remember_long_name (found[cnt], bname, bnamelen);
1256 int newfd = open (argv[cnt], O_RDONLY);
1259 error (0, errno, gettext ("cannot open %s"), argv[cnt]);
1262 else if (fstat (newfd, &newst) == -1)
1264 error (0, errno, gettext ("cannot stat %s"), argv[cnt]);
1268 else if (!S_ISREG (newst.st_mode))
1270 error (0, errno, gettext ("%s is no regular file"), argv[cnt]);
1274 else if (update_newer
1275 && found[cnt]->old_off != -1l
1276 && found[cnt]->sec > st.st_mtime)
1277 /* Do nothing, the file in the archive is younger. */
1279 else if ((newelf = elf_begin (newfd, ELF_C_READ_MMAP, NULL))
1283 gettext ("cannot get ELF descriptor for %s: %s\n"),
1284 argv[cnt], elf_errmsg (-1));
1290 printf ("%c - %s\n",
1291 found[cnt]->old_off == -1l ? 'a' : 'r', argv[cnt]);
1293 found[cnt]->elf = newelf;
1294 found[cnt]->sec = arlib_deterministic_output ? 0 : newst.st_mtime;
1295 found[cnt]->uid = arlib_deterministic_output ? 0 : newst.st_uid;
1296 found[cnt]->gid = arlib_deterministic_output ? 0 : newst.st_gid;
1297 found[cnt]->mode = newst.st_mode;
1298 found[cnt]->name = bname;
1300 found[cnt]->mem = elf_rawfile (newelf, &found[cnt]->size);
1301 if (found[cnt]->mem == NULL
1302 || elf_cntl (newelf, ELF_C_FDDONE) != 0)
1303 error (EXIT_FAILURE, 0, gettext ("cannot read %s: %s"),
1304 argv[cnt], elf_errmsg (-1));
1308 if (found[cnt]->old_off != -1l)
1309 /* Remember long file names. */
1310 remember_long_name (found[cnt], bname, bnamelen);
1328 /* If we have no entry point so far add at the end. AFTER_MEMBERELEM
1329 being NULL when adding before an entry means add at the beginning. */
1330 if (ipos != ipos_before && after_memberelem == NULL)
1331 after_memberelem = all;
1333 /* Convert the circular list into a normal list first. */
1336 struct armem *tmp = all;
1341 struct armem *last_added = after_memberelem;
1342 for (int cnt = 0; cnt < argc; ++cnt)
1343 if (oper != oper_replace || found[cnt]->old_off == -1)
1345 if (last_added == NULL)
1347 found[cnt]->next = all;
1348 last_added = all = found[cnt];
1352 found[cnt]->next = last_added->next;
1353 last_added = last_added->next = found[cnt];
1357 /* Finally compute the offset and add the symbols for the files
1358 after the insert point. */
1359 if (likely (all != NULL))
1360 for (struct armem *memp = all; memp != NULL; memp = memp->next)
1362 memp->off = cur_off;
1364 if (memp->mem == NULL)
1367 /* Fake initializing arhdr and subelf to keep gcc calm. */
1368 asm ("" : "=m" (arhdr), "=m" (subelf));
1369 if (elf_rand (elf, memp->old_off) == 0
1370 || (subelf = elf_begin (fd, ELF_C_READ_MMAP, elf)) == NULL
1371 || (arhdr = elf_getarhdr (subelf)) == NULL)
1372 /* This should never happen since we already looked at the
1373 archive content. But who knows... */
1374 error (EXIT_FAILURE, 0, "%s: %s", arfname, elf_errmsg (-1));
1376 arlib_add_symbols (subelf, arfname, arhdr->ar_name, cur_off);
1381 arlib_add_symbols (memp->elf, arfname, memp->name, cur_off);
1383 cur_off += (((memp->size + 1) & ~((off_t) 1))
1384 + sizeof (struct ar_hdr));
1387 /* Now we have all the information for the symbol table and long
1388 file name table. Construct the final layout. */
1391 /* Create a new, temporary file in the same directory as the
1393 char tmpfname[strlen (arfname) + 7];
1394 strcpy (stpcpy (tmpfname, arfname), "XXXXXX");
1397 newfd = mkstemp (tmpfname);
1400 newfd = open (arfname, O_RDWR | O_CREAT | O_EXCL, DEFFILEMODE);
1401 if (newfd == -1 && errno == EEXIST)
1402 /* Bah, first the file did not exist, now it does. Restart. */
1403 return do_oper_insert (oper, arfname, argv, argc, member);
1405 if (unlikely (newfd == -1))
1408 /* Create the header. */
1409 if (unlikely (write_retry (newfd, ARMAG, SARMAG) != SARMAG))
1414 // XXX Use /prof/self/fd/%d ???
1420 error (0, errno, gettext ("cannot create new file"));
1425 /* If the new archive is not empty we actually have something to do. */
1426 if (likely (all != NULL))
1428 /* Write the symbol table or the long file name table or both. */
1429 if (symtab.symsnamelen != 0
1430 && ((write_retry (newfd, symtab.symsoff, symtab.symsofflen)
1431 != (ssize_t) symtab.symsofflen)
1432 || (write_retry (newfd, symtab.symsname, symtab.symsnamelen)
1433 != (ssize_t) symtab.symsnamelen)))
1436 if (symtab.longnameslen > sizeof (struct ar_hdr)
1437 && (write_retry (newfd, symtab.longnames, symtab.longnameslen)
1438 != (ssize_t) symtab.longnameslen))
1446 if (all->mem != NULL)
1448 /* This is a new file. If there is anything from the
1449 archive left to be written do it now. */
1450 if (start != -1 && copy_content (elf, newfd, start, len))
1456 /* Create the header. */
1457 struct ar_hdr arhdr;
1458 char tmpbuf[sizeof (arhdr.ar_name) + 1];
1459 if (all->long_name_off == -1)
1461 size_t namelen = strlen (all->name);
1462 char *p = mempcpy (arhdr.ar_name, all->name, namelen);
1464 memset (p, ' ', sizeof (arhdr.ar_name) - namelen - 1);
1468 snprintf (tmpbuf, sizeof (arhdr.ar_name) + 1, "/%-*ld",
1469 (int) sizeof (arhdr.ar_name), all->long_name_off);
1470 memcpy (arhdr.ar_name, tmpbuf, sizeof (arhdr.ar_name));
1473 no0print (false, arhdr.ar_date, sizeof (arhdr.ar_date),
1475 no0print (false, arhdr.ar_uid, sizeof (arhdr.ar_uid), all->uid);
1476 no0print (false, arhdr.ar_gid, sizeof (arhdr.ar_gid), all->gid);
1477 no0print (true, arhdr.ar_mode, sizeof (arhdr.ar_mode),
1479 no0print (false, arhdr.ar_size, sizeof (arhdr.ar_size),
1481 memcpy (arhdr.ar_fmag, ARFMAG, sizeof (arhdr.ar_fmag));
1483 if (unlikely (write_retry (newfd, &arhdr, sizeof (arhdr))
1487 /* Now the file itself. */
1488 if (unlikely (write_retry (newfd, all->mem, all->size)
1489 != (off_t) all->size))
1492 /* Pad the file if its size is odd. */
1493 if ((all->size & 1) != 0)
1494 if (unlikely (write_retry (newfd, "\n", 1) != 1))
1499 /* This is a member from the archive. */
1500 if (write_member (all, &start, &len, elf, cur_off, newfd)
1508 /* Write the last part. */
1509 if (start != -1 && copy_content (elf, newfd, start, len))
1513 /* Set the mode of the new file to the same values the original file
1516 && (fchmod (newfd, st.st_mode & ALLPERMS) != 0
1517 /* Never complain about fchown failing. */
1518 || (({asm ("" :: "r" (fchown (newfd, st.st_uid, st.st_gid))); }),
1520 || (newfd = -1, rename (tmpfname, arfname) != 0)))
1536 #include "debugpred.h"