def merge_segments(): try: if pil.run_at_finish: try: thread = threading.Thread(target=helpers.run_command, args=(pil.run_at_finish, )) thread.daemon = True thread.start() logger.binfo("Launched finish command: {:s}".format( pil.run_at_finish)) except Exception as e: logger.warn('Could not execute command: {:s}'.format(str(e))) live_mp4_file = '{}{}_{}_{}_{}_live.mp4'.format( pil.dl_path, pil.datetime_compat, pil.dl_user, pil.livestream_obj.get('id'), pil.epochtime) live_segments_path = os.path.normpath( pil.broadcast_downloader.output_dir) if pil.segments_json_thread_worker and pil.segments_json_thread_worker.is_alive( ): pil.segments_json_thread_worker.join() if pil.comment_thread_worker and pil.comment_thread_worker.is_alive(): logger.info("Waiting for comment downloader to finish.") pil.comment_thread_worker.join() logger.info('Merging downloaded files into video.') try: pil.broadcast_downloader.stitch( live_mp4_file, cleartempfiles=pil.clear_temp_files) logger.info('Successfully merged downloaded files into video.') if pil.clear_temp_files: helpers.remove_temp_folder() helpers.remove_lock() except ValueError as e: logger.separator() logger.error('Could not merge downloaded files: {:s}'.format( str(e))) if os.listdir(live_segments_path): logger.separator() logger.binfo( "Segment directory is not empty. Trying to merge again.") logger.separator() pil.assemble_arg = live_mp4_file.replace( ".mp4", "_downloads.json") assembler.assemble(user_called=False) else: logger.separator() logger.error( "Segment directory is empty. There is nothing to merge.") logger.separator() helpers.remove_lock() except Exception as e: logger.error('Could not merge downloaded files: {:s}'.format( str(e))) helpers.remove_lock() except KeyboardInterrupt: logger.binfo('Aborted merging process, no video was created.') helpers.remove_lock()
def main(): parser = argparse.ArgumentParser(prog="mipsal", description='Assemble and link a MIPS assembly program.') parser.add_argument("files", action="store", nargs="+", type=str, help="list of assembly files to process") parser.add_argument("--int", action="store_true", default=False, help="output intermediate files") parser.add_argument("--obj", action="store_true", default=False, help="output object files") parser.add_argument("-o", action="store", dest="out_name", type=str, default="mips.out", help="override output file name", metavar="file_name") parser.add_argument("-l", "--link", action="append", help="add file to program when linking. This option can be used more than once", metavar="file_name") args = parser.parse_args() obj_code = [] for input_file in args.files: ints, objs = assembler.assemble(input_file) obj_code.append(objs) file_name = utils.get_file_name(input_file) if args.int: int_file = file_name + ".int" utils.write_file_from_list(int_file, ints) if args.obj: obj_file = file_name + ".o" utils.write_file_from_list(obj_file, objs) if args.link != None: for link_file in args.link: obj_code.append([x.strip() for x in utils.read_file_to_list(link_file)]) output = linker.link(obj_code) utils.write_file_from_list(args.out_name, output)
def assembleFile(f_in_name, f_out_name): """ Okay, so this is the entry point for the assembler. This calls the lexer, which calls the parser, which calls the assembler, which calls the s19 generator. The flow will look like this f_in_name >> lexer >> parser >> assembler >> s19_gen >> f_out_name The lexer will take in the in file, and return a token stream The parser will take in the token stream and return an ast The assembler will take in an ast and return a list of binary data, with it's memory location The s19 gen will take that list, and return the list of records. Then this function, now that it has this list of records, will write them to the file. """ print(f_in_name + " >> " + f_out_name) toks = lex(f_in_name) # print("\n".join(str(x) for x in toks)) # print("\n\n") ast = parse(toks) # print("\n".join([str(x) for x in ast])) outFile = link([assemble(ast)]) with open(f_out_name, "w+") as f: f.write(outFile) f.write("\n")
def main(config): with open(config.assembly, 'r') as assembly: try: instructions, breakpoints = assemble(assembly, config.breakpoints) except AssemblyException as e: print(e) exit() mcm = minecraft_machine(randomized=False, num_ticks=config.num_ticks) mcm.load_instructions(instructions) for j in myrange(config.num_cycles): try: if to_dec(mcm.PC.pc) in breakpoints: if not config.nb: print() print('cycle', j) print(mcm) print_mem(config, mcm) input() mcm.cycle() if config.verbose: print('cycle', j) print(mcm) print_mem(config, mcm) input() except CPUException as e: print() print('cycle', j) print('Memory contents') print_mem(config, mcm) print(e) exit() print_mem(config, mcm)
def upload_program(self, path, addr): print(f"Assembling {src}...\n") success, binary = assembler.assemble(path) if not success: print("\nError: Assembly failed. Aborting.") else: print("\nAssembly successfull, uploading...") self.rom_write(addr, binary)
def execute(self): shellcode = assembler.assemble(self.options) if not self.module_object.run(self.options, shellcode): #Run module with selected options print("[-]An error has occured.") else: print("[*]Exploit completed. Starting handler.") handler.start(self.options)
def test_examples(self): ex_dir = os.path.join(os.path.dirname(__file__), "examples") for example in EXAMPLES: infile = os.path.join(ex_dir, "%s.a32" % example) outname = "%s.mif" % example outfile = os.path.join(self.tempdir, outname) expected_outfile = os.path.join(ex_dir, outname) # Assemble! assembler.assemble(infile, outfile) # Make sure that the produced code is the same as expected with open(expected_outfile) as f: expected_bytecode = strip_comments(f.read()) with open(outfile) as f: actual_bytecode = strip_comments(f.read()) self.assertEqual(expected_bytecode, actual_bytecode)
def main(): if len(sys.argv) == 1: print "USAGE: galapagos-as [-d] source.gas [source2.gas ...]" print "use --ascii to get output ascii strings of 0s and 1s" \ "instead of real binary" print "use --vhdl to generate fake VHDL ram for testing purposes" print "use --c to generate C code for uploading the program" return debug = '-d' in sys.argv paths = filter(lambda x: x[0] != '-', [item for sublist in map(glob.glob, sys.argv[1:]) for item in sublist]) for path in paths: with open(path, 'r') as f: assembly = [line for line in f] assembled = assemble(assembly) if not assembled: return address = 1 ascii_binary = [] for line in assembled: ascii_binary.append(line.toBinary()) if debug: print 'Address: %s' % address print 'text: ' + str(line) print line.toBinary(debug=debug) print address += 1 ascii_binary = ''.join(ascii_binary) ascii_mode = '--ascii' in sys.argv vhdl_mode = '--vhdl' in sys.argv c_mode = '--c' in sys.argv fakemem_mode = '--fakemem' in sys.argv if vhdl_mode: ascii_binary_to_vhdl_code(ascii_binary) if c_mode: ascii_binary_to_c_code(ascii_binary) if fakemem_mode: ascii_binary_to_fakemem_code(ascii_binary) with open(path + '.out', 'w') as f: f.write( ascii_binary if ascii_mode else ascii_binary_to_real_binary(ascii_binary) )
def on_assemble_click( self, element ): if not self.config[ 'file_exists' ] or self.editor.is_content_changed(): self.show_ask_save_changes_dialog() self.console.show_message( 'Assembling...' ) ret, success = assemble( self.config[ 'file_name' ] ) self.console.show_message( ret, 'success' if success else 'error' ) if success: self.assembleButton.set_sensitive( False ) self.runButton.set_sensitive( True )
def do_it(): global _des im = assembler.assemble(_file, 1024, 1024, HEPTA, desizing=_des, variance_factor=8, theme="SunsetWaters", condense=True, ignore=False) if(im == 'terminate'): print("Time taken too long, checking again with reduced sizes.") _des += 6 do_it() if(im != None and im != 'terminate' and type(im) != 'str'): im.show() im.save("first.png")
def main(): parser = argparse.ArgumentParser( prog="mipsal", description='Assemble and link a MIPS assembly program.') parser.add_argument("files", action="store", nargs="+", type=str, help="list of assembly files to process") parser.add_argument("--int", action="store_true", default=False, help="output intermediate files") parser.add_argument("--obj", action="store_true", default=False, help="output object files") parser.add_argument("-o", action="store", dest="out_name", type=str, default="mips.out", help="override output file name", metavar="file_name") parser.add_argument( "-l", "--link", action="append", help= "add file to program when linking. This option can be used more than once", metavar="file_name") args = parser.parse_args() obj_code = [] for input_file in args.files: ints, objs = assembler.assemble(input_file) obj_code.append(objs) file_name = utils.get_file_name(input_file) if args.int: int_file = file_name + ".int" utils.write_file_from_list(int_file, ints) if args.obj: obj_file = file_name + ".o" utils.write_file_from_list(obj_file, objs) if args.link != None: for link_file in args.link: obj_code.append( [x.strip() for x in utils.read_file_to_list(link_file)]) output = linker.link(obj_code) utils.write_file_from_list(args.out_name, output)
def main(argv): files = argv if len(files) is not 1: usage() for filename in files: myFile = open(filename) instructions = myFile.readlines() instruction_array = assembly_parser.parse(instructions) print(instruction_array) output = assembler.assemble( instruction_array ) print(output) with open('guiOutput.bin','w') as f: for i in output: f.write(i) f.write('\n')
def generate(): if request.method == 'POST': files = (request.form['files']).split(',') offset = int(request.form['offset']) loadfile = files[-1].split('.')[0] mainfile = loadfile + '.asm' symbols, symbol_table = assembler.assemble(files) linker.link(mainfile, symbols) loader.load(mainfile, offset) machine.convert(mainfile) f = open("Output/" + loadfile + '.pass1', 'r') code = f.read() f.close() code = code.split('\n') for i in range(0, len(code)): code[i] = code[i].replace(' ', ' ') code[i] = "<span id=\"" + str(i + 1) + "\">" + code[i] + "</span><br>" pass1code = ''.join(code) f = open("Output/" + loadfile + '.pass2', 'r') code = f.read() f.close() code = code.split('\n') for i in range(0, len(code)): code[i] = "<span id=\"" + str(i + 1) + "\">" + code[i] + "</span><br>" pass2code = ''.join(code) f = open("Output/" + loadfile + '.asm', 'r') code = f.read() f.close() code = code.split('\n') for i in range(0, len(code)): code[i] = "<span id=\"" + str(i + 1) + "\">" + code[i] + "</span><br>" link_code = ''.join(code) return json.dumps({ 'symbols': symbols, 'symbol_table': symbol_table, 'loadfile': loadfile, 'pass1code': pass1code, 'pass2code': pass2code, 'link_code': link_code })
def run_test(path: str): input_lines = open(path + '/input', "r").readlines() expected_output_lines = open(path + '/output', "r").read().splitlines() assembled = assembler.assemble(input_lines) success = expected_output_lines == assembled if not success: print('Fail!') print('Expected:') for line in expected_output_lines: print(line) print('Actual') for line in assembled: print(line) return success
def main(): options = getOptions() state = State(options.numExecuteUnits, options.instrBuffer) if options.assemble: with open(options.input) as f: program = f.read() program = assembler.assemble(program) else: with open(options.input) as f: program = f.read() state.loadProgram(program) executeProgram(state, options.debug, options.interactive, options.numMemPrint, options.numRegPrint, options.cycleLimit) return
def wordle(): global _des global _res global _file global _varfact global _theme global _font global _ignore im = assembler.assemble(_file, _res, _res, _font, sizing=_des, variance_factor=_varfact, theme=_theme, condense=True, ignore=_ignore) if(im == 'terminate'): print("Time taken too long, checking again with reduced sizes.") _des /= 2 wordle() if(im != None and im != 'terminate' and type(im) != 'str'): im.show() im.save("wordle.png")
def main(): p = programmer.Programmer() while 1: # get code from the user code = getCode() print "Assembling Code..." machine_code = assembler.assemble(code) print "Assembled Code: \n" for i in range(0, len(machine_code), 2): print '{:08b}'.format(machine_code[i]) + " " + '{:08b}'.format(machine_code[i + 1]) print "" writeIM = raw_input("Write Code To Instruction Memory? [y/n]") if writeIM.upper() == "Y": print "Writing To Instruction Memory...\n" p.writeBytes(machine_code) print "Codeload Successful!" exit = raw_input("Continue? [y/n]") if exit.upper() == "N": return
def generate(): if request.method == 'POST': files = (request.form['files']).split(',') offset = int(request.form['offset']) loadfile = files[-1].split('.')[0] mainfile=loadfile+'.asm' symbols,symbol_table=assembler.assemble(files) linker.link(mainfile, symbols) loader.load(mainfile, offset) machine.convert(mainfile) f=open("Output/"+loadfile+'.pass1','r') code=f.read() f.close() code = code.split('\n') for i in range(0,len(code)): code[i] = code[i].replace(' ',' ') code[i] = "<span id=\""+str(i+1)+"\">"+code[i]+"</span><br>" pass1code = ''.join(code) f=open("Output/"+loadfile+'.pass2','r') code=f.read() f.close() code = code.split('\n') for i in range(0,len(code)): code[i] = "<span id=\""+str(i+1)+"\">"+code[i]+"</span><br>" pass2code = ''.join(code) f=open("Output/"+loadfile+'.asm','r') code=f.read() f.close() code = code.split('\n') for i in range(0,len(code)): code[i] = "<span id=\""+str(i+1)+"\">"+code[i]+"</span><br>" link_code = ''.join(code) return json.dumps({'symbols':symbols,'symbol_table':symbol_table,'loadfile':loadfile,'pass1code':pass1code,'pass2code':pass2code,'link_code':link_code})
def compile_file(ifilename, ofilename): start = time.clock() printLog("Compiling " + ifilename + " into " + ofilename + "...") #Preprocess file & Handle includes/strings printLog("Preprocessing...") preprocessed = preprocess(ifilename) printLog("Done\n") #Split into tokens printLog("Tokenizing...") tokenizer = Tokenizer() tokens = tokenizer.tokenizeString('\n'.join(preprocessed)) printLog("Token stream:") printLog(tokens) printLog("\n") #Create parse tree printLog("Parsing...") tree = parse(tokens) printLog("Generated parse tree:") printLog(tree) printLog("\n") #Generate symbol table printLog("Locating symbols...") symbols = generateSymbolTable(tree) printLog("Symbol table:") printLog(symbols) printLog("\n") #Generate code printLog("Generating code...") assembly = generateCode(tree, symbols) printLog("Constructed high level assembly:") for i,line in enumerate(assembly.split('\n')): printLog(str(i) + max(5 - len(str(i)), 0) * " " + ": " + line) #Save to output file root_name = ifilename.split('.')[0] printLog("\nSaving to " + root_name + ".al...") with open(root_name + ".al", 'w') as outputf: outputf.write(assembly) printLog("Saved") #Save log print("Saving log...") saveLogFile() print("Done!") #Optimize code print("Switching to optimizer...") optimizer.optimize(root_name + ".al", optimizer.OPTIMIZATION_FULL, optimizer.PRIORITY_BALANCED) #Run assembler print("Switching to assembler...") assembler.assemble(root_name + ".al", ofilename, True, True) print("Done assembling!") print("Finished compiling in " + str(time.clock() - start) + "s")
if __name__ == '__main__': # Check if an assembly flag was supplied if '-a' in sys.argv: # Assembling job # Detect flags input_file_name = 'input.asm' output_file_name = 'input.b' if '-i' in sys.argv: input_file_name = sys.argv[sys.argv.index('-i') + 1] if '-o' in sys.argv: output_file_name = sys.argv[sys.argv.index('-o') + 1] input_file = open(input_file_name, 'r') output_file = open(output_file_name, 'w') # Run assembly function assemble(input_file, output_file) else: # Run MIPS simulation cpu = Processor(cli=True) input_file_name = 'input.b' output_file_name = 'sim_output.txt' # Check for flags if '-i' in sys.argv: input_file_name = sys.argv[sys.argv.index('-i') + 1] if '-o' in sys.argv: output_file_name = sys.argv[sys.argv.index('-o') + 1] input_file = open(input_file_name, 'r') output_file = open(output_file_name, 'w') # Set IO streams for the simulation cpu.load_instructions(input_file) cpu.output_stream = output_file
def load_program(program_lines, inputs): env = dict(('r%d'%i, i) for i in range(1, 10)) words = assembler.assemble(assemble1, program_lines, env) return VM(words, inputs, env)
def test_emu_cases(): for case in emu_cases: source, steps, predicate = case prog = assemble(source.split("\n")) dcpu = run_emu(prog, steps) assert predicate(dcpu)
import sys from cpu import CPU from assembler import assemble from cpu.pipeline import fetch_unit, decode_unit, execute_unit, writeback_unit from Benchmarks.memory_initialisation import INITIALISATION from cpu.Memory import MEMORY if len(sys.argv) < 2: sys.exit() else: debug = False if len(sys.argv) > 2: debug = sys.argv[2] == "debug" instructions, labels = assemble(sys.argv[1]) eus = [execute_unit.execute_unit(), execute_unit.execute_unit(), execute_unit.execute_unit(), execute_unit.execute_unit()] fu = fetch_unit.fetch_unit(len(eus)) du = decode_unit.decode_unit() wu = writeback_unit.writeback_unit() cpu = CPU.CPU(instructions, labels, fu, du, eus, wu) if sys.argv[1][11:] in INITIALISATION: MEMORY[:] = INITIALISATION[sys.argv[1][11:]] i = 0 while not cpu.check_done(): cpu.iterate(debug) # i += 1 # if i == 3000: # debug = True
print >>fp, '\tjal 0xa0' print >>fp, '\tli $9, 0x3f' storesizes = { 8: 'sb', 16: 'sh', 32: 'sw' } for name, setup, expects, load, code in tests: print >>fp, '# Test: %s' % name printf("Running test: %s" % name) print >>fp, '# Setup' gprvals = [0] * 32 for expr in setup: if expr[1][0] == 'gpr': gprvals[expr[1][1]] = expr[2] elif expr[1][0] == 'mem': print >>fp, '\tli $5, %s' % hexify(8, expr[1][2]) print >>fp, '\tli $6, %s' % hexify(8, expr[2]) print >>fp, '\t%s $6, 0($5)' % storesizes[expr[1][1]] for i in xrange(1, 32): print >>fp, '\tli $%i, %s' % (i, hexify(8, gprvals[i])) print >>fp, '# Code' print >>fp, code print >>fp, '# Checks' asm = fp.getvalue() print asm code = assemble(0x80080000, asm)
def main(): parser = argparse.ArgumentParser(description='Assemble and Run FlipJump programs.') parser.add_argument('file', help="the FlipJump files.", nargs='+') parser.add_argument('-s', '--silent', help="don't show assemble & run times", action='store_true') parser.add_argument('-o', '--outfile', help="output assembled file.") parser.add_argument('--no-macros', help="output no-macros file.") parser.add_argument('-d', '--debug', help="debug file (used for breakpoints).", nargs='?', const=True) parser.add_argument('-f', '--flags', help="running flags", type=int, default=0) parser.add_argument('-w', '--width', help="specify memory-width. 64 by default.", type=int, default=64, choices=[8, 16, 32, 64]) parser.add_argument('--Werror', help="make all warnings into errors.", action='store_true') parser.add_argument('--no-stl', help="don't assemble/link the standard library files.", action='store_true') parser.add_argument('--stats', help="show macro usage statistics.", action='store_true') parser.add_argument('-t', '--test', help="expects paths to input/expected-output files " "(s.t. the files are path.in, path.out)", nargs='+') parser.add_argument('-b', '--breakpoint', help="pause when reaching this label", default=[], action='append') parser.add_argument('-B', '--any_breakpoint', help="pause when reaching any label containing this", default=[], action='append') args = parser.parse_args() ##### - ASSEMBLE verbose_set = set() if not args.silent: verbose_set.add(Verbose.Time) if not args.no_stl: args.file = stl() + args.file for file in args.file: file = abspath(file) if not file.endswith('.fj'): parser.error(f'file {file} is not a .fj file.') if not isfile(abspath(file)): parser.error(f'file {file} does not exist.') temp_assembled_file, temp_assembled_fd = False, 0 if args.outfile is None: temp_assembled_fd, args.outfile = mkstemp() temp_assembled_file = True else: if not args.outfile.endswith('.fjm'): parser.error(f'output file {args.outfile} is not a .fjm file.') temp_debug_file, temp_debug_fd = False, 0 if args.debug is None and (len(args.breakpoint) > 0 or len(args.any_breakpoint) > 0): print(f"Warning - breakpoints are used but the debugging flag (-d) is not specified. " f"Debugging data will be saved.") args.debug = True if args.debug is True: temp_debug_fd, args.debug = mkstemp() temp_debug_file = True try: assemble(args.file, args.outfile, args.width, args.Werror, flags=args.flags, show_statistics=args.stats, preprocessed_file=args.no_macros, debugging_file=args.debug, verbose=verbose_set) except FJException as e: print() print(e) exit(1) if temp_assembled_file: os.close(temp_assembled_fd) ##### - RUN verbose_set = set() if args.test else {Verbose.PrintOutput} if not args.silent: verbose_set.add(Verbose.Time) if args.test: failures = [] total = 0 for test in args.test: total += 1 infile = f'{test}.in' outfile = f'{test}.out' if not isfile(infile): print(f'test "{test}" missing an infile ("{infile}").\n') failures.append(test) continue if not isfile(outfile): print(f'test "{test}" missing an outfile ("{outfile}").\n') failures.append(test) continue print(f'running {Path(test).name}:') with open(infile, 'r', encoding='utf-8') as inf: test_input = inf.read() with open(outfile, 'r', encoding='utf-8') as outf: expected_output = outf.read() try: run_time, ops_executed, flips_executed, output, finish_cause = \ debug_and_run(args.outfile, defined_input=test_input, verbose=verbose_set) if output != expected_output: print(f'test "{test}" failed. here\'s the diff:') print(''.join(difflib.context_diff(output.splitlines(1), expected_output.splitlines(True), fromfile='assembled file' if temp_assembled_file else args.outfile, tofile=outfile))) failures.append(test) if not args.silent: print(f'finished by {finish_cause.value} after {run_time:.3f}s ({ops_executed:,} ops executed, {flips_executed / ops_executed * 100:.2f}% flips)') except FJReadFjmException as e: print() print(e) failures.append(test) print() print() if len(failures) == 0: print(f'All tests passed! 100%') else: print(f'{total-len(failures)}/{total} tests passed ({(total-len(failures))/total*100:.2f}%).') print(f'Failed tests:') for test in failures: print(f' {test}') else: breakpoint_set = set(args.breakpoint) breakpoint_any_set = set(args.any_breakpoint) try: run_time, ops_executed, flips_executed, output, finish_cause = \ debug_and_run(args.outfile, debugging_file=args.debug, defined_input=None, verbose=verbose_set, breakpoint_labels=breakpoint_set, breakpoint_any_labels=breakpoint_any_set) if not args.silent: print(f'finished by {finish_cause.value} after {run_time:.3f}s ({ops_executed:,} ops executed, {flips_executed / ops_executed * 100:.2f}% flips)') print() except FJReadFjmException as e: print() print(e) exit(1) if temp_debug_file: os.close(temp_debug_fd)
return " popd eax\n mov eax, [eax]\n pushd eax\n" elif instr == "CALL": return " popd eax\n call eax\n" elif instr == "INT": return " pushd %s\n" % args[0] print "Unknown instruction:", instr raise Exception def ProduceCode( code ): output = "" for instruction in code: output += ProduceInstructionCode( instruction ) return output if __name__ == "__main__": import sys for path in sys.argv[1:]: openfile = open(path) data = openfile.read() openfile.close() code = assembler.disassemble( assembler.assemble( data ) ) print code asm = ProduceCode( code ) print asm
def compile_lisp(src): tokens = tokenizer.tokenize(src) ast = parser_.parse(tokens) asm = compiler.compile_(ast) bytecode = assembler.assemble(asm) return bytecode
line = re.sub('[\s]', '', line) if line.startswith('('): labelDict[line[1:-1]] = str(lineNumber) if (not line.startswith('(')) and (not line.startswith('/')) and (not line==''): lineNumber = lineNumber + 1 fileWithLabels.seek(0) varCounter = 16 for line in fileWithLabels: if '//' in line: pos = line.find('/') line = line[0:(pos-1)] line = re.sub('[\s]', '', line) if line.startswith('@'): if not isInt(line[1:]): try: fileWithoutLabels.write('@' + labelDict[line[1:]] + '\n') except: fileWithoutLabels.write('@' + str(varCounter) + '\n') labelDict[line[1:]] = str(varCounter) varCounter = varCounter + 1 else: fileWithoutLabels.write(line + '\n') elif line.startswith('(') or line == '': continue else: fileWithoutLabels.write(line + '\n') fileWithoutLabels.close() assembler.assemble(sys.argv[1][:-4]+ 'withoutLables' +'.asm')
# Description : Reads as an input an assembly file # (details of which can be found in the assembler folder) # and send it to the user chosen computer port to be # sent to the De0-Nano Board Programmed with the IITB-RISC Code import serial import serial.tools.list_ports import assembler ports = serial.tools.list_ports.comports() if (len(ports) == 0): raise Exception("No COM Ports Found. Ensure that a device is connected!") print("Available COM Ports:\nIndex\tPort\n") for i in range(len(ports)): print(i, "\t", ports[i], "\n") index = input("Select the port you wish to use(enter the index): ") index = int(index) if ((index < 0) or (index >= len(ports))): raise Exception("Invalid choice of COM Port") dump_port = serial.Serial(ports[index][0], 9600, 8, serial.PARITY_NONE, serial.STOPBITS_TWO) print("Succesfully opened specified COM Port containing ", ports[index][1]) file_name = input("Enter assembly file name: ") data = assembler.assemble(file_name) for i in data: dump_port.write(bytes([i])) file.close() dump_port.close()
if line[0] in ("JP", "CALL", "SYS"): if line[1][0] == "V": i = [line[0] + " " + line[1], line[2][2:]] else: i = [line[0], line[1][2:]] if "not" in line and "pressed" in line: i = "SKP " + line[1] elif "pressed" in line: i = "SKNP " + line[1] if "~=" in line: i = "RND " + line[0] + " " + line[2] if "return" in line: i = "RET" lines.append(i) currLine += 2 for c, i in enumerate(lines): if len(i) == 2: lines[c] = lines[c][0] + " " + hex(keywords[lines[c][1]])[2:] newFile = open(sys.argv[2] + ".c8c", "w") newFile.write("\n".join(lines)) newFile.close() import assembler assembler.assemble("\n".join(lines), sys.argv[3] + ".bin")
return [getattr(item, attr) for item in lst] mixer = Mixer() next_param_addr = assign_addresses(mixer.params, 0) next_sample_addr = assign_addresses(mixer.storage, 0) ## ## Exports ## def parameter_base_addr_for_channel_biquad(channel, biquad): return mixer.channel_biquads[channel].params[biquad][0].addr def parameter_base_addr_for_bus_biquad(bus, biquad): return mixer.bus_strips[bus].biquad_chain.params[biquad][0].addr def address_for_mixdown_gain(core, channel, bus): return mixer.downmixes[bus].gain[core][channel].addr constants_base = constants.base meter_filter_param_base = mixer.meter_filter_params[0].addr if __name__ == '__main__': with open('instr.mif', 'w') as f: assemble(mixer.program, f) print "Program length:", len(mixer.program) print "Used", next_param_addr, "params and", next_sample_addr, "sample memory addresses."
from pwn import * from binascii import hexlify from assembler import assemble # This was my assembler for the userland program ################################# # STAGE -1: MAKE SURE YOU CHANGE ld.so.2 TO MATCH YOUR LINKER ################################# ################################# # STAGE 0: COMPILE CODE AND DO STUFF ################################# # Code to pass to userland program code = assemble('exp3.asm') # Requires nasm, so this is already compiled for you. #p = process(['nasm', 'kernel_over.asm']) #p.wait() # Assuming this is successful # Compile our exploit code p = process(['make', '-C', 'exp_kernel']) p.wait() # Assuming this is successful # Read binary data. data = open('kernel_over', 'rb').read() kern = open('exp_kernel/hack.bin').read() #p = remote('35.200.23.198', 31733) ################################# # STAGE 1: EXPLOIT THE USERLAND PROGRAM
def load(filename, inputs): env = dict(('r%d' % i, i) for i in range(1, 10)) words = assemble(assemble1, open(filename), env) return VM(words, inputs, env)
def toplevel(filename): env = {} words = assemble(assemble1, open(filename), env) for word in words: print '%012o' % word
fastpath = True if fastpath: serv.wait_for_ready() else: serv.pwr_on_reset() serv.wait_for_connection() print("Connected") serv.send_packet(ucsp.get_ucode_packet(data)) r = serv.get_packet(1, UCSP_TYPE_SET_UCODE_R) if r.error != SERVER_ERROR_OK: print("Send ucode update failed.") quit(0) print("Sent ucode update.") # send testbench code data = assembler.assemble(mnem) serv.send_packet(ucsp.get_execute_code_packet(data)) r = serv.get_packet(1, UCSP_TYPE_EXECUTE_CODE_R) if r.error != SERVER_ERROR_OK: print("Send testbench failed.") quit(0) print("Sent testbench.") # apply the ucode update #serv.send_packet(ucsp.get_apply_ucode_packet()) serv.send_packet(ucsp.get_execute_code_noupdate_packet()) ret = serv.get_packet(1, UCSP_TYPE_APPLY_UCODE_R) if ret.error != SERVER_ERROR_OK: print("Apply ucode update failed.") quit(0)
import struct, test from disasm import disassemble from generator import * from glob import glob from importlib import import_module from assembler import assemble exchandler = ''' mfc0 $1, $14 rfe jr $1 nop ''' insns = assemble(0x80000080, exchandler) tests = [] for fn in glob('tests/*.py'): if fn == 'tests/__init__.py': continue test.setup = [] test.expects = [] testmod = import_module('tests.' + fn[6:-3]) testmod.setup = test.setup testmod.expects = test.expects #print 'Building test:', testmod.name insns = assemble(testmod.load, testmod.code + '\nj 0x0EADBEE0\nnop') """ for i, insn in enumerate(insns):
# copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # MIT License: http://www.opensource.org/licenses/mit-license.php # # Contributors: # Michael Pellaton # import assembler configpath = 'path/where/the/config/files/are' version = '42' distribution_name = 'myeclipsedistribution-{v}'.format(v=version) distribution_description = 'My Eclipse Distribution {v}'.format(v=version) eclipse_binary = '/path/to/the/eclipse/binary/used/for/assembly' if __name__ == '__main__': assembler.assemble(configpath, distribution_name, distribution_description, eclipse_binary)
import argparse import parser from pathlib import Path import assembler if __name__ == "__main__": command_line_parser = argparse.ArgumentParser( description="nand2tetris Hack assembler") command_line_parser.add_argument("source", type=str, nargs=1, help="hack computer .asm file") args = command_line_parser.parse_args() source = Path(args.source[0]).absolute() dest = Path(source.parent) / f"{source.stem}.hack" parser = parser.Parser() print("🏁 ASSEMBLING 🏁") with open(source) as f: instructions = parser.parse(f) assembler = assembler.Assembler() with open(dest, "w") as f: f.write(assembler.assemble(instructions)) print("🏆 DONE 🏆")
def main(): parser = argparse.ArgumentParser(description='Assemble FlipJump programs.') parser.add_argument('file', help="the FlipJump files.", nargs='+') parser.add_argument('-s', '--silent', help="don't show assemble times", action='store_true') parser.add_argument('-o', '--outfile', help="output assembled file.", default="a.fjm") parser.add_argument('--no-macros', help="output no-macros file.") parser.add_argument('-d', '--debug', help="output debug file (used for breakpoints).") parser.add_argument('-f', '--flags', help="default running flags", type=int, default=0) parser.add_argument('-w', '--width', help="specify memory-width. 64 by default.", type=int, default=64, choices=[8, 16, 32, 64]) parser.add_argument('--Werror', help="make all warnings into errors.", action='store_true') parser.add_argument('--no-stl', help="don't assemble/link the standard library files.", action='store_true') parser.add_argument( '--tests', help= "compile all .fj files in the given folder (instead of specifying a file).", action='store_true') parser.add_argument('--stats', help="show macro usage statistics.", action='store_true') args = parser.parse_args() verbose_set = set() if not args.silent: verbose_set.add(Verbose.Time) if args.tests: if len(args.file) != 1 or not isdir(args.file[0]): parser.error('the "file" argument should contain a folder path.') Path.mkdir(Path(args.file[0]) / 'compiled', exist_ok=True) failures = [] total = 0 for file in glob(join(args.file[0], '*.fj')): # if file in (r'tests\calc.fj', r'tests\func.fj', r'tests\pair_ns.fj') or file.startswith(r'tests\hexlib-'): # continue total += 1 print(f'compiling {Path(file).name}:') no_stl = args.no_stl or 'no-stl' in Path(file).stem try: assemble([file] if no_stl else stl() + [file], (Path(args.file[0]) / 'compiled' / (Path(file).stem + '.fjm')), args.width, args.Werror, flags=args.flags, verbose=verbose_set) except FJException as e: print() print(e) failures.append(file) print() print() if len(failures) == 0: print(f'All tests compiled successfully! 100%') else: print( f'{total-len(failures)}/{total} tests compiled successfully ({(total-len(failures))/total*100:.2f}%).' ) print(f'Failed compilations:') for test in failures: print(f' {test}') else: if not args.no_stl: args.file = stl() + args.file for file in args.file: file = abspath(file) if not file.endswith('.fj'): parser.error(f'file {file} is not a .fj file.') if not isfile(abspath(file)): parser.error(f'file {file} does not exist.') try: assemble(args.file, args.outfile, args.width, args.Werror, flags=args.flags, show_statistics=args.stats, preprocessed_file=args.no_macros, debugging_file=args.debug, verbose=verbose_set) except FJException as e: print() print(e) exit(1)
def generate(): if request.method == 'POST': files = (request.form['files']).split(',') offset = int(request.form['offset']) loadfile = files[-1].split('.')[0] mainfile = loadfile + '.asm' symbols1, symbols, symbol_table = assembler.assemble(files) linker.link(mainfile, symbols) f = open("Output/" + loadfile + '.asm', 'r') data = f.read() f.close() finallink = "" data = data.splitlines() temp = [] for line in data: if line.startswith('DC') or line.startswith('DM'): temp.append(line) else: finallink += line + "\n" for line in temp: finallink += line + "\n" f = open("Output/" + loadfile + "1" + '.asm', 'w') f.write(finallink) f.close() loader.load(mainfile, offset) machine.convert(mainfile) f = open("Output/" + loadfile + "1" + '.pass1', 'r') code = f.read() f.close() code = code.split('\n') for i in range(0, len(code)): code[i] = code[i].replace(' ', ' ') code[i] = "<span id=\"" + str(i + 1) + "\">" + code[i] + "</span><br>" pass1code = ''.join(code) f = open("Output/" + loadfile + "1" + '.pass2', 'r') code = f.read() f.close() code = code.split('\n') for i in range(0, len(code)): code[i] = code[i].replace(' ', ' ') code[i] = "<span id=\"" + str(i + 1) + "\">" + code[i] + "</span><br>" pass2code = ''.join(code) f = open("Output/" + loadfile + "1" + '.asm', 'r') code = f.read() f.close() code = code.split('\n') for i in range(0, len(code)): code[i] = code[i].replace(' ', ' ') code[i] = "<span id=\"" + str(i + 1) + "\">" + code[i] + "</span><br>" link_code = ''.join(code) return json.dumps({ 'symbols': symbols1, 'symbol_table': symbol_table, 'loadfile': loadfile, 'pass1code': pass1code, 'pass2code': pass2code, 'link_code': link_code })
def validate_inputs(config, args, unknown_args): error_arr = [] banner_shown = False try: if args.configpath: if os.path.isfile(args.configpath): pil.config_path = args.configpath else: logger.banner() banner_shown = True logger.warn("Custom config path is invalid, falling back to default path: {:s}".format(pil.config_path)) pil.config_path = os.path.join(os.getcwd(), "pyinstalive.ini") logger.separator() if not os.path.isfile(pil.config_path): # Create new config if it doesn't exist if not banner_shown: logger.banner() helpers.new_config() return False pil.config_path = os.path.realpath(pil.config_path) config.read(pil.config_path) if args.download: pil.dl_user = args.download if args.downloadfollowing or args.batchfile: logger.banner() logger.warn("Please use only one download method. Use -h for more information.") logger.separator() return False elif not args.clean and not args.info and not args.assemble and not args.downloadfollowing and not args.batchfile and not args.organize: logger.banner() logger.error("Please use a download method. Use -h for more information.") logger.separator() return False if helpers.bool_str_parse(config.get('pyinstalive', 'log_to_file')) == "Invalid": pil.log_to_file = True error_arr.append(['log_to_file', 'True']) elif helpers.bool_str_parse(config.get('pyinstalive', 'log_to_file')): pil.log_to_file = True else: pil.log_to_file = False logger.banner() if args.batchfile: if os.path.isfile(args.batchfile): pil.dl_batchusers = [user.rstrip('\n') for user in open(args.batchfile)] if not pil.dl_batchusers: logger.error("The specified file is empty.") logger.separator() return False else: logger.info("Downloading {:d} users from batch file.".format(len(pil.dl_batchusers))) logger.separator() else: logger.error('The specified file does not exist.') logger.separator() return False if unknown_args: pil.uargs = unknown_args logger.warn("The following unknown argument(s) were provided and will be ignored: ") logger.warn(' ' + ' '.join(unknown_args)) logger.separator() pil.ig_user = config.get('pyinstalive', 'username') pil.ig_pass = config.get('pyinstalive', 'password') pil.dl_path = config.get('pyinstalive', 'download_path') pil.run_at_start = config.get('pyinstalive', 'run_at_start') pil.run_at_finish = config.get('pyinstalive', 'run_at_finish') pil.ffmpeg_path = config.get('pyinstalive', 'ffmpeg_path') pil.verbose = config.get('pyinstalive', 'verbose') pil.skip_merge = config.get('pyinstalive', 'skip_merge') pil.args = args pil.config = config pil.proxy = config.get('pyinstalive', 'proxy') if args.dlpath: pil.dl_path = args.dlpath if helpers.bool_str_parse(config.get('pyinstalive', 'show_cookie_expiry')) == "Invalid": pil.show_cookie_expiry = False error_arr.append(['show_cookie_expiry', 'False']) elif helpers.bool_str_parse(config.get('pyinstalive', 'show_cookie_expiry')): pil.show_cookie_expiry = True else: pil.show_cookie_expiry = False if helpers.bool_str_parse(config.get('pyinstalive', 'verbose')) == "Invalid": pil.verbose = False error_arr.append(['verbose', 'False']) elif helpers.bool_str_parse(config.get('pyinstalive', 'verbose')): pil.verbose = True else: pil.verbose = False if helpers.bool_str_parse(config.get('pyinstalive', 'skip_merge')) == "Invalid": pil.skip_merge = False error_arr.append(['skip_merge', 'False']) elif helpers.bool_str_parse(config.get('pyinstalive', 'skip_merge')): pil.skip_merge = True else: pil.skip_merge = False if helpers.bool_str_parse(config.get('pyinstalive', 'use_locks')) == "Invalid": pil.use_locks = False error_arr.append(['use_locks', 'False']) elif helpers.bool_str_parse(config.get('pyinstalive', 'use_locks')): pil.use_locks = True else: pil.use_locks = False if helpers.bool_str_parse(config.get('pyinstalive', 'clear_temp_files')) == "Invalid": pil.clear_temp_files = False error_arr.append(['clear_temp_files', 'False']) elif helpers.bool_str_parse(config.get('pyinstalive', 'clear_temp_files')): pil.clear_temp_files = True else: pil.clear_temp_files = False if helpers.bool_str_parse(config.get('pyinstalive', 'do_heartbeat')) == "Invalid": pil.do_heartbeat = True error_arr.append(['do_heartbeat', 'True']) if helpers.bool_str_parse(config.get('pyinstalive', 'do_heartbeat')): pil.do_heartbeat = True if args.noheartbeat or not helpers.bool_str_parse(config.get('pyinstalive', 'do_heartbeat')): pil.do_heartbeat = False logger.warn("Getting livestream heartbeat is disabled, this may cause degraded performance.") logger.separator() if not args.nolives and helpers.bool_str_parse(config.get('pyinstalive', 'download_lives')) == "Invalid": pil.dl_lives = True error_arr.append(['download_lives', 'True']) elif helpers.bool_str_parse(config.get('pyinstalive', 'download_lives')): pil.dl_lives = True else: pil.dl_lives = False if not args.noreplays and helpers.bool_str_parse(config.get('pyinstalive', 'download_replays')) == "Invalid": pil.dl_replays = True error_arr.append(['download_replays', 'True']) elif helpers.bool_str_parse(config.get('pyinstalive', 'download_replays')): pil.dl_replays = True else: pil.dl_replays = False if helpers.bool_str_parse(config.get('pyinstalive', 'download_comments')) == "Invalid": pil.dl_comments = True error_arr.append(['download_comments', 'True']) elif helpers.bool_str_parse(config.get('pyinstalive', 'download_comments')): pil.dl_comments = True else: pil.dl_comments = False if args.nolives: pil.dl_lives = False if args.noreplays: pil.dl_replays = False if args.verbose: pil.verbose = True if args.skip_merge: pil.skip_merge = True if not pil.dl_lives and not pil.dl_replays: logger.error("You have disabled both livestream and replay downloading.") logger.error("Please enable at least one of them and try again.") logger.separator() return False if pil.ffmpeg_path: if not os.path.isfile(pil.ffmpeg_path): pil.ffmpeg_path = None cmd = "where" if platform.system() == "Windows" else "which" logger.warn("Custom FFmpeg binary path is invalid, falling back to environment variable.") else: logger.binfo("Overriding FFmpeg binary path: {:s}".format(pil.ffmpeg_path)) else: if not helpers.command_exists('ffmpeg') and not args.info: logger.error("FFmpeg framework not found, exiting.") logger.separator() return False if not pil.ig_user or not len(pil.ig_user): raise Exception("Invalid value for 'username'. This value is required.") if not pil.ig_pass or not len(pil.ig_pass): raise Exception("Invalid value for 'password'. This value is required.") if not pil.dl_path.endswith('/'): pil.dl_path = pil.dl_path + '/' if not pil.dl_path or not os.path.exists(pil.dl_path): pil.dl_path = os.getcwd() + "/" if not args.dlpath: error_arr.append(['download_path', os.getcwd() + "/"]) else: logger.warn("Custom config path is invalid, falling back to default path: {:s}".format(pil.dl_path)) logger.separator() if pil.proxy and pil.proxy != '': parsed_url = urlparse(pil.proxy) if not parsed_url.netloc or not parsed_url.scheme: error_arr.append(['proxy', 'None']) pil.proxy = None if error_arr: for error in error_arr: logger.warn("Invalid value for '{:s}'. Using default value: {:s}".format(error[0], error[1])) logger.separator() if args.info: helpers.show_info() return False elif args.clean: helpers.clean_download_dir() return False elif args.assemble: pil.assemble_arg = args.assemble assembler.assemble() return False elif args.organize: organize.organize_videos() return False return True except Exception as e: logger.error("An error occurred: {:s}".format(str(e))) logger.error("Make sure the config file and given arguments are valid and try again.") logger.separator() return False
import re import assembler, linker, loader, machine files = [] print 'Enter files to processed together (in order of execution):' while True: print 'File Name:', fname = raw_input() if fname is '': break files.append(fname) print 'Enter Offset:', # offset=int(raw_input()) offset = 0 print "" mainfile = files[-1].split('.')[0] + '.asm' symbols, symbol_table = assembler.assemble(files) linker.link(mainfile, symbols) loader.load(mainfile, offset) machine.convert(mainfile) print '\nSymbol Table:' for key in symbols: print 'File: ' + key print symbols[key]
def test_assemble(self): """DNA assembler should assemble correctly""" for pats, DNA in self.known_assemble: result = assembler.assemble(pats) self.assertEqual(DNA, result)
def printf(str): addr = stash(str) print >> fp, '\tli $4, %s' % hexify(8, addr) print >> fp, '\tjal 0xa0' print >> fp, '\tli $9, 0x3f' storesizes = {8: 'sb', 16: 'sh', 32: 'sw'} for name, setup, expects, load, code in tests: print >> fp, '# Test: %s' % name printf("Running test: %s" % name) print >> fp, '# Setup' gprvals = [0] * 32 for expr in setup: if expr[1][0] == 'gpr': gprvals[expr[1][1]] = expr[2] elif expr[1][0] == 'mem': print >> fp, '\tli $5, %s' % hexify(8, expr[1][2]) print >> fp, '\tli $6, %s' % hexify(8, expr[2]) print >> fp, '\t%s $6, 0($5)' % storesizes[expr[1][1]] for i in xrange(1, 32): print >> fp, '\tli $%i, %s' % (i, hexify(8, gprvals[i])) print >> fp, '# Code' print >> fp, code print >> fp, '# Checks' asm = fp.getvalue() print asm code = assemble(0x80080000, asm)
serv.wait_for_ready() else: serv.pwr_on_reset() serv.wait_for_connection() #print("Connected") serv.send_packet(ucsp.get_ucode_packet(data)) r = serv.get_packet(1, UCSP_TYPE_SET_UCODE_R) if r.error != SERVER_ERROR_OK: print("Send ucode update failed.") print("Address: %04X" % addr) fastpath = False continue #print("Sent ucode update.") # send testbench code data = assembler.assemble(mnem) serv.send_packet(ucsp.get_execute_code_packet(data)) r = serv.get_packet(1, UCSP_TYPE_EXECUTE_CODE_R) if r.error != SERVER_ERROR_OK: print("Send testbench failed.") print("Address: %04X" % addr) fastpath = False continue #print("Sent testbench.") # apply the ucode update #serv.send_packet(ucsp.get_apply_ucode_packet()) serv.send_packet(ucsp.get_execute_code_noupdate_packet()) ret = serv.get_packet(1, UCSP_TYPE_APPLY_UCODE_R) if ret.error != SERVER_ERROR_OK: print("Apply ucode update failed.")
parser.add_argument("-a", "--assemble", action="store_true", dest="assemble", default=False, help="assemble the code in FILE") parser.add_argument("-d", "--disassemble", action="store_true", dest="disassemble", default=False, help="disassemble the code in FILE") parser.add_argument("-q", "--quiet", action="store_true", dest="quiet", default=False, help="quiet mode") parser.add_argument("-t", "--trace", action="store_true", dest="trace", default=False, help="trace the code in FILE") parser.add_argument("-x", "--execute", action="store_true", dest="execute", default=False, help="execute the code in FILE") parser.add_argument("-v", "--version", action="version", version="%(prog)s " + app_version) parser.add_argument("filename") args = parser.parse_args() infile = args.filename if args.assemble: if not args.quiet: print ("Assembling...") assembler = assembler.Assembler(infile) code = assembler.assemble() if assembler.errorcount() > 0: sys.exit() outfile = infile + ".out" f = open(outfile, "w") json.dump(code, f) f.close() infile = outfile if args.disassemble: if not args.quiet: print ("Disassembling...") try:
help="Filename to save to (default is input filename with appropriate extension)") parser.add_argument("filename", type=str, default="", help="Filename to be compiled.") args = parser.parse_args() if args.filename == "": parser.print_help() sys.exit(-1) try: f = open(args.filename) except OSError: print("Failed to open file \"{0}\"!".format(args.filename)) data = assembler.assemble(f, args.format, args.hub_offset, syntax_version = args.syntax) # Now, write it out... outfile = os.path.splitext(args.filename)[0] if args.output: outfile = args.output elif args.format == "binary": outfile += ".binary" elif args.format == "eeprom": outfile += ".eeprom" else: outfile += ".raw" with open(outfile, "w+b") as f: f.write(data)
return text if __name__ == "__main__": argparser = ArgumentParser() argparser.add_argument('src', help='Source path') argparser.add_argument('-o', '--output-path', dest='output_path', help='Output path') argparser.add_argument('-S', dest='asm', help='Assembly', type=bool, default=False, nargs='?', const=True) args = argparser.parse_args() with open(args.src) as infile: code = infile.read() sys.setrecursionlimit(5000) asm = compile(code) if args.asm: asm = prettify(asm) if args.output_path: with open(args.output_path, 'w') as outfile: for line in asm: outfile.write(line + '\n') else: print(asm) else: machine_code = assemble(asm) if args.output_path: with open(args.output_path, 'w') as outfile: outfile.write(machine_code) else: print(machine_code)
next = stack.pop() if "Code" in next.types: interpret( code, next.value, fail=fail_continuation ) elif "Lambda" in next.types: next.value( fail=fail_continuation ) else: fail_continuation() elif inst[0] == "FAIL": fail_continuation() elif inst[0] == "RETURN": return ip += 1 if __name__ == "__main__": import sys for path in sys.argv[1:]: openfile = open(path) data = openfile.read() openfile.close() if not data.startswith( assembler.magic_number ): data = assembler.assemble( data ) code, jumptable = assembler.disassemble( data ) for name, addr in jumptable.iteritems(): namespace[name] = Value( types=["Code"], value=addr ) interpret( code, ip=jumptable["start"] )
def load(filename, inputs): env = dict(('r%d'%i, i) for i in range(1, 10)) words = assemble(assemble1, open(filename), env) return VM(words, inputs, env)
import argparse from assembler import assemble from assembly_interpreter import execute parser = argparse.ArgumentParser(description="Run an assembly file.") parser.add_argument("file", help="the file to run") args = parser.parse_args() with open(args.file, "r") as f: code = assemble(f.readlines()) execute(code, stack=[], mem=[0 for _ in range(0xFFFF)])
def load_program(program_lines, inputs): env = dict(('r%d' % i, i) for i in range(1, 10)) words = assembler.assemble(assemble1, program_lines, env) return VM(words, inputs, env)