runtest.py 61 KB

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