runtest.py 58 KB

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