runtest.py 62 KB

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