From d33632f7167b48754bb35387e1cb91e5ed90de0d Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Fri, 25 Oct 2024 17:39:49 +0100 Subject: Essential layout of virtual machine memory setup The virtual machine has three major segments for data storage: main memory, the registers and the stack. They are laid out in a flat buffer adjacent to each other: main memory, then the registers then the stack at the end. This would allow, later on, for the stack to be extended via memory reallocation. Crucially, registers cannot grow. This is intended to map closely to the x86-64 machines which have a static number of general registers (and also xmmp registers). --- main.c | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/main.c b/main.c index 2a38dde..a136a40 100644 --- a/main.c +++ b/main.c @@ -14,10 +14,58 @@ * Description: Entrypoint */ +#include +#include #include +#include + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; + +typedef int8_t i8; +typedef int16_t i16; +typedef int32_t i32; +typedef int64_t i64; + +typedef struct +{ + u8 *buffer; + u64 size_memory, size_stack, size_registers; +} vm_t; + +#define VM_DEFAULT_MEM_SIZE (1024) +#define VM_DEFAULT_STACK_SIZE (128 * sizeof(u64)) +#define VM_DEFAULT_REGISTERS_SIZE (8 * sizeof(u64)) + +#define VM_STACK(VM) ((VM)->buffer + (VM)->size_memory + (VM)->size_registers) +#define VM_REGISTERS(VM) ((u64 *)((VM)->buffer + (VM)->size_memory)) +#define VM_IP(VM) (VM_REGISTERS(VM)[0]) +#define VM_SP(VM) (VM_REGISTERS(VM)[1]) + +void vm_init_malloc(vm_t *vm) +{ + if (vm->size_stack == 0) + vm->size_stack = VM_DEFAULT_STACK_SIZE; + if (vm->size_registers == 0) + vm->size_registers = VM_DEFAULT_REGISTERS_SIZE; + if (vm->size_memory == 0) + vm->size_memory = VM_DEFAULT_MEM_SIZE; + + vm->buffer = calloc(1, vm->size_memory + vm->size_stack + vm->size_registers); +} + +void vm_stop(vm_t *vm) +{ + free(vm->buffer); + memset(vm, 0, sizeof(*vm)); +} int main(void) { - puts("Hello, world!"); + vm_t vm = {0}; + vm_init_malloc(&vm); + vm_stop(&vm); return 0; } -- cgit v1.2.3-13-gbd6f