0

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");
}
Seki
  • 11,135
  • 7
  • 46
  • 70
Andrew
  • 11
  • 1

2 Answers2

3

All your variables are unsigned. Even if you store -1 you are getting 4294967295 when reading it back.

Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65
1

Is it 32bits machine? enum typpe is signed integer. signed integer scope is -0x80000000 ~ 0x7fffffff.

You know signed integer -1 ---> unsigned integer 0xffffffff.

see your code

uint32_t binFile[] = {PUSH,1,PUSH,2,PUSH,3,STACKINC,-1,EXIT};

The type of binFile is uint32_t. unsigned integer!!!

your compiler make -1 ---> 0xffffffff (unsigned integer).

Let's see this codes

switch (bp[0])
    {
    case PUSH:      sp[0] = bp[1]; sp++; bp+=2;     break;
    case STACKINC:  sp[bp[1]]++; bp+=2;             break;
    }

Detailed...

    case STACKINC:  sp[bp[1]]++; bp+=2;             break;

More detailed...

sp[bp[1]]++;

You want to run as bellow...

sp[-1]++;

BUT, bp[1] == -1 ---> AND unsigned integer!!! So your code...

sp[0xffffffff]++;

Your stack size is 100. So, Page fault (Segmentation fault) occured...

booiljoung
  • 776
  • 6
  • 10