1e06d2998bca0642143bbb2deee1a51aaab14ed5
[centaur.git] / src / main.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include <getopt.h>
5 #include <libelf.h>
6 #include <gelf.h>
7
8 #include <libelfu/libelfu.h>
9
10 #include "elfhandle.h"
11 #include "options.h"
12 #include "printing.h"
13
14
15 int main(int argc, char **argv)
16 {
17   CLIOpts opts = { 0 };
18   ELFHandles hIn = { 0 };
19   ELFHandles hOut = { 0 };
20   int exitval = EXIT_SUCCESS;
21
22   /* Is libelf alive and well? */
23   if (elf_version(EV_CURRENT) == EV_NONE) {
24     fprintf(stderr, "libelf init error: %s\n", elf_errmsg(-1));
25   }
26
27
28   /* Parse and validate user input */
29   parseOptions(&opts, argc, argv);
30
31
32   /* Open input/output files */
33   openElf(&hIn, opts.fnInput, ELF_C_READ);
34   if (!hIn.e) {
35     exitval = EXIT_FAILURE;
36     goto EXIT;
37   }
38
39   if (opts.fnOutput) {
40     openElf(&hOut, opts.fnOutput, ELF_C_WRITE);
41     if (!hOut.e) {
42       exitval = EXIT_FAILURE;
43       goto EXIT;
44     }
45   }
46
47
48   /* Now that we have a (hopefully) sane environment, execute commands */
49   if (opts.printHeader) {
50     printHeader(hIn.e);
51   }
52
53   if (opts.printSegments) {
54     printSegments(hIn.e);
55   }
56
57   if (opts.printSections) {
58     printSections(hIn.e);
59   }
60
61
62   /* Copy the input ELF to the output file if the latter is specified */
63   if (opts.fnOutput) {
64     ElfuElf *me;
65
66     me = elfu_mFromElf(hIn.e);
67
68     if (me) {
69       printf("Model successfully loaded.\n");
70       elfu_mCheck(me);
71       printf("Input model checked.\n");
72
73       if (opts.insertBeforeSz) {
74         elfu_mInsertBefore(me, opts.insertBeforeOffs, opts.insertBeforeSz);
75       }
76
77       if (opts.insertAfterSz) {
78         elfu_mInsertAfter(me, opts.insertAfterOffs, opts.insertAfterSz);
79       }
80
81       elfu_mCheck(me);
82       printf("Output model checked.\n");
83       elfu_mToElf(me, hOut.e);
84       printf("Model converted to ELF, ready to be written.\n");
85     } else {
86       printf("Failed to load model.\n");
87     }
88   }
89
90
91
92 EXIT:
93   if (hOut.e) {
94     if (elf_update(hOut.e, ELF_C_WRITE) < 0) {
95       fprintf(stderr, "elf_update() failed: %s\n", elf_errmsg(-1));
96     }
97     closeElf(&hOut);
98   }
99
100   if (hIn.e) {
101     closeElf(&hIn);
102   }
103
104   return (exitval);
105 }