-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathVirtualMachine.cpp
More file actions
496 lines (455 loc) · 19.7 KB
/
Copy pathVirtualMachine.cpp
File metadata and controls
496 lines (455 loc) · 19.7 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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#include "VirtualMachine.h"
#include <fstream>
#include <iterator>
#include <cassert>
#include <iostream>
#include "Opcode.h"
#include "AtomicTypes.h"
#include <limits>
VirtualMachine::VirtualMachine()
{
m_RAM = new uint8[MAX_RAM];
}
VirtualMachine::~VirtualMachine()
{
delete[] m_RAM;
}
bool VirtualMachine::LoadProgram(std::string filename)
{
std::ifstream file( filename, std::ios::binary );
if(!file.good())
{
std::cerr << "[VM] Could not open bytecode executable" << std::endl;
return false;
}
file.unsetf(std::ios::skipws);
// get its size:
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// reserve capacity
std::vector<uint8> bytecode;
bytecode.reserve(static_cast<uint32>(fileSize));
// read the data:
bytecode.insert(bytecode.begin(),
std::istream_iterator<uint8>(file),
std::istream_iterator<uint8>());
SetProgram(bytecode);
return true;
}
void VirtualMachine::SetProgram(std::vector<uint8> bytecode)
{
uint32 headerSize = sizeof(uint32)*2;
m_StackSize = Unpack<uint32>(0, bytecode);
auto numStaticVars = Unpack<uint32>(1 * sizeof(uint32), bytecode);
m_NumInstructions = bytecode.size()- headerSize; //Header size for now
m_StaticBase = m_NumInstructions + m_StackSize;
for(uint32 i = 0; i < m_NumInstructions; ++i)
{
m_RAM[i+m_StackSize] = bytecode[i+ headerSize];
}
//Initialize Dynamic memory allocation
m_FirstSegmentPtr = m_StaticBase + numStaticVars;
m_HeapBase = m_FirstSegmentPtr+sizeof(uint32);
Pack<uint32>(m_FirstSegmentPtr, m_HeapBase);
Pack<uint32>(m_HeapBase, MAX_RAM - m_HeapBase);
Pack<uint32>(m_HeapBase + sizeof(uint32), 0);
#ifdef VM_DEBUG_HEAP
PrintHeap();
#endif
ProgramLoaded = true;
}
void VirtualMachine::Interpret()
{
if(!ProgramLoaded)
{
std::cerr << "[VM] No program loaded" << std::endl;
return;
}
m_ProgramCounter = m_StackSize;
while( m_ProgramCounter < m_StaticBase)
{
assert(m_ProgramCounter - m_StackSize < m_NumInstructions);
auto operation = static_cast<Opcode>(m_RAM[m_ProgramCounter]);
std::cout << "[DBG] operation: " << GetOpString(operation) << std::endl;
switch(operation)
{
//MEMORY OPERATIONS
//Add a byte to the stack
case Opcode::LITERAL:
{
Push(Unpack<int32>(++m_ProgramCounter));
m_ProgramCounter+=sizeof(int32);
}
continue;
//Add multiple bytes to the stack
case Opcode::LITERAL_ARRAY:
{
auto numValues = Unpack<int32>(++m_ProgramCounter);
m_ProgramCounter+=sizeof(int32);
while(numValues > 0)
{
Push(Unpack<int32>(m_ProgramCounter));
m_ProgramCounter+=sizeof(int32);
--numValues;
}
}
continue;
//put memory at address on stack
case Opcode::LOAD:
{
Push(Unpack<int32>(Pop()));
++m_ProgramCounter;
}
continue;
//store a in memory at b
case Opcode::STORE:
{
int32 address = Pop();
Pack<int32>(address, Pop());
++m_ProgramCounter;
}
continue;
//put memory at local address on stack
case Opcode::LOAD_LCL:
{
Push(Unpack<int32>(m_LCL+Pop()));
++m_ProgramCounter;
}
continue;
//store a in memory at local b
case Opcode::STORE_LCL:
{
int32 address = m_LCL+Pop();
Pack<int32>(address, Pop());
++m_ProgramCounter;
}
continue;
//put memory at argument address on stack
case Opcode::LOAD_ARG:
{
Push(Unpack<int32>(m_ARG+Pop()));
++m_ProgramCounter;
}
continue;
//Mark (a) bytes on the heap as used and push a pointer to the base
case Opcode::ALLOC:
{
uint32 requestedSize = Pop();
uint32 requiredSize = requestedSize + sizeof(uint32);//First 4 bytes of segment hold segment size -- maybe in future 4 more bytes for reference count
auto firstSegment = Unpack<uint32>(m_FirstSegmentPtr);
uint32 nextSegment = firstSegment;
uint32 bestFitSize = std::numeric_limits<uint32>::max();
uint32 bestFitPtr = 0;
uint32 prevNextPtr = m_FirstSegmentPtr;
//Get best fitting segment
bool earlyOut = false;
while (nextSegment != 0 && !earlyOut)
{
auto segmentSize = Unpack<uint32>(nextSegment);
if (segmentSize >= requiredSize && segmentSize < bestFitSize)
{
if (segmentSize == requiredSize) earlyOut = true;
bestFitPtr = nextSegment;
bestFitSize = segmentSize;
if(nextSegment != firstSegment) prevNextPtr = nextSegment + sizeof(uint32);
}
nextSegment = Unpack<uint32>(nextSegment + sizeof(uint32));
}
if (bestFitPtr == 0)
{
std::cerr << "[VM] Out of Memory Exception, could not allocate space for variable!" << std::endl;
return;
}
//use best found segment
uint32 remainingSize = bestFitSize - requiredSize;
if (remainingSize >= sizeof(uint32)*2)//Split segment in two if the remainder is big enough to allocate (ie its bigger than a segment header)
{
uint32 newSegPtr = bestFitPtr + requiredSize;
Pack<uint32>(newSegPtr, remainingSize); //set the new segment size
Pack<uint32>(newSegPtr + sizeof(uint32), Unpack<uint32>(bestFitPtr+sizeof(uint32))); //set the new segments nextPtr to the value of the allocated segments next ptr
Pack<uint32>(prevNextPtr, newSegPtr);//Link the previous segment to the new segment
Pack<uint32>(bestFitPtr, requiredSize); //Tell the allocated segment how big it is
}
else //Allocate the entire segment
{
Pack<uint32>(prevNextPtr, Unpack<uint32>(bestFitPtr+sizeof(uint32)));//Link the previous segment to next segment
}
Push(bestFitPtr+sizeof(uint32));
++m_ProgramCounter;
#ifdef VM_DEBUG_HEAP
PrintHeap();
#endif
}
continue;
//Mark the space at (a) as unused
case Opcode::FREE:
{
uint32 segmentPtr = Pop()-sizeof(uint32);
auto segmentSize = Unpack<uint32>(segmentPtr);
uint32 existingNextPtr = m_FirstSegmentPtr;
auto nextSegment = Unpack<uint32>(existingNextPtr);
uint32 existingSegment = existingNextPtr;
bool earlyOut = false;
while (nextSegment != 0 && !earlyOut)
{
if (segmentPtr < nextSegment)
{
//insert
bool standalone = true;
if ((nextSegment != m_FirstSegmentPtr) && (existingSegment + Unpack<uint32>(existingSegment) == segmentPtr))//Merge EXISTING+INSERTED
{
//simply expand the existing segment to accomodate our size
segmentPtr = existingSegment;
segmentSize += Unpack<uint32>(existingSegment);
Pack<uint32>(segmentPtr, segmentSize);
standalone = false;
}
else
{
Pack<uint32>(segmentPtr + sizeof(uint32), nextSegment);//next = existing.next
Pack<uint32>(existingNextPtr, segmentPtr); //existing.next = this
}
if (segmentPtr + segmentSize == nextSegment)//Merge INSERTED+NEXT
{
segmentSize += Unpack<uint32>(nextSegment);
Pack<uint32>(segmentPtr, segmentSize);
Pack<uint32>(segmentPtr + sizeof(uint32), Unpack<uint32>(nextSegment + sizeof(uint32))); //next = next.next
}
else if(standalone) Pack<uint32>(segmentPtr + sizeof(uint32), nextSegment);
earlyOut = true;
}
existingSegment = nextSegment;
existingNextPtr = existingSegment + sizeof(uint32);
nextSegment = Unpack<uint32>(existingNextPtr);
}
if (!earlyOut)
{
std::cerr << "[VM] Failed to free memory at " << segmentPtr << "; " << segmentSize << " bytes" << std::endl;
return;
}
++m_ProgramCounter;
#ifdef VM_DEBUG_HEAP
PrintHeap();
#endif
}
continue;
//ARITHMETIC OPERATIONS
//Add values together
case Opcode::ADD:
{
int32 b = Pop();
int32 a = Pop();
Push(a + b);
++m_ProgramCounter;
}
continue;
//a - b
case Opcode::SUB:
{
int32 b = Pop();
int32 a = Pop();
Push(a - b);
++m_ProgramCounter;
}
continue;
//LOGICAL OPERATIONS
//a < b
case Opcode::LESS:
{
int32 b = Pop();
int32 a = Pop();
Push(a < b);
++m_ProgramCounter;
}
continue;
//a > b
case Opcode::GREATER:
{
int32 b = Pop();
int32 a = Pop();
Push(a > b);
++m_ProgramCounter;
}
continue;
//!a
case Opcode::NOT:
{
int32 a = Pop();
Push(!a);
++m_ProgramCounter;
}
continue;
//a == b
case Opcode::EQUALS:
{
int32 b = Pop();
int32 a = Pop();
Push(a == b);
++m_ProgramCounter;
}
continue;
//FLOW CONTROL
//goto a
case Opcode::JMP:
{
int32 address = Pop();
m_ProgramCounter = static_cast<uint32>(address);
}
continue;
//if(a) goto b
case Opcode::JMP_IF:
{
int32 address = Pop();
int32 condition = Pop();
if(condition)
{
m_ProgramCounter = static_cast<uint32>(address);
}
else
{
++m_ProgramCounter;
}
}
continue;
//FUNCTIONS
//put a new frame on the stack with n arguments and k local variables
case Opcode::CALL:
{
uint32 ret = m_ProgramCounter + 1;
m_ProgramCounter = static_cast<uint32>(Pop());
Push(m_RTN);
m_RTN = ret;
Push(m_LCL);
Push(m_ARG);
Push(m_THIS); //This stays the same because we are doing a function not a method
m_ARG = m_StackPointer - (Unpack<int32>(m_ProgramCounter) + 12 /*difference from this to return*/);
m_ProgramCounter += sizeof(int32);
m_LCL = m_StackPointer + sizeof(int32);
m_StackPointer = m_LCL + Unpack<int32>(m_ProgramCounter);
m_ProgramCounter += sizeof(int32);
}
continue;
//Return from current function to previous function on stack and copy end values over
case Opcode::RETURN: //#todo stop assuming return value size
{
m_ProgramCounter = m_RTN;
Pack<int32>(m_ARG, Pop());
m_StackPointer = m_ARG;
m_THIS = Unpack<int32>(m_LCL - (sizeof(int32) * 1));
m_ARG = Unpack<int32>(m_LCL - (sizeof(int32) * 2));
m_RTN = Unpack<int32>(m_LCL - (sizeof(int32) * 4));
m_LCL = Unpack<int32>(m_LCL - (sizeof(int32) * 3));
}
continue;
//"Library functions" should later be implemented differently
//print x chars to console
case Opcode::PRINT:
{
uint32 size = Pop();
std::string out;
for(uint32 j = 0; j<size; ++j)
{
out = static_cast<char>(Pop()) + out;
}
std::cout << out;
++m_ProgramCounter;
}
continue;
//print one integer to console
case Opcode::PRINT_INT:
{
std::cout << Pop();
++m_ProgramCounter;
}
continue;
//print one integer to console
case Opcode::PRINT_ENDL:
{
std::cout << std::endl;
++m_ProgramCounter;
}
continue;
//INVALID
default:
std::cerr << "Invalid opcode: " << GetOpString(operation) << std::endl;
assert(false);
continue;
}
}
}
void VirtualMachine::Push(int32 value)
{
assert(m_StackPointer + sizeof(int32) < m_StackSize); //Stack Overflow
Pack<int32>(m_StackPointer+=sizeof(int32), value);
}
int VirtualMachine::Pop()
{
assert(m_StackPointer >= 0); //Invalid memory access "Stack underflow" - this does not protect against the SP underflowing the working stack
auto value = Unpack<int32>(m_StackPointer);
m_StackPointer -= sizeof(int32);
return value;
}
template<typename T>
T VirtualMachine::Unpack(uint32 address)
{
#ifdef WORD_BIG_ENDIAN
uint32 value = static_cast<uint8>(m_RAM[address+3]) << 24 |
static_cast<uint8>(m_RAM[address+2]) << 16 |
static_cast<uint8>(m_RAM[address+1]) << 8 |
static_cast<uint8>(m_RAM[address+0]);
#elif
uint32 value = static_cast<uint8>(m_RAM[address+0]) << 24 |
static_cast<uint8>(m_RAM[address+1]) << 16 |
static_cast<uint8>(m_RAM[address+2]) << 8 |
static_cast<uint8>(m_RAM[address+3]);
#endif
return static_cast<T>(value);
}
template<typename T>
T VirtualMachine::Unpack(uint32 address, std::vector<uint8> data)
{
assert(data.size() > address + 3);
#ifdef WORD_BIG_ENDIAN
uint32 value = static_cast<uint8>(data[address+3]) << 24 |
static_cast<uint8>(data[address+2]) << 16 |
static_cast<uint8>(data[address+1]) << 8 |
static_cast<uint8>(data[address+0]);
#elif
uint32 value = static_cast<uint8>(data[address+0]) << 24 |
static_cast<uint8>(data[address+1]) << 16 |
static_cast<uint8>(data[address+2]) << 8 |
static_cast<uint8>(data[address+3]);
#endif
return static_cast<T>(value);
}
template<typename T>
void VirtualMachine::Pack(uint32 address, T value)
{
auto n = static_cast<uint32>(value);
#ifdef WORD_BIG_ENDIAN
m_RAM[address+3] = (n >> 24) & 0xFF;
m_RAM[address+2] = (n >> 16) & 0xFF;
m_RAM[address+1] = (n >> 8) & 0xFF;
m_RAM[address+0] = n & 0xFF;
#elif //WORD_LITTLE_ENDIAN
m_RAM[address+0] = (n >> 24) & 0xFF;
m_RAM[address+1] = (n >> 16) & 0xFF;
m_RAM[address+2] = (n >> 8) & 0xFF;
m_RAM[address+3] = n & 0xFF;
#endif
}
void VirtualMachine::PrintHeap(bool baseOffset)
{
uint32 offset = baseOffset ? m_HeapBase : 0;
auto nextSegment = Unpack<uint32>(m_FirstSegmentPtr);
std::cout << "[DBG Heap]: "<< m_FirstSegmentPtr-offset << " first: " << nextSegment-offset << " \t";
while (nextSegment != 0)
{
std::cout << "@" << nextSegment-offset << "{s: " << Unpack<uint32>(nextSegment);
nextSegment = Unpack<uint32>(nextSegment + sizeof(uint32));
std::cout << "; n: " << nextSegment-offset << "} ";
}
std::cout << std::endl;
}