Skip to content

Instantly share code, notes, and snippets.

@itsbth
Created November 9, 2011 15:06
Show Gist options
  • Select an option

  • Save itsbth/1351699 to your computer and use it in GitHub Desktop.

Select an option

Save itsbth/1351699 to your computer and use it in GitHub Desktop.
Uploaded by UploadToGist for Sublime Text 2
#include "vm.h"
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#define VM_REG_MASK (1<<31)
#define VM_CODE_MASK (1<<30)
#define VM_DATA_MASK ((1<<16)-1)
struct _vm_state {
int regi[8];
double regf[8];
unsigned int code_len;
int *code;
unsigned int data_len;
int *data;
unsigned int iptr;
unsigned int sptr;
vm_interrupt_handler interrupt_table[VM_INTERRUPT_TABLE_SIZE];
};
vm_state vm_create_state(int *code, unsigned int code_len, unsigned int data_len) {
vm_state s = malloc(sizeof(struct _vm_state));
memset(s, 0, sizeof(struct _vm_state));
s->code = code; // TODO: Create a copy?
s->code_len = code_len;
s->data_len = data_len;
s->data = malloc(sizeof(int) * data_len);
return s;
}
void *vm_decode_rm(vm_state s, unsigned int rm, bool write) {
unsigned int data_val = rm & VM_DATA_MASK;
if (rm & VM_REG_MASK) {
assert(data_val < 16);
return &s->regi[data_val];
}
if (rm & VM_CODE_MASK && !write) {
assert(data_val < s->code_len);
return &s->code[data_val];
}
assert(data_val < s->data_len);
return s->data + data_val;
}
int vm_get_int(vm_state s, unsigned int ptr) {
int *ret = vm_decode_rm(s, ptr, false);
return *ret;
}
void vm_set_int(vm_state s, unsigned int ptr, int val) {
int *ret = vm_decode_rm(s, ptr, true);
*ret = val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment