runtest.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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('--eh', default=False, action='store_true',
  258. help="Enable Exception Handling")
  259. parser.add_argument('--multi-module', default=False, action='store_true',
  260. help="Enable Multi-thread")
  261. parser.add_argument('--multi-thread', default=False, action='store_true',
  262. help="Enable Multi-thread")
  263. parser.add_argument('--gc', default=False, action='store_true',
  264. help='Test with GC')
  265. parser.add_argument('--qemu', default=False, action='store_true',
  266. help="Enable QEMU")
  267. parser.add_argument('--qemu-firmware', default='', help="Firmware required by qemu")
  268. parser.add_argument('--verbose', default=False, action='store_true',
  269. help='show more logs')
  270. # regex patterns of tests to skip
  271. C_SKIP_TESTS = ()
  272. PY_SKIP_TESTS = (
  273. # names.wast
  274. 'invoke \"~!',
  275. # conversions.wast
  276. '18446742974197923840.0',
  277. '18446744073709549568.0',
  278. '9223372036854775808',
  279. 'reinterpret_f.*nan',
  280. # endianness
  281. '.const 0x1.fff' )
  282. def read_forms(string):
  283. forms = []
  284. form = ""
  285. depth = 0
  286. line = 0
  287. pos = 0
  288. while pos < len(string):
  289. # Keep track of line number
  290. if string[pos] == '\n': line += 1
  291. # Handle top-level elements
  292. if depth == 0:
  293. # Add top-level comments
  294. if string[pos:pos+2] == ";;":
  295. end = string.find("\n", pos)
  296. if end == -1: end == len(string)
  297. forms.append(string[pos:end])
  298. pos = end
  299. continue
  300. # TODO: handle nested multi-line comments
  301. if string[pos:pos+2] == "(;":
  302. # Skip multi-line comment
  303. end = string.find(";)", pos)
  304. if end == -1:
  305. raise Exception("mismatch multiline comment on line %d: '%s'" % (
  306. line, string[pos:pos+80]))
  307. pos = end+2
  308. continue
  309. # Ignore whitespace between top-level forms
  310. if string[pos] in (' ', '\n', '\t'):
  311. pos += 1
  312. continue
  313. # Read a top-level form
  314. if string[pos] == '(': depth += 1
  315. if string[pos] == ')': depth -= 1
  316. if depth == 0 and not form:
  317. raise Exception("garbage on line %d: '%s'" % (
  318. line, string[pos:pos+80]))
  319. form += string[pos]
  320. if depth == 0 and form:
  321. forms.append(form)
  322. form = ""
  323. pos += 1
  324. return forms
  325. def get_module_exp_from_assert(string):
  326. depth = 0
  327. pos = 0
  328. module = ""
  329. exception = ""
  330. start_record = False
  331. result = []
  332. while pos < len(string):
  333. # record from the " (module "
  334. if string[pos:pos+7] == "(module":
  335. start_record = True
  336. if start_record:
  337. if string[pos] == '(' : depth += 1
  338. if string[pos] == ')' : depth -= 1
  339. module += string[pos]
  340. # if we get all (module ) .
  341. if depth == 0 and module:
  342. result.append(module)
  343. start_record = False
  344. # get expected exception
  345. if string[pos] == '"':
  346. end = string.find("\"", pos+1)
  347. if end != -1:
  348. end_rel = string.find("\"",end+1)
  349. if end_rel == -1:
  350. result.append(string[pos+1:end])
  351. pos += 1
  352. return result
  353. def string_to_unsigned(number_in_string, lane_type):
  354. if not lane_type in ['i8x16', 'i16x8', 'i32x4', 'i64x2']:
  355. raise Exception("invalid value {} and type {} and lane_type {}".format(number_in_string, type, lane_type))
  356. number = int(number_in_string, 16) if '0x' in number_in_string else int(number_in_string)
  357. if "i8x16" == lane_type:
  358. if number < 0:
  359. packed = struct.pack('b', number)
  360. number = struct.unpack('B', packed)[0]
  361. elif "i16x8" == lane_type:
  362. if number < 0:
  363. packed = struct.pack('h', number)
  364. number = struct.unpack('H', packed)[0]
  365. elif "i32x4" == lane_type:
  366. if number < 0:
  367. packed = struct.pack('i', number)
  368. number = struct.unpack('I', packed)[0]
  369. else: # "i64x2" == lane_type:
  370. if number < 0:
  371. packed = struct.pack('q', number)
  372. number = struct.unpack('Q', packed)[0]
  373. return number
  374. def cast_v128_to_i64x2(numbers, type, lane_type):
  375. numbers = [n.replace("_", "") for n in numbers]
  376. if "i8x16" == lane_type:
  377. assert(16 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  378. # str -> int
  379. numbers = [string_to_unsigned(n, lane_type) for n in numbers]
  380. # i8 -> i64
  381. packed = struct.pack(16 * "B", *numbers)
  382. elif "i16x8" == lane_type:
  383. assert(8 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  384. # str -> int
  385. numbers = [string_to_unsigned(n, lane_type) for n in numbers]
  386. # i16 -> i64
  387. packed = struct.pack(8 * "H", *numbers)
  388. elif "i32x4" == lane_type:
  389. assert(4 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  390. # str -> int
  391. numbers = [string_to_unsigned(n, lane_type) for n in numbers]
  392. # i32 -> i64
  393. packed = struct.pack(4 * "I", *numbers)
  394. elif "i64x2" == lane_type:
  395. assert(2 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  396. # str -> int
  397. numbers = [string_to_unsigned(n, lane_type) for n in numbers]
  398. # i64 -> i64
  399. packed = struct.pack(2 * "Q", *numbers)
  400. elif "f32x4" == lane_type:
  401. assert(4 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  402. # str -> int
  403. numbers = [parse_simple_const_w_type(n, "f32")[0] for n in numbers]
  404. # f32 -> i64
  405. packed = struct.pack(4 * "f", *numbers)
  406. elif "f64x2" == lane_type:
  407. assert(2 == len(numbers)), "{} should like {}".format(numbers, lane_type)
  408. # str -> int
  409. numbers = [parse_simple_const_w_type(n, "f64")[0] for n in numbers]
  410. # f64 -> i64
  411. packed = struct.pack(2 * "d", *numbers)
  412. else:
  413. raise Exception("invalid value {} and type {} and lane_type {}".format(numbers, type, lane_type))
  414. assert(packed)
  415. unpacked = struct.unpack("Q Q", packed)
  416. return unpacked, f"[{unpacked[0]:#x} {unpacked[1]:#x}]:{lane_type}:v128"
  417. def parse_simple_const_w_type(number, type):
  418. number = number.replace('_', '')
  419. number = re.sub(r"nan\((ind|snan)\)", "nan", number)
  420. if type in ["i32", "i64"]:
  421. number = int(number, 16) if '0x' in number else int(number)
  422. return number, "0x{:x}:{}".format(number, type) \
  423. if number >= 0 \
  424. else "-0x{:x}:{}".format(0 - number, type)
  425. elif type in ["f32", "f64"]:
  426. if "nan:" in number:
  427. return float('nan'), "nan:{}".format(type)
  428. else:
  429. number = float.fromhex(number) if '0x' in number else float(number)
  430. return number, "{:.7g}:{}".format(number, type)
  431. elif type == "ref.null":
  432. if number == "func":
  433. return "func", "func:ref.null"
  434. elif number == "extern":
  435. return "extern", "extern:ref.null"
  436. elif number == "any":
  437. return "any", "any:ref.null"
  438. else:
  439. raise Exception("invalid value {} and type {}".format(number, type))
  440. elif type == "ref.extern":
  441. number = int(number, 16) if '0x' in number else int(number)
  442. return number, "0x{:x}:ref.extern".format(number)
  443. elif type == "ref.host":
  444. number = int(number, 16) if '0x' in number else int(number)
  445. return number, "0x{:x}:ref.host".format(number)
  446. else:
  447. raise Exception("invalid value {} and type {}".format(number, type))
  448. def parse_assertion_value(val):
  449. """
  450. Parse something like:
  451. "ref.null extern" in (assert_return (invoke "get-externref" (i32.const 0)) (ref.null extern))
  452. "ref.extern 1" in (assert_return (invoke "get-externref" (i32.const 1)) (ref.extern 1))
  453. "i32.const 0" in (assert_return (invoke "is_null-funcref" (i32.const 1)) (i32.const 0))
  454. in summary:
  455. type.const (sub-type) (val1 val2 val3 val4) ...
  456. type.const val
  457. ref.extern val
  458. ref.null ref_type
  459. ref.array
  460. ref.struct
  461. ref.func
  462. ref.i31
  463. """
  464. if not val:
  465. return None, ""
  466. splitted = re.split('\s+', val)
  467. splitted = [s for s in splitted if s]
  468. type = splitted[0].split(".")[0]
  469. lane_type = splitted[1] if len(splitted) > 2 else ""
  470. numbers = splitted[2:] if len(splitted) > 2 else splitted[1:]
  471. if type in ["i32", "i64", "f32", "f64"]:
  472. return parse_simple_const_w_type(numbers[0], type)
  473. elif type == "ref":
  474. if splitted[0] in ["ref.array", "ref.struct", "ref.func", "ref.i31"]:
  475. return splitted[0]
  476. # need to distinguish between "ref.null" and "ref.extern"
  477. return parse_simple_const_w_type(numbers[0], splitted[0])
  478. else:
  479. return cast_v128_to_i64x2(numbers, type, lane_type)
  480. def int2uint32(i):
  481. return i & 0xffffffff
  482. def int2int32(i):
  483. val = i & 0xffffffff
  484. if val & 0x80000000:
  485. return val - 0x100000000
  486. else:
  487. return val
  488. def int2uint64(i):
  489. return i & 0xffffffffffffffff
  490. def int2int64(i):
  491. val = i & 0xffffffffffffffff
  492. if val & 0x8000000000000000:
  493. return val - 0x10000000000000000
  494. else:
  495. return val
  496. def num_repr(i):
  497. if isinstance(i, int) or isinstance(i, long):
  498. return re.sub("L$", "", hex(i))
  499. else:
  500. return "%.16g" % i
  501. def hexpad16(i):
  502. return "0x%04x" % i
  503. def hexpad24(i):
  504. return "0x%06x" % i
  505. def hexpad32(i):
  506. return "0x%08x" % i
  507. def hexpad64(i):
  508. return "0x%016x" % i
  509. def invoke(r, args, cmd):
  510. r.writeline(cmd)
  511. return r.read_to_prompt(['\r\nwebassembly> ', '\nwebassembly> '],
  512. timeout=args.test_timeout)
  513. def vector_value_comparison(out, expected):
  514. """
  515. out likes "<number number>:v128"
  516. expected likes "[number number]:v128"
  517. """
  518. # print("vector value comparision {} vs {}".format(out, expected))
  519. out_val, out_type = out.split(':')
  520. # <number nubmer> => number number
  521. out_val = out_val[1:-1]
  522. expected_val, lane_type, expected_type = expected.split(':')
  523. # [number nubmer] => number number
  524. expected_val = expected_val[1:-1]
  525. assert("v128" == out_type), "out_type should be v128"
  526. assert("v128" == expected_type), "expected_type should be v128"
  527. if out_type != expected_type:
  528. return False
  529. out_val = out_val.split(" ")
  530. expected_val = expected_val.split(" ")
  531. # since i64x2
  532. out_packed = struct.pack("QQ", int(out_val[0], 16), int(out_val[1], 16))
  533. expected_packed = struct.pack("QQ",
  534. int(expected_val[0]) if not "0x" in expected_val[0] else int(expected_val[0], 16),
  535. int(expected_val[1]) if not "0x" in expected_val[1] else int(expected_val[1], 16))
  536. if lane_type in ["i8x16", "i16x8", "i32x4", "i64x2"]:
  537. return out_packed == expected_packed;
  538. else:
  539. assert(lane_type in ["f32x4", "f64x2"]), "unexpected lane_type"
  540. if "f32x4" == lane_type:
  541. out_unpacked = struct.unpack("ffff", out_packed)
  542. expected_unpacked = struct.unpack("ffff", expected_packed)
  543. else:
  544. out_unpacked = struct.unpack("dd", out_packed)
  545. expected_unpacked = struct.unpack("dd", expected_packed)
  546. out_is_nan = [math.isnan(o) for o in out_unpacked]
  547. expected_is_nan = [math.isnan(e) for e in expected_unpacked]
  548. if any(out_is_nan):
  549. nan_comparision = [o == e for o, e in zip(out_is_nan, expected_is_nan)]
  550. if all(nan_comparision):
  551. print(f"Pass NaN comparision")
  552. return True
  553. # print(f"compare {out_unpacked} and {expected_unpacked}")
  554. result = [o == e for o, e in zip(out_unpacked, expected_unpacked)]
  555. if not all(result):
  556. result = [
  557. "{:.7g}".format(o) == "{:.7g}".format(e)
  558. for o, e in zip(out_unpacked, expected_packed)
  559. ]
  560. return all(result)
  561. def simple_value_comparison(out, expected):
  562. """
  563. compare out of simple types which may like val:i32, val:f64 and so on
  564. """
  565. if expected == "2.360523e+13:f32" and out == "2.360522e+13:f32":
  566. # one case in float_literals.wast, due to float precision of python
  567. return True
  568. if expected == "1.797693e+308:f64" and out == "inf:f64":
  569. # one case in float_misc.wast:
  570. # (assert_return (invoke "f64.add" (f64.const 0x1.fffffffffffffp+1023)
  571. # (f64.const 0x1.fffffffffffffp+969))
  572. # (f64.const 0x1.fffffffffffffp+1023))
  573. # the add result in x86_32 is inf
  574. return True
  575. out_val, out_type = out.split(':')
  576. expected_val, expected_type = expected.split(':')
  577. if not out_type == expected_type:
  578. return False
  579. out_val, _ = parse_simple_const_w_type(out_val, out_type)
  580. expected_val, _ = parse_simple_const_w_type(expected_val, expected_type)
  581. if out_val == expected_val \
  582. or (math.isnan(out_val) and math.isnan(expected_val)):
  583. return True
  584. if "i32" == expected_type:
  585. out_val_binary = struct.pack('I', out_val) if out_val > 0 \
  586. else struct.pack('i', out_val)
  587. expected_val_binary = struct.pack('I', expected_val) \
  588. if expected_val > 0 \
  589. else struct.pack('i', expected_val)
  590. elif "i64" == expected_type:
  591. out_val_binary = struct.pack('Q', out_val) if out_val > 0 \
  592. else struct.pack('q', out_val)
  593. expected_val_binary = struct.pack('Q', expected_val) \
  594. if expected_val > 0 \
  595. else struct.pack('q', expected_val)
  596. elif "f32" == expected_type:
  597. out_val_binary = struct.pack('f', out_val)
  598. expected_val_binary = struct.pack('f', expected_val)
  599. elif "f64" == expected_type:
  600. out_val_binary = struct.pack('d', out_val)
  601. expected_val_binary = struct.pack('d', expected_val)
  602. elif "ref.extern" == expected_type:
  603. out_val_binary = out_val
  604. expected_val_binary = expected_val
  605. elif "ref.host" == expected_type:
  606. out_val_binary = out_val
  607. expected_val_binary = expected_val
  608. else:
  609. assert(0), "unknown 'expected_type' {}".format(expected_type)
  610. if out_val_binary == expected_val_binary:
  611. return True
  612. if expected_type in ["f32", "f64"]:
  613. # compare with a lower precision
  614. out_str = "{:.7g}".format(out_val)
  615. expected_str = "{:.7g}".format(expected_val)
  616. if out_str == expected_str:
  617. return True
  618. return False
  619. def value_comparison(out, expected):
  620. if out == expected:
  621. return True
  622. if not expected:
  623. return False
  624. if not out in ["ref.array", "ref.struct", "ref.func", "ref.any", "ref.i31"]:
  625. assert(':' in out), "out should be in a form likes numbers:type, but {}".format(out)
  626. if not expected in ["ref.array", "ref.struct", "ref.func", "ref.any", "ref.i31"]:
  627. assert(':' in expected), "expected should be in a form likes numbers:type, but {}".format(expected)
  628. if 'v128' in out:
  629. return vector_value_comparison(out, expected)
  630. else:
  631. return simple_value_comparison(out, expected)
  632. def is_result_match_expected(out, expected):
  633. # compare value instead of comparing strings of values
  634. return value_comparison(out, expected)
  635. def test_assert(r, opts, mode, cmd, expected):
  636. log("Testing(%s) %s = %s" % (mode, cmd, expected))
  637. out = invoke(r, opts, cmd)
  638. if '\n' in out or ' ' in out:
  639. outs = [''] + out.split('\n')[1:]
  640. out = outs[-1]
  641. if mode=='trap':
  642. o = re.sub('^Exception: ', '', out)
  643. e = re.sub('^Exception: ', '', expected)
  644. if o.find(e) >= 0 or e.find(o) >= 0:
  645. return True
  646. if mode=='exhaustion':
  647. o = re.sub('^Exception: ', '', out)
  648. expected = 'Exception: stack overflow'
  649. e = re.sub('^Exception: ', '', expected)
  650. if o.find(e) >= 0 or e.find(o) >= 0:
  651. return True
  652. # wasm-exception thrown out of function call, not a trap
  653. if mode=='wasmexception':
  654. o = re.sub('^Exception: ', '', out)
  655. e = re.sub('^Exception: ', '', expected)
  656. if o.find(e) >= 0 or e.find(o) >= 0:
  657. return True
  658. ## 0x9:i32,-0x1:i32 -> ['0x9:i32', '-0x1:i32']
  659. expected_list = re.split(',', expected)
  660. out_list = re.split(',', out)
  661. if len(expected_list) != len(out_list):
  662. raise Exception("Failed:\n Results count incorrect:\n expected: '%s'\n got: '%s'" % (expected, out))
  663. for i in range(len(expected_list)):
  664. if not is_result_match_expected(out_list[i], expected_list[i]):
  665. raise Exception("Failed:\n Result %d incorrect:\n expected: '%s'\n got: '%s'" % (i, expected_list[i], out_list[i]))
  666. return True
  667. def test_assert_return(r, opts, form):
  668. """
  669. m. to search a pattern like (assert_return (invoke function_name ... ) ...)
  670. n. to search a pattern like (assert_return (invoke $module_name function_name ... ) ...)
  671. """
  672. # params, return
  673. m = re.search('^\(assert_return\s+\(invoke\s+"((?:[^"]|\\\")*)"\s+(\(.*\))\s*\)\s*(\(.*\))\s*\)\s*$', form, re.S)
  674. # judge if assert_return cmd includes the module name
  675. n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"((?:[^"]|\\\")*)"\s+(\(.*\))\s*\)\s*(\(.*\))\s*\)\s*$', form, re.S)
  676. # print("assert_return with {}".format(form))
  677. if not m:
  678. # no params, return
  679. m = re.search('^\(assert_return\s+\(invoke\s+"((?:[^"]|\\\")*)"\s*\)\s+()(\(.*\))\s*\)\s*$', form, re.S)
  680. if not m:
  681. # params, no return
  682. m = re.search('^\(assert_return\s+\(invoke\s+"([^"]*)"\s+(\(.*\))()\s*\)\s*\)\s*$', form, re.S)
  683. if not m:
  684. # no params, no return
  685. m = re.search('^\(assert_return\s+\(invoke\s+"([^"]*)"\s*()()\)\s*\)\s*$', form, re.S)
  686. if not m:
  687. # params, return
  688. if not n:
  689. # no params, return
  690. n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"((?:[^"]|\\\")*)"\s*\)\s+()(\(.*\))\s*\)\s*$', form, re.S)
  691. if not n:
  692. # params, no return
  693. n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"\s+(\(.*\))()\s*\)\s*\)\s*$', form, re.S)
  694. if not n:
  695. # no params, no return
  696. n = re.search('^\(assert_return\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"*()()\)\s*\)\s*$', form, re.S)
  697. if not m and not n:
  698. if re.search('^\(assert_return\s+\(get.*\).*\)$', form, re.S):
  699. log("ignoring assert_return get");
  700. return
  701. else:
  702. raise Exception("unparsed assert_return: '%s'" % form)
  703. if m and not n:
  704. func = m.group(1)
  705. if ' ' in func:
  706. func = func.replace(' ', '\\')
  707. if m.group(2) == '':
  708. args = []
  709. else:
  710. #args = [re.split(' +', v)[1].replace('_', "") for v in re.split("\)\s*\(", m.group(2)[1:-1])]
  711. # split arguments with ')spaces(', remove leading and tailing ) and (
  712. args_type_and_value = re.split(r'\)\s+\(', m.group(2)[1:-1])
  713. args_type_and_value = [s.replace('_', '') for s in args_type_and_value]
  714. # args are in two forms:
  715. # f32.const -0x1.000001fffffffffffp-50
  716. # v128.const i32x4 0 0 0 0
  717. args = []
  718. for arg in args_type_and_value:
  719. # remove leading and tailing spaces, it might confuse following assertions
  720. arg = arg.strip()
  721. splitted = re.split('\s+', arg)
  722. splitted = [s for s in splitted if s]
  723. if splitted[0] in ["i32.const", "i64.const"]:
  724. assert(2 == len(splitted)), "{} should have two parts".format(splitted)
  725. # in wast 01234 means 1234
  726. # in c 0123 means 83 in oct
  727. number, _ = parse_simple_const_w_type(splitted[1], splitted[0][:3])
  728. args.append(str(number))
  729. elif splitted[0] in ["f32.const", "f64.const"]:
  730. # let strtof or strtod handle original arguments
  731. assert(2 == len(splitted)), "{} should have two parts".format(splitted)
  732. args.append(splitted[1])
  733. elif "v128.const" == splitted[0]:
  734. assert(len(splitted) > 2), "{} should have more than two parts".format(splitted)
  735. numbers, _ = cast_v128_to_i64x2(splitted[2:], 'v128', splitted[1])
  736. assert(len(numbers) == 2), "has to reform arguments into i64x2"
  737. args.append(f"{numbers[0]:#x}\{numbers[1]:#x}")
  738. elif "ref.null" == splitted[0]:
  739. args.append("null")
  740. elif "ref.extern" == splitted[0]:
  741. number, _ = parse_simple_const_w_type(splitted[1], splitted[0])
  742. args.append(str(number))
  743. elif "ref.host" == splitted[0]:
  744. number, _ = parse_simple_const_w_type(splitted[1], splitted[0])
  745. args.append(str(number))
  746. else:
  747. assert(0), "an unkonwn parameter type"
  748. if m.group(3) == '':
  749. returns= []
  750. else:
  751. returns = re.split("\)\s*\(", m.group(3)[1:-1])
  752. # processed numbers in strings
  753. if len(returns) == 1 and returns[0] in ["ref.array", "ref.struct", "ref.i31",
  754. "ref.eq", "ref.any", "ref.extern",
  755. "ref.func", "ref.null"]:
  756. expected = [returns[0]]
  757. elif len(returns) == 1 and returns[0] in ["func:ref.null", "any:ref.null",
  758. "extern:ref.null"]:
  759. expected = [returns[0]]
  760. else:
  761. expected = [parse_assertion_value(v)[1] for v in returns]
  762. expected = ",".join(expected)
  763. test_assert(r, opts, "return", "%s %s" % (func, " ".join(args)), expected)
  764. elif not m and n:
  765. module = temp_module_table[n.group(1)].split(".wasm")[0]
  766. # assume the cmd is (assert_return(invoke $ABC "func")).
  767. # run the ABC.wasm firstly
  768. if test_aot:
  769. r = compile_wasm_to_aot(module+".wasm", module+".aot", True, opts, r)
  770. try:
  771. assert_prompt(r, ['Compile success'], opts.start_timeout, False)
  772. except:
  773. _, exc, _ = sys.exc_info()
  774. log("Run wamrc failed:\n got: '%s'" % r.buf)
  775. sys.exit(1)
  776. r = run_wasm_with_repl(module+".wasm", module+".aot" if test_aot else module, opts, r)
  777. # Wait for the initial prompt
  778. try:
  779. assert_prompt(r, ['webassembly> '], opts.start_timeout, False)
  780. except:
  781. _, exc, _ = sys.exc_info()
  782. raise Exception("Failed:\n expected: '%s'\n got: '%s'" % \
  783. (repr(exc), r.buf))
  784. func = n.group(2)
  785. if ' ' in func:
  786. func = func.replace(' ', '\\')
  787. if n.group(3) == '':
  788. args=[]
  789. else:
  790. # convert (ref.null extern/func) into (ref.null null)
  791. n1 = n.group(3).replace("(ref.null extern)", "(ref.null null)")
  792. n1 = n1.replace("ref.null func)", "(ref.null null)")
  793. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", n1[1:-1])]
  794. _, expected = parse_assertion_value(n.group(4)[1:-1])
  795. test_assert(r, opts, "return", "%s %s" % (func, " ".join(args)), expected)
  796. def test_assert_trap(r, opts, form):
  797. # params
  798. m = re.search('^\(assert_trap\s+\(invoke\s+"([^"]*)"\s+(\(.*\))\s*\)\s*"([^"]+)"\s*\)\s*$', form)
  799. # judge if assert_return cmd includes the module name
  800. n = re.search('^\(assert_trap\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"\s+(\(.*\))\s*\)\s*"([^"]+)"\s*\)\s*$', form, re.S)
  801. if not m:
  802. # no params
  803. m = re.search('^\(assert_trap\s+\(invoke\s+"([^"]*)"\s*()\)\s*"([^"]+)"\s*\)\s*$', form)
  804. if not m:
  805. if not n:
  806. # no params
  807. n = re.search('^\(assert_trap\s+\(invoke\s+\$((?:[^\s])*)\s+"([^"]*)"\s*()\)\s*"([^"]+)"\s*\)\s*$', form, re.S)
  808. if not m and not n:
  809. raise Exception("unparsed assert_trap: '%s'" % form)
  810. if m and not n:
  811. func = m.group(1)
  812. if m.group(2) == '':
  813. args = []
  814. else:
  815. # convert (ref.null extern/func) into (ref.null null)
  816. m1 = m.group(2).replace("(ref.null extern)", "(ref.null null)")
  817. m1 = m1.replace("ref.null func)", "(ref.null null)")
  818. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", m1[1:-1])]
  819. expected = "Exception: %s" % m.group(3)
  820. test_assert(r, opts, "trap", "%s %s" % (func, " ".join(args)), expected)
  821. elif not m and n:
  822. module = n.group(1)
  823. module = tempfile.gettempdir() + "/" + module
  824. # will trigger the module named in assert_return(invoke $ABC).
  825. # run the ABC.wasm firstly
  826. if test_aot:
  827. r = compile_wasm_to_aot(module+".wasm", module+".aot", True, opts, r)
  828. try:
  829. assert_prompt(r, ['Compile success'], opts.start_timeout, False)
  830. except:
  831. _, exc, _ = sys.exc_info()
  832. log("Run wamrc failed:\n got: '%s'" % r.buf)
  833. sys.exit(1)
  834. r = run_wasm_with_repl(module+".wasm", module+".aot" if test_aot else module, opts, r)
  835. # Wait for the initial prompt
  836. try:
  837. assert_prompt(r, ['webassembly> '], opts.start_timeout, False)
  838. except:
  839. _, exc, _ = sys.exc_info()
  840. raise Exception("Failed:\n expected: '%s'\n got: '%s'" % \
  841. (repr(exc), r.buf))
  842. func = n.group(2)
  843. if n.group(3) == '':
  844. args = []
  845. else:
  846. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", n.group(3)[1:-1])]
  847. expected = "Exception: %s" % n.group(4)
  848. test_assert(r, opts, "trap", "%s %s" % (func, " ".join(args)), expected)
  849. def test_assert_exhaustion(r,opts,form):
  850. # params
  851. m = re.search('^\(assert_exhaustion\s+\(invoke\s+"([^"]*)"\s+(\(.*\))\s*\)\s*"([^"]+)"\s*\)\s*$', form)
  852. if not m:
  853. # no params
  854. m = re.search('^\(assert_exhaustion\s+\(invoke\s+"([^"]*)"\s*()\)\s*"([^"]+)"\s*\)\s*$', form)
  855. if not m:
  856. raise Exception("unparsed assert_exhaustion: '%s'" % form)
  857. func = m.group(1)
  858. if m.group(2) == '':
  859. args = []
  860. else:
  861. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", m.group(2)[1:-1])]
  862. expected = "Exception: %s\n" % m.group(3)
  863. test_assert(r, opts, "exhaustion", "%s %s" % (func, " ".join(args)), expected)
  864. # added to support WASM_ENABLE_EXCE_HANDLING
  865. def test_assert_wasmexception(r,opts,form):
  866. # params
  867. # ^
  868. # \(assert_exception\s+
  869. # \(invoke\s+"([^"]+)"\s+
  870. # (\(.*\))\s*
  871. # ()
  872. # \)\s*
  873. # \)\s*
  874. # $
  875. m = re.search('^\(assert_exception\s+\(invoke\s+"([^"]+)"\s+(\(.*\))\s*\)\s*\)\s*$', form)
  876. if not m:
  877. # no params
  878. # ^
  879. # \(assert_exception\s+
  880. # \(invoke\s+"([^"]+)"\s*
  881. # ()
  882. # \)\s*
  883. # \)\s*
  884. # $
  885. m = re.search('^\(assert_exception\s+\(invoke\s+"([^"]+)"\s*()\)\s*\)\s*$', form)
  886. if not m:
  887. raise Exception("unparsed assert_exception: '%s'" % form)
  888. func = m.group(1) # function name
  889. if m.group(2) == '': # arguments
  890. args = []
  891. else:
  892. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", m.group(2)[1:-1])]
  893. expected = "Exception: uncaught wasm exception\n"
  894. test_assert(r, opts, "wasmexception", "%s %s" % (func, " ".join(args)), expected)
  895. def do_invoke(r, opts, form):
  896. # params
  897. m = re.search('^\(invoke\s+"([^"]+)"\s+(\(.*\))\s*\)\s*$', form)
  898. if not m:
  899. # no params
  900. m = re.search('^\(invoke\s+"([^"]+)"\s*()\)\s*$', form)
  901. if not m:
  902. raise Exception("unparsed invoke: '%s'" % form)
  903. func = m.group(1)
  904. if ' ' in func:
  905. func = func.replace(' ', '\\')
  906. if m.group(2) == '':
  907. args = []
  908. else:
  909. args = [re.split(' +', v)[1] for v in re.split("\)\s*\(", m.group(2)[1:-1])]
  910. log("Invoking %s(%s)" % (
  911. func, ", ".join([str(a) for a in args])))
  912. invoke(r, opts, "%s %s" % (func, " ".join(args)))
  913. def skip_test(form, skip_list):
  914. for s in skip_list:
  915. if re.search(s, form):
  916. return True
  917. return False
  918. def compile_wast_to_wasm(form, wast_tempfile, wasm_tempfile, opts):
  919. log("Writing WAST module to '%s'" % wast_tempfile)
  920. with open(wast_tempfile, 'w') as file:
  921. file.write(form)
  922. log("Compiling WASM to '%s'" % wasm_tempfile)
  923. # default arguments
  924. if opts.gc:
  925. cmd = [opts.wast2wasm, "-u", "-d", wast_tempfile, "-o", wasm_tempfile]
  926. elif opts.eh:
  927. cmd = [opts.wast2wasm, "--enable-thread", "--no-check", "--enable-exceptions", "--enable-tail-call", wast_tempfile, "-o", wasm_tempfile ]
  928. else:
  929. cmd = [opts.wast2wasm, "--enable-thread", "--no-check",
  930. wast_tempfile, "-o", wasm_tempfile ]
  931. # remove reference-type and bulk-memory enabling options since a WABT
  932. # commit 30c1e983d30b33a8004b39fd60cbd64477a7956c
  933. # Enable reference types by default (#1729)
  934. log("Running: %s" % " ".join(cmd))
  935. try:
  936. subprocess.check_call(cmd)
  937. except subprocess.CalledProcessError as e:
  938. print(str(e))
  939. return False
  940. return True
  941. def compile_wasm_to_aot(wasm_tempfile, aot_tempfile, runner, opts, r, output = 'default'):
  942. log("Compiling AOT to '%s'" % aot_tempfile)
  943. cmd = [opts.aot_compiler]
  944. if test_target in aot_target_options_map:
  945. cmd += aot_target_options_map[test_target]
  946. if opts.sgx:
  947. cmd.append("-sgx")
  948. if not opts.simd:
  949. cmd.append("--disable-simd")
  950. if opts.xip:
  951. cmd.append("--enable-indirect-mode")
  952. cmd.append("--disable-llvm-intrinsics")
  953. if opts.multi_thread:
  954. cmd.append("--enable-multi-thread")
  955. if output == 'object':
  956. cmd.append("--format=object")
  957. elif output == 'ir':
  958. cmd.append("--format=llvmir-opt")
  959. # disable llvm link time optimization as it might convert
  960. # code of tail call into code of dead loop, and stack overflow
  961. # exception isn't thrown in several cases
  962. cmd.append("--disable-llvm-lto")
  963. # Bounds checks is disabled by default for 64-bit targets, to
  964. # use the hardware based bounds checks. But it is not supported
  965. # in QEMU with NuttX.
  966. # Enable bounds checks explicitly for all targets if running in QEMU.
  967. if opts.qemu:
  968. cmd.append("--bounds-checks=1")
  969. # RISCV64 requires -mcmodel=medany, which can be set by --size-level=1
  970. if test_target.startswith("riscv64"):
  971. cmd.append("--size-level=1")
  972. cmd += ["-o", aot_tempfile, wasm_tempfile]
  973. log("Running: %s" % " ".join(cmd))
  974. if not runner:
  975. subprocess.check_call(cmd)
  976. else:
  977. if (r != None):
  978. r.cleanup()
  979. r = Runner(cmd, no_pty=opts.no_pty)
  980. return r
  981. def run_wasm_with_repl(wasm_tempfile, aot_tempfile, opts, r):
  982. tmpfile = aot_tempfile if test_aot else wasm_tempfile
  983. log("Starting interpreter for module '%s'" % tmpfile)
  984. cmd_iwasm = [opts.interpreter, "--heap-size=0", "-v=5" if opts.verbose else "-v=0", "--repl", tmpfile]
  985. if opts.multi_module:
  986. cmd_iwasm.insert(1, "--module-path=" + (tempfile.gettempdir() if not opts.qemu else "/tmp" ))
  987. if opts.qemu:
  988. if opts.qemu_firmware == '':
  989. raise Exception("QEMU firmware missing")
  990. if opts.target.startswith("aarch64"):
  991. 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()
  992. cmd.append(opts.qemu_firmware)
  993. elif opts.target.startswith("thumbv7"):
  994. cmd = "qemu-system-arm -semihosting -M sabrelite -m 1024 -smp 1 -nographic -kernel".split()
  995. cmd.append(opts.qemu_firmware)
  996. elif opts.target.startswith("riscv32"):
  997. cmd = "qemu-system-riscv32 -semihosting -M virt,aclint=on -cpu rv32 -smp 1 -nographic -bios none -kernel".split()
  998. cmd.append(opts.qemu_firmware)
  999. elif opts.target.startswith("riscv64"):
  1000. cmd = "qemu-system-riscv64 -semihosting -M virt,aclint=on -cpu rv64 -smp 1 -nographic -bios none -kernel".split()
  1001. cmd.append(opts.qemu_firmware)
  1002. else:
  1003. raise Exception("Unknwon target for QEMU: %s" % opts.target)
  1004. else:
  1005. cmd = cmd_iwasm
  1006. log("Running: %s" % " ".join(cmd))
  1007. if (r != None):
  1008. r.cleanup()
  1009. r = Runner(cmd, no_pty=opts.no_pty)
  1010. if opts.qemu:
  1011. r.read_to_prompt(['nsh> '], 10)
  1012. r.writeline("mount -t hostfs -o fs={} /tmp".format(tempfile.gettempdir()))
  1013. r.read_to_prompt(['nsh> '], 10)
  1014. r.writeline(" ".join(cmd_iwasm))
  1015. return r
  1016. def create_tmpfiles(wast_name):
  1017. tempfiles = []
  1018. tempfiles.append(create_tmp_file(".wast"))
  1019. tempfiles.append(create_tmp_file(".wasm"))
  1020. if test_aot:
  1021. tempfiles.append(create_tmp_file(".aot"))
  1022. # add these temp file to temporal repo, will be deleted when finishing the test
  1023. temp_file_repo.extend(tempfiles)
  1024. return tempfiles
  1025. def test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile, opts, r, loadable = True):
  1026. details_inside_ast = get_module_exp_from_assert(form)
  1027. log("module is ....'%s'"%details_inside_ast[0])
  1028. log("exception is ....'%s'"%details_inside_ast[1])
  1029. # parse the module
  1030. module = details_inside_ast[0]
  1031. expected = details_inside_ast[1]
  1032. if not compile_wast_to_wasm(module, wast_tempfile, wasm_tempfile, opts):
  1033. raise Exception("compile wast to wasm failed")
  1034. if test_aot:
  1035. r = compile_wasm_to_aot(wasm_tempfile, aot_tempfile, True, opts, r)
  1036. try:
  1037. assert_prompt(r, ['Compile success'], opts.start_timeout, True)
  1038. except:
  1039. _, exc, _ = sys.exc_info()
  1040. if (r.buf.find(expected) >= 0):
  1041. log("Out exception includes expected one, pass:")
  1042. log(" Expected: %s" % expected)
  1043. log(" Got: %s" % r.buf)
  1044. return
  1045. else:
  1046. log("Run wamrc failed:\n expected: '%s'\n got: '%s'" % \
  1047. (expected, r.buf))
  1048. sys.exit(1)
  1049. r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1050. # Some module couldn't load so will raise an error directly, so shell prompt won't show here
  1051. if loadable:
  1052. # Wait for the initial prompt
  1053. try:
  1054. assert_prompt(r, ['webassembly> '], opts.start_timeout, True)
  1055. except:
  1056. _, exc, _ = sys.exc_info()
  1057. if (r.buf.find(expected) >= 0):
  1058. log("Out exception includes expected one, pass:")
  1059. log(" Expected: %s" %expected)
  1060. log(" Got: %s" % r.buf)
  1061. else:
  1062. raise Exception("Failed:\n expected: '%s'\n got: '%s'" % \
  1063. (expected, r.buf))
  1064. if __name__ == "__main__":
  1065. opts = parser.parse_args(sys.argv[1:])
  1066. # print('Input param :',opts)
  1067. if opts.aot: test_aot = True
  1068. # default x86_64
  1069. test_target = opts.target
  1070. if opts.rundir: os.chdir(opts.rundir)
  1071. if opts.log_file: log_file = open(opts.log_file, "a")
  1072. if opts.debug_file: debug_file = open(opts.debug_file, "a")
  1073. if opts.interpreter.endswith(".py"):
  1074. SKIP_TESTS = PY_SKIP_TESTS
  1075. else:
  1076. SKIP_TESTS = C_SKIP_TESTS
  1077. wast_tempfile = create_tmp_file(".wast")
  1078. wasm_tempfile = create_tmp_file(".wasm")
  1079. if test_aot:
  1080. aot_tempfile = create_tmp_file(".aot")
  1081. ret_code = 0
  1082. try:
  1083. log("\n################################################")
  1084. log("### Testing %s" % opts.test_file.name)
  1085. log("################################################")
  1086. forms = read_forms(opts.test_file.read())
  1087. r = None
  1088. for form in forms:
  1089. # log("\n### Current Case is " + form + "\n")
  1090. if ";;" == form[0:2]:
  1091. log(form)
  1092. elif skip_test(form, SKIP_TESTS):
  1093. log("Skipping test: %s" % form[0:60])
  1094. elif re.match("^\(assert_trap\s+\(module", form):
  1095. test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1096. elif re.match("^\(assert_exhaustion\\b.*", form):
  1097. test_assert_exhaustion(r, opts, form)
  1098. elif re.match("^\(assert_exception\\b.*", form):
  1099. test_assert_wasmexception(r, opts, form)
  1100. elif re.match("^\(assert_unlinkable\\b.*", form):
  1101. test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile if test_aot else None, opts, r, False)
  1102. elif re.match("^\(assert_malformed\\b.*", form):
  1103. # remove comments in wast
  1104. form,n = re.subn(";;.*\n", "", form)
  1105. m = re.match("^\(assert_malformed\s*\(module binary\s*(\".*\").*\)\s*\"(.*)\"\s*\)$", form, re.DOTALL)
  1106. if m:
  1107. # workaround: spec test changes error message to "malformed" while iwasm still use "invalid"
  1108. error_msg = m.group(2).replace("malformed", "invalid")
  1109. log("Testing(malformed)")
  1110. with open(wasm_tempfile, 'wb') as f:
  1111. s = m.group(1)
  1112. while s:
  1113. res = re.match("[^\"]*\"([^\"]*)\"(.*)", s, re.DOTALL)
  1114. if IS_PY_3:
  1115. context = res.group(1).replace("\\", "\\x").encode("latin1").decode("unicode-escape").encode("latin1")
  1116. f.write(context)
  1117. else:
  1118. f.write(res.group(1).replace("\\", "\\x").decode("string-escape"))
  1119. s = res.group(2)
  1120. # compile wasm to aot
  1121. if test_aot:
  1122. r = compile_wasm_to_aot(wasm_tempfile, aot_tempfile, True, opts, r)
  1123. try:
  1124. assert_prompt(r, ['Compile success'], opts.start_timeout, True)
  1125. except:
  1126. _, exc, _ = sys.exc_info()
  1127. if (r.buf.find(error_msg) >= 0):
  1128. log("Out exception includes expected one, pass:")
  1129. log(" Expected: %s" % error_msg)
  1130. log(" Got: %s" % r.buf)
  1131. else:
  1132. log("Run wamrc failed:\n expected: '%s'\n got: '%s'" % \
  1133. (error_msg, r.buf))
  1134. continue
  1135. r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1136. if (error_msg == "unexpected end of section or function"):
  1137. # one case in binary.wast
  1138. assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True)
  1139. elif (error_msg == "invalid value type"):
  1140. # one case in binary.wast
  1141. assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True)
  1142. elif (error_msg == "length out of bounds"):
  1143. # one case in custom.wast
  1144. assert_prompt(r, ["unexpected end", error_msg], opts.start_timeout, True)
  1145. elif (error_msg == "integer representation too long"):
  1146. # several cases in binary-leb128.wast
  1147. assert_prompt(r, ["invalid section id", error_msg], opts.start_timeout, True)
  1148. elif re.match("^\(assert_malformed\s*\(module quote", form):
  1149. log("ignoring assert_malformed module quote")
  1150. else:
  1151. log("unrecognized assert_malformed")
  1152. elif re.match("^\(assert_return[_a-z]*_nan\\b.*", form):
  1153. log("ignoring assert_return_.*_nan")
  1154. pass
  1155. elif re.match(".*\(invoke\s+\$\\b.*", form):
  1156. # invoke a particular named module's function
  1157. if form.startswith("(assert_return"):
  1158. test_assert_return(r,opts,form)
  1159. elif form.startswith("(assert_trap"):
  1160. test_assert_trap(r,opts,form)
  1161. elif re.match("^\(module\\b.*", form):
  1162. # if the module includes the particular name startswith $
  1163. m = re.search("^\(module\s+\$.\S+", form)
  1164. if m:
  1165. # get module name
  1166. module_name = re.split('\$', m.group(0).strip())[1]
  1167. if module_name:
  1168. # create temporal files
  1169. temp_files = create_tmpfiles(module_name)
  1170. if not compile_wast_to_wasm(form, temp_files[0], temp_files[1], opts):
  1171. raise Exception("compile wast to wasm failed")
  1172. if test_aot:
  1173. r = compile_wasm_to_aot(temp_files[1], temp_files[2], True, opts, r)
  1174. try:
  1175. assert_prompt(r, ['Compile success'], opts.start_timeout, False)
  1176. except:
  1177. _, exc, _ = sys.exc_info()
  1178. log("Run wamrc failed:\n got: '%s'" % r.buf)
  1179. sys.exit(1)
  1180. temp_module_table[module_name] = temp_files[1]
  1181. r = run_wasm_with_repl(temp_files[1], temp_files[2] if test_aot else None, opts, r)
  1182. else:
  1183. if not compile_wast_to_wasm(form, wast_tempfile, wasm_tempfile, opts):
  1184. raise Exception("compile wast to wasm failed")
  1185. if test_aot:
  1186. r = compile_wasm_to_aot(wasm_tempfile, aot_tempfile, True, opts, r)
  1187. try:
  1188. assert_prompt(r, ['Compile success'], opts.start_timeout, False)
  1189. except:
  1190. _, exc, _ = sys.exc_info()
  1191. log("Run wamrc failed:\n got: '%s'" % r.buf)
  1192. sys.exit(1)
  1193. r = run_wasm_with_repl(wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1194. # Wait for the initial prompt
  1195. try:
  1196. assert_prompt(r, ['webassembly> '], opts.start_timeout, False)
  1197. except:
  1198. _, exc, _ = sys.exc_info()
  1199. raise Exception("Failed:\n expected: '%s'\n got: '%s'" % \
  1200. (repr(exc), r.buf))
  1201. elif re.match("^\(assert_return\\b.*", form):
  1202. assert(r), "iwasm repl runtime should be not null"
  1203. test_assert_return(r, opts, form)
  1204. elif re.match("^\(assert_trap\\b.*", form):
  1205. test_assert_trap(r, opts, form)
  1206. elif re.match("^\(invoke\\b.*", form):
  1207. assert(r), "iwasm repl runtime should be not null"
  1208. do_invoke(r, opts, form)
  1209. elif re.match("^\(assert_invalid\\b.*", form):
  1210. test_assert_with_exception(form, wast_tempfile, wasm_tempfile, aot_tempfile if test_aot else None, opts, r)
  1211. elif re.match("^\(register\\b.*", form):
  1212. # get module's new name from the register cmd
  1213. name_new =re.split('\"',re.search('\".*\"',form).group(0))[1]
  1214. if name_new:
  1215. new_module = os.path.join(tempfile.gettempdir(), name_new + ".wasm")
  1216. shutil.copyfile(temp_module_table.get(name_new, wasm_tempfile), new_module)
  1217. # add new_module copied from the old into temp_file_repo[]
  1218. temp_file_repo.append(new_module)
  1219. if test_aot:
  1220. new_module_aot = os.path.join(tempfile.gettempdir(), name_new + ".aot")
  1221. r = compile_wasm_to_aot(new_module, new_module_aot, True, opts, r)
  1222. try:
  1223. assert_prompt(r, ['Compile success'], opts.start_timeout, True)
  1224. except:
  1225. raise Exception("compile wasm to aot failed")
  1226. # add aot module into temp_file_repo[]
  1227. temp_file_repo.append(new_module_aot)
  1228. else:
  1229. # there is no name defined in register cmd
  1230. raise Exception("can not find module name from the register")
  1231. else:
  1232. raise Exception("unrecognized form '%s...'" % form[0:40])
  1233. except Exception as e:
  1234. traceback.print_exc()
  1235. print("THE FINAL EXCEPTION IS {}".format(e))
  1236. ret_code = 101
  1237. shutil.copyfile(wasm_tempfile, os.path.join(opts.log_dir, os.path.basename(wasm_tempfile)))
  1238. if opts.aot or opts.xip:
  1239. shutil.copyfile(aot_tempfile, os.path.join(opts.log_dir,os.path.basename(aot_tempfile)))
  1240. if "indirect-mode" in str(e):
  1241. compile_wasm_to_aot(wasm_tempfile, aot_tempfile, None, opts, None, "object")
  1242. shutil.copyfile(aot_tempfile, os.path.join(opts.log_dir,os.path.basename(aot_tempfile)+'.o'))
  1243. subprocess.check_call(["llvm-objdump", "-r", aot_tempfile])
  1244. compile_wasm_to_aot(wasm_tempfile, aot_tempfile, None, opts, None, "ir")
  1245. shutil.copyfile(aot_tempfile, os.path.join(opts.log_dir,os.path.basename(aot_tempfile)+".ir"))
  1246. else:
  1247. ret_code = 0
  1248. finally:
  1249. if not opts.no_cleanup:
  1250. log("Removing tempfiles")
  1251. os.remove(wast_tempfile)
  1252. os.remove(wasm_tempfile)
  1253. if test_aot:
  1254. os.remove(aot_tempfile)
  1255. # remove the files under /tempfiles/ and copy of .wasm files
  1256. if temp_file_repo:
  1257. for t in temp_file_repo:
  1258. if(len(str(t))!=0 and os.path.exists(t)):
  1259. os.remove(t)
  1260. log("### End testing %s" % opts.test_file.name)
  1261. else:
  1262. log("Leaving tempfiles: %s" % ([wast_tempfile, wasm_tempfile]))
  1263. sys.exit(ret_code)