forked from wasm3/wasm3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
398 lines (343 loc) · 10.7 KB
/
main.c
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//
// Wasm3 - high performance WebAssembly interpreter written in C.
//
// Copyright © 2019 Steven Massey, Volodymyr Shymanskyy.
// All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include "wasm3.h"
#include "m3_api_wasi.h"
#include "m3_api_libc.h"
#include "m3_api_tracer.h"
#include "m3_env.h"
#define FATAL(msg, ...) { printf("Error: [Fatal] " msg "\n", ##__VA_ARGS__); goto _onfatal; }
M3Result repl_load (IM3Runtime runtime, const char* fn)
{
M3Result result = m3Err_none;
u8* wasm = NULL;
u32 fsize = 0;
FILE* f = fopen (fn, "rb");
if (!f) {
return "cannot open file";
}
fseek (f, 0, SEEK_END);
fsize = ftell(f);
fseek (f, 0, SEEK_SET);
if (fsize < 8) {
return "file is too small";
} else if (fsize > 10*1024*1024) {
return "file too big";
}
wasm = (u8*) malloc(fsize);
if (!wasm) {
return "cannot allocate memory for wasm binary";
}
if (fread (wasm, 1, fsize, f) != fsize) {
return "cannot read file";
}
fclose (f);
IM3Module module;
result = m3_ParseModule (runtime->environment, &module, wasm, fsize);
if (result) return result;
result = m3_LoadModule (runtime, module);
if (result) return result;
result = m3_LinkSpecTest (runtime->modules);
return result;
}
M3Result repl_load_hex (IM3Runtime runtime, u32 fsize)
{
M3Result result = m3Err_none;
if (fsize < 8) {
return "file is too small";
} else if (fsize > 10*1024*1024) {
return "file too big";
}
u8* wasm = (u8*) malloc(fsize);
if (!wasm) {
return "cannot allocate memory for wasm binary";
}
{ // Load hex data from stdin
u32 wasm_idx = 0;
char hex[3] = { 0, };
int hex_idx = 0;
while (wasm_idx < fsize) {
int c = fgetc(stdin);
if (!isxdigit(c)) continue; // Skip non-hex chars
hex[hex_idx++] = c;
if (hex_idx == 2) {
int val = strtol(hex, NULL, 16);
wasm[wasm_idx++] = val;
hex_idx = 0;
}
}
if (!fgets(hex, 3, stdin)) // Consume a newline
return "cannot read EOL";
}
IM3Module module;
result = m3_ParseModule (runtime->environment, &module, wasm, fsize);
if (result) return result;
result = m3_LoadModule (runtime, module);
if (result) return result;
result = m3_LinkSpecTest (runtime->modules);
return result;
}
M3Result repl_call (IM3Runtime runtime, const char* name, int argc, const char* argv[])
{
M3Result result = m3Err_none;
IM3Function func;
result = m3_FindFunction (&func, runtime, name);
if (result) return result;
// TODO
if (argc) {
if (!strcmp(name, "main") || !strcmp(name, "_main")) {
return "passing arguments to libc main() not implemented";
}
}
result = m3_CallWithArgs (func, argc, argv);
if (result) return result;
return result;
}
M3Result repl_dump(IM3Runtime runtime)
{
uint32_t len;
uint8_t* mem = m3_GetMemory(runtime, &len, 0);
if (mem) {
FILE* f = fopen ("wasm3_dump.bin", "wb");
if (!f) {
return "cannot open file";
}
if (fwrite (mem, 1, len, f) != len) {
return "cannot write file";
}
fclose (f);
}
return m3Err_none;
}
void repl_free(IM3Runtime* runtime)
{
if (*runtime) {
m3_FreeRuntime (*runtime);
}
}
M3Result repl_init(IM3Environment env, IM3Runtime* runtime, unsigned stack)
{
repl_free(runtime);
*runtime = m3_NewRuntime (env, stack, NULL);
if (*runtime == NULL) {
return "m3_NewRuntime failed";
}
return m3Err_none;
}
static
void unescape(char* buff)
{
char* outp = buff;
while (*buff) {
if (*buff == '\\') {
switch (*(buff+1)) {
case '0': *outp++ = '\0'; break;
case 'b': *outp++ = '\b'; break;
case 'n': *outp++ = '\n'; break;
case 'r': *outp++ = '\r'; break;
case 't': *outp++ = '\t'; break;
case 'x': {
char hex[3] = { *(buff+2), *(buff+3), '\0' };
*outp = strtol(hex, NULL, 16);
buff += 2; outp += 1;
break;
}
// Otherwise just pass the letter
// Also handles '\\'
default: *outp++ = *(buff+1); break;
}
buff += 2;
} else {
*outp++ = *buff++;
}
}
*outp = '\0';
}
static
int split_argv(char *str, char** argv)
{
int result = 0;
char* curr = str;
int len = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (strchr(" \n\r\t", str[i])) {
if (len) { // Found space after non-space
str[i] = '\0';
//unescape(curr); // TODO: breaks windows build?
argv[result++] = curr;
len = 0;
}
} else {
if (!len) { // Found non-space after space
curr = &str[i];
}
len++;
}
}
argv[result] = NULL;
return result;
}
void print_version() {
const char* wasm3_env = getenv("WASM3");
const char* wasm3_arch = getenv("WASM3_ARCH");
printf("Wasm3 v" M3_VERSION "%s on %s\n",
(wasm3_arch || wasm3_env) ? " self-hosting" : "",
wasm3_arch ? wasm3_arch : M3_ARCH);
printf("Build: " __DATE__ " " __TIME__ ", " M3_COMPILER_VER "\n");
}
void print_usage() {
puts("Usage:");
puts(" wasm3 [options] <file> [args...]");
puts(" wasm3 --repl [file]");
puts("Options:");
puts(" --func <function> function to run default: _start)");
puts(" --stack-size <size> stack size in bytes default: 64KB)");
puts(" --dump-on-trap dump wasm memory");
}
#define ARGV_SHIFT() { i_argc--; i_argv++; }
#define ARGV_SET(x) { if (i_argc > 0) { x = i_argv[0]; ARGV_SHIFT(); } }
int main (int i_argc, const char* i_argv[])
{
M3Result result = m3Err_none;
IM3Environment env = m3_NewEnvironment ();
IM3Runtime runtime = NULL;
bool argRepl = false;
bool argDumpOnTrap = false;
const char* argFile = NULL;
const char* argFunc = "_start";
unsigned argStackSize = 64*1024;
// m3_PrintM3Info ();
ARGV_SHIFT(); // Skip executable name
while (i_argc > 0)
{
const char* arg = i_argv[0];
if (arg[0] != '-') break;
ARGV_SHIFT();
if (!strcmp("--help", arg) or !strcmp("-h", arg)) {
print_usage();
return 0;
} else if (!strcmp("--version", arg)) {
print_version();
return 0;
} else if (!strcmp("--repl", arg)) {
argRepl = true;
} else if (!strcmp("--dump-on-trap", arg)) {
argDumpOnTrap = true;
} else if (!strcmp("--stack-size", arg)) {
const char* tmp;
ARGV_SET(tmp);
argStackSize = atol(tmp);
} else if (!strcmp("--dir", arg)) {
const char* argDir;
ARGV_SET(argDir);
(void)argDir;
} else if (!strcmp("--func", arg) or !strcmp("-f", arg)) {
ARGV_SET(argFunc);
}
}
if ((argRepl and (i_argc > 1)) or // repl supports 0 or 1 args
(not argRepl and (i_argc < 1)) // normal expects at least 1
) {
print_usage();
return 1;
}
ARGV_SET(argFile);
result = repl_init(env, &runtime, argStackSize);
if (result) FATAL("repl_init: %s", result);
if (argFile) {
result = repl_load(runtime, argFile);
if (result) FATAL("repl_load: %s", result);
#if defined(d_m3HasWASI) || defined(d_m3HasMetaWASI) || defined(d_m3HasUVWASI)
result = m3_LinkWASI (runtime->modules);
if (result) FATAL("m3_LinkWASI: %s", result);
#endif
#if defined(d_m3HasTracer)
result = m3_LinkTracer (runtime->modules);
if (result) FATAL("m3_LinkTracer: %s", result);
#endif
result = m3_LinkLibC (runtime->modules);
if (result) FATAL("m3_LinkLibC: %s", result);
if (argFunc and not argRepl) {
if (!strcmp(argFunc, "_start")) {
// When passing args to WASI, include wasm filename as argv[0]
result = repl_call(runtime, argFunc, i_argc+1, i_argv-1);
} else {
result = repl_call(runtime, argFunc, i_argc, i_argv);
}
if (result == m3Err_trapExit) {
return runtime->exit_code;
}
if (result) {
if (argDumpOnTrap) {
repl_dump(runtime);
}
FATAL("repl_call: %s", result);
}
}
}
while (argRepl)
{
char cmd_buff[2048] = { 0, };
char* argv[32] = { 0, };
fprintf(stdout, "wasm3> ");
fflush(stdout);
if (!fgets(cmd_buff, sizeof(cmd_buff), stdin)) {
return 0;
}
int argc = split_argv(cmd_buff, argv);
if (argc <= 0) {
continue;
}
result = m3Err_none;
if (!strcmp(":init", argv[0])) {
result = repl_init(env, &runtime, argStackSize);
} else if (!strcmp(":version", argv[0])) {
print_version();
} else if (!strcmp(":exit", argv[0])) {
repl_free(&runtime);
return 0;
} else if (!strcmp(":load", argv[0])) { // :load <filename>
result = repl_load(runtime, argv[1]);
} else if (!strcmp(":load-hex", argv[0])) { // :load-hex <size>\n <hex-encoded-binary>
result = repl_load_hex(runtime, atol(argv[1]));
} else if (!strcmp(":dump", argv[0])) { // :load <filename>
result = repl_dump(runtime);
} else if (argv[0][0] == ':') {
result = "no such command";
} else {
unescape(argv[0]);
result = repl_call(runtime, argv[0], argc-1, (const char**)(argv+1));
}
if (result) {
fprintf (stderr, "Error: %s", result);
M3ErrorInfo info;
m3_GetErrorInfo (runtime, &info);
fprintf (stderr, " (%s)\n", info.message);
if (result == m3Err_trapExit) {
// warn that exit was called
fprintf(stderr, M3_ARCH "-wasi: exit(%d)\n", runtime->exit_code);
}
}
}
_onfatal:
if (result) {
fprintf (stderr, "Error: %s", result);
if (runtime)
{
M3ErrorInfo info;
m3_GetErrorInfo (runtime, &info);
fprintf (stderr, " (%s)", info.message);
}
fprintf (stderr, "\n");
}
m3_FreeRuntime (runtime);
m3_FreeEnvironment (env);
return 0;
}