-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cpp
More file actions
117 lines (98 loc) · 2.71 KB
/
Copy pathMain.cpp
File metadata and controls
117 lines (98 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <stdexcept>
#include "Executable.hpp"
#include "Buffer.hpp"
#include "Utils.hpp"
#define USAGE "Usage: ExeInterpreter <program_name>"
#define OP_OPEN1 "Opening file "
#define OP_OPEN2 " ..."
#define OP_OPEN_FAIL "Could not open file"
#define OP_MALLOC "Allocating memory..."
#define OP_MALLOC_FAIL "Memory allocation failed"
#define OP_READ "Reading file..."
#define OP_READ_FAIL "Could not read file"
#define OP_PARSE "Parsing executable..."
#define OP_PARSE_FAIL "Executable file failed to validate"
#define OP_RELOCATE "Relocating executable..."
#define OP_RELOCATE_FAIL "Could not relocate executable"
void usage(void) {
print(USAGE);
}
int main(int argc, char** argv) {
// Check arguments
if(argc < 2) {
usage();
return 0;
}
// Find windows executable path
// First find relative path
char relative_path[PATH_MAX];
relative_path[0] = 0;
for(int i = 1; i < argc; i++) {
strcat(relative_path, argv[i]);
if(i != argc -1) {
strcat(relative_path, " ");
}
}
// Then find the absolute path
char absolute_path[PATH_MAX];
if(relative_path[0] == '/') {
strcpy(absolute_path, relative_path);
} else {
char pwd[PATH_MAX];
getcwd(pwd, sizeof(pwd));
strcpy(absolute_path, pwd);
strcat(absolute_path, "/");
strcat(absolute_path, relative_path);
}
// Open as file
print(std::string(OP_OPEN1) + absolute_path + OP_OPEN2);
FILE* exe_file = fopen(absolute_path, "rb");
if(!exe_file) {
printf(OP_OPEN_FAIL);
printf(absolute_path);
printf("\n");
usage();
return 0;
}
// Read file
fseek(exe_file, 0, SEEK_END);
size_t file_size = ftell(exe_file);
fseek(exe_file, 0, SEEK_SET);
print(OP_MALLOC);
unsigned char* data = (unsigned char*) malloc(file_size);
if(!data) {
print(OP_MALLOC_FAIL);
return 1;
}
print(OP_READ);
size_t read_amount = fread(data, sizeof(unsigned char), file_size, exe_file);
if(read_amount != file_size) {
print(OP_READ_FAIL);
return 1;
}
// Parse the executable file
Executable executable;
print(OP_PARSE);
try {
executable.parse(Buffer(file_size, data));
} catch(EIException* ex) {
print(OP_PARSE_FAIL);
ex->printMessage();
return 1;
}
print(OP_RELOCATE);
try {
executable.relocate(0);
} catch(EIException* ex) {
print(OP_RELOCATE_FAIL);
ex->printMessage();
return 1;
}
return 0;
}