#/usr/bin/python3 """ Маленький скрипт для сборки бинарных файликов для потока-симулятора из +- человекочитаемого текста """ import argparse import sys import struct import re time_suffixes = { "": 1, "ms": 1, "s": 1000, } size_suffiexes = { "": 1, "kb": 2 ** 10, "Mb": 2 ** 20, "Gb": 2 ** 30 } operations = { "exit": 0x00, "reserve_region": 0x01, "pass_block": 0x02, "non_save_block": 0x03, "free_region": 0x04, "return_block": 0x05, "lock_block": 0x06, "unlock_block": 0x07, "mess_region": 0x08 } access = { "page_noaccess": 0x01, "page_readonly": 0x02, "r": 0x02, "page_readwrite": 0x04, "rw": 0x04, "page_execute": 0x10, "e": 0x10, "page_execute_read": 0x20, "re": 0x20, "page_execute_readwrite": 0x40, "rwe": 0x40 } def main(): parser = argparse.ArgumentParser(prog="simasm") parser.add_argument("--file", "-f", type=str, help="file with program") parser.add_argument("--output", "-o", type=str, help="file to store program") args = parser.parse_args() program = "" if args.file: with open(args.file, "r", encoding="utf-8") as f: program = f.read() else: program = sys.stdin.read() program = re.sub("#.*$", "", program, flags=re.M) program = " ".join(program.split()) lines = list(filter(lambda s: s!="", program.split(";"))) binary = bytearray() for line in lines: words = line.split() if len(words) != 5: print("wrong line") sys.exit(1) # timestamp m = re.match(r"(\d+)(\w*)", words[0]) assert m time_offset = int(m.group(1)) * time_suffixes[m.group(2)] region_in = words[1] region = 0 if region_in.startswith("0x"): region = int(region_in, 16) else: region = int(region_in) operation = operations[words[2]] m = re.match(r"(\d+)(\w*)", words[3]) assert m size = int(m.group(1)) * size_suffiexes[m.group(2)] pg_access = access[words[4]] binary += struct.pack("QQQQQ", time_offset, operation, region, size, pg_access) if args.output: with open(args.output, "wb") as f: f.write(binary) else: print(binary.hex()) if __name__ == "__main__": main()