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 = 0;
50 unsigned long phsize = 0;
51 unsigned long prevaddr = 0;
53 if (ac > 3 || (ac > 1 && av[1][0] == '-')) {
54 fprintf(stderr, "Usage: %s [elf-file [image-file]]\n", av[0]);
73 if (eh.e_ident[EI_MAG0] != ELFMAG0
74 || eh.e_ident[EI_MAG1] != ELFMAG1
75 || eh.e_ident[EI_MAG2] != ELFMAG2
76 || eh.e_ident[EI_MAG3] != ELFMAG3) {
77 fprintf(stderr, "%s: not an ELF file\n", ni);
81 fseek(fi, eh.e_phoff, 0);
83 for (i = 0; i < eh.e_phnum; ++i) {
85 if (ph.p_type != PT_LOAD)
87 if (phsize == 0 || prevaddr == 0) {
88 phoffset = ph.p_offset;
91 phsize = ph.p_offset + ph.p_filesz - phoffset;
92 prevaddr = ph.p_vaddr;
95 fprintf(stderr, "%s: doesn't have a loadable segment\n", ni);
101 fo = fopen(no, "wb");
108 fseek(fi, phoffset, 0);
109 for (len = phsize; len != 0; len -= nb) {
111 if (nb > sizeof(buf))
114 if (fwrite(buf, 1, nb, fo) != nb) {
115 fprintf(stderr, "%s: write error\n", no);