Compare commits
2 Commits
e1f984c72d
...
96ff9873ff
Author | SHA1 | Date | |
---|---|---|---|
|
96ff9873ff | ||
|
1431f6e104 |
@ -10,21 +10,21 @@ int main(int argc, char *argv[]) {
|
||||
std::streamsize bytecode_size;
|
||||
uint8_t * bytecode;
|
||||
|
||||
if (argc < 2) {
|
||||
printf("Usage: %s <program>\n", argv[0]);
|
||||
if (argc < 3) {
|
||||
printf("Usage: %s <opcodes_key> <program>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
reading bytecode
|
||||
*/
|
||||
bytecode_if.open(argv[1], std::ios::binary | std::ios::ate);
|
||||
bytecode_if.open(argv[2], std::ios::binary | std::ios::ate);
|
||||
bytecode_size = bytecode_if.tellg();
|
||||
bytecode_if.seekg(0, std::ios::beg);
|
||||
|
||||
bytecode = new uint8_t[bytecode_size];
|
||||
bytecode_if.read((char*)bytecode, bytecode_size);
|
||||
VM vm(bytecode, bytecode_size);
|
||||
VM vm((uint8_t*)argv[1], bytecode, bytecode_size);
|
||||
vm.run();
|
||||
vm.status();
|
||||
return 0;
|
||||
|
55
cpp/vm.cpp
55
cpp/vm.cpp
@ -3,6 +3,36 @@
|
||||
#include "vmas.h"
|
||||
#include <string.h>
|
||||
|
||||
unsigned rol(unsigned x, int L, int N) {
|
||||
unsigned lsbs = x & ((1 >> L) - 1);
|
||||
return (x << L) | (lsbs >> (N - L));
|
||||
}
|
||||
|
||||
void VM::defineOpcodes(uint8_t *key) {
|
||||
uint32_t i, j, keysize;
|
||||
keysize = strlen((char *)key);
|
||||
for (i = 0; i < keysize; i++) {
|
||||
for (j = 0; j < NUM_OPS; j++) {
|
||||
if (key[i] % 2) {
|
||||
ops[j].setValue(rol(key[i] ^ ops[j].getValue(), key[i] % 8, 8));
|
||||
} else {
|
||||
ops[j].setValue(rol(key[i] ^ ops[j].getValue(), (key[i] + 1) % 8, 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i = 0; i < NUM_OPS; i++) {
|
||||
for (j = 0; j < NUM_OPS; j++) {
|
||||
ops[j].setValue(rol(ops[j].getValue(), ops[i].getValue() % 8, 8));
|
||||
}
|
||||
}
|
||||
#ifdef DBG
|
||||
DBG_INFO(("OPCODES:\n"));
|
||||
for (i = 0; i < NUM_OPS; i++) {
|
||||
DBG_INFO(("%s: 0x%x\n", ops[i].getName(), ops[i].getValue()));
|
||||
}
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
/*
|
||||
DBG UTILS
|
||||
*/
|
||||
@ -101,26 +131,31 @@ void VM::status(void) {
|
||||
/*
|
||||
CONSTRUCTORS
|
||||
*/
|
||||
VM::VM() {
|
||||
VM::VM(uint8_t *key) {
|
||||
DBG_SUCC(("Creating VM without code.\n"));
|
||||
as.allocate();
|
||||
init_regs();
|
||||
initVariables();
|
||||
defineOpcodes(key);
|
||||
}
|
||||
|
||||
VM::VM(uint8_t *code, uint32_t codesize) {
|
||||
VM::VM(uint8_t *key, uint8_t *code, uint32_t codesize) {
|
||||
DBG_SUCC(("Creating VM with code.\n"));
|
||||
if (as.allocate()) {
|
||||
as.insCode(code, codesize);
|
||||
}
|
||||
init_regs();
|
||||
initVariables();
|
||||
defineOpcodes(key);
|
||||
}
|
||||
|
||||
void VM::init_regs(void) {
|
||||
uint8_t i;
|
||||
void VM::initVariables(void) {
|
||||
uint32_t i;
|
||||
|
||||
for (i = R0; i <= SP; i++) {
|
||||
for (i = R0; i < NUM_REGS; i++) {
|
||||
this->regs[i] = 0;
|
||||
}
|
||||
for (i = MOVI; i < NUM_OPS; i++) {
|
||||
ops[i].setValue(i);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@ -217,11 +252,11 @@ void VM::run(void) {
|
||||
exec_movr();
|
||||
regs[IP] += MOVR_SIZE;
|
||||
break;
|
||||
case GETM:
|
||||
case LOAD:
|
||||
exec_getm();
|
||||
regs[IP] += GETM_SIZE;
|
||||
break;
|
||||
case PUTM:
|
||||
case STOR:
|
||||
exec_putm();
|
||||
regs[IP] += PUTM_SIZE;
|
||||
break;
|
||||
@ -229,7 +264,7 @@ void VM::run(void) {
|
||||
exec_addi();
|
||||
regs[IP] += ADDI_SIZE;
|
||||
break;
|
||||
case HALT:
|
||||
case SHIT:
|
||||
DBG_INFO(("HALT\n"));
|
||||
finished = true;
|
||||
break;
|
||||
|
28
cpp/vm.h
28
cpp/vm.h
@ -1,6 +1,7 @@
|
||||
#ifndef VM_H
|
||||
#define VM_H
|
||||
#include "vmas.h"
|
||||
#include "vmcomp.h"
|
||||
#include <stdint.h>
|
||||
|
||||
#define MOVI_SIZE 4
|
||||
@ -8,7 +9,7 @@
|
||||
#define GETM_SIZE 4
|
||||
#define PUTM_SIZE 4
|
||||
#define ADDI_SIZE 4
|
||||
enum regs { R0, R1, R2, R3, S0, S1, S2, S3, IP, BP, SP };
|
||||
enum regs { R0, R1, R2, R3, S0, S1, S2, S3, IP, BP, SP, NUM_REGS };
|
||||
|
||||
/*
|
||||
MEMORY LOCATIONS AND IMMEDIATES ARE 16 BITS LONG
|
||||
@ -16,8 +17,8 @@ MEMORY LOCATIONS AND IMMEDIATES ARE 16 BITS LONG
|
||||
enum ins {
|
||||
MOVI,
|
||||
MOVR,
|
||||
GETM,
|
||||
PUTM,
|
||||
LOAD,
|
||||
STOR,
|
||||
ADDI,
|
||||
ADDR,
|
||||
SUBI,
|
||||
@ -33,19 +34,31 @@ enum ins {
|
||||
PUSH,
|
||||
POOP,
|
||||
CALL,
|
||||
HALT,
|
||||
NOPE
|
||||
SHIT,
|
||||
NOPE,
|
||||
GERM,
|
||||
NUM_OPS
|
||||
};
|
||||
|
||||
class VM {
|
||||
private:
|
||||
////////////////////////
|
||||
// VARIABLES
|
||||
////////////////////////
|
||||
|
||||
uint16_t regs[0xb];
|
||||
VMComponent ops[NUM_OPS];
|
||||
struct flags {
|
||||
uint8_t zf : 1;
|
||||
uint8_t cf : 1;
|
||||
};
|
||||
VMAddrSpace as;
|
||||
|
||||
////////////////////////
|
||||
// FUNCTIONS
|
||||
///////////////////////
|
||||
void initVariables(void);
|
||||
void defineOpcodes(uint8_t * key);
|
||||
/*
|
||||
DBG UTILS
|
||||
*/
|
||||
@ -61,9 +74,8 @@ private:
|
||||
bool exec_addi(void);
|
||||
|
||||
public:
|
||||
VM();
|
||||
VM(uint8_t *code, uint32_t codesize);
|
||||
void init_regs(void);
|
||||
VM(uint8_t * key);
|
||||
VM(uint8_t * key, uint8_t *code, uint32_t codesize);
|
||||
void status(void);
|
||||
void run();
|
||||
};
|
||||
|
38
cpp/vmcomp.cpp
Normal file
38
cpp/vmcomp.cpp
Normal file
@ -0,0 +1,38 @@
|
||||
#include "debug.h"
|
||||
#include "vmcomp.h"
|
||||
|
||||
VMComponent::VMComponent(void) {
|
||||
name = NULL;
|
||||
value = 0;
|
||||
}
|
||||
VMComponent::VMComponent(uint8_t * name, uint16_t value) {
|
||||
this->name = name;
|
||||
this->value = value;
|
||||
}
|
||||
|
||||
uint8_t * VMComponent::getName(void){
|
||||
return name;
|
||||
}
|
||||
|
||||
uint8_t VMComponent::getValue(void) {
|
||||
return value;
|
||||
}
|
||||
|
||||
void VMComponent::setName(uint8_t * name) {
|
||||
this->name = name;
|
||||
return;
|
||||
}
|
||||
|
||||
void VMComponent::setValue(uint16_t value) {
|
||||
this->value = value;
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t VMComponent::toUint8(void) {
|
||||
return (uint8_t) value;
|
||||
}
|
||||
|
||||
uint16_t VMComponent::toUint16(void) {
|
||||
return (uint16_t) value;
|
||||
}
|
||||
|
19
cpp/vmcomp.h
Normal file
19
cpp/vmcomp.h
Normal file
@ -0,0 +1,19 @@
|
||||
#ifndef VMCOMP_H
|
||||
#define VMCOMP_H
|
||||
#include <stdint.h>
|
||||
class VMComponent {
|
||||
private:
|
||||
uint8_t * name;
|
||||
uint16_t value;
|
||||
public:
|
||||
VMComponent();
|
||||
VMComponent(uint8_t * name, uint16_t value);
|
||||
uint8_t * getName(void);
|
||||
uint8_t getValue(void);
|
||||
void setName(uint8_t * name);
|
||||
void setValue(uint16_t value);
|
||||
uint8_t toUint8(void);
|
||||
uint16_t toUint16(void);
|
||||
};
|
||||
|
||||
#endif
|
@ -2,33 +2,38 @@ import sys
|
||||
import re
|
||||
import struct
|
||||
import IPython
|
||||
import copy
|
||||
|
||||
|
||||
class InvalidRegisterException(Exception):
|
||||
class AssemblerException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidRegister(AssemblerException):
|
||||
|
||||
def __init__(self, register):
|
||||
super().__init__("Invalid register: {}".format(register))
|
||||
|
||||
|
||||
class InvalidOperationException(Exception):
|
||||
class InvalidOperation(AssemblerException):
|
||||
|
||||
def __init__(self, operation):
|
||||
super().__init__("Invalid operation: {}".format(operation))
|
||||
|
||||
|
||||
class ExpectedImmediateException(Exception):
|
||||
class ExpectedImmediate(AssemblerException):
|
||||
|
||||
def __init__(self, value):
|
||||
super().__init__("Expected immediate, got {}".format(value))
|
||||
|
||||
|
||||
class ExpectedRegisterException(Exception):
|
||||
class ExpectedRegister(AssemblerException):
|
||||
|
||||
def __init__(self, value):
|
||||
super().__init__("Expected register, got {}".format(value))
|
||||
|
||||
|
||||
class IPOverwriteException(Exception):
|
||||
class IPOverwrite(AssemblerException):
|
||||
|
||||
def __init__(self, instruction=None):
|
||||
if instruction:
|
||||
@ -37,17 +42,23 @@ class IPOverwriteException(Exception):
|
||||
super().__init__("IP can't be overwritten.")
|
||||
|
||||
|
||||
class InvalidValueException(Exception):
|
||||
class InvalidValue(AssemblerException):
|
||||
|
||||
def __init__(self, instruction):
|
||||
super().__init__("Invalid value while assembling: {}".format(instruction))
|
||||
|
||||
rol = lambda val, r_bits, max_bits: \
|
||||
(val << r_bits%max_bits) & (2**max_bits-1) | \
|
||||
((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits)))
|
||||
|
||||
class VMAssembler:
|
||||
assembled_code = bytearray()
|
||||
|
||||
def __init__(self, key):
|
||||
self.assembled_code = bytearray()
|
||||
self.define_ops(key)
|
||||
|
||||
def parse(self, instruction):
|
||||
action = getattr(self, "{}".format(instruction.opcode.name))
|
||||
action = getattr(self, "op_{}".format(instruction.opcode.name))
|
||||
action(instruction)
|
||||
|
||||
def process_code_line(self, line):
|
||||
@ -64,20 +75,15 @@ class VMAssembler:
|
||||
opcode = instruction.opcode
|
||||
reg = instruction.args[0]
|
||||
imm = instruction.args[1]
|
||||
print(instruction)
|
||||
if reg.name != "ip":
|
||||
if imm.isimm():
|
||||
if reg.isreg():
|
||||
if opcode.uint8() and reg.uint8() and imm.uint16():
|
||||
self.assembled_code += opcode.uint8() + reg.uint8() + imm.uint16()
|
||||
else:
|
||||
raise InvalidValueException(instruction)
|
||||
else:
|
||||
raise ExpectedRegisterException(reg)
|
||||
else:
|
||||
raise ExpectedImmediateException(imm)
|
||||
else:
|
||||
raise IPOverwriteException(instruction)
|
||||
if reg.name == "ip":
|
||||
raise IPOverwrite(instruction)
|
||||
if not imm.isimm():
|
||||
raise ExpectedImmediate(imm)
|
||||
if not reg.isreg():
|
||||
raise ExpectedRegister(reg)
|
||||
if not opcode.uint8() or not reg.uint8() or not imm.uint16():
|
||||
raise InvalidValue(instruction)
|
||||
self.assembled_code += opcode.uint8() + reg.uint8() + imm.uint16()
|
||||
return
|
||||
|
||||
def reg2reg(self, instruction):
|
||||
@ -90,47 +96,55 @@ class VMAssembler:
|
||||
opcode = instruction.opcode
|
||||
imm = instruction.args[0]
|
||||
reg = instruction.args[1]
|
||||
print(instruction)
|
||||
if reg.name != "ip":
|
||||
if imm.isimm():
|
||||
if reg.isreg():
|
||||
if opcode.uint8() and reg.uint8() and imm.uint16():
|
||||
self.assembled_code += opcode.uint8() + imm.uint16() + reg.uint8()
|
||||
else:
|
||||
raise InvalidValueException(instruction)
|
||||
else:
|
||||
raise ExpectedRegisterException(reg)
|
||||
else:
|
||||
raise ExpectedImmediateException(imm)
|
||||
else:
|
||||
raise IPOverwriteException(instruction)
|
||||
if reg.name == "ip":
|
||||
raise IPOverwrite(instruction)
|
||||
if not imm.isimm():
|
||||
raise ExpectedImmediate(imm)
|
||||
if not reg.isreg():
|
||||
raise ExpectedRegister(reg)
|
||||
if not opcode.uint8() or not reg.uint8() or not imm.uint16():
|
||||
raise InvalidValue(instruction)
|
||||
self.assembled_code += opcode.uint8() + imm.uint16() + reg.uint8()
|
||||
return
|
||||
|
||||
def imm(self, instruction):
|
||||
return
|
||||
|
||||
def movi(self, instruction):
|
||||
def op_movi(self, instruction):
|
||||
self.imm2reg(instruction)
|
||||
|
||||
def movr(self, instruction):
|
||||
def op_movr(self, instruction):
|
||||
self.reg2reg(instruction)
|
||||
|
||||
def getm(self, instruction):
|
||||
def op_load(self, instruction):
|
||||
self.imm2reg(instruction)
|
||||
|
||||
def putm(self, instruction):
|
||||
def op_stor(self, instruction):
|
||||
self.reg2imm(instruction)
|
||||
|
||||
def addi(self, instruction):
|
||||
def op_addi(self, instruction):
|
||||
self.imm2reg(instruction)
|
||||
|
||||
def define_ops(self, key):
|
||||
key_ba = bytearray(key, 'utf-8')
|
||||
olds = copy.deepcopy(ops)
|
||||
for b in key_ba:
|
||||
for op_com in ops:
|
||||
if b % 2:
|
||||
op_com.set_value(rol(b ^ op_com.value, b % 8, 8))
|
||||
else:
|
||||
op_com.set_value(rol(b ^ op_com.value, (b + 1) % 8, 8))
|
||||
for i in ops:
|
||||
for j in ops:
|
||||
j.set_value(rol(j.value, i.value % 8, 8))
|
||||
for o, n in zip(olds, ops):
|
||||
print("{} : {}->{}".format(o.name, hex(o.value), hex(n.value)))
|
||||
|
||||
|
||||
class VMComponent:
|
||||
"""
|
||||
Represents a register, operation or an immediate the VM recognizes
|
||||
"""
|
||||
name = ""
|
||||
value = ""
|
||||
|
||||
def __init__(self, name, value):
|
||||
self.name = name.casefold()
|
||||
@ -139,6 +153,12 @@ class VMComponent:
|
||||
def __repr__(self):
|
||||
return "{}".format(self.name)
|
||||
|
||||
def set_name(self, name):
|
||||
self.name = name
|
||||
|
||||
def set_value(self, value):
|
||||
self.value = value
|
||||
|
||||
def uint8(self):
|
||||
numre = re.compile("^[0-9]+$")
|
||||
if isinstance(self.value, int):
|
||||
@ -203,8 +223,8 @@ class VMInstruction:
|
||||
|
||||
op_names = ["MOVI",
|
||||
"MOVR",
|
||||
"GETM",
|
||||
"PUTM",
|
||||
"LOAD",
|
||||
"STOR",
|
||||
"ADDI",
|
||||
"ADDR",
|
||||
"SUBI",
|
||||
@ -220,8 +240,10 @@ op_names = ["MOVI",
|
||||
"PUSH",
|
||||
"POOP",
|
||||
"CALL",
|
||||
"HALT",
|
||||
"NOPE"]
|
||||
"SHIT",
|
||||
"NOPE",
|
||||
"GERM"]
|
||||
|
||||
reg_names = ["R0", "R1", "R2", "R3", "S0", "S1", "S2", "S3", "IP", "BP", "SP"]
|
||||
section_names = ["DATA:", "CODE:", "STACK:"]
|
||||
section_flags = {s.casefold(): i + 1 for i, s in enumerate(section_names)}
|
||||
@ -230,7 +252,6 @@ regs = [VMComponent(s.casefold(), i) for i, s in enumerate(reg_names)]
|
||||
|
||||
|
||||
def value_from_list(fromlist, name):
|
||||
global ops, regs
|
||||
"""
|
||||
returns a tuple (name, value) from a list of VMComponents
|
||||
"""
|
||||
@ -238,9 +259,9 @@ def value_from_list(fromlist, name):
|
||||
if el.name == name:
|
||||
return (el.name, el.value)
|
||||
if fromlist == ops:
|
||||
raise InvalidOperationException(name)
|
||||
raise InvalidOperation(name)
|
||||
elif fromlist == regs:
|
||||
raise InvalidRegisterException(name)
|
||||
raise InvalidRegister(name)
|
||||
|
||||
|
||||
def name_from_list(fromlist, value):
|
||||
@ -259,12 +280,12 @@ def assemble_data(line):
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3:
|
||||
print("Usage: {} file_to_assemble output".format(sys.argv[0]))
|
||||
if len(sys.argv) < 4:
|
||||
print("Usage: {} opcodes_key file_to_assemble output".format(sys.argv[0]))
|
||||
return
|
||||
vma = VMAssembler()
|
||||
with open(sys.argv[1], 'r') as f:
|
||||
gen = (line.casefold().strip("\n") for line in f if line != "\n")
|
||||
vma = VMAssembler(sys.argv[1])
|
||||
with open(sys.argv[2], 'r') as f:
|
||||
gen = (line.casefold().strip() for line in f if line != "\n")
|
||||
flag = None
|
||||
|
||||
for line in gen:
|
||||
@ -278,7 +299,7 @@ def main():
|
||||
if not flag:
|
||||
sys.stderr.write(
|
||||
"Nothing was assembled! Did you use the section delimiters?\n")
|
||||
with open(sys.argv[2], 'wb') as f:
|
||||
with open(sys.argv[3], 'wb') as f:
|
||||
f.write(vma.assembled_code)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
Loading…
Reference in New Issue
Block a user