runtest.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import argparse
  4. import array
  5. import atexit
  6. import math
  7. import os
  8. import re
  9. import shutil
  10. import struct
  11. import subprocess
  12. import sys
  13. import tempfile
  14. import time
  15. import threading
  16. import traceback
  17. from select import select
  18. from queue import Queue
  19. from subprocess import PIPE, STDOUT, Popen
  20. from typing import BinaryIO, Optional, Tuple
  21. if sys.version_info[0] == 2:
  22. IS_PY_3 = False
  23. else:
  24. IS_PY_3 = True
  25. test_aot = False
  26. # Available targets:
  27. # "aarch64" "aarch64_vfp" "armv7" "armv7_vfp" "thumbv7" "thumbv7_vfp"
  28. # "riscv32" "riscv32_ilp32f" "riscv32_ilp32d" "riscv64" "riscv64_lp64f" "riscv64_lp64d"
  29. test_target = "x86_64"
  30. debug_file = None
  31. log_file = None
  32. # to save the register module with self-define name
  33. temp_file_repo = []
  34. # to save the mapping of module files in /tmp by name
  35. temp_module_table = {}
  36. # AOT compilation options mapping
  37. aot_target_options_map = {
  38. "i386": ["--target=i386"],
  39. "x86_32": ["--target=i386"],
  40. "x86_64": ["--target=x86_64", "--cpu=skylake"],
  41. "aarch64": ["--target=aarch64", "--target-abi=eabi", "--cpu=cortex-a53"],
  42. "aarch64_vfp": ["--target=aarch64", "--target-abi=gnueabihf", "--cpu=cortex-a53"],
  43. "armv7": ["--target=armv7", "--target-abi=eabi", "--cpu=cortex-a9", "--cpu-features=-neon"],
  44. "armv7_vfp": ["--target=armv7", "--target-abi=gnueabihf", "--cpu=cortex-a9"],
  45. "thumbv7": ["--target=thumbv7", "--target-abi=eabi", "--cpu=cortex-a9", "--cpu-features=-neon,-vfpv3"],
  46. "thumbv7_vfp": ["--target=thumbv7", "--target-abi=gnueabihf", "--cpu=cortex-a9", "--cpu-features=-neon"],
  47. "riscv32": ["--target=riscv32", "--target-abi=ilp32", "--cpu=generic-rv32", "--cpu-features=+m,+a,+c"],
  48. "riscv32_ilp32f": ["--target=riscv32", "--target-abi=ilp32f", "--cpu=generic-rv32", "--cpu-features=+m,+a,+c,+f"],
  49. "riscv32_ilp32d": ["--target=riscv32", "--target-abi=ilp32d", "--cpu=generic-rv32", "--cpu-features=+m,+a,+c,+f,+d"],
  50. "riscv64": ["--target=riscv64", "--target-abi=lp64", "--cpu=generic-rv64", "--cpu-features=+m,+a,+c"],
  51. "riscv64_lp64f": ["--target=riscv64", "--target-abi=lp64f", "--cpu=generic-rv64", "--cpu-features=+m,+a,+c,+f"],
  52. "riscv64_lp64d": ["--target=riscv64", "--target-abi=lp64d", "--cpu=generic-rv64", "--cpu-features=+m,+a,+c,+f,+d"],
  53. }
  54. def debug(data):
  55. if debug_file:
  56. debug_file.write(data)
  57. debug_file.flush()
  58. def log(data, end='\n'):
  59. if log_file:
  60. log_file.write(data + end)
  61. log_file.flush()
  62. print(data, end=end)
  63. sys.stdout.flush()
  64. def create_tmp_file(suffix: str) -> str:
  65. with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp_file:
  66. return tmp_file.name
  67. # TODO: do we need to support '\n' too
  68. import platform
  69. if platform.system().find("CYGWIN_NT") >= 0:
  70. # TODO: this is weird, is this really right on Cygwin?
  71. sep = "\n\r\n"
  72. else:
  73. sep = "\r\n"
  74. rundir = None
  75. class AsyncStreamReader:
  76. def __init__(self, stream: BinaryIO) -> None:
  77. self._queue = Queue()
  78. self._reader_thread = threading.Thread(
  79. daemon=True,
  80. target=AsyncStreamReader._stdout_reader,
  81. args=(self._queue, stream))
  82. self._reader_thread.start()
  83. def read(self) -> Optional[bytes]:
  84. return self._queue.get()
  85. def cleanup(self) -> None:
  86. self._reader_thread.join()
  87. @staticmethod
  88. def _stdout_reader(queue: Queue, stdout: BinaryIO) -> None:
  89. while True:
  90. try:
  91. queue.put(stdout.read(1))
  92. except ValueError as e:
  93. if stdout.closed:
  94. queue.put(None)
  95. break
  96. raise e
  97. class Runner():
  98. def __init__(self, args, no_pty=False):
  99. self.no_pty = no_pty
  100. # Cleanup child process on exit
  101. atexit.register(self.cleanup)
  102. self.process = None
  103. env = os.environ
  104. env['TERM'] = 'dumb'
  105. env['INPUTRC'] = '/dev/null'
  106. env['PERL_RL'] = 'false'
  107. if no_pty:
  108. self.process = Popen(args, bufsize=0,
  109. stdin=PIPE, stdout=PIPE, stderr=STDOUT,
  110. env=env)
  111. self.stdin = self.process.stdin
  112. self.stdout = self.process.stdout
  113. else:
  114. import fcntl
  115. # Pseudo-TTY and terminal manipulation
  116. import pty
  117. import termios
  118. # Use tty to setup an interactive environment
  119. master, slave = pty.openpty()
  120. # Set terminal size large so that readline will not send
  121. # ANSI/VT escape codes when the lines are long.
  122. buf = array.array('h', [100, 200, 0, 0])
  123. fcntl.ioctl(master, termios.TIOCSWINSZ, buf, True)
  124. self.process = Popen(args, bufsize=0,
  125. stdin=slave, stdout=slave, stderr=STDOUT,
  126. preexec_fn=os.setsid,
  127. env=env)
  128. # Now close slave so that we will get an exception from
  129. # read when the child exits early
  130. # http://stackoverflow.com/questions/11165521
  131. os.close(slave)
  132. self.stdin = os.fdopen(master, 'r+b', 0)
  133. self.stdout = self.stdin
  134. if platform.system().lower() == "windows":
  135. self._stream_reader = AsyncStreamReader(self.stdout)
  136. else:
  137. self._stream_reader = None
  138. self.buf = ""
  139. def _read_stdout_byte(self) -> Tuple[bool, Optional[bytes]]:
  140. if self._stream_reader:
  141. return True, self._stream_reader.read()
  142. else:
  143. # select doesn't work on file descriptors on Windows.
  144. # however, this method is much faster than using
  145. # queue, so we keep it for non-windows platforms.
  146. [outs,_,_] = select([self.stdout], [], [], 1)
  147. if self.stdout in outs:
  148. return True, self.stdout.read(1)
  149. else:
  150. return False, None
  151. def read_to_prompt(self, prompts, timeout):
  152. wait_until = time.time() + timeout
  153. while time.time() < wait_until:
  154. has_value, read_byte = self._read_stdout_byte()
  155. if not has_value:
  156. continue
  157. if not read_byte:
  158. # EOF on macOS ends up here.
  159. break
  160. read_byte = read_byte.decode('utf-8') if IS_PY_3 else read_byte
  161. debug(read_byte)
  162. if self.no_pty:
  163. self.buf += read_byte.replace('\n', '\r\n')
  164. else:
  165. self.buf += read_byte
  166. self.buf = self.buf.replace('\r\r', '\r')
  167. # filter the prompts
  168. for prompt in prompts:
  169. pattern = re.compile(prompt)
  170. match = pattern.search(self.buf)
  171. if match:
  172. end = match.end()
  173. buf = self.buf[0:end-len(prompt)]
  174. self.buf = self.buf[end:]
  175. return buf
  176. return None
  177. def writeline(self, str):
  178. str_to_write = str + '\n'
  179. str_to_write = bytes(
  180. str_to_write, 'utf-8') if IS_PY_3 else str_to_write
  181. self.stdin.write(str_to_write)
  182. def cleanup(self):
  183. atexit.unregister(self.cleanup)
  184. if self.process:
  185. try:
  186. self.writeline("__exit__")
  187. time.sleep(.020)
  188. self.process.kill()
  189. except OSError:
  190. pass
  191. except IOError:
  192. pass
  193. self.process = None
  194. self.stdin.close()
  195. if self.stdin != self.stdout:
  196. self.stdout.close()
  197. self.stdin = None
  198. self.stdout = None
  199. if not IS_PY_3:
  200. sys.exc_clear()
  201. if self._stream_reader:
  202. self._stream_reader.cleanup()
  203. def assert_prompt(runner, prompts, timeout, is_need_execute_result):
  204. # Wait for the initial prompt
  205. header = runner.read_to_prompt(prompts, timeout=timeout)
  206. if not header and is_need_execute_result:
  207. log(" ---------- will terminate cause the case needs result while there is none inside of buf. ----------")
  208. sys.exit(1)
  209. if not header == None:
  210. if header:
  211. log("Started with:\n%s" % header)
  212. else:
  213. log("Did not one of following prompt(s): %s" % repr(prompts))
  214. log(" Got : %s" % repr(r.buf))
  215. sys.exit(1)
  216. ### WebAssembly specific
  217. parser = argparse.ArgumentParser(
  218. description="Run a test file against a WebAssembly interpreter")
  219. parser.add_argument('--wast2wasm', type=str,
  220. default=os.environ.get("WAST2WASM", "wast2wasm"),
  221. help="Path to wast2wasm program")
  222. parser.add_argument('--interpreter', type=str,
  223. default=os.environ.get("IWASM_CMD", "iwasm"),
  224. help="Path to WebAssembly interpreter")
  225. parser.add_argument('--aot-compiler', type=str,
  226. default=os.environ.get("WAMRC_CMD", "wamrc"),
  227. help="Path to WebAssembly AoT compiler")
  228. parser.add_argument('--no_cleanup', action='store_true',
  229. help="Keep temporary *.wasm files")
  230. parser.add_argument('--rundir',
  231. help="change to the directory before running tests")
  232. parser.add_argument('--start-timeout', default=30, type=int,
  233. help="default timeout for initial prompt")
  234. parser.add_argument('--test-timeout', default=20, type=int,
  235. help="default timeout for each individual test action")
  236. parser.add_argument('--no-pty', action='store_true',
  237. help="Use direct pipes instead of pseudo-tty")
  238. parser.add_argument('--log-file', type=str,
  239. help="Write messages to the named file in addition the screen")
  240. parser.add_argument('--log-dir', type=str,
  241. help="The log directory to save the case file if test failed")
  242. parser.add_argument('--debug-file', type=str,
  243. help="Write all test interaction the named file")
  244. parser.add_argument('test_file', type=argparse.FileType('r'),
  245. help="a WebAssembly *.wast test file")
  246. parser.add_argument('--aot', action='store_true',
  247. help="Test with AOT")
  248. parser.add_argument('--target', type=str,
  249. default="x86_64",
  250. help="Set running target")
  251. parser.add_argument('--sgx', action='store_true',
  252. help="Test SGX")
  253. parser.add_argument('--simd', default=False, action='store_true',
  254. help="Enable SIMD")
  255. parser.add_argument('--xip', default=False, action='store_true',
  256. help="Enable XIP")
  257. parser.add_argument('--multi-module', default=False, action='store_true',
  258. help="Enable Multi-thread")
  259. parser.add_argument('--multi-thread', default=False, action='store_true',
  260. help="Enable Multi-thread")
  261. parser.add_argument('--gc', default=False, action='store_true',
  262. help='Test with GC')
  263. parser.add_argument('--qemu', default=False, action='store_true',
  264. help="Enable QEMU")
  265. parser.add_argument('--qemu-firmware', default='', help="Firmware required by qemu")
  266. parser.add_argument('--verbose', default=False, action='store_true',
  267. help='show more logs')
  268. # regex patterns of tests to skip
  269. C_SKIP_TESTS = ()
  270. PY_SKIP_TESTS = (
  271. # names.wast
  272. 'invoke \"~!',
  273. # conversions.wast
  274. '18446742974197923840.0',
  275. '18446744073709549568.0',
  276. '9223372036854775808',
  277. 'reinterpret_f.*nan',
  278. # endianness
  279. '.const 0x1.fff' )
  280. def read_forms(string):
  281. forms = []
  282. form = ""
  283. depth = 0
  284. line = 0
  285. pos = 0
  286. while pos < len(string):
  287. # Keep track of line number
  288. if string[pos] == '\n': line += 1
  289. # Handle top-level elements
  290. if depth == 0:
  291. # Add top-level comments
  292. if string[pos:pos+2] == ";;":
  293. end = string.find("\n", pos)
  294. if end == -1: end == len(string)
  295. forms.append(string[pos:end])
  296. pos = end
  297. continue
  298. # TODO: handle nested multi-line comments
  299. if string[pos:pos+2] == "(;":
  300. # Skip multi-line comment
  301. end = string.find(";)", pos)
  302. if end == -1:
  303. raise Exception("mismatch multiline comment on line %d: '%s'" % (
  304. line, string[pos:pos+80]))
  305. pos = end+2
  306. continue
  307. # Ignore whitespace between top-level forms
  308. if string[pos] in (' ', '\n', '\t'):
  309. pos += 1
  310. continue
  311. # Read a top-level form
  312. if string[pos] == '(': depth += 1
  313. if string[pos] == ')': depth -= 1
  314. if depth == 0 and not form:
  315. raise Exception("garbage on line %d: '%s'" % (
  316. line, string[pos:pos+80]))
  317. form += string[pos]
  318. if depth == 0 and form:
  319. forms.append(form)
  320. form = ""
  321. pos += 1
  322. return forms
  323. def get_module_exp_from_assert(string):
  324. depth = 0
  325. pos = 0
  326. module = ""
  327. exception = ""
  328. start_record = False
  329. result = []
  330. while pos < len(string):
  331. # record from the " (module "
  332. if string[pos:pos+7] == "(module":
  333. start_record = True
  334. if start_record:
  335. if string[pos] == '(' : depth += 1
  336. if string[pos] == ')' : depth -= 1
  337. module += string[pos]
  338. # if we get all (module ) .
  339. if depth == 0 and module:
  340. result.append(module)
  341. start_record = False
  342. # get expected exception
  343. if string[pos] == '"':
  344. end = string.find("\"", pos+1)
  345. if end != -1:
  346. end_rel = string.find("\"",end+1)
  347. if end_rel == -1:
  348. result.append(string[pos+1:end])
  349. pos += 1
  350. return result
  351. def string_to_unsigned(number_in_string, lane_type):
  352. if not lane_type in ['i8x16', 'i16x8', 'i32x4', 'i64x2']:
  353. raise Exception("invalid value {} and type {} and lane_type {}".format(number_in_string, type, lane_type))
  354. number = int(number_in_string, 16) if '0x' in number_in_string else int(number_in_string)
  355. if "i8x16" == lane_type:
  356. if number < 0:
  357. packed = struct.pack('b', number)
  358. number = struct.unpack('B', packed)[0]
  359. elif "i16x8" == lane_type:
  360. if number < 0:
  361. packed = struct.pack('h', number)
  362. number = struct.unpack('H', packed)[0]
  363. elif "i32x4" == lane_type:
  364. if number < 0:
  365. packed = struct.pack('i', number)
  366. number = struct.unpack('I', packed)[0]
  367. else: # "i64x2" == lane_type:
  368. if number < 0:
  369. packed = struct.pack('q', number)
  370. number = struct.unpack('Q', packed)[0]
  371. return number
  372. def cast_v128_to_i64x2(numbers, type, lane_type):
  373. numbers = [n.replace("_", "") for n in numbers]
  374. if "i8x16" == lane_type:
  375. assert(16 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  376. # str -> int
  377. numbers = [string_to_unsigned(n, lane_type) for n in numbers]
  378. # i8 -> i64
  379. packed = struct.pack(16 * "B", *numbers)
  380. elif "i16x8" == lane_type:
  381. assert(8 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  382. # str -> int
  383. numbers = [string_to_unsigned(n, lane_type) for n in numbers]
  384. # i16 -> i64
  385. packed = struct.pack(8 * "H", *numbers)
  386. elif "i32x4" == lane_type:
  387. assert(4 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  388. # str -> int
  389. numbers = [string_to_unsigned(n, lane_type) for n in numbers]
  390. # i32 -> i64
  391. packed = struct.pack(4 * "I", *numbers)
  392. elif "i64x2" == lane_type:
  393. assert(2 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  394. # str -> int
  395. numbers = [string_to_unsigned(n, lane_type) for n in numbers]
  396. # i64 -> i64
  397. packed = struct.pack(2 * "Q", *numbers)
  398. elif "f32x4" == lane_type:
  399. assert(4 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  400. # str -> int
  401. numbers = [parse_simple_const_w_type(n, "f32")[0] for n in numbers]
  402. # f32 -> i64
  403. packed = struct.pack(4 * "f", *numbers)
  404. elif "f64x2" == lane_type:
  405. assert(2 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  406. # str -> int
  407. numbers = [parse_simple_const_w_type(n, "f64")[0] for n in numbers]
  408. # f64 -> i64
  409. packed = struct.pack(2 * "d", *numbers)
  410. else:
  411. raise Exception("invalid value {} and type {} and lane_type {}".format(numbers, type, lane_type))
  412. assert(packed)
  413. unpacked = struct.unpack("Q Q", packed)
  414. return unpacked, f"[{unpacked[0]:#x} {unpacked[1]:#x}]:{lane_type}:v128"
  415. def parse_simple_const_w_type(number, type):
  416. number = number.replace('_', '')
  417. number = re.sub(r"nan\((ind|snan)\)", "nan", number)
  418. if type in ["i32", "i64"]:
  419. number = int(number, 16) if '0x' in number else int(number)
  420. return number, "0x{:x}:{}".format(number, type) \
  421. if number >= 0 \
  422. else "-0x{:x}:{}".format(0 - number, type)
  423. elif type in ["f32", "f64"]:
  424. if "nan:" in number:
  425. return float('nan'), "nan:{}".format(type)
  426. else:
  427. number = float.fromhex(number) if '0x' in number else float(number)
  428. return number, "{:.7g}:{}".format(number, type)
  429. elif type == "ref.null":
  430. if number == "func":
  431. return "func", "func:ref.null"
  432. elif number == "extern":
  433. return "extern", "extern:ref.null"
  434. elif number == "any":
  435. return "any", "any:ref.null"
  436. else:
  437. raise Exception("invalid value {} and type {}".format(number, type))
  438. elif type == "ref.extern":
  439. number = int(number, 16) if '0x' in number else int(number)
  440. return number, "0x{:x}:ref.extern".format(number)
  441. elif type == "ref.host":
  442. number = int(number, 16) if '0x' in number else int(number)
  443. return number, "0x{:x}:ref.host".format(number)
  444. else:
  445. raise Exception("invalid value {} and type {}".format(number, type))
  446. def parse_assertion_value(val):
  447. """
  448. Parse something like:
  449. "ref.null extern" in (assert_return (invoke "get-externref" (i32.const 0)) (ref.null extern))
  450. "ref.extern 1" in (assert_return (invoke "get-externref" (i32.const 1)) (ref.extern 1))
  451. "i32.const 0" in (assert_return (invoke "is_null-funcref" (i32.const 1)) (i32.const 0))
  452. in summary:
  453. type.const (sub-type) (val1 val2 val3 val4) ...
  454. type.const val
  455. ref.extern val
  456. ref.null ref_type
  457. ref.array
  458. ref.struct
  459. ref.func
  460. ref.i31
  461. """
  462. if not val:
  463. return None, ""
  464. splitted = re.split('\s+', val)
  465. splitted = [s for s in splitted if s]
  466. type = splitted[0].split(".")[0]
  467. lane_type = splitted[1] if len(splitted) > 2 else ""
  468. numbers = splitted[2:] if len(splitted) > 2 else splitted[1:]
  469. if type in ["i32", "i64", "f32", "f64"]:
  470. return parse_simple_const_w_type(numbers[0], type)
  471. elif type == "ref":
  472. if splitted[0] in ["ref.array", "ref.struct", "ref.func", "ref.i31"]:
  473. return splitted[0]
  474. # need to distinguish between "ref.null" and "ref.extern"
  475. return parse_simple_const_w_type(numbers[0], splitted[0])
  476. else:
  477. return cast_v128_to_i64x2(numbers, type, lane_type)
  478. def int2uint32(i):
  479. return i & 0xffffffff
  480. def int2int32(i):
  481. val = i & 0xffffffff
  482. if val & 0x80000000:
  483. return val - 0x100000000
  484. else:
  485. return val
  486. def int2uint64(i):
  487. return i & 0xffffffffffffffff
  488. def int2int64(i):
  489. val = i & 0xffffffffffffffff
  490. if val & 0x8000000000000000:
  491. return val - 0x10000000000000000
  492. else:
  493. return val
  494. def num_repr(i):
  495. if isinstance(i, int) or isinstance(i, long):
  496. return re.sub("L$", "", hex(i))
  497. else:
  498. return "%.16g" % i
  499. def hexpad16(i):
  500. return "0x%04x" % i
  501. def hexpad24(i):
  502. return "0x%06x" % i
  503. def hexpad32(i):
  504. return "0x%08x" % i
  505. def hexpad64(i):
  506. return "0x%016x" % i
  507. def invoke(r, args, cmd):
  508. r.writeline(cmd)
  509. return r.read_to_prompt(['\r\nwebassembly> ', '\nwebassembly> '],
  510. timeout=args.test_timeout)
  511. def vector_value_comparison(out, expected):
  512. """
  513. out likes "<number number>:v128"
  514. expected likes "[number number]:v128"
  515. """
  516. # print("vector value comparision {} vs {}".format(out, expected))
  517. out_val, out_type = out.split(':')
  518. # <number nubmer> => number number
  519. out_val = out_val[1:-1]
  520. expected_val, lane_type, expected_type = expected.split(':')
  521. # [number nubmer] => number number
  522. expected_val = expected_val[1:-1]
  523. assert("v128" == out_type), "out_type should be v128"
  524. assert("v128" == expected_type), "expected_type should be v128"
  525. if out_type != expected_type:
  526. return False
  527. out_val = out_val.split(" ")
  528. expected_val = expected_val.split(" ")
  529. # since i64x2
  530. out_packed = struct.pack("QQ", int(out_val[0], 16), int(out_val[1], 16))
  531. expected_packed = struct.pack("QQ",
  532. int(expected_val[0]) if not "0x" in expected_val[0] else int(expected_val[0], 16),
  533. int(expected_val[1]) if not "0x" in expected_val[1] else int(expected_val[1], 16))
  534. if lane_type in ["i8x16", "i16x8", "i32x4", "i64x2"]:
  535. return out_packed == expected_packed;
  536. else:
  537. assert(lane_type in ["f32x4", "f64x2"]), "unexpected lane_type"
  538. if "f32x4" == lane_type:
  539. out_unpacked = struct.unpack("ffff", out_packed)
  540. expected_unpacked = struct.unpack("ffff", expected_packed)
  541. else:
  542. out_unpacked = struct.unpack("dd", out_packed)
  543. expected_unpacked = struct.unpack("dd", expected_packed)
  544. out_is_nan = [math.isnan(o) for o in out_unpacked]
  545. expected_is_nan = [math.isnan(e) for e in expected_unpacked]
  546. if any(out_is_nan):
  547. nan_comparision = [o == e for o, e in zip(out_is_nan, expected_is_nan)]
  548. if all(nan_comparision):
  549. print(f"Pass NaN comparision")
  550. return True
  551. # print(f"compare {out_unpacked} and {expected_unpacked}")
  552. result = [o == e for o, e in zip(out_unpacked, expected_unpacked)]
  553. if not all(result):
  554. result = [
  555. "{:.7g}".format(o) == "{:.7g}".format(e)
  556. for o, e in zip(out_unpacked, expected_packed)
  557. ]
  558. return all(result)
  559. def simple_value_comparison(out, expected):
  560. """
  561. compare out of simple types which may like val:i32, val:f64 and so on
  562. """
  563. if expected == "2.360523e+13:f32" and out == "2.360522e+13:f32":
  564. # one case in float_literals.wast, due to float precision of python
  565. return True
  566. if expected == "1.797693e+308:f64" and out == "inf:f64":
  567. # one case in float_misc.wast:
  568. # (assert_return (invoke "f64.add" (f64.const 0x1.fffffffffffffp+1023)
  569. # (f64.const 0x1.fffffffffffffp+969))
  570. # (f64.const 0x1.fffffffffffffp+1023))
  571. # the add result in x86_32 is inf
  572. return True
  573. out_val, out_type = out.split(':')
  574. expected_val, expected_type = expected.split(':')
  575. if not out_type == expected_type:
  576. return False
  577. out_val, _ = parse_simple_const_w_type(out_val, out_type)
  578. expected_val, _ = parse_simple_const_w_type(expected_val, expected_type)
  579. if out_val == expected_val \
  580. or (math.isnan(out_val) and math.isnan(expected_val)):
  581. return True
  582. if "i32" == expected_type:
  583. out_val_binary = struct.pack('I', out_val) if out_val > 0 \
  584. else struct.pack('i', out_val)
  585. expected_val_binary = struct.pack('I', expected_val) \
  586. if expected_val > 0 \
  587. else struct.pack('i', expected_val)
  588. elif "i64" == expected_type:
  589. out_val_binary = struct.pack('Q', out_val) if out_val > 0 \
  590. else struct.pack('q', out_val)
  591. expected_val_binary = struct.pack('Q', expected_val) \
  592. if expected_val > 0 \
  593. else struct.pack('q', expected_val)
  594. elif "f32" == expected_type:
  595. out_val_binary = struct.pack('f', out_val)
  596. expected_val_binary = struct.pack('f', expected_val)
  597. elif "f64" == expected_type:
  598. out_val_binary = struct.pack('d', out_val)
  599. expected_val_binary = struct.pack('d', expected_val)
  600. elif "ref.extern" == expected_type:
  601. out_val_binary = out_val
  602. expected_val_binary = expected_val
  603. elif "ref.host" == expected_type:
  604. out_val_binary = out_val
  605. expected_val_binary = expected_val
  606. else:
  607. assert(0), "unknown 'expected_type' {}".format(expected_type)
  608. if out_val_binary == expected_val_binary:
  609. return True
  610. if expected_type in ["f32", "f64"]:
  611. # compare with a lower precision
  612. out_str = "{:.7g}".format(out_val)
  613. expected_str = "{:.7g}".format(expected_val)
  614. if out_str == expected_str:
  615. return True
  616. return False
  617. def value_comparison(out, expected):
  618. if out == expected:
  619. return True
  620. if not expected:
  621. return False
  622. if not out in ["ref.array", "ref.struct", "ref.func", "ref.any", "ref.i31"]:
  623. assert(':' in out), "out should be in a form likes numbers:type, but {}".format(out)
  624. if not expected in ["ref.array", "ref.struct", "ref.func", "ref.any", "ref.i31"]:
  625. assert(':' in expected), "expected should be in a form likes numbers:type, but {}".format(expected)
  626. if 'v128' in out:
  627. return vector_value_comparison(out, expected)
  628. else:
  629. return simple_value_comparison(out, expected)
  630. def is_result_match_expected(out, expected):
  631. # compare value instead of comparing strings of values
  632. return value_comparison(out, expected)
  633. def test_assert(r, opts, mode, cmd, expected):
  634. log("Testing(%s) %s = %s" % (mode, cmd, expected))
  635. out = invoke(r, opts, cmd)
  636. if '\n' in out or ' ' in out:
  637. outs = [''] + out.split('\n')[1:]
  638. out = outs[-1]
  639. if mode=='trap':
  640. o = re.sub('^Exception: ', '', out)
  641. e = re.sub('^Exception: ', '', expected)
  642. if o.find(e) >= 0 or e.find(o) >= 0:
  643. return True
  644. if mode=='exhaustion':
  645. o = re.sub('^Exception: ', '', out)
  646. expected = 'Exception: stack overflow'
  647. e = re.sub('^Exception: ', '', expected)
  648. if o.find(e) >= 0 or e.find(o) >= 0:
  649. return True
  650. ## 0x9:i32,-0x1:i32 -> ['0x9:i32', '-0x1:i32']
  651. expected_list = re.split(',', expected)
  652. out_list = re.split(',', out)
  653. if len(expected_list) != len(out_list):
  654. raise Exception("Failed:\n Results count incorrect:\n expected: '%s'\n got: '%s'" % (expected, out))
  655. for i in range(len(expected_list)):
  656. if not is_result_match_expected(out_list[i], expected_list[i]):
  657. raise Exception("Failed:\n Result %d incorrect:\n expected: '%s'\n got: '%s'" % (i, expected_list[i], out_list[i]))
  658. return True
  659. def test_assert_return(r, opts, form):
  660. """
  661. m. to search a pattern like (assert_return (invoke function_name ... ) ...)
  662. n. to search a pattern like (assert_return (invoke $module_name function_name ... ) ...)
  663. """
  664. # params, return
  665. m = re.search('^\(assert_return\s+\(invoke\s+"((?:[^"]|\\\")*)"\s+(\(.*\))\s*\)\s*(\(.*\))\s*\)\s*$', form, re.S)
  666. # judge if assert_return cmd includes the module name
  667. n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"((?:[^"]|\\\")*)"\s+(\(.*\))\s*\)\s*(\(.*\))\s*\)\s*$', form, re.S)
  668. # print("assert_return with {}".format(form))
  669. if not m:
  670. # no params, return
  671. m = re.search('^\(assert_return\s+\(invoke\s+"((?:[^"]|\\\")*)"\s*\)\s+()(\(.*\))\s*\)\s*$', form, re.S)
  672. if not m:
  673. # params, no return
  674. m = re.search('^\(assert_return\s+\(invoke\s+"([^"]*)"\s+(\(.*\))()\s*\)\s*\)\s*$', form, re.S)
  675. if not m:
  676. # no params, no return
  677. m = re.search('^\(assert_return\s+\(invoke\s+"([^"]*)"\s*()()\)\s*\)\s*$', form, re.S)
  678. if not m:
  679. # params, return
  680. if not n:
  681. # no params, return
  682. n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"((?:[^"]|\\\")*)"\s*\)\s+()(\(.*\))\s*\)\s*$', form, re.S)
  683. if not n:
  684. # params, no return
  685. n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"\s+(\(.*\))()\s*\)\s*\)\s*$', form, re.S)
  686. if not n:
  687. # no params, no return
  688. n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"*()()\)\s*\)\s*$', form, re.S)
  689. if not m and not n:
  690. if re.search('^\(assert_return\s+\(get.*\).*\)$', form, re.S):
  691. log("ignoring assert_return get");
  692. return
  693. else:
  694. raise Exception("unparsed assert_return: '%s'" % form)
  695. if m and not n:
  696. func = m.group(1)
  697. if ' ' in func:
  698. func = func.replace(' ', '\\')
  699. if m.group(2) == '':
  700. args = []
  701. else:
  702. #args = [re.split(' +', v)[1].replace('_', "") for v in re.split("\)\s*\(", m.group(2)[1:-1])]
  703. # split arguments with ')spaces(', remove leading and tailing ) and (
  704. args_type_and_value = re.split(r'\)\s+\(', m.group(2)[1:-1])
  705. args_type_and_value = [s.replace('_', '') for s in args_type_and_value]
  706. # args are in two forms:
  707. # f32.const -0x1.000001fffffffffffp-50
  708. # v128.const i32x4 0 0 0 0
  709. args = []
  710. for arg in args_type_and_value:
  711. # remove leading and tailing spaces, it might confuse following assertions
  712. arg = arg.strip()
  713. splitted = re.split('\s+', arg)
  714. splitted = [s for s in splitted if s]
  715. if splitted[0] in ["i32.const", "i64.const"]:
  716. assert(2 == len(splitted)), "{} should have two parts".format(splitted)
  717. # in wast 01234 means 1234
  718. # in c 0123 means 83 in oct
  719. number, _ = parse_simple_const_w_type(splitted[1], splitted[0][:3])
  720. args.append(str(number))
  721. elif splitted[0] in ["f32.const", "f64.const"]:
  722. # let strtof or strtod handle original arguments
  723. assert(2 == len(splitted)), "{} should have two parts".format(splitted)
  724. args.append(splitted[1])
  725. elif "v128.const" == splitted[0]:
  726. assert(len(splitted) > 2), "{} should have more than two parts".format(splitted)
  727. numbers, _ = cast_v128_to_i64x2(splitted[2:], 'v128', splitted[1])
  728. assert(len(numbers) == 2), "has to reform arguments into i64x2"
  729. args.append(f"{numbers[0]:#x}\{numbers[1]:#x}")
  730. elif "ref.null" == splitted[0]:
  731. args.append("null")
  732. elif "ref.extern" == splitted[0]:
  733. number, _ = parse_simple_const_w_type(splitted[1], splitted[0])
  734. args.append(str(number))
  735. elif "ref.host" == splitted[0]:
  736. number, _ = parse_simple_const_w_type(splitted[1], splitted[0])
  737. args.append(str(number))
  738. else:
  739. assert(0), "an unkonwn parameter type"
  740. if m.group(3) == '':
  741. returns= []
  742. else:
  743. returns = re.split("\)\s*\(", m.group(3)[1:-1])
  744. # processed numbers in strings
  745. if len(returns) == 1 and returns[0] in ["ref.array", "ref.struct", "ref.i31",
  746. "ref.eq", "ref.any", "ref.extern",
  747. "ref.func", "ref.null"]:
  748. expected = [returns[0]]
  749. elif len(returns) == 1 and returns[0] in ["func:ref.null", "any:ref.null",
  750. "extern:ref.null"]:
  751. expected = [returns[0]]
  752. else:
  753. expected = [parse_assertion_value(v)[1] for v in returns]
  754. expected = ",".join(expected)
  755. test_assert(r, opts, "return", "%s %s" % (func, " ".join(args)), expected)
  756. elif not m and n:
  757. module = temp_module_table[n.group(1)].split(".wasm")[0]
  758. # assume the cmd is (assert_return(invoke $ABC "func")).
  759. # run the ABC.wasm firstly
  760. if test_aot:
  761. r = compile_wasm_to_aot(module+".wasm", module+".aot", True, opts, r)
  762. try:
  763. assert_prompt(r, ['Compile success'], opts.start_timeout, False)
  764. except:
  765. _, exc, _ = sys.exc_info()
  766. log("Run wamrc failed:\n got: '%s'" % r.buf)
  767. sys.exit(1)
  768. r = run_wasm_with_repl(module+".wasm", module+".aot" if test_aot else module, opts, r)
  769. # Wait for the initial prompt
  770. try:
  771. assert_prompt(r, ['webassembly> '], opts.start_timeout, False)
  772. except:
  773. _, exc, _ = sys.exc_info()
  774. raise Exception("Failed:\n expected: '%s'\n got: '%s'" % \
  775. (repr(exc), r.buf))
  776. func = n.group(2)
  777. if ' ' in func:
  778. func = func.replace(' ', '\\')
  779. if n.group(3) == '':
  780. args=[]
  781. else:
  782. # convert (ref.null extern/func) into (ref.null null)
  783. n1 = n.group(3).replace("(ref.null extern)", "(ref.null null)")
  784. n1 = n1.replace("ref.null func)", "(ref.null null)")
  785. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", n1[1:-1])]
  786. _, expected = parse_assertion_value(n.group(4)[1:-1])
  787. test_assert(r, opts, "return", "%s %s" % (func, " ".join(args)), expected)
  788. def test_assert_trap(r, opts, form):
  789. # params
  790. m = re.search('^\(assert_trap\s+\(invoke\s+"([^"]*)"\s+(\(.*\))\s*\)\s*"([^"]+)"\s*\)\s*$', form)
  791. # judge if assert_return cmd includes the module name
  792. n = re.search('^\(assert_trap\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"\s+(\(.*\))\s*\)\s*"([^"]+)"\s*\)\s*$', form, re.S)
  793. if not m:
  794. # no params
  795. m = re.search('^\(assert_trap\s+\(invoke\s+"([^"]*)"\s*()\)\s*"([^"]+)"\s*\)\s*$', form)
  796. if not m:
  797. if not n:
  798. # no params
  799. n = re.search('^\(assert_trap\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"\s*()\)\s*"([^"]+)"\s*\)\s*$', form, re.S)
  800. if not m and not n:
  801. raise Exception("unparsed assert_trap: '%s'" % form)
  802. if m and not n:
  803. func = m.group(1)
  804. if m.group(2) == '':
  805. args = []
  806. else:
  807. # convert (ref.null extern/func) into (ref.null null)
  808. m1 = m.group(2).replace("(ref.null extern)", "(ref.null null)")
  809. m1 = m1.replace("ref.null func)", "(ref.null null)")
  810. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", m1[1:-1])]
  811. expected = "Exception: %s" % m.group(3)
  812. test_assert(r, opts, "trap", "%s %s" % (func, " ".join(args)), expected)
  813. elif not m and n:
  814. module = n.group(1)
  815. module = tempfile.gettempdir() + "/" + module
  816. # will trigger the module named in assert_return(invoke $ABC).
  817. # run the ABC.wasm firstly
  818. if test_aot:
  819. r = compile_wasm_to_aot(module+".wasm", module+".aot", True, opts, r)
  820. try:
  821. assert_prompt(r, ['Compile success'], opts.start_timeout, False)
  822. except:
  823. _, exc, _ = sys.exc_info()
  824. log("Run wamrc failed:\n got: '%s'" % r.buf)
  825. sys.exit(1)
  826. r = run_wasm_with_repl(module+".wasm", module+".aot" if test_aot else module, opts, r)
  827. # Wait for the initial prompt
  828. try:
  829. assert_prompt(r, ['webassembly> '], opts.start_timeout, False)
  830. except:
  831. _, exc, _ = sys.exc_info()
  832. raise Exception("Failed:\n expected: '%s'\n got: '%s'" % \
  833. (repr(exc), r.buf))
  834. func = n.group(2)
  835. if n.group(3) == '':
  836. args = []
  837. else:
  838. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", n.group(3)[1:-1])]
  839. expected = "Exception: %s" % n.group(4)
  840. test_assert(r, opts, "trap", "%s %s" % (func, " ".join(args)), expected)
  841. def test_assert_exhaustion(r,opts,form):
  842. # params
  843. m = re.search('^\(assert_exhaustion\s+\(invoke\s+"([^"]*)"\s+(\(.*\))\s*\)\s*"([^"]+)"\s*\)\s*$', form)
  844. if not m:
  845. # no params
  846. m = re.search('^\(assert_exhaustion\s+\(invoke\s+"([^"]*)"\s*()\)\s*"([^"]+)"\s*\)\s*$', form)
  847. if not m:
  848. raise Exception("unparsed assert_exhaustion: '%s'" % form)
  849. func = m.group(1)
  850. if m.group(2) == '':
  851. args = []
  852. else:
  853. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", m.group(2)[1:-1])]
  854. expected = "Exception: %s\n" % m.group(3)
  855. test_assert(r, opts, "exhaustion", "%s %s" % (func, " ".join(args)), expected)
  856. def do_invoke(r, opts, form):
  857. # params
  858. m = re.search('^\(invoke\s+"([^"]+)"\s+(\(.*\))\s*\)\s*$', form)
  859. if not m:
  860. # no params
  861. m = re.search('^\(invoke\s+"([^"]+)"\s*()\)\s*$', form)
  862. if not m:
  863. raise Exception("unparsed invoke: '%s'" % form)
  864. func = m.group(1)
  865. if ' ' in func:
  866. func = func.replace(' ', '\\')
  867. if m.group(2) == '':
  868. args = []
  869. else:
  870. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", m.group(2)[1:-1])]
  871. log("Invoking %s(%s)" % (
  872. func, ", ".join([str(a) for a in args])))
  873. invoke(r, opts, "%s %s" % (func, " ".join(args)))
  874. def skip_test(form, skip_list):
  875. for s in skip_list:
  876. if re.search(s, form):
  877. return True
  878. return False
  879. def compile_wast_to_wasm(form, wast_tempfile, wasm_tempfile, opts):
  880. log("Writing WAST module to '%s'" % wast_tempfile)
  881. with open(wast_tempfile, 'w') as file:
  882. file.write(form)
  883. log("Compiling WASM to '%s'" % wasm_tempfile)
  884. # default arguments
  885. if opts.gc:
  886. cmd = [opts.wast2wasm, "-u", "-d", wast_tempfile, "-o", wasm_tempfile]
  887. else:
  888. cmd = [opts.wast2wasm, "--enable-thread", "--no-check",
  889. wast_tempfile, "-o", wasm_tempfile ]
  890. # remove reference-type and bulk-memory enabling options since a WABT
  891. # commit 30c1e983d30b33a8004b39fd60cbd64477a7956c
  892. # Enable reference types by default (#1729)
  893. log("Running: %s" % " ".join(cmd))
  894. try:
  895. subprocess.check_call(cmd)
  896. except subprocess.CalledProcessError as e:
  897. print(str(e))
  898. return False
  899. return True
  900. def compile_wasm_to_aot(wasm_tempfile, aot_tempfile, runner, opts, r, output = 'default'):
  901. log("Compiling AOT to '%s'" % aot_tempfile)
  902. cmd = [opts.aot_compiler]
  903. if test_target in aot_target_options_map:
  904. cmd += aot_target_options_map[test_target]
  905. if opts.sgx:
  906. cmd.append("-sgx")
  907. if not opts.simd:
  908. cmd.append("--disable-simd")
  909. if opts.xip:
  910. cmd.append("--enable-indirect-mode")
  911. cmd.append("--disable-llvm-intrinsics")
  912. if opts.multi_thread:
  913. cmd.append("--enable-multi-thread")
  914. if output == 'object':
  915. cmd.append("--format=object")
  916. elif output == 'ir':
  917. cmd.append("--format=llvmir-opt")
  918. # disable llvm link time optimization as it might convert
  919. # code of tail call into code of dead loop, and stack overflow
  920. # exception isn't thrown in several cases
  921. cmd.append("--disable-llvm-lto")
  922. # Bounds checks is disabled by default for 64-bit targets, to
  923. # use the hardware based bounds checks. But it is not supported
  924. # in QEMU with NuttX.
  925. # Enable bounds checks explicitly for all targets if running in QEMU.
  926. if opts.qemu:
  927. cmd.append("--bounds-checks=1")
  928. # RISCV64 requires -mcmodel=medany, which can be set by --size-level=1
  929. if test_target.startswith("riscv64"):
  930. cmd.append("--size-level=1")
  931. cmd += ["-o", aot_tempfile, wasm_tempfile]
  932. log("Running: %s" % " ".join(cmd))
  933. if not runner:
  934. subprocess.check_call(cmd)
  935. else:
  936. if (r != None):
  937. r.cleanup()
  938. r = Runner(cmd, no_pty=opts.no_pty)
  939. return r
  940. def run_wasm_with_repl(wasm_tempfile, aot_tempfile, opts, r):
  941. tmpfile = aot_tempfile if test_aot else wasm_tempfile
  942. log("Starting interpreter for module '%s'" % tmpfile)
  943. cmd_iwasm = [opts.interpreter, "--heap-size=0", "-v=5" if opts.verbose else "-v=0", "--repl", tmpfile]
  944. if opts.multi_module:
  945. cmd_iwasm.insert(1, "--module-path=" + (tempfile.gettempdir() if not opts.qemu else "/tmp" ))
  946. if opts.qemu:
  947. if opts.qemu_firmware == '':
  948. raise Exception("QEMU firmware missing")
  949. if opts.target.startswith("aarch64"):
  950. cmd = "qemu-system-aarch64 -cpu cortex-a53 -nographic -machine virt,virtualization=on,gic-version=3 -net none -chardev stdio,id=con,mux=on -serial chardev:con -mon chardev=con,mode=readline -kernel".split()
  951. cmd.append(opts.qemu_firmware)
  952. elif opts.target.startswith("thumbv7"):
  953. cmd = "qemu-system-arm -semihosting -M sabrelite -m 1024 -smp 1 -nographic -kernel".split()
  954. cmd.append(opts.qemu_firmware)
  955. elif opts.target.startswith("riscv32"):
  956. cmd = "qemu-system-riscv32 -semihosting -M virt,aclint=on -cpu rv32 -smp 1 -nographic -bios none -kernel".split()
  957. cmd.append(opts.qemu_firmware)
  958. elif opts.target.startswith("riscv64"):
  959. cmd = "qemu-system-riscv64 -semihosting -M virt,aclint=on -cpu rv64 -smp 1 -nographic -bios none -kernel".split()
  960. cmd.append(opts.qemu_firmware)
  961. else:
  962. raise Exception("Unknwon target for QEMU: %s" % opts.target)
  963. else:
  964. cmd = cmd_iwasm
  965. log("Running: %s" % " ".join(cmd))
  966. if (r != None):
  967. r.cleanup()
  968. r = Runner(cmd, no_pty=opts.no_pty)
  969. if opts.qemu:
  970. r.read_to_prompt(['nsh> '], 10)
  971. r.writeline("mount -t hostfs -o fs={} /tmp".format(tempfile.gettempdir()))
  972. r.read_to_prompt(['nsh> '], 10)
  973. r.writeline(" ".join(cmd_iwasm))
  974. return r
  975. def create_tmpfiles(wast_name):
  976. tempfiles = []
  977. tempfiles.append(create_tmp_file(".wast"))
  978. tempfiles.append(create_tmp_file(".wasm"))
  979. if test_aot:
  980. tempfiles.append(create_tmp_file(".aot"))
  981. # add these temp file to temporal repo, will be deleted when finishing the test
  982. temp_file_repo.extend(tempfiles)
  983. return tempfiles
  984. def test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile, opts, r, loadable = True):
  985. details_inside_ast = get_module_exp_from_assert(form)
  986. log("module is ....'%s'"%details_inside_ast[0])
  987. log("exception is ....'%s'"%details_inside_ast[1])
  988. # parse the module
  989. module = details_inside_ast[0]
  990. expected = details_inside_ast[1]
  991. if not compile_wast_to_wasm(module, wast_tempfile, wasm_tempfile, opts):
  992. raise Exception("compile wast to wasm failed")
  993. if test_aot:
  994. r = compile_wasm_to_aot(wasm_tempfile, aot_tempfile, True, opts, r)
  995. try:
  996. assert_prompt(r, ['Compile success'], opts.start_timeout, True)
  997. except:
  998. _, exc, _ = sys.exc_info()
  999. if (r.buf.find(expected) >= 0):
  1000. log("Out exception includes expected one, pass:")
  1001. log(" Expected: %s" % expected)
  1002. log(" Got: %s" % r.buf)
  1003. return
  1004. else:
  1005. log("Run wamrc failed:\n expected: '%s'\n got: '%s'" % \
  1006. (expected, r.buf))
  1007. sys.exit(1)
  1008. r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1009. # Some module couldn't load so will raise an error directly, so shell prompt won't show here
  1010. if loadable:
  1011. # Wait for the initial prompt
  1012. try:
  1013. assert_prompt(r, ['webassembly> '], opts.start_timeout, True)
  1014. except:
  1015. _, exc, _ = sys.exc_info()
  1016. if (r.buf.find(expected) >= 0):
  1017. log("Out exception includes expected one, pass:")
  1018. log(" Expected: %s" %expected)
  1019. log(" Got: %s" % r.buf)
  1020. else:
  1021. raise Exception("Failed:\n expected: '%s'\n got: '%s'" % \
  1022. (expected, r.buf))
  1023. if __name__ == "__main__":
  1024. opts = parser.parse_args(sys.argv[1:])
  1025. # print('Input param :',opts)
  1026. if opts.aot: test_aot = True
  1027. # default x86_64
  1028. test_target = opts.target
  1029. if opts.rundir: os.chdir(opts.rundir)
  1030. if opts.log_file: log_file = open(opts.log_file, "a")
  1031. if opts.debug_file: debug_file = open(opts.debug_file, "a")
  1032. if opts.interpreter.endswith(".py"):
  1033. SKIP_TESTS = PY_SKIP_TESTS
  1034. else:
  1035. SKIP_TESTS = C_SKIP_TESTS
  1036. wast_tempfile = create_tmp_file(".wast")
  1037. wasm_tempfile = create_tmp_file(".wasm")
  1038. if test_aot:
  1039. aot_tempfile = create_tmp_file(".aot")
  1040. ret_code = 0
  1041. try:
  1042. log("\n################################################")
  1043. log("### Testing %s" % opts.test_file.name)
  1044. log("################################################")
  1045. forms = read_forms(opts.test_file.read())
  1046. r = None
  1047. for form in forms:
  1048. # log("\n### Current Case is " + form + "\n")
  1049. if ";;" == form[0:2]:
  1050. log(form)
  1051. elif skip_test(form, SKIP_TESTS):
  1052. log("Skipping test: %s" % form[0:60])
  1053. elif re.match("^\(assert_trap\s+\(module", form):
  1054. test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1055. elif re.match("^\(assert_exhaustion\\b.*", form):
  1056. test_assert_exhaustion(r, opts, form)
  1057. elif re.match("^\(assert_unlinkable\\b.*", form):
  1058. test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile if test_aot else None, opts, r, False)
  1059. elif re.match("^\(assert_malformed\\b.*", form):
  1060. # remove comments in wast
  1061. form,n = re.subn(";;.*\n", "", form)
  1062. m = re.match("^\(assert_malformed\s*\(module binary\s*(\".*\").*\)\s*\"(.*)\"\s*\)$", form, re.DOTALL)
  1063. if m:
  1064. # workaround: spec test changes error message to "malformed" while iwasm still use "invalid"
  1065. error_msg = m.group(2).replace("malformed", "invalid")
  1066. log("Testing(malformed)")
  1067. with open(wasm_tempfile, 'wb') as f:
  1068. s = m.group(1)
  1069. while s:
  1070. res = re.match("[^\"]*\"([^\"]*)\"(.*)", s, re.DOTALL)
  1071. if IS_PY_3:
  1072. context = res.group(1).replace("\\", "\\x").encode("latin1").decode("unicode-escape").encode("latin1")
  1073. f.write(context)
  1074. else:
  1075. f.write(res.group(1).replace("\\", "\\x").decode("string-escape"))
  1076. s = res.group(2)
  1077. # compile wasm to aot
  1078. if test_aot:
  1079. r = compile_wasm_to_aot(wasm_tempfile, aot_tempfile, True, opts, r)
  1080. try:
  1081. assert_prompt(r, ['Compile success'], opts.start_timeout, True)
  1082. except:
  1083. _, exc, _ = sys.exc_info()
  1084. if (r.buf.find(error_msg) >= 0):
  1085. log("Out exception includes expected one, pass:")
  1086. log(" Expected: %s" % error_msg)
  1087. log(" Got: %s" % r.buf)
  1088. else:
  1089. log("Run wamrc failed:\n expected: '%s'\n got: '%s'" % \
  1090. (error_msg, r.buf))
  1091. continue
  1092. r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1093. if (error_msg == "unexpected end of section or function"):
  1094. # one case in binary.wast
  1095. assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True)
  1096. elif (error_msg == "invalid value type"):
  1097. # one case in binary.wast
  1098. assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True)
  1099. elif (error_msg == "length out of bounds"):
  1100. # one case in custom.wast
  1101. assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True)
  1102. elif (error_msg == "integer representation too long"):
  1103. # several cases in binary-leb128.wast
  1104. assert_prompt(r, ["invalid section id", error_msg], opts.start_timeout, True)
  1105. elif re.match("^\(assert_malformed\s*\(module quote", form):
  1106. log("ignoring assert_malformed module quote")
  1107. else:
  1108. log("unrecognized assert_malformed")
  1109. elif re.match("^\(assert_return[_a-z]*_nan\\b.*", form):
  1110. log("ignoring assert_return_.*_nan")
  1111. pass
  1112. elif re.match(".*\(invoke\s+\$\\b.*", form):
  1113. # invoke a particular named module's function
  1114. if form.startswith("(assert_return"):
  1115. test_assert_return(r,opts,form)
  1116. elif form.startswith("(assert_trap"):
  1117. test_assert_trap(r,opts,form)
  1118. elif re.match("^\(module\\b.*", form):
  1119. # if the module includes the particular name startswith $
  1120. m = re.search("^\(module\s+\$.\S+", form)
  1121. if m:
  1122. # get module name
  1123. module_name = re.split('\$', m.group(0).strip())[1]
  1124. if module_name:
  1125. # create temporal files
  1126. temp_files = create_tmpfiles(module_name)
  1127. if not compile_wast_to_wasm(form, temp_files[0], temp_files[1], opts):
  1128. raise Exception("compile wast to wasm failed")
  1129. if test_aot:
  1130. r = compile_wasm_to_aot(temp_files[1], temp_files[2], True, opts, r)
  1131. try:
  1132. assert_prompt(r, ['Compile success'], opts.start_timeout, False)
  1133. except:
  1134. _, exc, _ = sys.exc_info()
  1135. log("Run wamrc failed:\n got: '%s'" % r.buf)
  1136. sys.exit(1)
  1137. temp_module_table[module_name] = temp_files[1]
  1138. r = run_wasm_with_repl(temp_files[1], temp_files[2] if test_aot else None, opts, r)
  1139. else:
  1140. if not compile_wast_to_wasm(form, wast_tempfile, wasm_tempfile, opts):
  1141. raise Exception("compile wast to wasm failed")
  1142. if test_aot:
  1143. r = compile_wasm_to_aot(wasm_tempfile, aot_tempfile, True, opts, r)
  1144. try:
  1145. assert_prompt(r, ['Compile success'], opts.start_timeout, False)
  1146. except:
  1147. _, exc, _ = sys.exc_info()
  1148. log("Run wamrc failed:\n got: '%s'" % r.buf)
  1149. sys.exit(1)
  1150. r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1151. # Wait for the initial prompt
  1152. try:
  1153. assert_prompt(r, ['webassembly> '], opts.start_timeout, False)
  1154. except:
  1155. _, exc, _ = sys.exc_info()
  1156. raise Exception("Failed:\n expected: '%s'\n got: '%s'" % \
  1157. (repr(exc), r.buf))
  1158. elif re.match("^\(assert_return\\b.*", form):
  1159. assert(r), "iwasm repl runtime should be not null"
  1160. test_assert_return(r, opts, form)
  1161. elif re.match("^\(assert_trap\\b.*", form):
  1162. test_assert_trap(r, opts, form)
  1163. elif re.match("^\(invoke\\b.*", form):
  1164. assert(r), "iwasm repl runtime should be not null"
  1165. do_invoke(r, opts, form)
  1166. elif re.match("^\(assert_invalid\\b.*", form):
  1167. test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1168. elif re.match("^\(register\\b.*", form):
  1169. # get module's new name from the register cmd
  1170. name_new =re.split('\"',re.search('\".*\"',form).group(0))[1]
  1171. if name_new:
  1172. new_module = os.path.join(tempfile.gettempdir(), name_new + ".wasm")
  1173. shutil.copyfile(temp_module_table.get(name_new, wasm_tempfile), new_module)
  1174. # add new_module copied from the old into temp_file_repo[]
  1175. temp_file_repo.append(new_module)
  1176. if test_aot:
  1177. new_module_aot = os.path.join(tempfile.gettempdir(), name_new + ".aot")
  1178. r = compile_wasm_to_aot(new_module, new_module_aot, True, opts, r)
  1179. try:
  1180. assert_prompt(r, ['Compile success'], opts.start_timeout, True)
  1181. except:
  1182. raise Exception("compile wasm to aot failed")
  1183. # add aot module into temp_file_repo[]
  1184. temp_file_repo.append(new_module_aot)
  1185. else:
  1186. # there is no name defined in register cmd
  1187. raise Exception("can not find module name from the register")
  1188. else:
  1189. raise Exception("unrecognized form '%s...'" % form[0:40])
  1190. except Exception as e:
  1191. traceback.print_exc()
  1192. print("THE FINAL EXCEPTION IS {}".format(e))
  1193. ret_code = 101
  1194. shutil.copyfile(wasm_tempfile, os.path.join(opts.log_dir, os.path.basename(wasm_tempfile)))
  1195. if opts.aot or opts.xip:
  1196. shutil.copyfile(aot_tempfile, os.path.join(opts.log_dir,os.path.basename(aot_tempfile)))
  1197. if "indirect-mode" in str(e):
  1198. compile_wasm_to_aot(wasm_tempfile, aot_tempfile, None, opts, None, "object")
  1199. shutil.copyfile(aot_tempfile, os.path.join(opts.log_dir,os.path.basename(aot_tempfile)+'.o'))
  1200. subprocess.check_call(["llvm-objdump", "-r", aot_tempfile])
  1201. compile_wasm_to_aot(wasm_tempfile, aot_tempfile, None, opts, None, "ir")
  1202. shutil.copyfile(aot_tempfile, os.path.join(opts.log_dir,os.path.basename(aot_tempfile)+".ir"))
  1203. else:
  1204. ret_code = 0
  1205. finally:
  1206. if not opts.no_cleanup:
  1207. log("Removing tempfiles")
  1208. os.remove(wast_tempfile)
  1209. os.remove(wasm_tempfile)
  1210. if test_aot:
  1211. os.remove(aot_tempfile)
  1212. # remove the files under /tempfiles/ and copy of .wasm files
  1213. if temp_file_repo:
  1214. for t in temp_file_repo:
  1215. if(len(str(t))!=0 and os.path.exists(t)):
  1216. os.remove(t)
  1217. log("### End testing %s" % opts.test_file.name)
  1218. else:
  1219. log("Leaving tempfiles: %s" % ([wast_tempfile, wasm_tempfile]))
  1220. sys.exit(ret_code)