-
Notifications
You must be signed in to change notification settings - Fork 0
/
vm.py
60 lines (59 loc) · 1.62 KB
/
vm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import sys
import codecs
try:
file = open(sys.argv[1], "rb")
except:
print("File does not exist or is not given.")
sys.exit()
bytecode = file.read()
file.close()
bytecode = list(bytecode)
hexcode = []
for dec in bytecode:
hexcode += [hex(dec)]
# print(hexcode)
# magic number check
if hexcode[0] == "0x68" and hexcode[1] == "0x69":
pass
else:
print("Not a CHex bianary file.")
# set offset to 2 because of magic number
offset = 2
# init mem
memory = {}
while True:
try:
hex = hexcode[offset]
except:
sys.exit()
# blank hex
if hex == "0x0":
offset += 1
# print ascii from memory
elif hex == "0x1":
# print(memory[int(hexcode[offset + 1][2:], 16)][2:])
hexval = memory[int(hexcode[offset + 1][2:], 16)][2:]
if not len(hexval) == 2:
hexval = "0" + hexval
print(str(codecs.decode(hexval, "hex"), "utf-8"), end="")
offset += 2
# same as asm jmp
elif hex == "0x2":
offset = int(hexcode[offset + 1], 16)
# store value in mem
elif hex == "0x3":
memory[int(hexcode[offset + 1], 16)] = hexcode[offset + 2]
offset += 3
# jump to hex stored in memory
elif hex == "0x4":
offset = int(memory[int(hexcode[offset + 1], 16)], 16)
# check if values in memory are equal and jump if so
elif hex == "0x5":
if int(memory[int(hexcode[offset + 1], 16)], 16) == int(memory[int(hexcode[offset + 2], 16)], 16):
offset = int(hexcode[offset + 3], 16)
else:
offset += 4
else:
print("Unknown hex at offset: " + str(offset))
sys.exit()