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