2 * elfextract.c - Extract the loadable program segment from an elf file.
4 * Copyright 1996 Paul Mackerras.
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 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 #include <linux/elf.h>
29 rd(void *buf, int len)
33 nr = fread(buf, 1, len, fi);
37 fprintf(stderr, "%s: read error\n", ni);
39 fprintf(stderr, "%s: short file\n", ni);
44 main(int ac, char **av)
49 unsigned long phoffset, phsize, prevaddr;
51 if (ac > 3 || (ac > 1 && av[1][0] == '-')) {
52 fprintf(stderr, "Usage: %s [elf-file [image-file]]\n", av[0]);
71 if (eh.e_ident[EI_MAG0] != ELFMAG0
72 || eh.e_ident[EI_MAG1] != ELFMAG1
73 || eh.e_ident[EI_MAG2] != ELFMAG2
74 || eh.e_ident[EI_MAG3] != ELFMAG3) {
75 fprintf(stderr, "%s: not an ELF file\n", ni);
79 fseek(fi, eh.e_phoff, 0);
81 for (i = 0; i < eh.e_phnum; ++i) {
83 if (ph.p_type != PT_LOAD)
85 if (phsize == 0 || prevaddr == 0) {
86 phoffset = ph.p_offset;
89 phsize = ph.p_offset + ph.p_filesz - phoffset;
90 prevaddr = ph.p_vaddr;
93 fprintf(stderr, "%s: doesn't have a loadable segment\n", ni);
106 fseek(fi, phoffset, 0);
107 for (len = phsize; len != 0; len -= nb) {
109 if (nb > sizeof(buf))
112 if (fwrite(buf, 1, nb, fo) != nb) {
113 fprintf(stderr, "%s: write error\n", no);