Skip to content

Instantly share code, notes, and snippets.

@carasuca
Created December 24, 2017 00:01
Show Gist options
  • Save carasuca/2bac7f9495cbb6344fe60e55c59cf354 to your computer and use it in GitHub Desktop.
Save carasuca/2bac7f9495cbb6344fe60e55c59cf354 to your computer and use it in GitHub Desktop.
Micro VM sandbox + CLI
typedef unsigned char byte;
byte memory[byte(-1)+1]; // global 8-bit memory pool
struct { char name[32]; void(*fn)(byte&); }
const instructions[byte(-1)+1] =
{
{ "NOP", [](byte&) {} },
{ "INC <%i>", [](byte& b) {
byte addr1 = b + memory[b++];
memory[addr1]++; }
},
{ "JMP <%i>", [](byte& b) { b += memory[b]; } },
{ "SET [%i] at <%i>", [](byte& b) {
byte val = memory[b++];
memory[memory[b++]] = val;
} },
{ "CPY from <%i> to <%i>", [](byte& b) {
byte addr1 = memory[b++] + b;
byte addr2 = memory[b++] + b;
memory[addr2] = memory[addr1];
} },
};
void step(byte& counter)
{
if (auto fn = instructions[memory[counter]].fn)
fn(++counter);
}
enum : byte {NOP, INC, JMP, SET, CPY};
const byte worm1[] = { INC, 2, INC, 2, JMP };
const byte worm2[] = { CPY, 1, 5, INC, -2, JMP, -6 };
byte counters[] = { 0 };
#include <Windows.h>
#include <stdio.h>
void print()
{
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {});
for (int i = 0; i != 16; i++) printf("%5X", i); putchar('\n');
for (int j = 0; j != 16; j++)
{
printf("%X", j);
for (int i = 0; i != 16; i++)
{
byte id = i + 16 * j;
byte m = memory[id];
printf(" %c%2hhX", (id == *counters) ? '>' : ' ', m);
}
putchar('\n');
}
for (auto& counter : counters)
{
printf("#%i @%02X: ", &counter - counters, counter);
if (auto name = instructions[memory[counter]].name) if (*name)
{
char arg1 = memory[byte(counter + 1)];
char arg2 = memory[byte(counter + 2)];
printf(name, arg1, arg2, 0, 0, 0);
}
else puts("INVALID INSTRUCTION");
puts(" \r");
}
}
template<byte N>
byte write(const byte(&worm)[N], byte offset)
{
for (auto w : worm) memory[offset++] = w;
return offset;
}
#define pressed(X) (GetAsyncKeyState(X) & 1)
void main()
{
write(worm2, counters[0]);
puts("hold SPACE to step");
const CONSOLE_CURSOR_INFO cursor = {0, FALSE};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor);
print();
while (!pressed(VK_ESCAPE)) for (auto& counter : counters)
{
if (pressed(VK_SPACE)) step(counter);
else if (pressed(VK_PRIOR)) memory[counter]++;
else if (pressed(VK_NEXT)) memory[counter]--;
else if (pressed(VK_LEFT)) counter--;
else if (pressed(VK_RIGHT)) counter++;
else if (pressed(VK_UP)) counter-=16;
else if (pressed(VK_DOWN)) counter+=16;
else
{
Sleep(20);
continue;
}
print();
}
}
@carasuca
Copy link
Author

wormbox

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment