def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): if not silent: self.output = '' #new output for current cell newWatFile = self.createNewFile() currentFile = open(newWatFile,'w') currentFile.write(code) currentFile.close() newWasmFile = self.tempDir + self.tempWasmFile convertProcess = self.convertWatWasm(newWatFile, newWasmFile) convertOutput, convertErrs = convertProcess.communicate() if convertProcess.returncode != 0: stream_content = {'name': 'stderr', 'text': str(convertErrs)} self.send_response(self.iopub_socket, 'stream', stream_content) return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}, } #Directory compile current binary pywasm.load(newWasmFile, {'P0lib': {'write': self.write}}) stream_content = {'name': 'stdout', 'text': str(self.output)} self.send_response(self.iopub_socket, 'stream', stream_content) return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}, }
def get_ans(page_num): headers = { 'Host': 'match.yuanrenxue.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36', 'Referer': 'http://match.yuanrenxue.com/match/15', 'Cookie': 'sessionid=ah3it1h5672m69x73moc7dlufwy1krby', } ans = 0 get_wasm() for page in range(1, page_num + 1): timestamp1 = int(int(time.time()) / 2) timestamp2 = int( int(time.time()) / 2 - math.floor(random.random() * 50 + 1)) vm = pywasm.load('match15.wasm') m = str(vm.exec('encode', [timestamp1, timestamp2 ])) + '|' + str(timestamp1) + '|' + str(timestamp2) url = f'http://match.yuanrenxue.com/api/match/15?m={m}&page={page}' if page > 3: headers['User-Agent'] = 'yuanrenxue.project' res = requests.get(url=url, headers=headers) print(res.json()) for data in res.json()['data']: ans += data['value'] print('总和:' + str(ans))
def get_one_page(page): # t1 = parseInt(Date.parse(new Date())/1000/2); t1 = int(time.time()) // 2 # t2 = parseInt(Date.parse(new Date())/1000/2 - Math.floor(Math.random() * (50) + 1)); t2 = int(time.time()) // 2 - math.floor(random.random() * 50 + 1) # 1. 加载wasm文件 runtime = pywasm.load('./main.wasm') # 2. 调用执行wasm文件中的方法 r = runtime.exec('encode', [t1, t2]) m = str(r) + '|' + str(t1) + '|' + str(t2) params = {'page': page, 'm': m} base_url = 'http://match.yuanrenxue.com/api/match/15?' + urlencode(params) with requests.get( url=base_url, headers= { 'Referer': 'http://match.yuanrenxue.com/match/15', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/88.0.4324.104 Safari/537.36' }) as response: if response.status_code == 200: res = response.json() if 'data' in res.keys() and res.get('data'): for item in res.get('data'): SUM_TOTAL_LIST.append(item.get('value'))
def three(): def env_abort(_: pywasm.Ctx): return vm = pywasm.load('./main.wasm', {'env': { 'abort': env_abort, }}) r = vm.exec('encode', [804134733, 804134714]) print(r)
def encode1(): t1 = int(int(time.time() * 1000) / 1000 / 2) t2 = int( int(time.time() * 1000) / 1000 / 2 - math.floor(random.randint(0, 50) + 1)) print(t1, t2) vm = pywasm.load('a.wasm') result = vm.exec("encode", [t1, t2]) print(result) return f'{result}|{t1}|{t2}'
def case(path: str): case_name = os.path.basename(path) json_path = os.path.join(path, case_name + '.json') with open(json_path, 'r') as f: case_data = json.load(f) runtime: pywasm.Runtime = None for command in case_data['commands']: print(command) if command['type'] == 'module': filename = command['filename'] runtime = pywasm.load(os.path.join(path, filename), imps()) # {'type': 'assert_return', 'line': 104, 'action': {'type': 'invoke', 'field': '8u_good1', 'args': [{'type': 'i32', 'value': '0'}]}, 'expected': [{'type': 'i32', 'value': '97'}]} elif command['type'] == 'assert_return': if command['action']['type'] == 'invoke': function_name = command['action']['field'] args = [parse_val(i) for i in command['action']['args']] r = runtime.exec_accu(function_name, args) expect = [parse_val(i) for i in command['expected']] for i in range(len(expect)): asset_val(r.data[i], expect[i]) else: raise NotImplementedError elif command['type'] in ['assert_trap', 'assert_exhaustion']: if command['action']['type'] == 'invoke': function_name = command['action']['field'] args = [parse_val(i) for i in command['action']['args']] try: r = runtime.exec_accu(function_name, args) except Exception as e: r = str(e)[8:] expect = command['text'] assert r == expect else: raise NotImplementedError elif command['type'] == 'assert_malformed': continue elif command['type'] == 'assert_invalid': continue elif command['type'] == 'assert_unlinkable': continue elif command['type'] == 'register': return elif command['type'] == 'action': if command['action']['type'] == 'invoke': function_name = command['action']['field'] args = [parse_val(i) for i in command['action']['args']] runtime.exec_accu(function_name, args) else: raise NotImplementedError elif command['type'] == 'assert_uninstantiable': continue else: raise NotImplementedError
def test_spec(): with open('./tests/spec/modules.json', 'r') as f: data = json.load(f) for case in data: file = case['file'] if file not in switch or switch[file] == 0: continue vm = pywasm.load(os.path.join('./tests/spec/', file)) for test in case['tests']: print(f'{file} {test}') function = test['function'] args = [parse_val(e) for e in test['args']] if 'return' in test: if test['return'] is None: assert vm.exec(function, args) is None continue ret = parse_val(test['return']) # execution out = vm.exec(function, args) # assert if isinstance(ret, float): if math.isnan(ret): assert math.isnan(out) else: assert math.isclose(out, ret, rel_tol=1e-05) else: assert out == ret continue if 'trap' in test: trap = test['trap'] try: vm.exec(function, args) except Exception as e: assert str(e).split(':')[1] == trap.split(':')[1] else: assert False continue raise NotImplementedError
def main(): sums = 0 headers = { "User-Agent": "yuanrenxue.project", } t = int(time.time()) t1 = int(t / 2) t2 = int(t / 2 - math.floor(random.random() * 50 + 1)) vm = pywasm.load("./main.wasm") r = vm.exec("encode", [t1, t2]) m = f"{r}|{t1}|{t2}" for i in range(1, 6): params = { "m": m, "page": i, } response = requests.get(url="http://match.yuanrenxue.com/api/match/15", params=params, headers=headers).json() for each in response["data"]: print(each["value"]) sums += each["value"] print(sums)
import os.path if not len(sys.argv) == 3: print("usage: %s [infile.zst] [outfile]" % sys.argv[0]) infile, outfile = sys.argv[1:] def grow(n): print("need more memory", n) wasm_module = os.path.join(os.path.dirname(__file__), "zstddec.wasm") vm = pywasm.load(wasm_module, {"env": { "emscripten_notify_memory_growth": grow }}) compressed = open(infile, "rb").read() compressed_ptr = vm.exec("malloc", [len(compressed)]) # copy data into memory vm.store.mems[0].data[compressed_ptr:compressed_ptr + len(compressed)] = compressed decompressed_size = vm.exec("ZSTD_findDecompressedSize", [compressed_ptr, len(compressed)]) print("%s -> %s" % (len(compressed), decompressed_size))
# You can limit cycles consumption, if your limit is too low, your work won't be finished when you hit it and an # "out of gas" exception will be throwed. This is used to ensure that any untrusted code can be stopped alwasys. import pywasm def instruction_cycle_func(i: pywasm.binary.Instruction) -> int: if i.opcode == pywasm.instruction.i32_add: return 1 if i.opcode == pywasm.instruction.i32_mul: return 3 # ... ... return 1 option = pywasm.Option() option.instruction_cycle_func = instruction_cycle_func option.cycle_limit = 100 # a number ge 0, 0 means no limit runtime = pywasm.load('./examples/add.wasm', opts=option) assert runtime.machine.opts.cycle == 0 r = runtime.exec('add', [4, 5]) assert r == 9 # 4 + 5 = 9 assert runtime.machine.opts.cycle == 4 print(runtime.machine.opts.cycle)
import sys import pywasm # pywasm.on_debug() vm = pywasm.load(sys.argv[1]) name = sys.argv[2] args = [int(arg) for arg in sys.argv[3:]] r = vm.exec(name, args) print(r)
import pywasm vm = pywasm.load('./examples/fib.wasm') r = vm.exec('fib', [10]) print(r)
subprocess.run(["mv", file_name[:-2] + ".s", file_name[:-2] + ".wat"]) subprocess.run(["wat2wasm", file_name[:-2] + ".wat"]) def rite(i): print(i) def writeln(): print() def reed(): return int(input()) def printify(c): print(chr(c), end='') # Load the assembled binary into a vm to run # Also load in references to the functions to run vm = pywasm.load(file_name[:-2] + ".wasm", { 'P0lib': { 'write': rite, 'writeln': writeln, 'read': reed, 'print': printify } })
import pywasm # pywasm.on_debug() runtime = pywasm.load('./examples/str.wasm') r = runtime.exec('get', []) print(runtime.store.memory_list[0].data[r:r + 12].decode())
import pywasm pywasm.on_debug() def _fib(n): if n <= 1: return n return _fib(n - 1) + _fib(n - 2) def fib(_: pywasm.Ctx, n: int): return _fib(n) vm = pywasm.load('./examples/env.wasm', {'env': {'fib': fib}}) r = vm.exec('get', [10]) print(r) # 55
def readNum(): return int(input("Enter a number: ")) env = { 'write': printNum, 'writeln': printLn, 'read': readNum, 'logdata': logdata } if len(sys.argv) != 2: print("Usage: runner.py <.wasm file>") sys.exit(1) vm = pywasm.load(sys.argv[1], {"P0lib": env, "env": env}) # Debug code # print(vm.exec('malloc',[1])) # Should malloc to 0 # print(vm.exec('malloc',[10])) # Should malloc to 4 + 1 = 5 # print(vm.exec('malloc', [1])) # Should malloc to 5 + 4 + 10 = 19 # print(vm.exec('malloc', [10])) # Should malloc to 19 + 4 + 1 = 24 # vm.exec('free', [5]) # print(vm.exec('malloc', [1])) # Should malloc to 5 again # print(vm.exec('malloc', [1])) # Should malloc to 5 + 4 + 1 = 10 # print(vm.exec('malloc', [10])) # Should malloc to 24 + 10 + 4 = 38 # vm.exec('free',[0]) # print(vm.exec('malloc', [10])) # Should malloc to 38 + 10 + 4 = 52 # print(vm.exec('malloc', [1])) # Should malloc to 0 # Super smart BF debug code print(vm.exec('malloc', [4])) # 0
limits.n = 256 limits.m = 256 memory_type = pywasm.binary.MemoryType() memory_type.limits = limits env['memory'] = pywasm.Memory(memory_type) limits = pywasm.Limits() limits.n = 99 limits.m = 99 env['table'] = pywasm.Table(0, limits) if __name__ == '__main__': vm = pywasm.load('ckey.wasm', { 'env': env, 'global': { 'NaN': None, 'Infinity': None } }) wa_stackAlloc = partial(vm.exec, 'stackAlloc') wa__malloc = partial(vm.exec, '_malloc') wa__getckey = partial(vm.exec, '_getckey') # func_addr = vm.func_addr('_malloc') # func = vm.machine.store.function_list[func_addr] # func_args_1 = func.type.args ckey = getckey(10201, '3.5.57', 'j002024w2wg', '', '1fcb9528b79f2065c9a281a7d554edd1', 1556590422) print(ckey) a = 0
import pywasm pywasm.on_debug() vm = pywasm.load('./examples/str.wasm') r = vm.exec('get', []) print(vm.store.mems[0].data[r:r + 12])
import pywasm def env_abort(_: pywasm.Ctx): return vm = pywasm.load('./build/optimized.wasm', {'env': { 'abort': env_abort, }}) r = vm.exec('add', [10, 20]) print(r)
import pywasm # pywasm.on_debug() runtime = pywasm.load('./examples/fib.wasm') r = runtime.exec('fib', [10]) print(r)
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): if not silent: if code.startswith('*MODULE*'): newWatFile = self.CreateNewFile() currentFile = open(newWatFile, "w") trimmedCode = '\n'.join(code.split('\n')[1:]) currentFile.write(trimmedCode) currentFile.close() newWasmFile = newWatFile[:-4] + ".wasm" #convert code from .wat to a .wasm binary (same file path + name just different extension) watSysCommand = "wat2wasm " + newWatFile + " -o " + newWasmFile cmdAsArray = watSysCommand.split(' ') subpros = Popen(cmdAsArray, stdin=PIPE, stdout=PIPE, stderr=PIPE) subpros.wait() output, errs = subpros.communicate() if subpros.returncode != 0: stream_content = {'name': 'stderr', 'text': str(errs)} self.send_response(self.iopub_socket, 'stream', stream_content) else: self.compiledFiles.append(newWasmFile) stream_content = { 'name': 'stdout', 'text': str('Module Written - ' + newWasmFile) } self.send_response(self.iopub_socket, 'stream', stream_content) elif code.startswith('*EXEC*'): output = "" trimmedCode = '\n'.join(code.split('\n')[1:]) #multiple function callable on separate lines callLines = trimmedCode.split('\n') for line in callLines: function = line.split(' ')[0] parameters = [] if ' ' in line: parameters = line.split(' ')[1:] for i in range(0, len( parameters)): #convert parameters to integers parameters[i] = int(parameters[i]) #load all exported functions for module in self.compiledFiles: vm = pywasm.load(str(module)) for func in vm.module_instance.exports: if func.name == function: output += str( vm.exec(str(func.name), parameters)) + '\n' if output == "": stream_content = { 'name': 'stderr', 'text': 'No matching function found' } self.send_response(self.iopub_socket, 'stream', stream_content) else: stream_content = {'name': 'stdout', 'text': output} self.send_response(self.iopub_socket, 'stream', stream_content) else: stream_content = { 'name': 'stderr', 'text': 'Missing header, should be *MODULE* or *EXEC*' } self.send_response(self.iopub_socket, 'stream', stream_content) return { 'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}, }
import pywasm vm = pywasm.load('./examples/sum.wasm') r = vm.exec('sum', [100]) print(r) # 1 + 2 + ... + 99 = 4950
import pywasm pywasm.on_debug() vm = pywasm.load('./examples/add.wasm') r = vm.exec('add', [4, 5]) print(r) # 4 + 5 = 9
""" @author: coderfly @file: answer_py @time: 2021/3/5 @email: [email protected] @desc: """ import subprocess import time import random from math import floor import pywasm from spiders.猿人学 import get_session runtime = pywasm.load("main.wasm") session = get_session() total = [] for i in range(1,6): t1 = int(int(time.time()) / 2) t2 = int(int(time.time()) / 2 - floor(random.random() * (50) + 1)) r = runtime.exec("encode", [t1, t2]) m = '{}|{}|{}'.format(r, t1, t2) params = { "page":i, "m":m } response = session.get('http://match.yuanrenxue.com/api/match/15', params=params).json() total.extend([item['value'] for item in response['data']])
import pywasm # pywasm.on_debug() runtime = pywasm.load('./examples/add.wasm') r = runtime.exec('add', [4, 5]) print(r) # 4 + 5 = 9