My virtual machine below is segfaulting at my stack increment instruction which takes the stack offset from the bin pointer and increments it by one. If I use the value -1 this works correctly, but when i access -1
through the bp[1]
offset it crashes. This really doesn't make sense to me, what am I doing wrong?
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
typedef enum {PUSH,STACKINC,EXIT} opCodes;
char * opCode[] = {"Push","Stack Increment","Exit"};
typedef struct VirtualMachine
{
uint32_t * sp; /* Stack Pointer */
uint32_t * bp; /* Bin Pointer */
uint32_t stack[100]; /* VM stack */
} VM;
void processVM(VM * vm)
{
uint32_t * bp = vm->bp;
uint32_t * sp = vm->sp;
printf("OP: %s\n",opCode[bp[0]]);
switch (bp[0])
{
case PUSH: sp[0] = bp[1]; sp++; bp+=2; break;
case STACKINC: sp[bp[1]]++; bp+=2; break;
}
vm->bp = bp;
vm->sp = sp;
/* Set out stack and bin pointers back */
}
int main()
{
uint32_t binFile[] = {PUSH,1,PUSH,2,PUSH,3,STACKINC,-1,EXIT};
VM myVM;
myVM.bp = binFile;
myVM.sp = myVM.stack;
while(myVM.bp[0] != EXIT)
{
processVM(&myVM);
usleep(200000);
}
printf("VM done executing\n");
}