From fa58d701f14098d682691ea6568e49e1d9a3d566 Mon Sep 17 00:00:00 2001 From: Dominik Roth Date: Fri, 29 May 2020 00:41:13 +0200 Subject: [PATCH] initial commit --- asm.py | 495 ++++++++++++++++++++++ asm.pyc | Bin 0 -> 15950 bytes asmCust.py | 249 +++++++++++ compiler.py | 605 +++++++++++++++++++++++++++ compiler_beta.py | 658 ++++++++++++++++++++++++++++++ deCompiler.py | 214 ++++++++++ mima.py | 544 ++++++++++++++++++++++++ multiply_test.txt | 80 ++++ pow_test.txt | 57 +++ saves/bug_find.asmTron | Bin 0 -> 4317 bytes saves/color.asmTron | 1 + saves/gbi_test.asmTron | Bin 0 -> 4316 bytes saves/haltingNonDivergent.asmTron | Bin 0 -> 88 bytes saves/multiply.asmTron | Bin 0 -> 129 bytes saves/pow.asmTron | Bin 0 -> 178 bytes saves/powPerf.asmTron | Bin 0 -> 178 bytes test.asmTron | Bin 0 -> 140 bytes tronScript/assemblyTest.asmTron | Bin 0 -> 87 bytes tronScript/assemblyTest.tron | 6 + tronScript/forTest.asmTron | Bin 0 -> 131 bytes tronScript/forTest.tron | 7 + tronScript/henrik.asmTron | Bin 0 -> 100 bytes tronScript/henrik.tron | 4 + tronScript/powCompiled.asmTron | Bin 0 -> 180 bytes tronScript/powCompiled.tron | 33 ++ tronScript/stack_test.asmTron | Bin 0 -> 228 bytes tronScript/stack_test.tron | 14 + tronScript/tronScript_README.txt | 45 ++ 28 files changed, 3012 insertions(+) create mode 100644 asm.py create mode 100644 asm.pyc create mode 100644 asmCust.py create mode 100644 compiler.py create mode 100644 compiler_beta.py create mode 100644 deCompiler.py create mode 100644 mima.py create mode 100644 multiply_test.txt create mode 100644 pow_test.txt create mode 100644 saves/bug_find.asmTron create mode 100644 saves/color.asmTron create mode 100644 saves/gbi_test.asmTron create mode 100644 saves/haltingNonDivergent.asmTron create mode 100644 saves/multiply.asmTron create mode 100644 saves/pow.asmTron create mode 100644 saves/powPerf.asmTron create mode 100644 test.asmTron create mode 100644 tronScript/assemblyTest.asmTron create mode 100644 tronScript/assemblyTest.tron create mode 100644 tronScript/forTest.asmTron create mode 100644 tronScript/forTest.tron create mode 100644 tronScript/henrik.asmTron create mode 100644 tronScript/henrik.tron create mode 100644 tronScript/powCompiled.asmTron create mode 100644 tronScript/powCompiled.tron create mode 100644 tronScript/stack_test.asmTron create mode 100644 tronScript/stack_test.tron create mode 100644 tronScript/tronScript_README.txt diff --git a/asm.py b/asm.py new file mode 100644 index 0000000..6451bdb --- /dev/null +++ b/asm.py @@ -0,0 +1,495 @@ +import os +import sys +import pickle +import zlib +import hashlib +import copy +from termcolor import colored +from base64 import * +from colorama import init +init() + +OS = "Linux" +#OS = "Windows" + +doc = """ +0000 NOP +0001 LDA memory > A +0010 ADD A + memspace +0011 SUB A - memspace +0100 STA A > memory +0101 OUT A > OUT +0110 JMP Jump to adress +0111 LDI par > A +1000 JIF Jump if greater +1001 JIE Jump if equal +1010 LDP memory[A] > A +1011 INP IN > A +1100 JMA Jump to A +1101 --- NOP equivalent +1110 STP memory[par] > memory[A] +1111 HLT Halt +""" + +asmMap = ["NOP","LDA","ADD","SUB","STA","OUT","JMP","LDI","JIF","JIE","---","INP","JMA","HLO","HST","HLT"] + +bits = 12 + +pointer = 0 + +registerA = 0 +out = 0 + +color = [["green","on_grey"],["blue","on_grey"],["red","on_grey"],["magenta","on_grey"],["cyan","on_grey"], + ["grey","on_white"],["green","on_white"],["blue","on_white"],["red","on_white"],["magenta","on_white"],["cyan","on_white"], + ["grey","on_green"],["white","on_green"],["blue","on_green"],["red","on_green"],["magenta","on_green"],["cyan","on_green"], + ["grey","on_blue"],["white","on_blue"],["green","on_blue"],["red","on_blue"],["magenta","on_blue"],["cyan","on_blue"], + ["grey","on_red"],["white","on_red"],["green","on_red"],["blue","on_red"],["magenta","on_red"],["cyan","on_red"], + ["grey","on_magenta"],["white","on_magenta"],["green","on_magenta"],["blue","on_magenta"],["red","on_magenta"],["cyan","on_magenta"], + ["grey","on_cyan"],["white","on_cyan"],["green","on_cyan"],["blue","on_cyan"],["red","on_cyan"],["magenta","on_cyan"]] + +memory = [] + +for i in range(2**8): + memory.append(0) + +def clear(): + if OS=="Windows": + os.system("cls") + elif OS=="Linux": + os.system("clear") + else: + print("Error: Unknown OS") + exit() + +def toDec(binary): + try: + return int(binary, 2) + except: + return -1 + +def toBin(decimal): + try: + return int(bin(decimal)[2:]) + except: + print("Error: The dec-number "+decimal+" could not be converted to binary") + return decimal + +def padBin(binary,bit=bits): + return str(binary).zfill(bit)[-bit:] + +def bin_input(display,bit=bits): + raw = raw_input(display) + if raw=="x": + return -1 + raw = raw.replace(" ","") + ret = toDec(raw) + if ret>2**bit: + print("[!] input exceted maximal size for "+str(bit)+"-bit integer!") + return bin_input(display) + if ret==-1: + print("[!] "+raw+" is not a valid binary number!") + return bin_input(display) + return ret + +def parse(cmd,par,verbose=False,adress=0): + global registerA + global memory + global out + global pointer + v=verbose + cmd16 = cmd + cmd = cmd[-4:] + if cmd=="0000": #nop + if v: print padBin(toBin(adress),bit=8)+": NOP" + elif cmd=="0001": #lda + registerA = memory[par] + if v: print padBin(toBin(adress),bit=8)+": LDA memory["+padBin(toBin(par),bit=8)+"] > Register A" + elif cmd=="0010": #add + registerA = (registerA + memory[par]) % 2**8 + if v: print padBin(toBin(adress),bit=8)+": ADD Register A + memory["+padBin(toBin(par),bit=8)+"]" + elif cmd=="0011": #sub + registerA = (registerA - memory[par]) % 2**8 + if registerA<0: + registerA = (2**bits+registerA) % 2**8 + if v: print padBin(toBin(adress),bit=8)+": SUB Register A - memory["+padBin(toBin(par),bit=8)+"]" + elif cmd=="0100": #sta + memory[par] = registerA + if v: print padBin(toBin(adress),bit=8)+": STA Register A > memory["+padBin(toBin(par),bit=8)+"]" + elif cmd=="0101": #out + out = registerA + print("[OUT] "+padBin(toBin(out),bit=8)) + if v: print padBin(toBin(adress),bit=8)+": OUT Register A > out" + elif cmd=="0110": #jmp + pointer = par - 1 + if v: print padBin(toBin(adress),bit=8)+": JMP "+padBin(toBin(par),bit=8) + elif cmd=="0111": #ldi + registerA = par + if v: print padBin(toBin(adress),bit=8)+": LDI "+padBin(toBin(par),bit=8)+" > Register A" + elif cmd=="1000": #jif + if registerA>=(2**8)/2: #10000000 + pointer = par - 1 + if v: print padBin(toBin(adress),bit=8)+": JIF {TRUE} > "+padBin(toBin(par),bit=8) + else: + if v: print padBin(toBin(adress),bit=8)+": JIF {FALSE} > "+padBin(toBin(par),bit=8) + elif cmd=="1001": #fie + if registerA==(2**8)/2: #10000000 + pointer = par - 1 + if v: print padBin(toBin(adress),bit=8)+": JIE {TRUE} > "+padBin(toBin(par),bit=8) + else: + if v: print padBin(toBin(adress),bit=8)+": JIE {FALSE} > "+padBin(toBin(par),bit=8) + elif cmd=="1010": #ldp + registerA = memory[registerA] + if v: print padBin(toBin(adress),bit=8)+": LDP memory["+padBin(toBin(registerA),bit=8)+"] > Register A" + elif cmd=="1011": #inp + if v: print padBin(toBin(adress),bit=8)+": INP input > Register A" + registerA = bin_input("[INPUT]> ") + elif cmd=="1100": #jma + pointer = registerA - 1 + if v: print padBin(toBin(adress),bit=8)+": JMA Jump to Register A" + elif cmd=="1101": #--- + if v: print "Got unimplemented op-code: 1101" + elif cmd=="1110": #STP + memory[par] = memory[registerA] + if v: print padBin(toBin(adress),bit=8)+": STP memory["+padBin(toBin(registerA),bit=8)+"] > memory["+padBin(toBin(par),bit=8)+"]" + elif cmd=="1111": #hlt + return -1 + return True + +if __name__=="__main__": + print("[asmTron by CyberCodeDragon]") + while True: + x = "" + x=raw_input("#> ") + x = x.split(" ") + for i in range(2): + x.append("") + y = x[1] + z = x[2] + x = x[0] + if x=="help" or x=="h": + print("Avaible Commands:") + print("docs - display avaible operants") + print("write [w] - write value to adress") + print("read [r] - read value from adress") + print("dump [d] - dump from adress with length") + print("run [u] - execute programm") + print("edit [e] - edit from adress til >x<") + print("cls - clear screen") + print("clear / reset - clear memory,register,pointer") + print("highClear [hc] - clear highMem,register,pointer") + print("step [s] - run one command from programm") + print("debug - execute programm with verbose output") + print("pointer - display pointer") + print("setPointer - sets pointer") + print("resetPointer [rp] - sets pointer to zero") + print("register [reg] - displays A register") + print("setRegister - sets A register") + print("save - saves memory to local file") + print("load - loads memory from local file") + print("code / exec - execute one line of shellcode") + print("guiDebug [gd] - graphical debugger") + print("asm - shellcode visualizer (assembly / jump-arrows)") + print("halting - tries to determin, if algorythm will diverge") + elif x=="docs": + print(doc) + elif x=="write" or x=="w": + if y=="" or z=="": + y=bin_input("adress> ") + z=bin_input("value> ") + try: + memory[y] = z + except: + print("[!] Unknown error while writing") + elif x=="read" or x=="r": + if y=="": + y=bin_input("adress> ") + print(padBin(toBin(memory[y]))) + elif x=="dump" or x=="d": + if y=="" and z=="": + y=bin_input("adress> ") + z=bin_input("length> ") + elif z=="": + z=toDec(y) + y=0 + for m in range(z): + print(padBin(toBin(y+m),bit=8)+": "+padBin(toBin(memory[y+m]))) + elif x=="run" or x=="u": + while True: + cmd = padBin(toBin(memory[pointer]))[:4] + par = int(toDec(padBin(toBin(memory[pointer]))[-8:])) + if parse(cmd,par)==-1: + pointer = 0 + break + pointer = (pointer + 1) % 2**bits + elif x=="verboseRun" or x=="vu": + while True: + cmd = padBin(toBin(memory[pointer]))[:4] + par = int(toDec(padBin(toBin(memory[pointer]))[-8:])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = 0 + break + pointer = (pointer + 1) % 2**bits + elif x=="edit" or x=="e": + adress=bin_input("offset> ",bit=8) + while True: + value=bin_input(padBin(toBin(adress),bit=8)+": "+padBin(toBin(memory[adress]))+" > ") + if value==-1: + break + try: + memory[adress] = value + except: + print("[!] Unknown error while writing") + if adress==len(memory)-1: + adress = -1 + print("[*] End of mem") + adress = adress + 1 + elif x=="cls": + clear() + elif x=="clear" or x=="reset": + pointer = 0 + registerA = 0 + out = 0 + memory = [] + for i in range(2**bits): + memory.append(0) + elif x=="highClear" or x=="highReset" or x=="hr" or x=="hc": + pointer = 0 + registerA = 0 + out = 0 + for i in range((2**bits)/2): + memory[(2**bits)/2+i] = 0 + elif x=="step" or x=="s": + cmd = padBin(toBin(memory[pointer]))[:4] + par = int(toDec(padBin(toBin(memory[pointer]))[-8:])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = 0 + print("[*] Programm halted") + pointer = (pointer + 1) % (2**bits) + elif x=="debug": + while True: + cmd = padBin(toBin(memory[pointer]))[:4] + par = int(toDec(padBin(toBin(memory[pointer]))[-8:])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = -1 + print("[*] Programm halted") + break + pointer = (pointer + 1) % (2**bits) + elif x=="pointer": + print("POINTER: "+padBin(toBin(pointer),bit=8)) + elif x=="setPointer": + if y=="": + pointer = bin_input("pointer> ",bit=8) + else: + pointer = y + elif x=="resetPointer" or x=="rp": + pointer = 0 + elif x=="register" or x=="reg": + print("REGISTER: "+padBin(toBin(registerA))) + elif x=="setRegister": + if y=="": + registerA = bin_input("register> ") + else: + registerA = y + elif x=="save": + if y=="": + print("[*] Current saves:") + for f in os.listdir("."): + if f[-8:]==".asmTron": + print("> "+f[:-8]) + name = raw_input("name> ") + else: + name = y + with open(name+".asmTron", 'wb') as f: + t=pickle.dumps([12,memory]) + t=zlib.compress(t) + f.write(t) + elif x=="load" or x=="l": + if y=="": + print("[*] Avaible saves:") + for f in os.listdir("."): + if f[-8:]==".asmTron": + print("> "+f[:-8]) + for f in os.listdir("tronScript"): + if f[-8:]==".asmTron": + print("> tronScript/"+f[:-8]) + name = raw_input("name> ") + else: + name = y + try: + with open(name+".asmTron", "rb") as f: + t = f.read() + t=zlib.decompress(t) + magicBit,memory = pickle.loads(t) + except Exception as e: + try: + with open("tronScripts/"+name+".asmTron", "rb") as f: + t = f.read() + t=zlib.decompress(t) + magicBit,memory = pickle.loads(t) + except Exception as e: + if b64encode(str(e))[:25]=="W0Vycm5vIDJdIE5vIHN1Y2ggZ": + print(" [!] Error: File '"+name+".asmTron' does not exist") + else: + print(" [!] Error: Unknown Error while reading File '"+name+"' with Errorcode: "+str(b64encode(str(e)))) + if not magicBit==12: + print("[!] Error: Invalid Magical Bit: "+str(magicBit)) + exit() + print("[*] loaded "+name+".asmTron") + elif x=="code" or x=="exec": + if y=="": + data=bin_input("code> ") + else: + data=y + cmd = padBin(toBin(memory[pointer]))[:4] + par = int(toDec(padBin(toBin(memory[pointer]))[-8:])) + parse(cmd,par,verbose=True,adress=0) + elif x=="guiDebug" or x=="gd": + runtime = 0 + tracker = raw_input("trackers> ").split(",") + running = True + lastPointer = 0 + while running: + clear() + print(" +"+"-"*34+"+"+"-"*28+"+"+"-"*24+"+") + print(" |"+" "*8+" - Instructions - "+" "*8+"|"+" "*8+" - Hi-mem - "+" "*8+"|"+" "*24+"|") + if pointer <= 20: + starter = 0 + else: + starter = pointer - 20 + for i in range(36): + m = i + starter + if pointer == m: + outI = "> "+padBin(toBin(m),bit=8)+": "+padBin(toBin(memory[m]))+" ["+doc.split("\n")[toDec(padBin(toBin(memory[m]))[:4])+1][:8][5:]+"]"+" <" + elif lastPointer == m and pointer-1 != lastPointer: + outI = "- "+padBin(toBin(m),bit=8)+": "+padBin(toBin(memory[m]))+" ["+doc.split("\n")[toDec(padBin(toBin(memory[m]))[:4])+1][:8][5:]+"]"+" -" + else: + outI = " "+padBin(toBin(m),bit=8)+": "+padBin(toBin(memory[m]))+" ["+doc.split("\n")[toDec(padBin(toBin(memory[m]))[:4])+1][:8][5:]+"]"+" " + outII = " "+padBin(toBin(128+i),bit=8)+": "+padBin(toBin(memory[128+i]))+" " + if i==1: + outIII = " - Register A - " + elif i==2: + outIII = " "*8+padBin(toBin(registerA),bit=8)+" "*8 + elif i==4: + outIII = " - Runtime - " + elif i==5: + outIII = " "+padBin(toBin(runtime),bit=12)+" " + elif i==7: + outIII = " - Command - " + elif i==8: + temp=doc.split("\n")[toDec(padBin(toBin(memory[pointer]))[:4])+1][5:] + outIII = int((24-len(temp))/2-1)*" "+" "+temp+int((24-len(temp))/2)*" " + elif i==10: + outIII = " - Parameter - " + elif i==11: + outIII = " "+padBin(toBin(memory[pointer]))[-8:]+" " + elif i==13: + outIII = " - OUT-Register - " + elif i==14: + outIII = " "+padBin(toBin(out),bit=8)+" " + elif i==16: + outIII = " - Pointer - " + elif i==17: + outIII = " "+padBin(toBin(pointer))+" " + elif i==19: + if len(tracker[0]): + outIII = " - Trackers - " + else: + outIII = " "*24 + elif i>19 and i<=19+len(tracker): + if len(tracker[0]): + outIII = " "+str(tracker[i-19-1]) + ": " + padBin(toBin(memory[toDec(tracker[i-19-1])]))+" " + else: + outIII = " "*24 + else: + outIII = " "*24 + print(" | "+outI+" | "+outII+" |"+outIII+"|") + print(" |"+" "*34+"|"+" "*28+"|"+" "*24+"|") + print(" +"+"-"*34+"+"+"-"*28+"+"+"-"*24+"+") + + lastPointer = pointer + + cmd = padBin(toBin(memory[pointer]))[:4] + par = int(toDec(padBin(toBin(memory[pointer]))[-8:])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = 0 + break + pointer = (pointer + 1) % 2**bits + + step=raw_input(" ") + if step=="x": + break + + runtime = runtime + 1 + elif x=="asm": + end = 0 + for m in range(len(memory)): + if padBin(toBin(memory[len(memory)-m-1]))[:4] != "0000": + end = len(memory)-m + break + toPrint = [] + for m in range(end): + cmd = doc.split("\n")[toDec(padBin(toBin(memory[m]))[:4])+1][:8][5:] + if toDec(padBin(toBin(memory[m]))[4:]) >= toDec("10000000") and toDec(padBin(toBin(memory[m]))[4:]) <= toDec("10101000"): + toPrint.append(padBin(toBin(m),bit=8)+": "+cmd+" "+colored(padBin(toBin(memory[m]))[4:],color[(toDec(padBin(toBin(memory[m]))[4:])-toDec("10000000"))][0],color[(toDec(padBin(toBin(memory[m]))[4:])-toDec("10000000"))][1])) + else: + toPrint.append(padBin(toBin(m),bit=8)+": "+cmd+" "+padBin(toBin(memory[m]))[4:]) + origPrint = copy.copy(toPrint) + for l in range(len(toPrint)): + cmd = origPrint[l][10:][:3] + par = origPrint[l][14:] + if cmd == "JMP" or cmd == "JIF" or cmd == "JIE": + toPrint[toDec(par)] = toPrint[toDec(par)] + " <-+" + toPrint[l] = toPrint[l] + " --+" + if l < toDec(par): + for i in range(len(toPrint)): + if l < i < toDec(par): + toPrint[i] = toPrint[i] + " |" + elif i==toDec(par) or i==l: + t=1 + else: + toPrint[i] = toPrint[i] + " " + else: + for i in range(len(toPrint)): + if toDec(par) < i < l: + toPrint[i] = toPrint[i] + " |" + elif i==toDec(par) or i==l: + t=1 + else: + toPrint[i] = toPrint[i] + " " + for p in range(len(toPrint)): + print(toPrint[p]) + elif x=="halting": + print("[i] Will try to give you information about the divergity of your algorythm") + print("[i] This algorythm may itself not diverge!") + bPointer = pointer + bRegisterA = registerA + bMemory = memory + runtime = 0 + stateHashes = [] + print("[*] Simulating...") + while True: + runtime+=1 + cmd = padBin(toBin(memory[pointer]))[:4] + par = int(toDec(padBin(toBin(memory[pointer]))[-8:])) + if parse(cmd,par)==-1: + pointer = 0 + halts = True + print("[*] Algorythm will diverge after "+str(runtime)+" steps") + break + pointer = (pointer + 1) % 2**bits + stateHash = hashlib.sha256(str(pointer)+str(registerA)+str(memory)).digest() + if stateHash in stateHashes: + print("[*] Algorythm will not diverge: State-Collision after "+str(runtime)+" steps") + break + else: + stateHashes.append(stateHash) + pointer = bPointer + registerA = bRegisterA + memory = bMemory + elif x=="exit": + exit() + elif x=="": + _=0 + else: + print("[!] Error") diff --git a/asm.pyc b/asm.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e4c5a611b1d68ad831e45d2791135d1c88daef6 GIT binary patch literal 15950 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 sjgg*61zwAG{!W1Y5za#ta3e-RX`EGZ A +0010 ADD A + memspace +0011 SUB A - memspace +0100 STA A > memory +0101 OUT A > OUT +0110 JMP Jump to adress +0111 LDI par > A +1000 JIF Jump if (JC) +1001 HLO H-mem[memspace] > A +1010 HST A > H-mem[memspace] +1011 INP IN > A +1100 JMA Jump to A +1111 HLT Halt +""", 16: """ +0000 0000 NOP +0000 0001 LDA memory > A +0000 0010 ADD A + memspace +0000 0011 SUB A - memspace +0000 0100 STA A > memory +0000 0101 OUT A > OUT +0000 0110 JMP Jump to adress +0000 0111 LDI par > A +0000 1000 JIF Jump if (JC) +0000 1001 HLO H-mem[memspace] > A +0000 1010 HST A > H-mem[memspace] +0000 1011 INP IN > A +0000 1111 HLT Halt +"""} + +#bits = int(raw_input("arch [8/16]> ")) +bits = 8 + +pointer = 0 + +registerA = 0 +out = 0 + +memory = [] + +for i in range(2**bits): + memory.append(0) + +def toDec(binary): + try: + return int(binary, 2) + except: + return -1 + +def toBin(decimal): + return int(bin(decimal)[2:]) + +def padBin(binary,bit=bits): + return str(binary).zfill(bit) + +def bin_input(display,bit=bits): + raw = raw_input(display) + if raw=="x": + return -1 + raw = raw.replace(" ","") + ret = toDec(raw) + if ret>2**bit: + print("[!] input exceted maxial size for "+str(bit)+"-bit integer") + return bin_input(display) + if ret==-1: + print("[!] "+raw+" is not a valid binary number!") + return bin_input(display) + return ret + +def parse(cmd,par,verbose=False,adress=0): + global registerA + global memory + global out + global pointer + v=verbose + cmd16 = cmd + cmd = cmd[-4:] + if cmd=="0000": #nop + if v: print padBin(toBin(adress),bit=bits/2)+": NOP" + elif cmd=="0001": #lda + registerA = memory[par] + if v: print padBin(toBin(adress),bit=bits/2)+": LDA memory["+padBin(toBin(par),bit=bits/2)+"] > Register A" + elif cmd=="0010": #add + registerA = (registerA + memory[par]) % 2**bits + if v: print padBin(toBin(adress))+": ADD Register A + memory["+padBin(toBin(par),bit=bits/2)+"]" + elif cmd=="0011": #sub + registerA = (registerA - memory[par]) + if registerA<0: + registerA = 2**bits+registerA + if v: print padBin(toBin(adress),bit=bits/2)+": SUB Register A - memory["+padBin(toBin(par),bit=bits/2)+"]" + elif cmd=="0100": #sta + memory[par] = registerA + if v: print padBin(toBin(adress),bit=bits/2)+": STA Register A > memory["+padBin(toBin(par),bit=bits/2)+"]" + elif cmd=="0101": #out + out = registerA + print("[OUT] "+padBin(toBin(out))) + if v: print padBin(toBin(adress),bit=bits/2)+": OUT Register A > out" + elif cmd=="0110": #jmp + pointer = par - 1 + if v: print padBin(toBin(adress),bit=bits/2)+": JMP "+padBin(toBin(par),bit=bits/2) + elif cmd=="0111": #ldi + registerA = par + if v: print padBin(toBin(adress),bit=bits/2)+": LDI "+padBin(toBin(par),bit=bits/2)+" > Register A" + elif cmd=="1000": #jif + if registerA>=(2**bits)/2: + pointer = par - 1 + if v: print padBin(toBin(adress),bit=bits/2)+": JIF {TRUE} > "+padBin(toBin(par),bit=bits/2) + else: + if v: print padBin(toBin(adress),bit=bits/2)+": JIF {FALSE} > "+padBin(toBin(par),bit=bits/2) + elif cmd=="1001": #hlo + registerA = memory[memory[par]] + elif cmd=="1010": #hst + memory[memory[par]] = registerA + elif cmd=="1011": #inp + if v: print padBin(toBin(adress),bit=bits/2)+": INP input > Register A" + registerA = bin_input("[INPUT]> ") + elif cmd=="1100": + pointer = registerA - 1 + elif cmd=="1111": #hlt + return -1 + return True + +if __name__=="__main__": + while True: + x=raw_input("#> ") + if x=="help" or x=="h": + print("Help Screen goes here") + elif x=="docs": + print(doc[bits]) + elif x=="write" or x=="w": + adress=bin_input("adress> ") + value=bin_input("value> ") + try: + memory[adress] = value + except: + print("[!] Unknown error while writing") + elif x=="read" or x=="r": + adress=bin_input("adress> ") + print(padBin(toBin(memory[adress]))) + elif x=="dump" or x=="d": + for m in range(len(memory)): + print(padBin(toBin(m),bit=bits/2)+": "+padBin(toBin(memory[m]))) + elif x=="dump32" or x=="d32": + for m in range(32): + print(padBin(toBin(m),bit=bits/2)+": "+padBin(toBin(memory[m]))) + elif x=="dumpSpace" or x=="ds": + begin=bin_input("adress> ") + length=bin_input("length> ") + for m in range(length): + print(padBin(toBin(begin+m),bit=bits/2)+": "+padBin(toBin(memory[begin+m]))) + elif x=="run" or x=="u": + while True: + cmd = padBin(toBin(memory[pointer]))[:(bits/2)] + par = int(toDec(padBin(toBin(memory[pointer]))[-1*(bits/2):])) + if parse(cmd,par)==-1: + pointer = 0 + break + pointer = (pointer + 1) % bits + elif x=="edit" or x=="e": + adress=bin_input("offset> ",bit=bits/2) + while True: + value=bin_input(padBin(toBin(adress),bit=bits/2)+": "+padBin(toBin(memory[adress]))+" > ") + if value==-1: + break + try: + memory[adress] = value + except: + print("[!] Unknown error while writing") + if adress==len(memory)-1: + adress = -1 + print("[*] End of mem") + adress = adress + 1 + elif x=="asm": + adress=bin_input("offset> ",bit=bits/2) + while True: + print("[!] Not yet implemented error") + break + toWrite=raw_input(padBin(toBin(adress),bit=bits/2)+" > ") + cmd,par = toWrite.split(" ") + if value==-1: + break + try: + memory[adress] = value + except: + print("[!] Unknown error while writing") + adress = adress + 1 + elif x=="cls": + os.system("cls") + elif x=="clear": + pointer = 0 + registerA = 0 + out = 0 + memory = [] + for i in range(2**(bits/2)): + memory.append(0) + elif x=="step" or x=="s": + cmd = padBin(toBin(memory[pointer]))[:(bits/2)] + par = int(toDec(padBin(toBin(memory[pointer]))[-1*(bits/2):])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = 0 + print("[*] Programm halted") + pointer = (pointer + 1) % bits + elif x=="debug": + while True: + cmd = padBin(toBin(memory[pointer]))[:(bits/2)] + par = int(toDec(padBin(toBin(memory[pointer]))[-1*(bits/2):])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = -1 + print("[*] Programm halted") + break + pointer = (pointer + 1) % (2**bits/2) + elif x=="pointer": + print("POINTER: "+padBin(toBin(pointer),bit=bits/2)) + elif x=="setPointer": + pointer = bin_input("pointer> ",bit=bits/2) + elif x=="register": + print("REGISTER: "+padBin(toBin(registerA))) + elif x=="setRegister": + registerA = bin_input("register> ") + elif x=="save": + name = raw_input("name> ") + with open(name+".asmTron", 'wb') as f: + pickle.dump([bits,memory],f) + elif x=="load": + print("[*] Avaible saves:") + for f in os.listdir("."): + if f[-8:]==".asmTron": + print("> "+f[:-8]) + name = raw_input("name> ") + with open(name+".asmTron", "rb") as f: + newBits,memory = pickle.load(f) + if not newBits==bits: + print("[!] Error: Uncompatible arch: "+str(newBits)) + exit() + if not pointer==0: + print("[*] Pointer has been set to "+str(pointer)) + elif x=="code": + data=bin_input("code> ") + cmd = padBin(toBin(memory[pointer]))[:(bits/2)] + par = int(toDec(padBin(toBin(memory[pointer]))[-1*(bits/2):])) + parse(cmd,par,verbose=True,adress=0) + else: + print("[!] Error") diff --git a/compiler.py b/compiler.py new file mode 100644 index 0000000..7d3b4c3 --- /dev/null +++ b/compiler.py @@ -0,0 +1,605 @@ +import asm + +def padBin(number,bit=8): + return asm.padBin(asm.toBin(number),bit=bit) + +def toDec(binNumber): + return asm.toDec(binNumber) + +doc = """ +0000 NOP +0001 LDA memory > A +0010 ADD A + memspace +0011 SUB A - memspace +0100 STA A > memory +0101 OUT A > OUT +0110 JMP Jump to adress +0111 LDI par > A +1000 JIF Jump if greater +1001 JIE Jump if equal +1010 --- nop equivalent +1011 INP IN > A +1100 JMA Jump to A +1101 HLO memspace[memspace[par]] > A +1110 HST A > memspace[memspace[par]] +1111 HLT Halt +""" + +def compile(cmd,par,memAddr): + # Every function creates unknown vars, even if it makes no sense in it case, + # because if the function sits inside a user-defined function vars may be + # defined later + try: + if cmd=="newVar": # creates new var and allocates memory-adress for it + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + print("[i] newVar is obsolete in this version of tronScript") + elif cmd=="newArray": # creates new array and allocates memory-adress for it + print("Creating array '"+par[0].upper()+"' at memory-space "+padBin(len(varRec)+(2**8)/2)+" - "+padBin(len(varRec)+int(par[1])+(2**8)/2)) + for i in range(int(par[1])): + varRec["array_"par[0].upper()+"["+i+"]"] = len(varRec)+(2**8)/2 + elif cmd=="jumpMark": # creates a jumpMark and saves current adress in the DB for later use by the jump-name-replacement + print("Creating jumpMark '"+par[0].upper()+"' at memory-address "+padBin(memAddr)) + jumpMark[par[0].upper()] = memAddr + elif cmd=="jump": # creates dummy jump code for later replacement + # we have to do it this way, beacause a jumpMark may be defined after the jump-call + return [ + # will be replaced after script-compilation + "Jump_"+par[0].upper() + ] + elif cmd=="getVarAddress": # stores the memory-adress of a var into another + # maybe needed, if user want to access vars with + # custom asssembly code + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + return [ + ## load the Var-Adress into A Register and save it into specified var + # LDI + toDec("0111"+padBin(varRec[par[0].upper()])), + # STA variable to store the current pointer in + toDec("0100"+padBin(varRec[par[1].upper()])), + ] + elif cmd=="getArrayAddress": # like getVarAdress, but for arrays + # arrayName Index storeVar + try: + t = varRec["array_"par[0].upper()+"["+par[1]+"]"] + except: + print("Undefined Array") + exit() + try: + _ = int(par[1]) + except: + print("Expected array-index (integer)") + exit() + return [ + ## load the Var-Adress into A Register and save it into specified var + # LDI + toDec("0111"+padBin(varRec["array_"par[0].upper()+"["+par[1]+"]"])), + # STA variable to store the current pointer in + toDec("0100"+padBin(varRec[par[2].upper()])), + ] + elif cmd=="exec": # execute a user defined function + try: + t = varRec[par[0].upper()] + except: + print("Creating function-jumpback-var '"+par[0].upper()+"_JUMPBACK' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()+"_JUMPBACK"] = len(varRec)+(2**8)/2 + return [ + ## remember current pointer, so you can jump back here after function execution is done + # LDI + toDec("0111"+padBin(pointer)), + # STA variable to store the current pointer in + toDec("0100"+padBin(varRec[par[0].upper()+"_JUMPBACK"])), + # will be replaced after script-compilation + "Exec_"+par[0].upper()# jumpback function-call-var + ] + elif cmd=="setVar": # gives a var a defined value + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + if par[1][0]=="b": + par[1] = toDec(par[1][1:]) + return [ + ## loads desired value into the A register and then stores it at the variables memory adress + # LDI value + toDec("0111" + padBin(int(par[1]))), + # STA var Name + toDec("0100" + padBin(varRec[par[0].upper()])) + ] + elif cmd=="copyVar": # gives a var the value of another var + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + return [ + ## load memory-space of var 1 into register A and the store it into memory-space of var 2 + # LDA var 1 + toDec("0001" + padBin(varRec[par[0].upper()])), + # STA var 2 + toDec("0100" + padBin(varRec[par[1].upper()])) + ] + elif cmd=="setArrayIndex": # defines the value of an array (par0) index (par1) to be (par2) + try: + t = varRec["array_"par[0].upper()+"["+par[1]+"]"] + except: + print("Undefined array") + exit() + try: + _=int(par[1]) + except: + print("Expected array-index (integer)") + exit() + if par[2][0]=="b": + par[2] = toDec(par[2][1:]) + return [ + ## loads desired value into the A register and then stores it at the variables memory adress + # LDI value + toDec("0111" + padBin(int(par[2]))), + # STA var Name + toDec("0100" + padBin(varRec["array_"par[0].upper()+"["+par[1]+"]"])) + ] + elif cmd=="getArrayIndex": # puts the value of an array (par0) index (par1) into var (par2) + try: + t = varRec["array_"par[0].upper()+"["+par[1]+"]"] + except: + print("Undefined Array") + exit() + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + try: + _=int(par[1]) + except: + print("Expected array-index (integer)") + exit() + return [ + ## load memory-space of var 1 into register A and the store it into memory-space of var 2 + # LDA var 1 + toDec("0001" + padBin(varRec["array_"par[0].upper()+"["+par[1]+"]"])), + # STA var 2 + toDec("0100" + padBin(varRec[par[2].upper()])) + ] + elif cmd=="write": # writes to the console + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + return [ + ## load the variable into register A, then print it + # LDA var Name + toDec("0001" + padBin(varRec[par[0].upper()])), + # OUT null + toDec("0101" + "00000000") + ] + elif cmd=="read": # reads from the console + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + return [ + ## input > register A; register A > var + # INP null + toDec("1011" + "00000000"), + # STA var Name + toDec("0100" + padBin(varRec[par[0].upper()])) + ] + elif cmd=="add": # adds to numbers and stores the answer in another + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + return [ + ## load var 1 into register A; add var 2, store in var 3 + # LDA var Name in1 + toDec("0001" + padBin(varRec[par[0].upper()])), + # ADD var Name in2 + toDec("0010" + padBin(varRec[par[1].upper()])), + # STA var Name out + toDec("0100" + padBin(varRec[par[2].upper()])) + ] + elif cmd=="subtract": # in1 - in2 = out + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + return [ + ## laod var 1 into register A; subtract var 2; store in var 3 + # LDA var Name in1 + toDec("0001" + padBin(varRec[par[0]])), + # SUB var Name in2 + toDec("0011" + padBin(varRec[par[1]])), + # STA var Name out + toDec("0100" + padBin(varRec[par[2]])) + ] + elif cmd=="if": # if clause + #cmd p0 p1 p2 p3 p4: + #if VAR ?? VAR cmd pars + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + comp1=par[0].upper() + comp2=par[2].upper() + comp=par[1] + shellcode=compile(par[3],par[4:],memAddr+4) + if not shellcode: + return ["Error","I had problems getting the internal shellcode. Sorry :("] + if shellcode[0]=="Error": + return ["Error","Internal shellcode compilation thew an Error:\n"+shellcode[1]] + ## binary code that magicaly works: + if comp=="==": + ret = [ + # LDI konst + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp1 + toDec("0001" + padBin(varRec[comp1])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp2 + toDec("0011" + padBin(varRec[comp2])), + # JIE + toDec("1001" + padBin(memAddr+7)), + # JMP + toDec("0110" + padBin(memAddr+7+len(shellcode))) + ] + elif comp=="!=": + ret = [ + # LDI konst + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp1 + toDec("0001" + padBin(varRec[comp1])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp2 + toDec("0011" + padBin(varRec[comp2])), + # JIE + toDec("1001" + padBin(memAddr+6+len(shellcode))) + ] + elif comp==">=": + ret = [ + # LDI konst + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp1 + toDec("0001" + padBin(varRec[comp1])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp2 + toDec("0011" + padBin(varRec[comp2])), + # JIF + toDec("1000" + padBin(memAddr+6+len(shellcode))) + ] + elif comp==">": + ret = [ + # LDI konst + toDec("0111" + "01111111"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp1 + toDec("0001" + padBin(varRec[comp1])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp2 + toDec("0011" + padBin(varRec[comp2])), + # JIF + toDec("1000" + padBin(memAddr+6+len(shellcode))) + ] + elif comp=="<=": + ret = [ + # LDI konst + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp2 + toDec("0001" + padBin(varRec[comp2])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp1 + toDec("0011" + padBin(varRec[comp1])), + # JIF + toDec("1000" + padBin(memAddr+6+len(shellcode))) + ] + elif comp=="<": + ret = [ + # LDI konst + toDec("0111" + "01111111"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp2 + toDec("0001" + padBin(varRec[comp2])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp1 + toDec("0011" + padBin(varRec[comp1])), + # JIF + toDec("1000" + padBin(memAddr+6+len(shellcode))) + ] + for s in shellcode: + ret.append(s) + return ret + elif cmd=="for": # for loop: "for [goal] [counter] [step] [cmd] [pars]" + # == for [counter] in range(0,[goal],[step]): + # [cmd]([pars]) + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + goal = par[0].upper() + clock = par[1].upper() + step = par[2].upper() + shellcode=compile(par[3],par[4:],memAddr+12) + ret = [ + # LDI konst + toDec("0111" + "00000000"), + # STA temp + toDec("0100" + padBin(varRec[clock])), + # LDI konst <-- jump back to + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA clock + toDec("0001" + padBin(varRec[clock])), + # ADD konst + toDec("0010" + "11111111"), + # SUB goal + toDec("0011" + padBin(varRec[goal])), + # JIE + toDec("1001" + padBin(memAddr+12+len(shellcode)+1)), + # LDA clock + toDec("0001" + padBin(varRec[goal])), + # ADD step + toDec("0010" + padBin(varRec[step])), + # STA clock + toDec("0100" + padBin(varRec[goal])) + ] + for s in shellcode: + ret.append(s) + # JMP + ret.append(toDec("0110" + padBin(memAddr+2))) + return ret + elif cmd=="asm" or cmd[0]==":": # compiles assembler to machine-code + if cmd=="asm": + opcode = par[0] + param = par[1] + else: + opcode = cmd[1:] + param = par[0] + if param[:2]=="b#": + param = toDec(param[2:]) + elif param[:2]=="d#": + param = param[2:] + elif param[:2]=="v#": + try: + t = varRec[param[2:].upper()] + except: + print("Creating var '"+param[2:].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[param[2:].upper()] = len(varRec)+(2**8)/2 + param = varRec[param[2:].upper()] + elif param in ["-","none"]: + param = toDec("00000000") + elif param in ["~","all"]: + param = toDec("11111111") + else: + return ["Error","Invalid param supplied to asm-command (no valid prefix found)"] + for a in range(len(asm.asmMap)): + if asm.asmMap[a]==opcode: + print("Found matching opcode") + return [toDec(padBin(a,bit=4)+padBin(param))] + elif cmd=="shellcode": # insertes raw shellcode into the programm + return [toDec("".join(par))] + elif cmd=="nop": # nothing... + return [toDec("0000" + "00000000")] + elif cmd=="halt": # halts execution of programm + return [toDec("1111" + "11111111")] + else: + return ["Error","Unimplemented Function: "+str(cmd)] + except Exception as e: + return ["Error","Unknown Error: "+str(e)] + +bits = 12 + +varRec = {} # to store VarName -> memory-address +jumpMark = {} # to store jumpMarkName -> jump-address + +if __name__ == "__main__": + print("[tronScript-Compiler by CyberCodeDragon]") + memory = [] + for i in range(2**bits): #expand memory + memory.append(0) + + pointer = 0 + funcTable = [] # [[funcName,funcCode],...] + + for f in asm.os.listdir("tronScript"): #display all found scripts + if f[-5:]==".tron": + print("> "+"tronScript/"+f) + filePath = raw_input("file to compile> ") + inFile = filePath.split("\\") + inFile = inFile[len(inFile)-1] + tmp = inFile.split(".") + ext = tmp[len(tmp)-1] + name = inFile.split("."+ext)[0] + print("[*] Reading "+inFile) + with open(filePath) as f: + code = f.read().replace(" ","") #read file and remove tabs + c = code.split("\n") #c = lines of code + #detect functions + for l in range(len(c)): #for every line of code + elems = c[l].split(" ") #elems = [cmd,pa1,par2,...,parN] + if elems[0]=="function": + funcName = elems[1] + funcCode = code.split("function "+funcName+" {")[1].split("}")[0].split("\n") #get the function Code + funcName = funcName.upper() + print("detected function '"+funcName+"' in line "+str(l)+":\n"+"\n".join(funcCode)) + for i in range(len(funcCode)+0): + c[l+i]="#function-code" #replace function with a comment -> dont mess up later parsing + funcTable.append([funcName,funcCode]) + try: #create jumpback-var if not existing (does probably not exist) + t = varRec[funcName+"_JUMPBACK"] + except: + print("Creating function-jumpback-var '"+funcName+"_JUMPBACK' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[funcName+"_JUMPBACK"] = len(varRec)+(2**8)/2 + + #parse code + for l in range(len(c)): #for every line in code + if c[l] not in ["","\n"]: #if lines is not empty + print("Parsing line "+str(l)+": "+c[l]) + cmd = c[l].split(" ")[0] + if not cmd[0]=="#": #dont parse comments + if cmd in ["halt","nop"]: #cmds without params + par = [] + else: + par = c[l].split(cmd+" ")[1].split(" ") + r = compile(cmd,par,pointer) #compile + if r: + if r[0]=="Error": #print error + print("Error compiling line "+str(l)+" {"+c[l]+"}: \n"+str(r[1])) + exit() + for ret in r: + veryVerbose = False + if veryVerbose: + try: + print("Compiled to: "+padBin(ret,bit=12)) + except: + print("Compiled to: "+str(ret)) + memory[pointer] = ret #write code to memory + pointer+=1 + try: + if padBin(memory[pointer-1],bit=12)[:4]!="1111": #if the last command is not a HLT command + print("Appending HLT-Command") + # HLT + memory[pointer] = toDec("1111"+"11111111") + print("HLT at "+padBin(pointer)+": "+padBin(memory[pointer],bit=12)) + pointer+=1 + except: #looks like the last command was a placeholder: not a HLT command + print("Appending HLT-Command") + # HLT + memory[pointer] = toDec("1111"+"11111111") + print("HLT at "+padBin(pointer)+": "+padBin(memory[pointer],bit=12)) + pointer+=1 + + #replace jump-names + for m in range(len(memory)): + try: + if memory[m][:5]=="Jump_": #if at memory-adress is just a jump-dummy + print("Inserting Jump-Adress at "+padBin(m,bit=12)) + memory[m]=toDec("0110"+padBin(jumpMark[memory[m][5:]])) #replace with real jump adress + except: + t=1 + #append function-shellcode + funcMapper = {} #map funcName to funcCode + for f in range(len(funcTable)): + print("Appending shellcode for function "+str(funcTable[f][0])+" at adress "+padBin(pointer)) + funcMapper[funcTable[f][0]] = pointer #remember where you put dat function + for l in range(len(funcTable[f][1])): + if funcTable[f][1][l] not in ["","halt","nop"]: + ret=compile(funcTable[f][1][l].split(" ")[0],funcTable[f][1][l].split(" ")[1:],pointer) + try: + if ret[0]=="Error": + print("An Error occured, when compiling function shellcode for function '"+funcTable[f][0]+"':\n"+str(e)) + else: + for r in range(len(ret)): + memory[pointer]=ret[r] #append compiled function memory + pointer+=1 + except: + t=1 + ## jump back after function execution + # LDI konst=3 + memory[pointer] = toDec("0111" + "00000011") + pointer+=1 + # ADD jumpBackVar + memory[pointer] = toDec("0010" + padBin(varRec[funcTable[f][0]+"_JUMPBACK"])) + pointer+=1 + # JMA null + memory[pointer] = toDec("1100" + "00000000") + pointer+=1 + print("FuncMapper: "+str(funcMapper)) + print("Var Assignment:") + varAss = str(varRec)[1:][:-1].split(", ") + print("#VAR-NAME# #ADDRESS#") + for va in range(len(varAss)): #print all vars with their memory-location + print(varAss[va].split("'")[1]+": "+" "*(12-len(varAss[va].split("'")[1]))+padBin(int(varAss[va].split("': ")[1]))) + #replace func-names + for m in range(len(memory)): + try: + if memory[m][:5]=="Exec_": #if there is just a function-call-dummy + print("Inserting Exec-Call-Adress at "+padBin(m,bit=12)) + memory[m]=toDec("0110"+padBin(funcMapper[memory[m][5:]])) #replace it with a jump to the function + except Exception as e: + if str(e) != "'int' object has no attribute '__getitem__'": + print "Error while replacing func-name: "+str(e)+"\n (I don't know why, sorry)" + try: + print("Removing old "+name+".asmTron") + os.remove(name+".asmTron") + except: + t=1 + print("Saving as "+name+".asmTron") + with open(name+".asmTron", 'wb') as f: + t=asm.pickle.dumps([12,memory]) + t=asm.zlib.compress(t) + f.write(t) + print("Done.") diff --git a/compiler_beta.py b/compiler_beta.py new file mode 100644 index 0000000..17788b1 --- /dev/null +++ b/compiler_beta.py @@ -0,0 +1,658 @@ +import asm + +def padBin(number,bit=8): + return asm.padBin(asm.toBin(number),bit=bit) + +def toDec(binNumber): + return asm.toDec(binNumber) + +doc = """ +0000 NOP +0001 LDA memory > A +0010 ADD A + memspace +0011 SUB A - memspace +0100 STA A > memory +0101 OUT A > OUT +0110 JMP Jump to adress +0111 LDI par > A +1000 JIF Jump if greater +1001 JIE Jump if equal +1010 LDP memory[A] > A +1011 INP IN > A +1100 JMA Jump to A +1101 --- not implemented +1110 STP memory[par] > memory[A] +1111 HLT Halt +""" + +def compile(cmd,par,memAddr): + # Every function creates unknown vars, even if it makes no sense in it case, + # because if the function sits inside a user-defined function vars may be + # defined later + #try: + if cmd=="newVar": # creates new var and allocates memory-adress for it + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + print("[i] newVar is obsolete in this version of tronScript") + elif cmd=="newArray": # creates new array and allocates memory-adress for it + print("Creating array '"+par[0].upper()+"' at memory-space "+padBin(len(varRec)+(2**8)/2)+" - "+padBin(len(varRec)+int(par[1])+(2**8)/2)) + for i in range(int(par[1])): + varRec["array_"+par[0].upper()+"["+i+"]"] = len(varRec)+(2**8)/2 + elif cmd=="jumpMark": # creates a jumpMark and saves current adress in the DB for later use by the jump-name-replacement + print("Creating jumpMark '"+par[0].upper()+"' at memory-address "+padBin(memAddr)) + jumpMark[par[0].upper()] = memAddr + elif cmd=="jump": # creates dummy jump code for later replacement + # we have to do it this way, beacause a jumpMark may be defined after the jump-call + return [ + # will be replaced after script-compilation + "Jump_"+par[0].upper() + ] + elif cmd=="getVarAddress": # stores the memory-adress of a var into another + # maybe needed, if user want to access vars with + # custom asssembly code + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + return [ + ## load the Var-Adress into A Register and save it into specified var + # LDI + toDec("0111"+padBin(varRec[par[0].upper()])), + # STA variable to store the current pointer in + toDec("0100"+padBin(varRec[par[1].upper()])), + ] + elif cmd=="getArrayAddress": # like getVarAdress, but for arrays + # arrayName Index storeVar + try: + t = varRec["array_"+par[0].upper()+"["+par[1]+"]"] + except: + print("Undefined Array") + exit() + try: + _ = int(par[1]) + except: + print("Expected array-index (integer)") + exit() + return [ + ## load the Var-Adress into A Register and save it into specified var + # LDI + toDec("0111"+padBin(varRec["array_"+par[0].upper()+"["+par[1]+"]"])), + # STA variable to store the current pointer in + toDec("0100"+padBin(varRec[par[2].upper()])), + ] + elif cmd=="exec": # execute a user defined function + try: + t = varRec[par[0].upper()] + except: + print("Creating function-jumpback-var '"+par[0].upper()+"_JUMPBACK' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()+"_JUMPBACK"] = len(varRec)+(2**8)/2 + return [ + ## remember current pointer, so you can jump back here after function execution is done + # LDI + toDec("0111"+padBin(pointer)), + # STA variable to store the current pointer in + toDec("0100"+padBin(varRec[par[0].upper()+"_JUMPBACK"])), + # will be replaced after script-compilation + "Exec_"+par[0].upper()# jumpback function-call-var + ] + elif cmd=="setVar": # gives a var a defined value + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + if par[1][0]=="b": + par[1] = toDec(par[1][1:]) + return [ + ## loads desired value into the A register and then stores it at the variables memory adress + # LDI value + toDec("0111" + padBin(int(par[1]))), + # STA var Name + toDec("0100" + padBin(varRec[par[0].upper()])) + ] + elif cmd=="copyVar": # gives a var the value of another var + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + return [ + ## load memory-space of var 1 into register A and the store it into memory-space of var 2 + # LDA var 1 + toDec("0001" + padBin(varRec[par[0].upper()])), + # STA var 2 + toDec("0100" + padBin(varRec[par[1].upper()])) + ] + elif cmd=="setArrayIndex": # defines the value of an array (par0) index (par1) to be (par2) + try: + t = varRec["array_"+par[0].upper()+"["+par[1]+"]"] + except: + print("Undefined array") + exit() + try: + _=int(par[1]) + except: + print("Expected array-index (integer)") + exit() + if par[2][0]=="b": + par[2] = toDec(par[2][1:]) + return [ + ## loads desired value into the A register and then stores it at the variables memory adress + # LDI value + toDec("0111" + padBin(int(par[2]))), + # STA var Name + toDec("0100" + padBin(varRec["array_"+par[0].upper()+"["+par[1]+"]"])) + ] + elif cmd=="getArrayIndex": # puts the value of an array (par0) index (par1) into var (par2) + try: + t = varRec["array_"+par[0].upper()+"["+par[1]+"]"] + except: + print("Undefined Array") + exit() + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + try: + _=int(par[1]) + except: + print("Expected array-index (integer)") + exit() + return [ + ## load memory-space of var 1 into register A and the store it into memory-space of var 2 + # LDA var 1 + toDec("0001" + padBin(varRec["array_"+par[0].upper()+"["+par[1]+"]"])), + # STA var 2 + toDec("0100" + padBin(varRec[par[2].upper()])) + ] + elif cmd=="write": # writes to the console + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + return [ + ## load the variable into register A, then print it + # LDA var Name + toDec("0001" + padBin(varRec[par[0].upper()])), + # OUT null + toDec("0101" + "00000000") + ] + elif cmd=="read": # reads from the console + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + return [ + ## input > register A; register A > var + # INP null + toDec("1011" + "00000000"), + # STA var Name + toDec("0100" + padBin(varRec[par[0].upper()])) + ] + elif cmd=="add": # adds to numbers and stores the answer in another + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + return [ + ## load var 1 into register A; add var 2, store in var 3 + # LDA var Name in1 + toDec("0001" + padBin(varRec[par[0].upper()])), + # ADD var Name in2 + toDec("0010" + padBin(varRec[par[1].upper()])), + # STA var Name out + toDec("0100" + padBin(varRec[par[2].upper()])) + ] + elif cmd=="subtract": # in1 - in2 = out + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + return [ + ## laod var 1 into register A; subtract var 2; store in var 3 + # LDA var Name in1 + toDec("0001" + padBin(varRec[par[0]])), + # SUB var Name in2 + toDec("0011" + padBin(varRec[par[1]])), + # STA var Name out + toDec("0100" + padBin(varRec[par[2]])) + ] + elif cmd=="if": # if clause + #cmd p0 p1 p2 p3 p4: + #if VAR ?? VAR cmd pars + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + comp1=par[0].upper() + comp2=par[2].upper() + comp=par[1] + shellcode=compile(par[3],par[4:],memAddr+4) + if not shellcode: + return ["Error","I had problems getting the internal shellcode. Sorry :("] + if shellcode[0]=="Error": + return ["Error","Internal shellcode compilation thew an Error:\n"+shellcode[1]] + ## binary code that magicaly works: + if comp=="==": + ret = [ + # LDI konst + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp1 + toDec("0001" + padBin(varRec[comp1])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp2 + toDec("0011" + padBin(varRec[comp2])), + # JIE + toDec("1001" + padBin(memAddr+7)), + # JMP + toDec("0110" + padBin(memAddr+7+len(shellcode))) + ] + elif comp=="!=": + ret = [ + # LDI konst + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp1 + toDec("0001" + padBin(varRec[comp1])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp2 + toDec("0011" + padBin(varRec[comp2])), + # JIE + toDec("1001" + padBin(memAddr+6+len(shellcode))) + ] + elif comp==">=": + ret = [ + # LDI konst + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp1 + toDec("0001" + padBin(varRec[comp1])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp2 + toDec("0011" + padBin(varRec[comp2])), + # JIF + toDec("1000" + padBin(memAddr+6+len(shellcode))) + ] + elif comp==">": + ret = [ + # LDI konst + toDec("0111" + "01111111"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp1 + toDec("0001" + padBin(varRec[comp1])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp2 + toDec("0011" + padBin(varRec[comp2])), + # JIF + toDec("1000" + padBin(memAddr+6+len(shellcode))) + ] + elif comp=="<=": + ret = [ + # LDI konst + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp2 + toDec("0001" + padBin(varRec[comp2])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp1 + toDec("0011" + padBin(varRec[comp1])), + # JIF + toDec("1000" + padBin(memAddr+6+len(shellcode))) + ] + elif comp=="<": + ret = [ + # LDI konst + toDec("0111" + "01111111"), + # STA temp + toDec("0100" + "11111111"), + # LDA comp2 + toDec("0001" + padBin(varRec[comp2])), + # ADD konst + toDec("0010" + "11111111"), + # SUB comp1 + toDec("0011" + padBin(varRec[comp1])), + # JIF + toDec("1000" + padBin(memAddr+6+len(shellcode))) + ] + for s in shellcode: + ret.append(s) + return ret + elif cmd=="for": # for loop: "for [goal] [counter] [step] [cmd] [pars]" + # == for [counter] in range(0,[goal],[step]): + # [cmd]([pars]) + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[1].upper()] + except: + print("Creating var '"+par[1].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[1].upper()] = len(varRec)+(2**8)/2 + try: + t = varRec[par[2].upper()] + except: + print("Creating var '"+par[2].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[2].upper()] = len(varRec)+(2**8)/2 + goal = par[0].upper() + clock = par[1].upper() + step = par[2].upper() + shellcode=compile(par[3],par[4:],memAddr+12) + ret = [ + # LDI konst + toDec("0111" + "00000000"), + # STA temp + toDec("0100" + padBin(varRec[clock])), + # LDI konst <-- jump back to + toDec("0111" + "10000000"), + # STA temp + toDec("0100" + "11111111"), + # LDA clock + toDec("0001" + padBin(varRec[clock])), + # ADD konst + toDec("0010" + "11111111"), + # SUB goal + toDec("0011" + padBin(varRec[goal])), + # JIE + toDec("1001" + padBin(memAddr+12+len(shellcode)+1)), + # LDA clock + toDec("0001" + padBin(varRec[goal])), + # ADD step + toDec("0010" + padBin(varRec[step])), + # STA clock + toDec("0100" + padBin(varRec[goal])) + ] + for s in shellcode: + ret.append(s) + # JMP + ret.append(toDec("0110" + padBin(memAddr+2))) + return ret + elif cmd=="asm" or cmd[0]==":": # compiles assembler to machine-code + if cmd=="asm": + opcode = par[0] + param = par[1] + else: + opcode = cmd[1:] + param = par[0] + if param[:2]=="b#": + param = toDec(param[2:]) + elif param[:2]=="d#": + param = param[2:] + elif param[:2]=="v#": + try: + t = varRec[param[2:].upper()] + except: + print("Creating var '"+param[2:].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[param[2:].upper()] = len(varRec)+(2**8)/2 + param = varRec[param[2:].upper()] + elif param in ["-","none"]: + param = toDec("00000000") + elif param in ["~","all"]: + param = toDec("11111111") + else: + return ["Error","Invalid param supplied to asm-command (no valid prefix found)"] + for a in range(len(asm.asmMap)): + if asm.asmMap[a]==opcode: + print("Found matching opcode") + return [toDec(padBin(a,bit=4)+padBin(param))] + elif cmd=="shellcode": # insertes raw shellcode into the programm + return [toDec("".join(par))] + elif cmd=="push": + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + ret = [ + ### value to temp + # LDA value + toDec("0001" + padBin(varRec[par[0]])), + # STA temp + toDec("0100" + padBin(varRec["temp"])), + + ### increment stackpointer + # LDI konst + toDec("0111" + "00000001"), # we are going to use a overflow to subtract (2's-complement) + # ADD stack_pointer + toDec("0010" + padBin(varRec["stack_pointer"])), + # STA stack_pointer + toDec("0100" + padBin(varRec["stack_pointer"])), + + ### A > write as new element + # STP temp + toDec("1110" + padBin(varRec["temp"])) + ] + return ret + elif cmd=="pop": + try: + t = varRec[par[0].upper()] + except: + print("Creating var '"+par[0].upper()+"' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[par[0].upper()] = len(varRec)+(2**8)/2 + ret = [ + ### read the last element > A + # LDI stack-base + toDec("0111" + "11111111"), + # SUB stack_pointer + toDec("0011" + padBin(varRec["stack_pointer"])), + # LDP konst + toDec("1010" + "00000000"), + # STA stack_pointer + toDec("0100" + padBin(varRec[par[0]])), + + ### decrement stackpointer + # LDI konst + toDec("0111" + "11111111"), # we are going to use a overflow to subtract (2's-complement) + # ADD stack_pointer + toDec("0010" + padBin(varRec["stack_pointer"])), + # STA stack_pointer + toDec("0100" + padBin(varRec["stack_pointer"])) + ] + return ret + elif cmd=="nop": # nothing... + return [toDec("0000" + "00000000")] + elif cmd=="halt": # halts execution of programm + return [toDec("1111" + "11111111")] + else: + return ["Error","Unimplemented Function: "+str(cmd)] + #except Exception as e: + # return ["Error","Unknown Error: "+str(e)] + +bits = 12 + +varRec = {"temp": (2**8)/2, "stack_pointer": (2**8)/2 + 1 } # to store VarName -> memory-address +jumpMark = {} # to store jumpMarkName -> jump-address + +if __name__ == "__main__": + print("[tronScript-Compiler by CyberCodeDragon]") + print("! Unstable Beta-Version with stack") + memory = [] + for i in range(2**bits): #expand memory + memory.append(0) + + pointer = 0 + funcTable = [] # [[funcName,funcCode],...] + + for f in asm.os.listdir("tronScript"): #display all found scripts + if f[-5:]==".tron": + print("> "+"tronScript/"+f) + filePath = raw_input("file to compile> ") + inFile = filePath.split("\\") + inFile = inFile[len(inFile)-1] + tmp = inFile.split(".") + ext = tmp[len(tmp)-1] + name = inFile.split("."+ext)[0] + print("[*] Reading "+inFile) + with open(filePath) as f: + code = f.read().replace(" ","") #read file and remove tabs + c = code.split("\n") #c = lines of code + #detect functions + for l in range(len(c)): #for every line of code + elems = c[l].split(" ") #elems = [cmd,pa1,par2,...,parN] + if elems[0]=="function": + funcName = elems[1] + funcCode = code.split("function "+funcName+" {")[1].split("}")[0].split("\n") #get the function Code + funcName = funcName.upper() + print("detected function '"+funcName+"' in line "+str(l)+":\n"+"\n".join(funcCode)) + for i in range(len(funcCode)+0): + c[l+i]="#function-code" #replace function with a comment -> dont mess up later parsing + funcTable.append([funcName,funcCode]) + try: #create jumpback-var if not existing (does probably not exist) + t = varRec[funcName+"_JUMPBACK"] + except: + print("Creating function-jumpback-var '"+funcName+"_JUMPBACK' at memory-address "+padBin(len(varRec)+(2**8)/2)) + varRec[funcName+"_JUMPBACK"] = len(varRec)+(2**8)/2 + + #parse code + for l in range(len(c)): #for every line in code + if c[l] not in ["","\n"]: #if lines is not empty + print("Parsing line "+str(l)+": "+c[l]) + cmd = c[l].split(" ")[0] + if not cmd[0]=="#": #dont parse comments + if cmd in ["halt","nop"]: #cmds without params + par = [] + else: + par = c[l].split(cmd+" ")[1].split(" ") + r = compile(cmd,par,pointer) #compile + if r: + if r[0]=="Error": #print error + print("Error compiling line "+str(l)+" {"+c[l]+"}: \n"+str(r[1])) + exit() + for ret in r: + veryVerbose = False + if veryVerbose: + try: + print("Compiled to: "+padBin(ret,bit=12)) + except: + print("Compiled to: "+str(ret)) + memory[pointer] = ret #write code to memory + pointer+=1 + try: + if padBin(memory[pointer-1],bit=12)[:4]!="1111": #if the last command is not a HLT command + print("Appending HLT-Command") + # HLT + memory[pointer] = toDec("1111"+"11111111") + print("HLT at "+padBin(pointer)+": "+padBin(memory[pointer],bit=12)) + pointer+=1 + except: #looks like the last command was a placeholder: not a HLT command + print("Appending HLT-Command") + # HLT + memory[pointer] = toDec("1111"+"11111111") + print("HLT at "+padBin(pointer)+": "+padBin(memory[pointer],bit=12)) + pointer+=1 + + #replace jump-names + for m in range(len(memory)): + try: + if memory[m][:5]=="Jump_": #if at memory-adress is just a jump-dummy + print("Inserting Jump-Adress at "+padBin(m,bit=12)) + memory[m]=toDec("0110"+padBin(jumpMark[memory[m][5:]])) #replace with real jump adress + except: + t=1 + #append function-shellcode + funcMapper = {} #map funcName to funcCode + for f in range(len(funcTable)): + print("Appending shellcode for function "+str(funcTable[f][0])+" at adress "+padBin(pointer)) + funcMapper[funcTable[f][0]] = pointer #remember where you put dat function + for l in range(len(funcTable[f][1])): + if funcTable[f][1][l] not in ["","halt","nop"]: + ret=compile(funcTable[f][1][l].split(" ")[0],funcTable[f][1][l].split(" ")[1:],pointer) + try: + if ret[0]=="Error": + print("An Error occured, when compiling function shellcode for function '"+funcTable[f][0]+"':\n"+str(e)) + else: + for r in range(len(ret)): + memory[pointer]=ret[r] #append compiled function memory + pointer+=1 + except: + t=1 + ## jump back after function execution + # LDI konst=3 + memory[pointer] = toDec("0111" + "00000011") + pointer+=1 + # ADD jumpBackVar + memory[pointer] = toDec("0010" + padBin(varRec[funcTable[f][0]+"_JUMPBACK"])) + pointer+=1 + # JMA null + memory[pointer] = toDec("1100" + "00000000") + pointer+=1 + print("FuncMapper: "+str(funcMapper)) + print("Var Assignment:") + varAss = str(varRec)[1:][:-1].split(", ") + print("#VAR-NAME# #ADDRESS#") + for va in range(len(varAss)): #print all vars with their memory-location + print(varAss[va].split("'")[1]+": "+" "*(12-len(varAss[va].split("'")[1]))+padBin(int(varAss[va].split("': ")[1]))) + #replace func-names + for m in range(len(memory)): + try: + if memory[m][:5]=="Exec_": #if there is just a function-call-dummy + print("Inserting Exec-Call-Adress at "+padBin(m,bit=12)) + memory[m]=toDec("0110"+padBin(funcMapper[memory[m][5:]])) #replace it with a jump to the function + except Exception as e: + if str(e) != "'int' object has no attribute '__getitem__'": + print "Error while replacing func-name: "+str(e)+"\n (I don't know why, sorry)" + try: + print("Removing old "+name+".asmTron") + os.remove(name+".asmTron") + except: + t=1 + print("Saving as "+name+".asmTron") + with open(name+".asmTron", 'wb') as f: + t=asm.pickle.dumps([12,memory]) + t=asm.zlib.compress(t) + f.write(t) + print("Done.") diff --git a/deCompiler.py b/deCompiler.py new file mode 100644 index 0000000..8904164 --- /dev/null +++ b/deCompiler.py @@ -0,0 +1,214 @@ +import asm + +import os +import pickle +import zlib +from base64 import * + +asmMap = ["NOP","LDA","ADD","SUB","STA","OUT","JMP","LDI","JIF","JIE","---","INP","JMA","HLO","HST","HLT"] + +bits = 12 + +pointer = 0 + +note=""" +newVar [var] + +jumpMark [jumpMark name] +jump [jumpMark name] +getVarAddress [var A] [var B] +getArrayAddress [array] [index] [var] +exec [func name] +setVar [var] [value] OK +setVar [var] b[value] OK +setArrayIndex [array] [index] [value] +setArrayIndex [array] [index] b[value] +getArrayIndex [array] [index] [var] +copyVar [var A] [var B] +write [var] OK +read [var] OK +add [var A] [var B] [var OUT] OK +subtract [var A] [var B] [var OUT] OK +if [var A] [??] [var B] [cmd] [pars] + +for [goal] [counter] [step] [cmd] [pars] + +:[asm] v#[var] +:[asm] d#[par] +:[asm] b#[par] +:[asm] - +:[asm] ~ +shellcode [code] +nop OK +halt OK + +user defined funtions +""" + +def padBin(number,bit=8): + return asm.padBin(asm.toBin(number),bit=bit) + +def toDec(binNumber): + return asm.toDec(binNumber) + +def load(): + print("[*] Avaible saves:") + for f in os.listdir("."): + if f[-8:]==".asmTron": + print("> "+f[:-8]) + for f in os.listdir("tronScript"): + if f[-8:]==".asmTron": + print("> tronScript/"+f[:-8]) + name = raw_input("name> ") + + try: + with open(name+".asmTron", "rb") as f: + t = f.read() + t=zlib.decompress(t) + magicBit,memory = pickle.loads(t) + except Exception as e: + try: + with open("tronScripts/"+name+".asmTron", "rb") as f: + t = f.read() + t=zlib.decompress(t) + magicBit,memory = pickle.loads(t) + except Exception as e: + if b64encode(str(e))[:25]=="W0Vycm5vIDJdIE5vIHN1Y2ggZ": + print(" [!] Error: File '"+name+".asmTron' does not exist") + else: + print(" [!] Error: Unknown Error while reading File '"+name+"' with Errorcode: "+str(b64encode(str(e)))) + if not magicBit==12: + print("[!] Error: Invalid Magical Bit: "+str(magicBit)) + exit() + lenMem = len(memory) + for i in range(lenMem): #remove end-zeros + if memory[lenMem-i-1]!=0: + endPoint = lenMem-i + break + print("[*] loaded "+name+".asmTron") + return memory[:endPoint] + +def main(): + pointer = 0 + memory = load() + lenMem = len(memory) + deco = [] + for i in range(lenMem): #expand deco + deco.append("") + while True: + t = padBin(memory[pointer],bit=12) + cmd = t[:4] + par = t[4:] + #print("["+str(pointer).zfill(3)+"]> "+cmd+" "+par) + if cmd=="0000": #NOP + pointer+=1 + elif cmd=="0001": #LDA + if padBin(memory[pointer+1],bit=12)[:4]=="0100": #STA + # LDI STA -> setVar + deco[pointer]="copyVar VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65)+" VAR_"+chr(toDec(padBin(memory[pointer+1])[4:])+65) + pointer+=2 + elif padBin(memory[pointer+1],bit=12)[:4]=="0101": #OUT + # LDI OUT -> write + deco[pointer]="write VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=2 + elif padBin(memory[pointer+1],bit=12)[:4]=="0010": #ADD + if padBin(memory[pointer+2],bit=12)[:4]=="0100": #STA + # LDI ADD STA -> add + deco[pointer]="add VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65)+" VAR_"+chr(toDec(padBin(memory[pointer+1])[4:])+65)+" VAR_"+chr(toDec(padBin(memory[pointer+2])[4:])+65) + pointer+=3 + else: + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif padBin(memory[pointer+1],bit=12)[:4]=="0011": #SUB + if padBin(memory[pointer+2],bit=12)[:4]=="0100": #STA + # LDI SUB STA -> subtract + deco[pointer]="subtract VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65)+" VAR_"+chr(toDec(padBin(memory[pointer+1])[4:])+65)+" VAR_"+chr(toDec(padBin(memory[pointer+2])[4:])+65) + pointer+=3 + else: + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + else: + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="0010": #ADD + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="0011": #SUB + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="0100": #STA + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="0101": #OUT + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="0110": #JMP + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="0111": #LDI + if padBin(memory[pointer+1],bit=12)[:4]=="0100": #STA + if padBin(memory[pointer+2],bit=12)[:4]=="0001": #LDA + if padBin(memory[pointer+3],bit=12)[:4]=="0010": #ADD + if padBin(memory[pointer+4],bit=12)[:4]=="0011": #SUB + if padBin(memory[pointer+5],bit=12)[:4]=="1001": #JIE + if padBin(memory[pointer+6],bit=12)[:4]=="0110": #JMP + # LDI STA LDA ADD SUB JIE JIF -> if == + deco[pointer]="if VAR_"+chr(toDec(padBin(memory[pointer+2])[4:])+65)+" == VAR_"+chr(toDec(padBin(memory[pointer+4])[4:])+65)+" jump "+str(toDec(padBin(memory[pointer+6])[4:])) + pointer+=6 + else: + # LDI STA LDA ADD SUB JIE -> if != + deco[pointer]="if VAR_"+chr(toDec(padBin(memory[pointer+2])[4:])+65)+" != VAR_"+chr(toDec(padBin(memory[pointer+4])[4:])+65)+" jump "+str(toDec(padBin(memory[pointer+5])[4:])) + pointer+=5 + else: + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + else: + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + else: + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + else: + # LDI STA -> setVar + deco[pointer]="setVar VAR_"+chr(toDec(padBin(memory[pointer+1])[4:])+65)+" "+str(toDec(par)) + pointer+=2 + else: + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" d#"+toDec(padBin(memory[pointer])[4:]) + pointer+=1 + elif cmd=="1000": #JIF + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="1001": #JIE + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="1010": #--- + deco[pointer]="#" + pointer+=1 + elif cmd=="1011": #INP + if padBin(memory[pointer+1],bit=12)[:4]=="0100": #STA + # INP STA -> read + deco[pointer]="read VAR_"+chr(toDec(padBin(memory[pointer+1])[4:])+65) + pointer+=2 + else: + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="1100": #JMA + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="1101": #HLO + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="1110": #HST + deco[pointer]=":"+asmMap[toDec(padBin(memory[pointer],bit=12)[:4])]+" v#VAR_"+chr(toDec(padBin(memory[pointer])[4:])+65) + pointer+=1 + elif cmd=="1111": #HLT + deco[pointer]="halt" + pointer+=1 + if pointer>=lenMem: + break + for d in range(len(deco)): + #if deco[d]!="": + print("["+str(d).zfill(3)+"]> "+deco[d]) + +if __name__=="__main__": + main() diff --git a/mima.py b/mima.py new file mode 100644 index 0000000..d76d1a9 --- /dev/null +++ b/mima.py @@ -0,0 +1,544 @@ +import os +import sys +import pickle +import zlib +import hashlib +import copy +from termcolor import colored +from base64 import * +from colorama import init +init() + +OS = "Linux" +#OS = "Windows" + +doc = """ +0000 NOP +0001 LDC par > A (max 20bit) +0010 LDV [par] > A +0011 STV A > [par] +0100 ADD A + [par] > A +0101 AND A AND [par] > A +0110 LOR A OR [par] > A +0111 XOR A XOR [par] > A +1000 EQL if A==[par]: -1 else 0 > A +1001 JMP Jump to [par] +1010 JMN if A<0: Jump to [par] +1011 NOT NOT A > A +1100 RAR A >> 1 > A +1101 LDI [[par]] > A +1110 STI A > [[par]] +1111 HLT Halt +""" + +asmMap = ["NOP","LDC","LDV","STV","ADD","AND","LOR","XOR","EQL","JMP","JMN","NOT","RAR","LDI","STI","HLT"] + +bits = 24 +opBits = 4 +parBits = 20 + +pointer = 0 + +registerA = 0 +out = 0 + +color = [["green","on_grey"],["blue","on_grey"],["red","on_grey"],["magenta","on_grey"],["cyan","on_grey"], + ["grey","on_white"],["green","on_white"],["blue","on_white"],["red","on_white"],["magenta","on_white"],["cyan","on_white"], + ["grey","on_green"],["white","on_green"],["blue","on_green"],["red","on_green"],["magenta","on_green"],["cyan","on_green"], + ["grey","on_blue"],["white","on_blue"],["green","on_blue"],["red","on_blue"],["magenta","on_blue"],["cyan","on_blue"], + ["grey","on_red"],["white","on_red"],["green","on_red"],["blue","on_red"],["magenta","on_red"],["cyan","on_red"], + ["grey","on_magenta"],["white","on_magenta"],["green","on_magenta"],["blue","on_magenta"],["red","on_magenta"],["cyan","on_magenta"], + ["grey","on_cyan"],["white","on_cyan"],["green","on_cyan"],["blue","on_cyan"],["red","on_cyan"],["magenta","on_cyan"]] + +memory = [] + +for i in range(2**parBits): + memory.append(0) + +def clear(): + if OS=="Windows": + os.system("cls") + elif OS=="Linux": + os.system("clear") + else: + print("Error: Unknown OS") + exit() + +def toDec(binary): + try: + return int(binary, 2) + except: + return -1 + +def toBin(decimal): + try: + return int(bin(decimal)[2:]) + except: + print("Error: The dec-number "+decimal+" could not be converted to binary") + return decimal + +def padBin(binary,bit=bits): + return str(binary).zfill(bit)[-bit:] + +def bin_input(display,bit=bits,allowAsm=False): + raw = input(display) + if raw=="x": + return -1 + if allowAsm: + for i in range(len(asmMap)): + if raw.find(asmMap[i])!=-1: + raw = raw.replace(asmMap[i],"") + raw = raw.replace(" ","") + if raw.find("_")!=-1: + raw = raw.replace("_","0"*(bit-(len(raw)-1)-4)) + raw = str(toBin(i)).zfill(opBits)+raw.zfill(bits-opBits) + break + else: + raw = raw.replace(" ","") + if raw.find("_")!=-1: + raw = raw.replace("_","0"*(bit-(len(raw)-1))) + else: + raw = raw.replace(" ","") + if raw.find("_")!=-1: + raw = raw.replace("_","0"*(bit-(len(raw)-1))) + if raw.find("_")!=-1: + print("[!] input contains multiple spread-zero characters ( _ )") + return bin_input(display) + ret = toDec(raw) + if ret>2**bits: + print("[!] input exceted maximal size for "+str(bit)+"-bit integer!") + return bin_input(display,allowAsm=allowAsm) + if ret==-1: + print("[!] "+raw+" is not a valid binary number!") + return bin_input(display,allowAsm=allowAsm) + return ret + +def parse(cmd,par,verbose=False,adress=0): + global registerA + global memory + global out + global pointer + v=verbose + cmd = cmd[-1*opBits:] + if cmd=="0000": #nop + if v: print(padBin(toBin(adress),bit=parBits)+": NOP") + elif cmd=="0001": #ldc + registerA = par + if v: print(padBin(toBin(adress),bit=parBits)+": LDC "+padBin(toBin(par),bit=parBits)+" > Akku") + elif cmd=="0010": #ldv + registerA = memory[par] + if v: print(padBin(toBin(adress),bit=parBits)+": LDV ["+padBin(toBin(par),bit=parBits)+"] > Akku") + elif cmd=="0011": #stv + memory[par] = registerA + if v: print(padBin(toBin(adress),bit=parBits)+": STA Akku > ["+padBin(toBin(par),bit=parBits)+"]") + elif cmd=="0100": #add + registerA = (registerA + memory[par]) % 2**parBits + if v: print(padBin(toBin(adress),bit=parBits)+": ADD Akku + ["+padBin(toBin(par),bit=parBits)+"]") + elif cmd=="0101": #and + newRegA = "" + for b in range(len(padBin(toBin(registerA)))): + if padBin(toBin(int(registerA)))[b]=="1" and padBin(toBin(int(memory[par])))[b]=="1": + newRegA+="1" + else: + newRegA+="0" + registerA = toDec(newRegA) + if v: print(padBin(toBin(adress),bit=parBits)+": AND Akku, ["+padBin(toBin(par),bit=parBits)+"]") + elif cmd=="0110": #lor + newRegA = "" + for b in range(len(str(registerA))): + newRegA+=str(int( int(padBin(toBin(int(registerA)))[b]) or int(padBin(toBin(int(memory[par])))[b]) )) + registerA = toDec(newRegA) + if v: print(padBin(toBin(adress),bit=parBits)+": OR Akku, ["+padBin(toBin(par),bit=parBits)+"]") + elif cmd=="0111": #XOR + newRegA = "" + for b in range(len(padBin(toBin(registerA)))): + if padBin(toBin(registerA))[b] == padBin(toBin(memory[par]))[b]: + newRegA+="0" + else: + newRegA+="1" + registerA = toDec(newRegA) + if v: print(padBin(toBin(adress),bit=parBits)+": XOR Akku, ["+padBin(toBin(par),bit=parBits)+"]") + elif cmd=="1000": #EQL + if registerA==memory[par]: + registerA = toDec("1"*bits) + if v: print(padBin(toBin(adress),bit=8)+": EQL {TRUE} Akku ?= "+padBin(toBin(par),bit=parBits)) + else: + registerA = 0 + if v: print(padBin(toBin(adress),bit=8)+": EQL {FALSE} Akku ?= "+padBin(toBin(par),bit=parBits)) + elif cmd=="1001": #jmp + pointer = par - 1 + if v: print(padBin(toBin(adress),bit=8)+": JMP "+padBin(toBin(par),bit=parBits)) + elif cmd=="1010": #jmn + if registerA>=int("1"+"0"*(bits-1)): + pointer = par - 1 + if v: print(padBin(toBin(adress),bit=8)+": JMN {TRUE} > "+padBin(toBin(par),bit=8)) + else: + if v: print(padBin(toBin(adress),bit=8)+": JMN {FALSE} > "+padBin(toBin(par),bit=8)) + elif cmd=="1011": #not + newRegA = "" + for b in range(len(padBin(toBin(registerA)))): + if padBin(toBin(registerA))[b]=="1": + newRegA+="0" + elif padBin(toBin(registerA))[b]=="0": + newRegA+="1" + else: + print("FUUUUUUUUUU") + exit() + registerA = toDec(newRegA) + if v: print(padBin(toBin(adress),bit=parBits)+": NOT Akku > Akku") + elif cmd=="1100": #rar + newRegA = padBin(toBin(registerA)) + newRegA = newRegA[-1]+newRegA[:-1] + registerA = toDec(newRegA) + if v: print(padBin(toBin(adress),bit=parBits)+": RAR Akku > Akku") + elif cmd=="1101": #LDI + mid = memory[par] + registerA = memory[mid % parBits] + if v: print(padBin(toBin(adress),bit=parBits)+": LDI [["+padBin(toBin(par),bit=parBits)+"]] > Akku") + elif cmd=="1110": #STI + mid = memory[par] + memory[mid] = registerA + if v: print(padBin(toBin(adress),bit=parBits)+": STI Akku > [["+padBin(toBin(par),bit=parBits)+"]]") + elif cmd=="1111": #hlt + return -1 + return True + +if __name__=="__main__": + print("[asmTron by CyberCodeDragon]") + while True: + x = "" + x=input("#> ") + x = x.split(" ") + for i in range(2): + x.append("") + y = x[1] + z = x[2] + x = x[0] + if x=="help" or x=="h": + print("Avaible Commands:") + print("docs - display avaible operants") + print("write [w] - write value to adress") + print("read [r] - read value from adress") + print("dump [d] - dump from adress with length") + print("run [u] - execute programm") + print("edit [e] - edit from adress til >x<") + print("cls - clear screen") + print("clear / reset - clear memory,register,pointer") + print("step [s] - run one command from programm") + print("debug - execute programm with verbose output") + print("pointer - display pointer") + print("setPointer - sets pointer") + print("resetPointer [rp] - sets pointer to zero") + print("register [reg] - displays A register") + print("setRegister - sets A register") + print("save - saves memory to local file") + print("load - loads memory from local file") + print("code / exec - execute one line of shellcode") + print("guiDebug [gd] - graphical debugger ") + print("asm - shellcode visualizer (assembly / jump-arrows) ") + print("halting - tries to determin, if algorythm will diverge") + elif x=="docs": + print(doc) + elif x=="write" or x=="w": + if y=="" or z=="": + y=bin_input("adress> ") + z=bin_input("value> ") + try: + memory[y] = z + except: + print("[!] Unknown error while writing") + elif x=="read" or x=="r": + if y=="": + y=bin_input("adress> ") + print(padBin(toBin(memory[y]))) + elif x=="dump" or x=="d": + if y=="" and z=="": + y=bin_input("adress> ") + z=bin_input("length> ") + elif z=="": + z=toDec(y) + y=0 + for m in range(z): + print(padBin(toBin(y+m),bit=parBits)+": "+padBin(toBin(memory[y+m]))) + elif x=="run" or x=="u": + while True: + cmd = padBin(toBin(memory[pointer]))[:opBits] + par = int(toDec(padBin(toBin(memory[pointer]))[-parBits:])) + if parse(cmd,par)==-1: + pointer = 0 + break + pointer = (pointer + 1) % 2**parBits + elif x=="verboseRun" or x=="vu": + while True: + cmd = padBin(toBin(memory[pointer]))[:opBits] + par = int(toDec(padBin(toBin(memory[pointer]))[-parBits:])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = 0 + break + pointer = (pointer + 1) % 2**parBits + elif x=="edit" or x=="e": + adress=bin_input("offset> ",bit=parBits) + while True: + value=bin_input(padBin(toBin(adress),bit=parBits)+": "+padBin(toBin(memory[adress]))+" > ",allowAsm=True) + if value==-1: + break + try: + memory[adress] = value + except: + print("[!] Unknown error while writing") + if adress==len(memory)-1: + adress = -1 + print("[*] End of mem") + adress = adress + 1 + elif x=="cls": + clear() + elif x=="clear" or x=="reset": + pointer = 0 + registerA = 0 + out = 0 + memory = [] + for i in range(2**parBits): + memory.append(0) + elif x=="varClear" or x=="vc": + pointer = 0 + registerA = 0 + out = 0 + for i in range((2**parBits)/2): + memory[(2**parBits)/2+i] = 0 + elif x=="step" or x=="s": + cmd = padBin(toBin(memory[pointer]))[:opBits] + par = int(toDec(padBin(toBin(memory[pointer]))[-parBits:])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = 0 + print("[*] Programm halted") + pointer = (pointer + 1) % (2**parBits) + elif x=="debug": + while True: + cmd = padBin(toBin(memory[pointer]))[:opBits] + par = int(toDec(padBin(toBin(memory[pointer]))[-parBits:])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = -1 + print("[*] Programm halted") + break + pointer = (pointer + 1) % (2**parBits) + elif x=="pointer": + print("POINTER: "+padBin(toBin(pointer),bit=parBits)) + elif x=="setPointer": + if y=="": + pointer = bin_input("pointer> ",bit=parBits) + else: + pointer = y + elif x=="resetPointer" or x=="rp": + pointer = 0 + elif x=="register" or x=="reg": + print("REGISTER: "+padBin(toBin(registerA))) + elif x=="setRegister": + if y=="": + registerA = bin_input("register> ") + else: + registerA = y + elif x=="save": + if y=="": + print("[*] Current saves:") + for f in os.listdir("saves"): + if f[-8:]==".asmTron": + print("> "+f[:-8]) + name = input("name> ") + else: + name = y + with open("saves/"+name+".asmTron", 'wb') as f: + t=pickle.dumps(["mima24_1",memory]) + t=zlib.compress(t) + f.write(t) + elif x=="load" or x=="l": + if y=="": + print("[*] Avaible saves:") + for f in os.listdir("saves"): + if f[-8:]==".asmTron": + print("> "+f[:-8]) + for f in os.listdir("tronScript"): + if f[-8:]==".asmTron": + print("> tronScript/"+f[:-8]) + name = input("name> ") + else: + name = y + try: + with open("saves/"+name+".asmTron", "rb") as f: + t = f.read() + t=zlib.decompress(t) + magicBit,memory = pickle.loads(t) + except Exception as e: + try: + with open("tronScripts/"+name+".asmTron", "rb") as f: + t = f.read() + t=zlib.decompress(t) + magicBit,memory = pickle.loads(t) + except Exception as e: + if b64encode(str(e))[:25]=="W0Vycm5vIDJdIE5vIHN1Y2ggZ": + print(" [!] Error: File '"+name+".asmTron' does not exist") + else: + print(" [!] Error: Unknown Error while reading File '"+name+"' with Errorcode: "+str(b64encode(str(e)))) + if not magicBit=="mima24_1": + print("[!] Error: Invalid Magical Bit: "+str(magicBit)) + exit() + print("[*] loaded "+name+".asmTron") + elif x=="code" or x=="exec": + if y=="": + data=bin_input("code> ",allowAsm=True) + else: + data=y + cmd = padBin(toBin(memory[pointer]))[:opBits] + par = int(toDec(padBin(toBin(memory[pointer]))[-parBits:])) + parse(cmd,par,verbose=True,adress=0) + elif x=="guiDebug" or x=="gd": + if y=="": + hiOffset = 2**(parBits-1) + else: + hiOffset = 2**(int(y)-1) + runtime = 0 + tracker = input("trackers> ").split(",") + running = True + lastPointer = 0 + while running: + clear() + print(" +"+"-"*58+"+"+"-"*52+"+"+"-"*36+"+") + print(" |"+" "*20+" - Instructions - "+" "*20+"|"+" "*20+" - Hi-mem - "+" "*20+"|"+" "*36+"|") + if pointer <= 20: + starter = 0 + else: + starter = pointer - 20 + for i in range(36): + m = i + starter + if pointer == m: + outI = "> "+padBin(toBin(m),bit=parBits)+": "+padBin(toBin(memory[m]))+" ["+doc.split("\n")[toDec(padBin(toBin(memory[m]))[:opBits])+1][:parBits][5:][:3]+"]"+" <" + elif lastPointer == m and pointer-1 != lastPointer: + outI = "- "+padBin(toBin(m),bit=parBits)+": "+padBin(toBin(memory[m]))+" ["+doc.split("\n")[toDec(padBin(toBin(memory[m]))[:opBits])+1][:parBits][5:][:3]+"]"+" -" + else: + outI = " "+padBin(toBin(m),bit=parBits)+": "+padBin(toBin(memory[m]))+" ["+doc.split("\n")[toDec(padBin(toBin(memory[m]))[:opBits])+1][:parBits][5:][:3]+"]"+" " + outII = " "+padBin(toBin(hiOffset+i),bit=parBits)+": "+padBin(toBin(memory[hiOffset+i]))+" " + if i==1: + outIII = " - Akku - " + elif i==2: + outIII = " "*8+padBin(toBin(registerA),bit=parBits)+" "*8 + elif i==4: + outIII = " - Runtime - " + elif i==5: + outIII = " "+padBin(toBin(runtime),bit=bits)+" " + elif i==7: + outIII = " - Command - " + elif i==8: + temp=doc.split("\n")[toDec(padBin(toBin(memory[pointer]))[:opBits])+1][5:] + outIII = int((36-len(temp)-1)/2)*" "+" "+temp+int((36-len(temp))/2)*" " + elif i==10: + outIII = " - Parameter - " + elif i==11: + outIII = " "+padBin(toBin(memory[pointer]))[-parBits:]+" " + elif i==13: + outIII = " - Pointer - " + elif i==14: + outIII = " "+padBin(toBin(pointer))+" " + elif i==16: + if len(tracker[0]): + outIII = " - Trackers - " + else: + outIII = " "*36 + elif i>16 and i<=16+len(tracker): + if len(tracker[0]): + outIII = " "+str(tracker[i-16-1]) + ": " + padBin(toBin(memory[toDec(tracker[i-16-1])]))+" " + else: + outIII = " "*36 + else: + outIII = " "*36 + print(" | "+outI+" | "+outII+" |"+outIII+"|") + print(" |"+" "*58+"|"+" "*52+"|"+" "*36+"|") + print(" +"+"-"*58+"+"+"-"*52+"+"+"-"*36+"+") + + lastPointer = pointer + + cmd = padBin(toBin(memory[pointer]))[:4] + par = int(toDec(padBin(toBin(memory[pointer]))[-8:])) + if parse(cmd,par,verbose=True,adress=pointer)==-1: + pointer = 0 + break + pointer = (pointer + 1) % 2**bits + + step=input(" ") + if step=="x": + break + + runtime = runtime + 1 + elif x=="asm": + end = 0 + for m in range(len(memory)): + if padBin(toBin(memory[len(memory)-m-1]))[:opBits] != "0"*opBits: + end = len(memory)-m + break + toPrint = [] + for m in range(end): + cmd = doc.split("\n")[toDec(padBin(toBin(memory[m]))[:opBits])+1][:parBits][5:] + if toDec(padBin(toBin(memory[m]))[opBits:]) >= toDec("1"+"0"*(parBits-1)) and toDec(padBin(toBin(memory[m]))[opBits:]) <= toDec("1"+"0"*(parBits-7)+"101000"): + toPrint.append(padBin(toBin(m),bit=parBits)+": "+cmd+" "+colored(padBin(toBin(memory[m]))[opBits:],color[(toDec(padBin(toBin(memory[m]))[opBits:])-toDec("1"+"0"*(parBits-1)))][0],color[(toDec(padBin(toBin(memory[m]))[opBits:])-toDec("1"+"0"*(parBits-1)))][1])) + else: + toPrint.append(padBin(toBin(m),bit=parBits)+": "+cmd+" "+padBin(toBin(memory[m]))[opBits:]) + origPrint = copy.copy(toPrint) + for l in range(len(toPrint)): + cmd = origPrint[l][10:][:3] + par = origPrint[l][14:] + if cmd == "JMP" or cmd == "JMN": + toPrint[toDec(par)] = toPrint[toDec(par)] + " <-+" + if cmd=="JMP": + toPrint[l] = toPrint[l] + " --+" + else: + toPrint[l] = toPrint[l] + " --?" + if l < toDec(par): + for i in range(len(toPrint)): + if l < i < toDec(par): + toPrint[i] = toPrint[i] + " |" + elif i==toDec(par) or i==l: + t=1 + else: + toPrint[i] = toPrint[i] + " " + else: + for i in range(len(toPrint)): + if toDec(par) < i < l: + toPrint[i] = toPrint[i] + " |" + elif i==toDec(par) or i==l: + t=1 + else: + toPrint[i] = toPrint[i] + " " + for p in range(len(toPrint)): + print(toPrint[p]) + elif x=="halting": + print("[i] Will try to give you information about the divergity of your algorythm") + print("[i] This algorythm may itself not diverge!") + bPointer = pointer + bRegisterA = registerA + bMemory = memory + runtime = 0 + stateHashes = [] + print("[*] Simulating...") + while True: + runtime+=1 + cmd = padBin(toBin(memory[pointer]))[:opBits] + par = int(toDec(padBin(toBin(memory[pointer]))[-parBits:])) + if parse(cmd,par)==-1: + pointer = 0 + halts = True + print("[*] Algorythm will diverge after "+str(runtime)+" steps") + break + pointer = (pointer + 1) % 2**parBits + stateHash = hashlib.sha256(str(pointer)+str(registerA)+str(memory)).digest() + if stateHash in stateHashes: + print("[*] Algorythm will not diverge: State-Collision after "+str(runtime)+" steps") + break + else: + stateHashes.append(stateHash) + pointer = bPointer + registerA = bRegisterA + memory = bMemory + elif x=="exit": + exit() + elif x=="": + _=0 + else: + print("[!] Error") diff --git a/multiply_test.txt b/multiply_test.txt new file mode 100644 index 0000000..425a11b --- /dev/null +++ b/multiply_test.txt @@ -0,0 +1,80 @@ +Multiplier V.1: + +Inputs: + +INP +STA 10000000 #Input 1 +INP +STA 10000001 #Input 2 + +Counter-Setup: 00000100 + +LDI 01111111 #konst +SUB 10000001 #Input 2 +STA 10000010 #Round-Pointer + +Add: 00001000 + +LDA 10000011 #Out +ADD 10000000 #Input 1 +STA 10000011 + +Count: 00001100 + +LDI 00000001 +ADD 10000010 +STA 10000010 + +Jump back: 00010001 + +LDA 10000010 +JIF to Add + +Outputs: 00010011 + +LDA 10000011 +OUT +HLT + + +########## + +Multiplier V.2: + +Inputs: + +INP +STA 10000000 #Input 1 +INP +STA 10000001 #Input 2 + +Counter-Setup: 00000100 + +LDI 10000000 #konst +ADD 10000001 #Input 2 +STA 10000010 #Round-Pointer + +Add: 00001000 + +LDA 10000011 #Out +ADD 10000000 #Input 1 +STA 10000011 + +Count: 00001100 + +LDI 00000001 +STA 10000100 #temp1 +LDA 10000010 #Round-Pointer +SUB 10000100 #temp1 +STA 10000010 #Round-Pointer + +Jump back: 00010001 + +LDA 10000010 +JIF to Add + +Outputs: 00010011 + +LDA 10000011 +OUT +HLT \ No newline at end of file diff --git a/pow_test.txt b/pow_test.txt new file mode 100644 index 0000000..d31f95a --- /dev/null +++ b/pow_test.txt @@ -0,0 +1,57 @@ +0000 NOP +0001 LDA memory > A +0010 ADD A + memspace +0011 SUB A - memspace +0100 STA A > memory +0101 OUT A > OUT +0110 JMP Jump to adress +0111 LDI par > A +1000 JIF Jump if (JC) +1001 HLO H-mem[memspace] > A +1010 HST A > H-mem[memspace] +1011 INP IN > A +1100 JMA Jump to A +1101 JRF Jump forward by par +1110 JRB Jump bachward by par +1111 HLT Halt + +##################### + +Start - Inputs #00011000 + +INP +STA 10001000 # Base +STA 10001011 # MultiplyRet +INP +STA 10001001 # Pow + +Pow Counter #00011101 + +LDI 01111111 +ADD 10001001 +STA 10001010 # Pow counter + +Call Multiply #00100001 + +LDA 10001000 +STA 10000000 # Multiply Inp 1 +LDA 10001011 +STA 10000001 # Mutliply Inp 2 +JMP 00000001 + +Loop # 00100111 + +STA 10001011 + +LDA 10001010 +SUB NopAtEnd # Pow Counter +STA 10001010 +JIF to Call Mutliply + +Out + +LDA 10001011 +OUT +HLT 11111111 + +NOP 00000001 \ No newline at end of file diff --git a/saves/bug_find.asmTron b/saves/bug_find.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..763b6230a789eb3e5be1b6cb2596b1f14b762f00 GIT binary patch literal 4317 zcmb=J^Y-dSPv=C2){F7EOqnvuQ&(6td_B!%=BOJK!E%P}WLn=7wo}X}nKYT^w_m>V zsqFs4w9WFXryrF_{=TugzNV`7MtttK>#H*j^NyEDd{2%#_u69p;R?CS=lAqI{=DVh zziSfl%fH%Q`+qoT@17s*3>KHmN?)=w9QY|B%fK~?N5fz=4UDFN(KIlc21e7sXc`zz m1EXnRG!2ZVfzdQDng&MGz-SsEFAeON^Y+_2@kifhiU0siNjMV# literal 0 HcmV?d00001 diff --git a/saves/color.asmTron b/saves/color.asmTron new file mode 100644 index 0000000..73da5c3 --- /dev/null +++ b/saves/color.asmTron @@ -0,0 +1 @@ +x˹@QHT !BPoIYg^g,m_~cl6K{mmmmm&m&m&m&m&mmmmmm6m6m6m69ϐ$I$I$I$I$I$I$I$]/Y~ \ No newline at end of file diff --git a/saves/gbi_test.asmTron b/saves/gbi_test.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..678198bd09f4fb5f587dfc67499072129ef462bb GIT binary patch literal 4316 zcmb=J^Y*Htm$RdY!^O@_o!DdRU5>Iw99LWFE6^<>#`vG_5noJ~cR}VSQ|k>JaeVA; z-`g~o?LPiBPww*NrxK4pR8{QUUB7Q``0k%cw|WXq&5jouo4r51@mH+8U%CBjiTS5@ z#V%W)T4ik;*WdqWKKn43}ALpJO=6(eLLDwar literal 0 HcmV?d00001 diff --git a/saves/multiply.asmTron b/saves/multiply.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..827c31f3d77f9ea29ccacb9764a5ca053c0f879f GIT binary patch literal 129 zcmb=J^Y+Yc-opkwtOw#I@8ELzxmwVsty=uv{;pJY4*><~n8HOr95&tVpL0zk^Yu67 zOHtEiT-xT=lm6xE*YuNbqZiLhm3nlpJ^Y^jXVK@@a`zt>zkQ#wtL;{F@xQydg(t6{ ac^)xksj2h2_t^}n;6VKC$DEyO0~i3oy*@+$ literal 0 HcmV?d00001 diff --git a/saves/pow.asmTron b/saves/pow.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..cf5ed36ef2073a12889127e0c00c91a73afe7cc0 GIT binary patch literal 178 zcmb=J^Y;91!Da)VhKKV!R}@X^iB~pYvt|7q?r7Ghe^a5n{-dIfw^gOBeq`C!rxEA9 z-|wH1Vp+C)=PdT#X#R`NSF75$yxjBYQ9zORX`R}%mU*6QPwWqUvieVRCltjuI}b9GX<;Fwk!Rgbs~TL@@5-TJC9&V zWv8omUKQt`{;0ijbNZUJziK@nA4_hO4YJ=7)0L`o>$%(KrK_e{DtTPJDX}U%KWV=iX7{=oJ8`AW)G2 literal 0 HcmV?d00001 diff --git a/test.asmTron b/test.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..f8611c775e1ad2aba7325999fb760e60b287aba0 GIT binary patch literal 140 zcmb=J^Y*NvP_u#v%Y}QBBT^YypK!<>zIW(%IHzK#{F@K_5>f8I%0xs8z n-xof8?cKurIiAU8f9Cct-&g(h9ybFjII#cmN0#qLL(c*Letkr6 literal 0 HcmV?d00001 diff --git a/tronScript/assemblyTest.asmTron b/tronScript/assemblyTest.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..5bc6fe080f65417b9913bf2b0f99b81580c891e9 GIT binary patch literal 87 zcmb=J^Y+9>-UbB`*NgK!*YM2mxF{&mJg@1m_QnF%)xmS_?AhKsGq`)wFSE2IVe2e{ h^94&|?_2f%se4*g{ABmK6b4lAK)<%0VY8@51pxnjBh>%^ literal 0 HcmV?d00001 diff --git a/tronScript/assemblyTest.tron b/tronScript/assemblyTest.tron new file mode 100644 index 0000000..1de3526 --- /dev/null +++ b/tronScript/assemblyTest.tron @@ -0,0 +1,6 @@ +:INP b#00000000 +:STA v#A +:INP b#00000000 +:ADD v#A +:OUT - +:HLT ~ diff --git a/tronScript/forTest.asmTron b/tronScript/forTest.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..553c447809a87fc4147aa9e48ffb5f8c1a70c394 GIT binary patch literal 131 zcmb=J^Y*N@ShIov>xFw$mz;X2y@6$VV*bN_t2@LzXa5r`e`YhI@p@rfYIo+%_~Vk( zb-(V=`z@Bdx34Z}-rC+jOFk|6vc&4PN8+|C$F3IThv&XtQ+q}|$nWdE8LP8B@7ou> c|DLq}d-hCb)gDV(22{{c|K>e^yFtKX0IfJa-2eap literal 0 HcmV?d00001 diff --git a/tronScript/forTest.tron b/tronScript/forTest.tron new file mode 100644 index 0000000..acebd21 --- /dev/null +++ b/tronScript/forTest.tron @@ -0,0 +1,7 @@ +read A +read B + +setVar STEP 1 + +for A CLOCK STEP write B + diff --git a/tronScript/henrik.asmTron b/tronScript/henrik.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..b40b1a73d53a04c2ade47954771c5bfe150b3d8f GIT binary patch literal 100 zcmb=J^Y+9>(G~>(mJ4&ddfqWE^5C52n3wSX;@WiH>3<)*e{-hjuI1dN%XY?;cdqZB w_bl>M*!&mCdvbdt`o+rgpU%CNe`|hFzs$u?HX_q>%}`$C44_-N>y>{9lmqmue-9ZsL&a%WqAc}syOWKthdf__qn|@ zzWh$#l|^~a1(PeMO`Gz2#WeRx6EAr@mE3ufu(Q>cCqhLox62EZwl9aX}Ou~xX1m?-WQ*5 UKh5P}zz+VjfBwumwKDD`0GaDl0RR91 literal 0 HcmV?d00001 diff --git a/tronScript/powCompiled.tron b/tronScript/powCompiled.tron new file mode 100644 index 0000000..bbdff51 --- /dev/null +++ b/tronScript/powCompiled.tron @@ -0,0 +1,33 @@ +#inputs +read BASE +read EXPONENT + +setVar ONE 1 +setVar ZERO 0 + +#newVar mulCOUNTER +#newVar mulOUT + +copyVar BASE powOUT +jumpMark powLoop + +copyVar powOUT IN_A +copyVar BASE IN_B +copyVar ZERO mulOUT +copyVar ZERO mulCOUNTER +jump mulLoop +jumpMark next +add powCOUNTER ONE powCOUNTER +if powCOUNTER != EXPONENT jump powLoop + +write mulOUT + +halt + +jumpMark mulLoop +add mulOUT IN_A mulOUT +add mulCOUNTER ONE mulCOUNTER +if IN_B != mulCOUNTER jump mulLoop +jump next + +halt diff --git a/tronScript/stack_test.asmTron b/tronScript/stack_test.asmTron new file mode 100644 index 0000000000000000000000000000000000000000..07e2b8ce96ea06f8e9daa555efa406199f0c7d6f GIT binary patch literal 228 zcmb=J^Y(&m_F)5ohKI5Hm7,<,>=,<=] if clause is true, + executes [cmd] with [pars] +for [goal] [counter] [step] [cmd] [pars]- Sets [counter] = 0; Executes [cmd] with [pars] and + adds [step] to [counter], until [goal]==[counter] +:[asm] v#[var] - Executes [asm]-assembler command with par [var] +:[asm] d#[par] - Executes [asm]-assembler command with par [par] (decimal) +:[asm] b#[par] - Executes [asm]-assembler command with par [par] (binary) +:[asm] - - Executes [asm]-assembler command with par b#00000000 / d#0 +:[asm] ~ - Executes [asm]-assembler command with par b#11111111 / d#255 +shellcode [code] - Executes binary code [code] +nop - Nothing; sleep one cycle +halt - Stops execution of program; automatically added to the end of + your program if not present + +function [funcName] { - Defines function [funcName] with code [funcCode] + [funcCode line 1] ! Every function can only have one instance at a time: + [funcCode line 2] ! A function shall not call itself and a sub function shall + [funcCode line 3] ! not call any of its root functions !!! + . ! If you need this functionality, implement it in assembly... + . + . Why is that so? This is a stupid compiler, which does not use + [funcCode line n] a stack to return from functions, but a function-specific variable +} to store the jump-back-address... :P