store current_pos in VM for better logging

This commit is contained in:
2024-11-16 22:05:20 +05:00
parent 83172df776
commit 9d2a26fae3
12 changed files with 110 additions and 51 deletions

View File

@@ -6,11 +6,15 @@ void VM_init(VM* vm){
vm->state = VMState_Initialized;
}
void VM_setErrorMessage(VM* vm, const char* format, ...){
void _VM_setError(VM* vm, const char* context, const char* format, ...){
va_list argv;
char position_str[32];
sprintf(position_str, "[at 0x%x][", (u32)vm->current_pos);
char* real_format = strcat_malloc(position_str, context, "] ", format);
va_start(argv, format);
char* NULLABLE(buf) = vsprintf_malloc(256, format, argv);
char* NULLABLE(buf) = vsprintf_malloc(256, real_format, argv);
va_end(argv);
free(real_format);
if(buf == NULL){
buf = malloc(16);
strcpy(buf, "SPRINTF FAILED");
@@ -20,11 +24,11 @@ void VM_setErrorMessage(VM* vm, const char* format, ...){
bool VM_loadProgram(VM* vm, u8* data, size_t size){
if(data == NULL){
VM_setErrorMessage(vm, "[VM_loadProgram] can't load program because data == NULL");
VM_setError(vm, "data == NULL");
return false;
}
if(size == 0){
VM_setErrorMessage(vm, "[VM_loadProgram] can't load program because size == 0");
VM_setError(vm, "size == 0");
return false;
}
@@ -35,30 +39,30 @@ bool VM_loadProgram(VM* vm, u8* data, size_t size){
i32 VM_executeProgram(VM* vm){
if(vm->data == NULL){
VM_setErrorMessage(vm, "[VM_executeProgram] data is null");
VM_setError(vm, "data == null");
return -1;
}
size_t pos = 0;
while (pos < vm->data_size){
u8 opcode = vm->data[pos];
vm->current_pos = 0;
while (vm->current_pos < vm->data_size){
u8 opcode = vm->data[vm->current_pos];
const Instruction* instr = Instruction_getFromOpcode(opcode);
if(instr == NULL){
VM_setErrorMessage(vm, "[%p] unknown opcode %02x", (void*)pos, opcode);
VM_setError(vm, "unknown opcode %02X", opcode);
return -1;
}
pos++;
i32 bytes_read = instr->implementation(vm, pos);
vm->current_pos++;
i32 bytes_read = instr->implementation(vm);
if(bytes_read < 0)
return -1;
pos += bytes_read;
vm->current_pos += bytes_read;
}
if(vm->state != VMState_Exited){
VM_setErrorMessage(vm, "[%p] unexpected end of program", (void*)pos);
VM_setError(vm, "unexpected end of the program");
return -1;
}
@@ -68,7 +72,8 @@ i32 VM_executeProgram(VM* vm){
bool VM_dataRead(VM* vm, void* dst, size_t pos, size_t size){
if(pos + size >= vm->data_size){
VM_setErrorMessage(vm, "[%p] unexpected end of data", (void*)vm->data_size);
VM_setError(vm, "can't read %lli bytes from 0x%x, because only %lli are avaliable",
size, (u32)pos, vm->data_size - size);
return false;
}