runtest.py 62 KB

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