-
Notifications
You must be signed in to change notification settings - Fork 7
/
interpreter.cc
464 lines (435 loc) · 12.6 KB
/
interpreter.cc
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <cstdio>
#include <exception>
#include <sys/mman.h>
#include <unistd.h>
#include <cmath>
#define ENABLE_DEBUG
#define CALLQ 0xe8
#define SYSCALL 0xf, 0x5
#define RETQ 0xc3
#define MOV_EAX 0xb8
#define MOV_EDX 0xba
#define MOV_EDI 0xbf
/* REX: 0x48, Op: 0xbb */
#define MOV_RBX 0x48, 0xbb
#define JE_SHORT 0x74
#define JE_NEAR 0xf, 0x84
#define JNE_NEAR 0xf, 0x85
#define JNE 0x75
/* Op: 0x80, ModR/M: 0x2b (MODRM.reg = 5) */
#define SUBB_RBX 0x80, 0x2b
/* Op: 0x80, ModR/M: 0x3 */
#define ADDB_RBX 0x80, 0x3
/* Op: 0xff, ModR/M: 0x24, SIB: 0x24 */
#define JMPQ_RSP 0xff, 0x24, 0x24
#define CMPB_RBX 0x80, 0x3b
#define REX_SUB_RBX 0x48, 0x83, 0xeb
#define REX_ADD_RBX 0x48, 0x83, 0xc3
#define REX_MOV_R10_RSI 0x4c, 0x89, 0xd6
#define REX_MOV_R11_RDX 0x4c, 0x89, 0xda
#define REX_MOV_RBX_RSI 0x48, 0x89, 0xde
#define REX_CMPD_R11 0x49, 0x83, 0xfb
#define REX_MOVQ_RBX_R12 0x4c, 0x8b, 0x23
#define REX_MOVQ_R12_R10_R11 0x4f, 0x89, 0x24, 0x1a
#define REX_INCQ_R11 0x49, 0xff, 0xc3
#define REX_CMPQ_R11 0x49, 0x81, 0xfb
#define REX_XORQ_R11_R11 0x4d, 0x31, 0xdb
constexpr size_t TAPE_SIZE = 30000;
constexpr size_t MAX_NESTING = 100;
#ifdef ENABLE_DEBUG
template<typename T>
void debugVec(std::vector<T> &vp) {
for (auto i = vp.cbegin(); i != vp.cend(); ++i) {
std::cout << std::hex << static_cast<size_t>(*i) << std::endl;
}
}
void debugTape(unsigned char *arr, size_t len) {
for (size_t i = 0; i < len; ++i) {
std::cout << static_cast<int>(arr[i]);
}
}
#endif
uint8_t* allocateExecMem(size_t size) {
return static_cast<uint8_t*>(
mmap(
NULL,
size,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0));
}
class VM {
uint8_t *mem = nullptr;
std::vector<uint8_t> *machineCode = nullptr;
void* stdoutBuf = nullptr;
size_t allocatedSize = 0;
size_t prependStaticSize = 0;
public:
VM(std::vector<uint8_t> *machineCode, size_t prependStaticSize) :
machineCode(machineCode), prependStaticSize(prependStaticSize) {
auto pageSize = getpagesize();
allocatedSize = static_cast<size_t>(std::ceil(machineCode->size() / static_cast<double>(pageSize)) * pageSize);
mem = allocateExecMem(allocatedSize);
if (mem == MAP_FAILED) {
throw std::runtime_error("[error] can't allocate memory.");
}
std::memcpy(mem, machineCode->data(), machineCode->size());
// setup a range of memory holding stdout buffer.
stdoutBuf = std::calloc(2048, sizeof(uint8_t));
}
void exec() {
// save the current %rip on stack (by PC-relative).
// %r10 - stdout buffer entry.
// %r11 - stdout buffer counter.
asm(R"(
pushq %%rax
pushq %%rbx
pushq %%r10
pushq %%r11
pushq %%r12
movq %1, %%r10
xorq %%r11, %%r11
lea 0x9(%%rip), %%rax
pushq %%rax
movq %0, %%rax
addq %2, %%rax
jmpq *%%rax
)":: "S" (mem), "m" (stdoutBuf), "D" (prependStaticSize));
// clean the stack.
asm(R"(
addq $8, %rsp
popq %r12
popq %r11
popq %r10
popq %rbx
popq %rax
)");
}
~VM() {
std::free(stdoutBuf);
munmap(mem, allocatedSize);
}
};
// abstract machine model.
struct BFState {
unsigned char tape[TAPE_SIZE] = { 0 };
unsigned char* ptr = nullptr;
BFState() {
ptr = tape;
}
};
void bfJITCompile(std::vector<char>* program, BFState* state) {
// helpers.
auto _appendBytecode = [](auto& byteCode, auto& machineCode) {
machineCode.insert(machineCode.end(), byteCode.begin(), byteCode.end());
};
auto _resolvePtrAddr = [](auto ptrAddr) -> auto {
// little-endian.
return std::vector<uint8_t> {
static_cast<uint8_t>(ptrAddr & 0xff),
static_cast<uint8_t>((ptrAddr & 0xff00) >> 8),
static_cast<uint8_t>((ptrAddr & 0xff0000) >> 16),
static_cast<uint8_t>((ptrAddr & 0xff000000) >> 24),
static_cast<uint8_t>((ptrAddr & 0xff00000000) >> 32),
static_cast<uint8_t>((ptrAddr & 0xff0000000000) >> 40),
static_cast<uint8_t>((ptrAddr & 0xff000000000000) >> 48),
static_cast<uint8_t>((ptrAddr & 0xff00000000000000) >> 56),
};
};
auto _resolveAddrDiff = [](auto addrDiff) -> auto {
// little-endian.
return std::vector<uint8_t> {
static_cast<uint8_t>(addrDiff & 0xff),
static_cast<uint8_t>((addrDiff & 0xff00) >> 8),
static_cast<uint8_t>((addrDiff & 0xff0000) >> 16),
static_cast<uint8_t>((addrDiff & 0xff000000) >> 24),
};
};
auto _relocateAddrOfPrintFunc = [&](
auto &byteCode,
auto &machineCode,
size_t offsetBytesFromLast) {
auto printCallOffset = _resolveAddrDiff(
static_cast<uint32_t>(-(machineCode.size() + byteCode.size() - offsetBytesFromLast + 4)));
byteCode.insert(byteCode.end() - offsetBytesFromLast, printCallOffset.begin(), printCallOffset.end());
};
// static routine definitions.
const std::vector<uint8_t> staticFuncBody {
// stdout function (current offset = 0).
/**
movl $0x2000004, %eax
movl $0x1, %edi
movq %r10, %rsi
movq %r11, %rdx
syscall
retq
*/
#if __APPLE__
MOV_EAX, 0x4, 0x0, 0x0, 0x2,
#elif __linux__
MOV_EAX, 0x1, 0x0, 0x0, 0x0,
#endif
MOV_EDI, 0x1, 0x0, 0x0, 0x0,
REX_MOV_R10_RSI,
REX_MOV_R11_RDX,
SYSCALL,
RETQ,
};
// prologue.
std::vector<uint8_t> machineCode {
// save dynamic pointer in %rbx.
MOV_RBX, /* mem slot */
};
std::vector<size_t> jmpLocIndex {};
// resolve base pointer, relocate and prepend static function body.
auto basePtrBytes = _resolvePtrAddr(reinterpret_cast<size_t>(state->ptr));
machineCode.insert(machineCode.end(), basePtrBytes.begin(), basePtrBytes.end());
machineCode.insert(machineCode.begin(), staticFuncBody.begin(), staticFuncBody.end());
// codegen.
for (auto tok = program->cbegin(); tok != program->cend(); ++tok) {
size_t n = 0;
auto ptrAddr = reinterpret_cast<size_t>(state->ptr);
switch(*tok) {
case '+': {
for (n = 0; *tok == '+'; ++n, ++tok);
std::vector<uint8_t> byteCode {
ADDB_RBX, static_cast<uint8_t>(n), // addb $0x1, (%rbx)
};
_appendBytecode(byteCode, machineCode);
--tok;
break;
}
case '-': {
for (n = 0; *tok == '-'; ++n, ++tok);
std::vector<uint8_t> byteCode {
SUBB_RBX, static_cast<uint8_t>(n), // subb $0x1, (%rbx)
};
_appendBytecode(byteCode, machineCode);
--tok;
break;
}
case '>': {
for (n = 0; *tok == '>'; ++n, ++tok);
std::vector<uint8_t> byteCode {
REX_ADD_RBX, static_cast<uint8_t>(n), // add $0x1, %rbx
};
_appendBytecode(byteCode, machineCode);
--tok; // counteract the tok++ in the main loop.
break;
}
case '<': {
for (n = 0; *tok == '<'; ++n, ++tok);
std::vector<uint8_t> byteCode {
REX_SUB_RBX, static_cast<uint8_t>(n), // sub $0x1, %rbx
};
_appendBytecode(byteCode, machineCode);
--tok; // counteract the tok++ in the main loop.
break;
}
case ',': {
/**
movl $0x2000003, %eax
movl $0x0, %edi
movq %rbx, %rsi
movl $0x1, %edx
syscall
*/
std::vector<uint8_t> byteCode {
#if __APPLE__
MOV_EAX, 0x3, 0x0, 0x0, 0x2,
#elif __linux__
MOV_EAX, 0x0, 0x0, 0x0, 0x0,
#endif
MOV_EDI, 0x0, 0x0, 0x0, 0x0,
REX_MOV_RBX_RSI,
MOV_EDX, 0x1, 0x0, 0x0, 0x0,
SYSCALL,
};
_appendBytecode(byteCode, machineCode);
break;
}
case '.': {
/**
movq (%rbx), %r12
movq %r12, (%r10,%r11)
incq %r11
cmpq $1024, %r11
jne 8
callq <print>
xorq %r11, %r11
*/
std::vector<uint8_t> byteCode {
// setup a simple buffer for stdout.
REX_MOVQ_RBX_R12,
REX_MOVQ_R12_R10_R11,
REX_INCQ_R11,
REX_CMPQ_R11, 0x0, 0x4, 0x0, 0x0,
JNE, 0x8,
// flush.
CALLQ, /* mem slot */
// reset counter.
REX_XORQ_R11_R11,
};
_relocateAddrOfPrintFunc(byteCode, machineCode, 3);
_appendBytecode(byteCode, machineCode);
break;
}
case '[': {
/*
cmpb $0x0, (%rbx)
je <>
*/
std::vector<uint8_t> byteCode {
CMPB_RBX, 0x0,
JE_NEAR, 0x0, 0x0, 0x0, 0x0, /* near jmp */
};
// record the jump relocation pos.
_appendBytecode(byteCode, machineCode);
jmpLocIndex.push_back(machineCode.size());
break;
}
case ']': {
/*
cmpb $0x0, (%rbx)
jne <>
*/
std::vector<uint8_t> byteCode {
CMPB_RBX, 0x0,
JNE_NEAR, 0x0, 0x0, 0x0, 0x0, /* near jmp */
};
_appendBytecode(byteCode, machineCode);
// calculate real offset.
auto bDiff = _resolveAddrDiff(static_cast<uint32_t>(jmpLocIndex.back() - machineCode.size()));
auto fDiff = _resolveAddrDiff(static_cast<uint32_t>(machineCode.size() - jmpLocIndex.back()));
// relocate the memory address of the generated machine code.
machineCode.erase(machineCode.end() - 4, machineCode.end());
machineCode.insert(machineCode.end(), bDiff.begin(), bDiff.end());
// relocate the corresponding previous "[".
machineCode.erase(machineCode.begin() + jmpLocIndex.back() - 4, machineCode.begin() + jmpLocIndex.back());
machineCode.insert(machineCode.begin() + jmpLocIndex.back() - 4, fDiff.begin(), fDiff.end());
jmpLocIndex.pop_back();
// reduce unnecessary `cmp`s, dedicated for patterns like "]]]]]...".
auto ctok = tok + 1;
for (n = 0; *ctok == ']'; ++n, ++ctok);
if (n > 0) {
std::vector<uint8_t> byteCode {
0xeb, static_cast<uint8_t>(n * 11 - 2),
};
_appendBytecode(byteCode, machineCode);
}
break;
}
}
}
// epilogue.
// mainly restoring the previous pc, flushing the stdout buffer.
/**
cmpq $0, %r11
je 8
callq <print>
jmpq *(%rsp)
*/
std::vector<uint8_t> byteCode {
REX_CMPD_R11, 0x0,
JE_SHORT, 0x8,
CALLQ, /* mem slot */
JMPQ_RSP,
};
_relocateAddrOfPrintFunc(byteCode, machineCode, 3);
_appendBytecode(byteCode, machineCode);
// dynamic execution.
VM(&machineCode, staticFuncBody.size()).exec();
}
void bfInterpret(const char* program, BFState* state) {
const char* loops[MAX_NESTING];
auto nloops = 0;
auto nskip = 0;
size_t n = 0;
while(true) {
// switch threading.
switch(*program++) {
case '<': {
for (n = 1; *program == '<'; ++n, ++program);
if (!nskip) state->ptr -= n;
break;
}
case '>': {
for (n = 1; *program == '>'; ++n, ++program);
if (!nskip) state->ptr += n;
break;
}
case '+': {
for (n = 1; *program == '+'; ++n, ++program);
if (!nskip) *state->ptr += n;
break;
}
case '-': {
for (n = 1; *program == '-'; ++n, ++program);
if (!nskip) *state->ptr -= n;
break;
}
case ',': {
if (!nskip) *state->ptr = static_cast<unsigned char>(std::getchar());
break;
}
case '.': {
if (!nskip)
std::cout << *state->ptr;
break;
}
case '[': {
if (nloops == MAX_NESTING) std::terminate();
loops[nloops++] = program;
if (!*state->ptr) ++nskip;
break;
}
case ']': {
if (nloops == 0) std::terminate();
if (*state->ptr) program = loops[nloops - 1];
else --nloops;
if (nskip) --nskip;
break;
}
case ' ': {
for (n = 1; *program == ' '; ++n, ++program); // clear spaces.
break;
}
case '\0': {
return;
}
}
}
}
inline void bfRunInterpret(const char* sourceCode) {
BFState bfs;
bfInterpret(sourceCode, &bfs);
}
inline void bfRunJIT(std::vector<char>* sourceCode) {
BFState bfs;
bfJITCompile(sourceCode, &bfs);
}
int main(int argc, char** argv) {
char token;
std::vector<char> v {};
if (argc > 1) {
std::string inputSourceFileName = std::string(*(argv + 1));
std::ifstream f(inputSourceFileName, std::ios::binary);
while (f.is_open() && f.good() && f >> token) {
v.push_back(token);
}
}
if (v.size() > 0) {
if (argc > 2 && std::string(*(argv + 2)) == "--jit") {
bfRunJIT(&v);
} else {
bfRunInterpret(v.data());
}
}
return 0;
}