2 * SPDX-License-Identifier: GPL-2.0-only
4 * Copyright 2009 Red Hat, Inc.
6 * Author: Peter Jones <pjones@redhat.com>
16 #include "elfcreator.h"
19 static int should_copy_scn(Elf
*elf
, GElf_Shdr
*shdr
, struct strlist
*scns
)
24 if (elf_getshdrstrndx(elf
, &shstrndx
) < 0)
26 name
= elf_strptr(elf
, shstrndx
, shdr
->sh_name
);
30 if (strlist__has_entry(scns
, name
))
35 int main(int argc
, char *argv
[])
38 struct strlist
*sections
;
39 char *infile
= NULL
, *outfile
= NULL
;
43 int copy_all_sections
= 0;
46 sections
= strlist__new(false);
47 for (n
= 1; n
< argc
; n
++) {
48 if (!strcmp(argv
[n
], "-a")) {
49 copy_all_sections
= 1;
50 } else if (!strcmp(argv
[n
], "-s")) {
52 fprintf(stderr
, "Missing argument to -s\n");
56 strlist__add(sections
, argv
[n
]);
58 } else if (!strcmp(argv
[n
], "-o")) {
60 fprintf(stderr
, "Missing argument to -o\n");
66 } else if (!strcmp(argv
[n
], "-?") ||
67 !strcmp(argv
[n
], "--help") ||
68 !strcmp(argv
[n
], "--usage")) {
69 printf("usage: scncopy [-s section0 [[-s section1] ... -s sectionN] | -a ] -o outfile infile\n");
71 } else if (n
== argc
-1) {
74 fprintf(stderr
, "usage: pjoc -s section 0 [[-s section1] ... -s sectionN] -o outfile infile\n");
78 if (!infile
|| !outfile
) {
79 fprintf(stderr
, "usage: pjoc -s section 0 [[-s section1] ... -s sectionN] -o outfile infile\n");
83 if (!(fd
= open(infile
, O_RDONLY
))) {
84 fprintf(stderr
, "Could not open \"%s\" for reading: %m\n", infile
);
88 elf_version(EV_CURRENT
);
90 if ((elf
= elf_begin(fd
, ELF_C_READ_MMAP_PRIVATE
, NULL
)) == NULL
) {
91 fprintf(stderr
, "cannot get elf descriptor for \"%s\": %s\n",
92 infile
, elf_errmsg(-1));
97 if (elf_kind(elf
) != ELF_K_ELF
) {
98 fprintf(stderr
, "\"%s\" is not an ELF file\n", infile
);
105 if ((ctor
= elfcreator_begin(outfile
, elf
)) == NULL
) {
106 fprintf(stderr
, "could not initialize ELF creator\n");
111 while ((scn
= elf_nextscn(elf
, scn
)) != NULL
) {
112 GElf_Shdr shdr_mem
, *shdr
;
114 shdr
= gelf_getshdr(scn
, &shdr_mem
);
118 if (!should_copy_scn(elf
, shdr
, sections
) && !copy_all_sections
)
121 elfcreator_copy_scn(ctor
, scn
);
123 elfcreator_end(ctor
);