Skip to content

Commit

Permalink
cvm: add a stack pointer and use it mostly unsafe
Browse files Browse the repository at this point in the history
  • Loading branch information
fichtner committed Jul 3, 2012
1 parent 7d6b56c commit 371b6d2
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions cvm.c
@@ -1,15 +1,20 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>


#define MEM_SIZE 256
#define REG_SIZE 4

struct cvm_instance { struct cvm_instance {
/* vm can issue halt command */ /* vm can issue halt command */
unsigned int running; unsigned int running;
/* program counter */ /* program counter */
unsigned int pc; unsigned int pc;
/* stack pointer */
unsigned int sp;
/* main registers */ /* main registers */
unsigned short r[4]; unsigned short r[REG_SIZE];
/* additional memory */ /* additional memory */
unsigned short m[256]; unsigned short m[MEM_SIZE];
}; };


struct cvm_instruction { struct cvm_instruction {
Expand Down Expand Up @@ -58,7 +63,7 @@ static void evaluate(struct cvm_instance *vm, const struct cvm_instruction *vi)
printf("syscall %d\n", vi->imm); printf("syscall %d\n", vi->imm);
switch (vi->imm) { switch (vi->imm) {
case 0: case 0:
printf("%s\n", (const char *) &vm->m[vm->r[0]]); printf("%s\n", (char *) &vm->m[vm->m[MEM_SIZE - (vm->sp--)]]);
break; break;
} }
break; break;
Expand All @@ -70,6 +75,14 @@ static void evaluate(struct cvm_instance *vm, const struct cvm_instruction *vi)
printf("halt\n"); printf("halt\n");
vm->running = 0; vm->running = 0;
break; break;
case 9:
printf("push r%d\n", vi->r1);
vm->m[MEM_SIZE - (++vm->sp)] = vm->r[vi->r1];
break;
case 10:
printf("pop r%d\n", vi->r1);
vm->r[vi->r1] = vm->m[MEM_SIZE - (vm->sp--)];
break;
} }


++vm->pc; ++vm->pc;
Expand All @@ -90,6 +103,8 @@ static void run(const unsigned short *program, size_t len)
memcpy(&vm.m, program, len); memcpy(&vm.m, program, len);
vm.running = 1; vm.running = 1;


printf("==========================\n");

while (vm.running) { while (vm.running) {
fetch_and_decode(&vm, &vi); fetch_and_decode(&vm, &vi);
evaluate(&vm, &vi); evaluate(&vm, &vi);
Expand All @@ -112,8 +127,25 @@ int main(void)
0x0000, 0x0000,
0x8000, 0x8000,
}; };
const unsigned short pushpop[] = {
0x100A,
0x9000,
0x1000,
0xA000,
0x1101,
0x9100,
0x1102,
0x9100,
0x1103,
0x9100,
0xA100,
0xA200,
0xA300,
0x8000,
};
const unsigned short hello[] = { const unsigned short hello[] = {
0x1003, 0x1004,
0x9000,
0x6000, 0x6000,
0x8000, 0x8000,
0x6548, 0x6548,
Expand All @@ -126,6 +158,7 @@ int main(void)
}; };


run(sample, sizeof(sample)); run(sample, sizeof(sample));
run(pushpop, sizeof(pushpop));
run(hello, sizeof(hello)); run(hello, sizeof(hello));


return 0; return 0;
Expand Down

0 comments on commit 371b6d2

Please sign in to comment.