Skip to content

Instantly share code, notes, and snippets.

@ratchetfreak
Last active June 1, 2023 12:30
Show Gist options
  • Save ratchetfreak/6e0e782f106ef4c218d9a824b7fd0809 to your computer and use it in GitHub Desktop.
Save ratchetfreak/6e0e782f106ef4c218d9a824b7fd0809 to your computer and use it in GitHub Desktop.
proposed callbackless vm-usage code
void foo(){
VMwasm vm;
initVM(&vm);
char* internalBuffer = nullptr;
defer{free(internalBuffer);}
{
size_t len;
char* buffer = readWholeFile(..., &len);
defer{free(buffer);}
size_t needed_buffer = VM_loadBin(&vm, buffer, len, nullptr, 0);
internalBuffer = malloc(needed_buffer);
VM_loadBin(&vm, buffer, len, internalBuffer, needed_buffer);
}
//reorder imported and exported functions?
size_t stackSize = 1<<12;
char* allocedStack = malloc(stackSize);
defer{free(allocedStack);}
VMStack stack;
VM_initStack(&stack, allocedStack, stackSize);
int32_t memorySize = 1<<20;
char* memory = malloc(memorySize);
defer{free(memory);}
VM_initGlobals(&vm, memory, memorySize);
int funID = VM_getExportedFunc(&vm, "main");
VM_prepCall(&vm, &stack, funID, ...);
int32_t result;
while(true){
VMResult res = VM_resume(&vm, memory, memorySize, &stack);
switch(res){
case VM_GROW_MEM:
case VM_SHRINK_MEM:
{
//must pop new memorySize from stack
memorySize = VM_popDesiredMem(&stack);
memory = realloc(memory, memorySize);
break;
}
case VM_STACK_OVERFLOW:
{
stackSize = stackSize*2;
allocedStack = realloc(allocedStack, stackSize);
VM_growStack(&stack, allocedStack, stackSize);
break;
}
case VM_TIMEOUT:
{
//called in case toomany instructions got executed
//no-op
break;
}
case VM_CALL_IMPORTED:
{
//must pop call params and push return value
int callID = getCalledFunctionID(&vm, &stack);
//can be done with a lookup table of functions
//foo(VMwasm vm, void* memory, Stack stack, void* userdata)
switch(callID){
case 1: //print(char*, int)
{
int32_t firstArg = VM_getArg(&stack, 0);
int32_t secondArg = VM_getArg(&stack, 1);
char* strPointer = memory+firstArg;
int stringlength = secondArg;
result = printf("print %.*s", stringlength, strPointer);
VM_popCallAndprepReturn(&stack, result);
break;
}
//...
}
break;
}
case VM_RETURN:
{
result = VM_popReturn(&stack);
goto afterCall;
}
}
}
afterCall:
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment