pahole: Describe expected use of 'default' in the man page
[dwarves.git] / scncopy.c
blob233cae2b8745e683e9b7b334c0248255cbeff5db
1 /*
2 * SPDX-License-Identifier: GPL-2.0-only
4 * Copyright 2009 Red Hat, Inc.
6 * Author: Peter Jones <pjones@redhat.com>
7 */
8 #include <gelf.h>
9 #include <stdio.h>
10 #include <strings.h>
11 #include <string.h>
12 #include <fcntl.h>
13 #include <stdlib.h>
14 #include <unistd.h>
16 #include "elfcreator.h"
17 #include "dutil.h"
19 static int should_copy_scn(Elf *elf, GElf_Shdr *shdr, struct strlist *scns)
21 char *name;
22 size_t shstrndx;
24 if (elf_getshdrstrndx(elf, &shstrndx) < 0)
25 return 0;
26 name = elf_strptr(elf, shstrndx, shdr->sh_name);
27 if (name == NULL)
28 return 0;
30 if (strlist__has_entry(scns, name))
31 return 1;
32 return 0;
35 int main(int argc, char *argv[])
37 int n;
38 struct strlist *sections;
39 char *infile = NULL, *outfile = NULL;
40 int fd;
41 Elf *elf;
42 Elf_Scn *scn;
43 int copy_all_sections = 0;
44 ElfCreator *ctor;
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")) {
51 if (n == argc-1) {
52 fprintf(stderr, "Missing argument to -s\n");
53 return -1;
55 n++;
56 strlist__add(sections, argv[n]);
57 continue;
58 } else if (!strcmp(argv[n], "-o")) {
59 if (n == argc-1) {
60 fprintf(stderr, "Missing argument to -o\n");
61 return -1;
63 n++;
64 outfile = argv[n];
65 continue;
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");
70 return 0;
71 } else if (n == argc-1) {
72 infile = argv[n];
73 } else {
74 fprintf(stderr, "usage: pjoc -s section 0 [[-s section1] ... -s sectionN] -o outfile infile\n");
75 return 1;
78 if (!infile || !outfile) {
79 fprintf(stderr, "usage: pjoc -s section 0 [[-s section1] ... -s sectionN] -o outfile infile\n");
80 return 1;
83 if (!(fd = open(infile, O_RDONLY))) {
84 fprintf(stderr, "Could not open \"%s\" for reading: %m\n", infile);
85 return 1;
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));
93 close(fd);
94 return 1;
97 if (elf_kind(elf) != ELF_K_ELF) {
98 fprintf(stderr, "\"%s\" is not an ELF file\n", infile);
99 err:
100 elf_end(elf);
101 close(fd);
102 return 1;
105 if ((ctor = elfcreator_begin(outfile, elf)) == NULL) {
106 fprintf(stderr, "could not initialize ELF creator\n");
107 goto err;
110 scn = NULL;
111 while ((scn = elf_nextscn(elf, scn)) != NULL) {
112 GElf_Shdr shdr_mem, *shdr;
114 shdr = gelf_getshdr(scn, &shdr_mem);
115 if (shdr == NULL)
116 continue;
118 if (!should_copy_scn(elf, shdr, sections) && !copy_all_sections)
119 continue;
121 elfcreator_copy_scn(ctor, scn);
123 elfcreator_end(ctor);
124 return 0;