runtest.py 59 KB

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