1 /* Copyright (C) 1999, 2000, 2002 Red Hat, Inc.
2 This file is part of elfutils.
3 Written by Ulrich Drepper <drepper@redhat.com>, 1999.
5 This file is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 elfutils is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
28 #include <sys/param.h>
32 main (int argc, char *argv[])
44 /* Open the archive. */
45 fd = open (argv[1], O_RDONLY);
48 printf ("Cannot open input file: %m");
52 /* Set the ELF version. */
53 elf_version (EV_CURRENT);
55 /* Create an ELF descriptor. */
57 elf = elf_begin (fd, cmd, NULL);
60 printf ("Cannot create ELF descriptor: %s\n", elf_errmsg (-1));
64 /* If it is no archive punt. */
65 if (elf_kind (elf) != ELF_K_AR)
67 printf ("`%s' is no archive\n", argv[1]);
71 /* Get the elements of the archive one after the other. */
72 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
74 /* The the header for this element. */
75 Elf_Arhdr *arhdr = elf_getarhdr (subelf);
79 printf ("cannot get arhdr: %s\n", elf_errmsg (-1));
83 if (strcmp (arhdr->ar_name, argv[2]) == 0)
87 /* Get the offset of the file in the archive. */
88 offset = elf_getbase (subelf);
92 Failed to get base address for the archive element: %s\n",
97 /* Open the output file. */
98 outfd = open (argv[3], O_CREAT | O_TRUNC | O_RDWR, 0666);
101 printf ("cannot open output file: %m");
105 /* Now write out the data. */
106 todo = arhdr->ar_size;
110 ssize_t n = pread (fd, buf, MIN (sizeof buf, todo), offset);
114 if (write (outfd, buf, n) != n)
116 puts ("Writing output failed");
124 /* Check whether all the date was read and written out. */
127 puts ("Reading archive member failed.");
131 /* Close the descriptors. */
132 if (elf_end (subelf) != 0 || elf_end (elf) != 0)
134 printf ("Freeing ELF descriptors failed: %s", elf_errmsg (-1));
145 /* Get next archive element. */
146 cmd = elf_next (subelf);
147 if (elf_end (subelf) != 0)
149 printf ("error while freeing sub-ELF descriptor: %s\n",
155 /* When we reach this point we haven't found the given file in the
157 printf ("File `%s' not found in archive\n", argv[2]);