5aec1a2bc2c5e50312dc32b5ddb8c932e7127534
[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
37   /* Now that we have a (hopefully) sane environment, execute commands. */
38   me = elfu_mFromElf(hIn.e);
39   if (me) {
40     closeElf(&hIn);
41     printf("Model successfully loaded.\n");
42
43     elfu_mDumpElf(me);
44
45     elfu_mCheck(me);
46     printf("Input model checked.\n");
47   } else {
48     printf("Failed to load model, aborting.\n");
49     goto EXIT;
50   }
51
52
53   /* Copy the input ELF to the output file if the latter is specified.
54    * Perform requested transformations on the memory model on-the-fly. */
55   if (!opts.fnOutput) {
56     printf("No output file specified - no further operations performed.\n");
57   } else {
58     if (opts.fnReladd) {
59       ELFHandles hRel = { 0 };
60       ElfuElf *mrel = NULL;
61
62       openElf(&hRel, opts.fnReladd, ELF_C_READ);
63       if (!hRel.e) {
64         printf("--reladd: Failed to open file for --reladd, skipping operation.\n");
65       } else {
66         mrel = elfu_mFromElf(hRel.e);
67         closeElf(&hRel);
68         if (!me) {
69           printf("--reladd: Failed to load model for --reladd, skipping operation.\n");
70         } else {
71           printf("--reladd: Model successfully loaded.\n");
72           elfu_mCheck(mrel);
73           printf("--reladd: Input model checked.\n");
74           elfu_mReladd(me, mrel);
75         }
76       }
77     }
78
79     elfu_mCheck(me);
80     printf("Output model checked.\n");
81
82     elfu_mDumpElf(me);
83
84     openElf(&hOut, opts.fnOutput, ELF_C_WRITE);
85     if (!hOut.e) {
86       printf("Failed to open output file. Aborting.\n");
87       exitval = EXIT_FAILURE;
88       goto EXIT;
89     }
90
91     elfu_mToElf(me, hOut.e);
92     printf("Model converted to ELF, ready to be written.\n");
93   }
94
95
96
97 EXIT:
98   if (hOut.e) {
99     if (elf_update(hOut.e, ELF_C_WRITE) < 0) {
100       fprintf(stderr, "elf_update() failed: %s\n", elf_errmsg(-1));
101     }
102     closeElf(&hOut);
103   }
104
105   if (hIn.e) {
106     closeElf(&hIn);
107   }
108
109   return (exitval);
110 }