. Run emrun --android --list-browsers to obtain a list of installed browsers you can use."
+ )
return 1
elif options.browser == 'firefox':
browser_app = 'org.mozilla.firefox/org.mozilla.gecko.BrowserApp'
@@ -1713,15 +1892,19 @@ def run(args): # noqa: C901, PLR0912, PLR0915
url = url.replace('&', '\\&')
browser = [ADB, 'shell', 'am', 'start', '-a', 'android.intent.action.VIEW', '-n', browser_app, '-d', url]
- processname_killed_atexit = browser_app[:browser_app.find('/')]
- else: # Launching a web page on local system.
+ processname_killed_atexit = browser_app[: browser_app.find('/')]
+ else: # Launching a web page on local system.
if options.browser:
options.browser = unwrap(options.browser)
if options.run_browser or options.browser_info:
browser = find_browser(str(options.browser))
if not browser:
- loge('Unable to find browser "' + str(options.browser) + '"! Check the correctness of the passed --browser=xxx parameter!')
+ loge(
+ 'Unable to find browser "'
+ + str(options.browser)
+ + '"! Check the correctness of the passed --browser=xxx parameter!'
+ )
return 1
browser_exe = browser[0]
browser_args = shlex.split(unwrap(options.browser_args))
@@ -1737,12 +1920,20 @@ def run(args): # noqa: C901, PLR0912, PLR0915
processname_killed_atexit = 'Safari'
elif 'chrome' in browser_exe.lower():
processname_killed_atexit = 'chrome'
- browser_args += ['--enable-nacl', '--enable-pnacl', '--disable-restore-session-state', '--enable-webgl',
- '--no-default-browser-check', '--no-first-run', '--allow-file-access-from-files', '--password-store=basic']
+ browser_args += [
+ '--enable-nacl',
+ '--enable-pnacl',
+ '--disable-restore-session-state',
+ '--enable-webgl',
+ '--no-default-browser-check',
+ '--no-first-run',
+ '--allow-file-access-from-files',
+ '--password-store=basic',
+ ]
if options.private_browsing:
browser_args += ['--incognito']
- # if not options.run_server:
- # browser_args += ['--disable-web-security']
+ # if not options.run_server:
+ # browser_args += ['--disable-web-security']
elif 'firefox' in browser_exe.lower():
processname_killed_atexit = 'firefox'
elif 'iexplore' in browser_exe.lower():
@@ -1777,7 +1968,9 @@ def run(cmd):
run(['adb', 'shell', 'mkdir', '/mnt/sdcard/safe_firefox_profile'])
run(['adb', 'push', os.path.join(profile_dir, 'prefs.js'), '/mnt/sdcard/safe_firefox_profile/prefs.js'])
except Exception as e:
- loge('Creating Firefox profile prefs.js file to internal storage in /mnt/sdcard failed with error ' + str(e) + '!')
+ loge(
+ 'Creating Firefox profile prefs.js file to internal storage in /mnt/sdcard failed with error ' + str(e) + '!'
+ )
loge('Try running without --safe-firefox-profile flag if unattended execution mode is not important, or')
loge('enable rooted debugging on the Android device to allow adb to write files to /mnt/sdcard.')
browser += ['--es', 'args', '"--profile /mnt/sdcard/safe_firefox_profile"']
@@ -1785,7 +1978,12 @@ def run(cmd):
# Create temporary Firefox profile to run the page with. This is important to
# run after kill_browser_process()/kill_start op above, since that cleans up
# the temporary profile if one exists.
- if processname_killed_atexit == 'firefox' and options.safe_firefox_profile and options.run_browser and not options.android:
+ if (
+ processname_killed_atexit == 'firefox'
+ and options.safe_firefox_profile
+ and options.run_browser
+ and not options.android
+ ):
profile_dir = create_emrun_safe_firefox_profile()
browser += ['-no-remote', '--profile', profile_dir.replace('\\', '/')]
@@ -1827,7 +2025,12 @@ def run(cmd):
logv(browser_exe)
previous_browser_processes = list_processes_by_name(browser_exe)
for p in previous_browser_processes:
- logv('Before spawning web browser, found a running ' + os.path.basename(browser_exe) + ' browser process id: ' + str(p['pid']))
+ logv(
+ 'Before spawning web browser, found a running '
+ + os.path.basename(browser_exe)
+ + ' browser process id: '
+ + str(p['pid'])
+ )
browser_process = subprocess.Popen(browser, env=subprocess_env())
logv('Launched browser process with pid=' + str(browser_process.pid))
if options.kill_exit:
@@ -1841,9 +2044,15 @@ def run(cmd):
premature_quit_code = browser_process.poll()
if premature_quit_code is not None:
options.serve_after_close = True
- logv('Warning: emrun got immediately detached from the target browser process (the process quit with exit code ' + str(premature_quit_code) + '). Cannot detect when user closes the browser. Behaving as if --serve-after-close was passed in.')
+ logv(
+ 'Warning: emrun got immediately detached from the target browser process (the process quit with exit code '
+ + str(premature_quit_code)
+ + '). Cannot detect when user closes the browser. Behaving as if --serve-after-close was passed in.'
+ )
if not options.browser:
- logv('Try passing the --browser=/path/to/browser option to avoid this from occurring. See https://github.com/emscripten-core/emscripten/issues/3234 for more discussion.')
+ logv(
+ 'Try passing the --browser=/path/to/browser option to avoid this from occurring. See https://github.com/emscripten-core/emscripten/issues/3234 for more discussion.'
+ )
if options.run_server:
try:
@@ -1880,7 +2089,11 @@ def main(args):
returncode = run(args)
logv('emrun quitting with process exit code ' + str(returncode))
if temp_firefox_profile_dir is not None:
- logi('Warning: Had to leave behind a temporary Firefox profile directory ' + temp_firefox_profile_dir + ' because --safe-firefox-profile was set and the browser did not quit before emrun did.')
+ logi(
+ 'Warning: Had to leave behind a temporary Firefox profile directory '
+ + temp_firefox_profile_dir
+ + ' because --safe-firefox-profile was set and the browser did not quit before emrun did.'
+ )
return returncode
diff --git a/emsize.py b/emsize.py
index 8bf92a3843c01..6ea849351f20a 100755
--- a/emsize.py
+++ b/emsize.py
@@ -61,8 +61,7 @@ def print_sizes(js_file):
if not os.path.isfile(wasm_file):
return error('Wasm file %s not found' % wasm_file)
- sizes = shared.check_call([LLVM_SIZE, '--format=sysv', wasm_file],
- stdout=subprocess.PIPE).stdout
+ sizes = shared.check_call([LLVM_SIZE, '--format=sysv', wasm_file], stdout=subprocess.PIPE).stdout
# llvm-size may emit some number of blank lines (after the total), ignore them
lines = [line for line in sizes.splitlines() if line]
diff --git a/emstrip.py b/emstrip.py
index f054fe7e9f1df..b330234f960cb 100755
--- a/emstrip.py
+++ b/emstrip.py
@@ -4,8 +4,7 @@
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
-"""Wrapper script around `llvm-strip`.
-"""
+"""Wrapper script around `llvm-strip`."""
import sys
from tools import shared
diff --git a/emsymbolizer.py b/emsymbolizer.py
index 7ba3b951c852b..37728882b53fb 100755
--- a/emsymbolizer.py
+++ b/emsymbolizer.py
@@ -22,8 +22,7 @@
from tools import shared
from tools import webassembly
-LLVM_SYMBOLIZER = os.path.expanduser(
- shared.build_llvm_tool_path(shared.exe_suffix('llvm-symbolizer')))
+LLVM_SYMBOLIZER = os.path.expanduser(shared.build_llvm_tool_path(shared.exe_suffix('llvm-symbolizer')))
class Error(BaseException):
@@ -68,8 +67,7 @@ def symbolize_address_symbolizer(module, address, is_dwarf):
vma_adjust = get_codesec_offset(module)
else:
vma_adjust = 0
- cmd = [LLVM_SYMBOLIZER, '-e', module.filename, f'--adjust-vma={vma_adjust}',
- str(address)]
+ cmd = [LLVM_SYMBOLIZER, '-e', module.filename, f'--adjust-vma={vma_adjust}', str(address)]
out = shared.run_process(cmd, stdout=subprocess.PIPE).stdout.strip()
out_lines = out.splitlines()
@@ -184,11 +182,7 @@ def lookup(self, offset):
nearest = self.find_offset(offset)
assert nearest in self.mappings, 'Sourcemap has an offset with no mapping'
info = self.mappings[nearest]
- return LocationInfo(
- self.sources[info.source] if info.source is not None else None,
- info.line,
- info.column
- )
+ return LocationInfo(self.sources[info.source] if info.source is not None else None, info.line, info.column)
def symbolize_address_sourcemap(module, address, force_file):
@@ -223,36 +217,32 @@ def main(args):
if args.addrtype == 'code':
address += get_codesec_offset(module)
- if ((has_debug_line_section(module) and not args.source) or
- 'dwarf' in args.source):
+ if (has_debug_line_section(module) and not args.source) or 'dwarf' in args.source:
symbolize_address_symbolizer(module, address, is_dwarf=True)
- elif ((get_sourceMappingURL_section(module) and not args.source) or
- 'sourcemap' in args.source):
+ elif (get_sourceMappingURL_section(module) and not args.source) or 'sourcemap' in args.source:
symbolize_address_sourcemap(module, address, args.file)
- elif ((has_name_section(module) and not args.source) or
- 'names' in args.source):
+ elif (has_name_section(module) and not args.source) or 'names' in args.source:
symbolize_address_symbolizer(module, address, is_dwarf=False)
- elif ((has_linking_section(module) and not args.source) or
- 'symtab' in args.source):
+ elif (has_linking_section(module) and not args.source) or 'symtab' in args.source:
symbolize_address_symbolizer(module, address, is_dwarf=False)
else:
- raise Error('No .debug_line or sourceMappingURL section found in '
- f'{module.filename}.'
- " I don't know how to symbolize this file yet")
+ raise Error(
+ 'No .debug_line or sourceMappingURL section found in '
+ f'{module.filename}.'
+ " I don't know how to symbolize this file yet"
+ )
def get_args():
parser = argparse.ArgumentParser()
- parser.add_argument('-s', '--source', choices=['dwarf', 'sourcemap',
- 'names', 'symtab'],
- help='Force debug info source type', default=())
- parser.add_argument('-f', '--file', action='store',
- help='Force debug info source file')
- parser.add_argument('-t', '--addrtype', choices=['code', 'file'],
- default='file',
- help='Address type (code section or file offset)')
- parser.add_argument('-v', '--verbose', action='store_true',
- help='Print verbose info for debugging this script')
+ parser.add_argument(
+ '-s', '--source', choices=['dwarf', 'sourcemap', 'names', 'symtab'], help='Force debug info source type', default=()
+ )
+ parser.add_argument('-f', '--file', action='store', help='Force debug info source file')
+ parser.add_argument(
+ '-t', '--addrtype', choices=['code', 'file'], default='file', help='Address type (code section or file offset)'
+ )
+ parser.add_argument('-v', '--verbose', action='store_true', help='Print verbose info for debugging this script')
parser.add_argument('wasm_file', help='Wasm file')
parser.add_argument('address', help='Address to lookup')
args = parser.parse_args()
diff --git a/pyproject.toml b/pyproject.toml
index 874462532f8e3..825e5e34451ce 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -11,6 +11,12 @@ exclude = [
"./tools/scons/",
".git",
]
+format.exclude = [
+ "./test/test_browser.py",
+]
+format.quote-style = "preserve"
+indent-width = 2
+line-length = 120
lint.select = [
"ARG",
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 84c824c5ee1b6..97d17eaf370d5 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -6,7 +6,7 @@
coverage[toml]==5.5
mypy==0.971
-ruff==0.8.2
+ruff==0.8.3
types-requests==2.27.14
unittest-xml-reporting==3.1.0
diff --git a/site/source/get_api_items.py b/site/source/get_api_items.py
index ee94f6909e6d3..404bb42eee026 100755
--- a/site/source/get_api_items.py
+++ b/site/source/get_api_items.py
@@ -26,77 +26,83 @@
def parseFiles():
- """Parse api-reference files to extract the code items.
- """
-
- def addapiitems(matchobj):
- # print 'matcobj0: %s' % matchobj.group(0)
- # print 'matcobj1: %s' % matchobj.group(1)
- # print 'matcobj2: %s' % matchobj.group(2)
- # print 'matcobj3: %s' % matchobj.group(3)
- # print 'matcobj4: %s' % matchobj.group(4)
-
- lang = matchobj.group(2)
- data_type = matchobj.group(3)
- if data_type == 'function':
- data_type = 'func'
- api_item = matchobj.group(4)
- api_item = api_item.strip()
- api_item = api_item.split('(')[0]
- try:
- api_item = api_item.split(' ')[1]
- except IndexError:
- pass
-
- # print lang
- # print data_type
- # print api_item
-
- api_reference_items[api_item] = ':%s:%s:`%s`' % (lang, data_type, api_item)
- # Add additional index for functions declared as func() rather than just func
- if data_type == 'func':
- api_item_index = api_item + '()'
- api_reference_items[api_item_index] = ':%s:%s:`%s`' % (lang, data_type, api_item)
-
- # print api_reference_items[api_item]
-
- for file in os.listdir(api_reference_directory):
- if file.endswith(".rst"):
- filepath = api_reference_directory + file
- print(file)
- # open file
- with open(filepath, 'r') as infile:
- for line in infile:
- # parse line for API items
- re.sub(r'^\.\.\s+((\w+)\:(\w+)\:\:(.*))', addapiitems, line)
+ """Parse api-reference files to extract the code items."""
+
+ def addapiitems(matchobj):
+ # print 'matcobj0: %s' % matchobj.group(0)
+ # print 'matcobj1: %s' % matchobj.group(1)
+ # print 'matcobj2: %s' % matchobj.group(2)
+ # print 'matcobj3: %s' % matchobj.group(3)
+ # print 'matcobj4: %s' % matchobj.group(4)
+
+ lang = matchobj.group(2)
+ data_type = matchobj.group(3)
+ if data_type == 'function':
+ data_type = 'func'
+ api_item = matchobj.group(4)
+ api_item = api_item.strip()
+ api_item = api_item.split('(')[0]
+ try:
+ api_item = api_item.split(' ')[1]
+ except IndexError:
+ pass
+
+ # print lang
+ # print data_type
+ # print api_item
+
+ api_reference_items[api_item] = ':%s:%s:`%s`' % (lang, data_type, api_item)
+ # Add additional index for functions declared as func() rather than just func
+ if data_type == 'func':
+ api_item_index = api_item + '()'
+ api_reference_items[api_item_index] = ':%s:%s:`%s`' % (lang, data_type, api_item)
+
+ # print api_reference_items[api_item]
+
+ for file in os.listdir(api_reference_directory):
+ if file.endswith(".rst"):
+ filepath = api_reference_directory + file
+ print(file)
+ # open file
+ with open(filepath, 'r') as infile:
+ for line in infile:
+ # parse line for API items
+ re.sub(r'^\.\.\s+((\w+)\:(\w+)\:\:(.*))', addapiitems, line)
def exportItems():
- """Export the API items into form for use in another script.
- """
- with open(api_item_filename, 'w') as infile:
- # write function lead in
- infile.write("# Auto-generated file (see get_api_items.py)\n\ndef get_mapped_items():\n mapped_wiki_inline_code = dict()\n")
+ """Export the API items into form for use in another script."""
+ with open(api_item_filename, 'w') as infile:
+ # write function lead in
+ infile.write(
+ "# Auto-generated file (see get_api_items.py)\n\ndef get_mapped_items():\n mapped_wiki_inline_code = dict()\n"
+ )
- items = list((key, value) for key, value in api_reference_items.items())
- items.sort()
- for key, value in items:
- # Write out each API item to add
- infile.write(" mapped_wiki_inline_code['%s'] = '%s'\n" % (key, value))
+ items = list((key, value) for key, value in api_reference_items.items())
+ items.sort()
+ for key, value in items:
+ # Write out each API item to add
+ infile.write(" mapped_wiki_inline_code['%s'] = '%s'\n" % (key, value))
- # write the return function
- infile.write(" return mapped_wiki_inline_code\n")
+ # write the return function
+ infile.write(" return mapped_wiki_inline_code\n")
def main():
- parser = optparse.OptionParser(usage="Usage: %prog [options] version")
- parser.add_option("-s", "--siteapi", dest="siteapi", default="http://www.developer.nokia.com/Community/Wiki/api.php", help="Location of API")
- (options, args) = parser.parse_args()
- # print 'Site: %s' % options.siteapi
- parseFiles()
- exportItems()
- return 0
+ parser = optparse.OptionParser(usage="Usage: %prog [options] version")
+ parser.add_option(
+ "-s",
+ "--siteapi",
+ dest="siteapi",
+ default="http://www.developer.nokia.com/Community/Wiki/api.php",
+ help="Location of API",
+ )
+ (options, args) = parser.parse_args()
+ # print 'Site: %s' % options.siteapi
+ parseFiles()
+ exportItems()
+ return 0
if __name__ == '__main__':
- sys.exit(main())
+ sys.exit(main())
diff --git a/site/source/get_wiki.py b/site/source/get_wiki.py
index 899531541f222..dbe2a3c5e5b78 100755
--- a/site/source/get_wiki.py
+++ b/site/source/get_wiki.py
@@ -39,185 +39,197 @@
temp_set_of_codemarkup = set()
logfile = open(logfilename, 'w')
# snapshot_version_information = '.. note:: This is a **snapshot** of the wiki: %s\n\n' % strftime("%a, %d %b %Y %H:%M", gmtime())
-snapshot_version_information = '.. note:: This article was migrated from the wiki (%s) and is now the "master copy" (the version in the wiki will be deleted). It may not be a perfect rendering of the original but we hope to fix that soon!\n\n' % time.strftime("%a, %d %b %Y %H:%M", time.gmtime())
+snapshot_version_information = (
+ '.. note:: This article was migrated from the wiki (%s) and is now the "master copy" (the version in the wiki will be deleted). It may not be a perfect rendering of the original but we hope to fix that soon!\n\n'
+ % time.strftime("%a, %d %b %Y %H:%M", time.gmtime())
+)
def CleanWiki():
- """Delete the wiki clone directory and all contained files.
- """
+ """Delete the wiki clone directory and all contained files."""
- def errorhandler(func, path, exc_info):
- # where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info()
- print(func)
- print(path)
- print(exc_info)
- os.chmod(path, stat.S_IWRITE)
- os.remove(path)
+ def errorhandler(func, path, exc_info):
+ # where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info()
+ print(func)
+ print(path)
+ print(exc_info)
+ os.chmod(path, stat.S_IWRITE)
+ os.remove(path)
- try:
- shutil.rmtree(output_dir, ignore_errors=False, onerror=errorhandler)
- print('Old wiki clone removed')
- except IOError:
- print('No directory to clean found')
+ try:
+ shutil.rmtree(output_dir, ignore_errors=False, onerror=errorhandler)
+ print('Old wiki clone removed')
+ except IOError:
+ print('No directory to clean found')
def CloneWiki():
- """
- Clone the wiki into a temporary location (first cleaning)
- """
- # Clean up existing repo
- CleanWiki()
+ """
+ Clone the wiki into a temporary location (first cleaning)
+ """
+ # Clean up existing repo
+ CleanWiki()
- # Create directory for output and temporary files
- try:
- os.makedirs(output_dir)
- print('Created directory')
- except OSError:
- pass
+ # Create directory for output and temporary files
+ try:
+ os.makedirs(output_dir)
+ print('Created directory')
+ except OSError:
+ pass
- # Clone
- git_clone_command = 'git clone %s %s' % (wiki_repo, wiki_checkout)
- print(git_clone_command)
- os.system(git_clone_command)
+ # Clone
+ git_clone_command = 'git clone %s %s' % (wiki_repo, wiki_checkout)
+ print(git_clone_command)
+ os.system(git_clone_command)
def ConvertFilesToRst():
- """
- Add template to specified page object (wikitools)
- """
- indexfiletext = '============================\nWiki snapshot (ready-for-review)\n============================\n\n%s\n.. toctree::\n :maxdepth: 2\n' % snapshot_version_information
- for file in os.listdir(wiki_checkout):
- if not file.endswith(".md"):
- continue
-
- inputfilename = wiki_checkout + file
- markdown = Path(inputfilename).read_text()
- if 'This article has moved from the wiki to the new site' in markdown:
- continue
- if 'This page has been migrated to the main site' in markdown:
- continue
-
- print(file)
- # get name of file
- filenamestripped = os.path.splitext(file)[0]
- indexfiletext += '\n %s' % filenamestripped
- outputfilename = output_dir + filenamestripped + '.rst'
-
- command = 'pandoc -f markdown -t rst -o "%s" "%s"' % (outputfilename, inputfilename)
- print(command)
- if os.system(command):
- sys.exit(1)
- title = filenamestripped.replace('-', ' ')
- # print title
- logfile.write('title from filename: %s \n' % title)
- # add import message to title
- title += ' (wiki-import)'
- length = len(title)
- # print length
- headerbar = ''
- for _ in range(length):
- headerbar += '='
- page_reference = filenamestripped
- page_reference_link_text = '.. _%s:\n\n' % page_reference
- titlebar = page_reference_link_text + headerbar + '\n' + title + '\n' + headerbar + '\n'
- textinfile = ''
- # Add titlebar to start of the file (from the filename)
- textinfile += titlebar
- # Add wiki snapshot information
-
- textinfile += snapshot_version_information
-
- with open(outputfilename) as infile:
- for line in infile:
- textinfile += line
-
- # print textinfile
- with open(outputfilename, 'w') as outfile:
- outfile.write(textinfile)
-
- # write the index
- with open(output_dir + 'index.rst', 'w') as outfile:
- outfile.write(indexfiletext)
+ """
+ Add template to specified page object (wikitools)
+ """
+ indexfiletext = (
+ '============================\nWiki snapshot (ready-for-review)\n============================\n\n%s\n.. toctree::\n :maxdepth: 2\n'
+ % snapshot_version_information
+ )
+ for file in os.listdir(wiki_checkout):
+ if not file.endswith(".md"):
+ continue
+
+ inputfilename = wiki_checkout + file
+ markdown = Path(inputfilename).read_text()
+ if 'This article has moved from the wiki to the new site' in markdown:
+ continue
+ if 'This page has been migrated to the main site' in markdown:
+ continue
+
+ print(file)
+ # get name of file
+ filenamestripped = os.path.splitext(file)[0]
+ indexfiletext += '\n %s' % filenamestripped
+ outputfilename = output_dir + filenamestripped + '.rst'
+
+ command = 'pandoc -f markdown -t rst -o "%s" "%s"' % (outputfilename, inputfilename)
+ print(command)
+ if os.system(command):
+ sys.exit(1)
+ title = filenamestripped.replace('-', ' ')
+ # print title
+ logfile.write('title from filename: %s \n' % title)
+ # add import message to title
+ title += ' (wiki-import)'
+ length = len(title)
+ # print length
+ headerbar = ''
+ for _ in range(length):
+ headerbar += '='
+ page_reference = filenamestripped
+ page_reference_link_text = '.. _%s:\n\n' % page_reference
+ titlebar = page_reference_link_text + headerbar + '\n' + title + '\n' + headerbar + '\n'
+ textinfile = ''
+ # Add titlebar to start of the file (from the filename)
+ textinfile += titlebar
+ # Add wiki snapshot information
+
+ textinfile += snapshot_version_information
+
+ with open(outputfilename) as infile:
+ for line in infile:
+ textinfile += line
+
+ # print textinfile
+ with open(outputfilename, 'w') as outfile:
+ outfile.write(textinfile)
+
+ # write the index
+ with open(output_dir + 'index.rst', 'w') as outfile:
+ outfile.write(indexfiletext)
def FixupConvertedRstFiles():
- """Add template to specified page object (wikitools)
+ """Add template to specified page object (wikitools)"""
+
+ def fixInternalWikiLinks(aOldText):
+ """
+ Fixes wiki links in [[linkname]] format by changing this to a document link in current directory.
+ """
+
+ def fixwikilinks(matchobj):
+ # print 'matcobj0: %s' % matchobj.group(0)
+ # print 'matcobj1: %s' % matchobj.group(1)
+ linktext = matchobj.group(1)
+ linktext = linktext.replace(' ', '-')
+ # linktext = ':doc:`%s`' % linktext
+ # use reference for linking as allows pages to be moved around
+ linktext = ':ref:`%s`' % linktext
+ # print 'linkdoc: %s' % linktext
+ logfile.write('linkdoc: %s \n' % linktext)
+ return linktext
+
+ # print 'fixing wiki links'
+ return re.sub(r'\[\[(.+?)\]\]', fixwikilinks, aOldText)
+
+ def fixWikiCodeMarkupToCodeLinks(aOldText):
"""
+ Links "known" code objects if they are found in wiki markup.
+ """
+
+ def fixcodemarkuplinks(matchobj):
+ # print 'Inline code: %s' % matchobj.group(0)
+ # print 'matcobj1: %s' % matchobj.group(1)
+ temp_set_of_codemarkup.add(matchobj.group(0))
+ linktext = matchobj.group(1)
+ if linktext in mapped_wiki_inline_code:
+ logfile.write('Replace: %s \n' % mapped_wiki_inline_code[linktext])
+ return mapped_wiki_inline_code[linktext]
+
+ return matchobj.group(0) # linktext
+
+ # print 'fixing up code markup to code reference'
+ return re.sub(r'``(.+?)``', fixcodemarkuplinks, aOldText)
+
+ for file in os.listdir(output_dir):
+ if file.endswith(".rst"):
+ input_file = output_dir + file
+ # print input_file
+ textinfile = ''
+ with open(input_file) as infile:
+ for line in infile:
+ textinfile += line
+
+ # print textinfile
+ # fix up broken wiki-page links in files
+ textinfile = fixInternalWikiLinks(textinfile)
+
+ # convert codemarkup to links if possible
+ textinfile = fixWikiCodeMarkupToCodeLinks(textinfile)
+
+ with open(input_file, 'w') as outfile:
+ outfile.write(textinfile)
- def fixInternalWikiLinks(aOldText):
- """
- Fixes wiki links in [[linkname]] format by changing this to a document link in current directory.
- """
- def fixwikilinks(matchobj):
- # print 'matcobj0: %s' % matchobj.group(0)
- # print 'matcobj1: %s' % matchobj.group(1)
- linktext = matchobj.group(1)
- linktext = linktext.replace(' ', '-')
- # linktext = ':doc:`%s`' % linktext
- # use reference for linking as allows pages to be moved around
- linktext = ':ref:`%s`' % linktext
- # print 'linkdoc: %s' % linktext
- logfile.write('linkdoc: %s \n' % linktext)
- return linktext
- # print 'fixing wiki links'
- return re.sub(r'\[\[(.+?)\]\]', fixwikilinks, aOldText)
-
- def fixWikiCodeMarkupToCodeLinks(aOldText):
- """
- Links "known" code objects if they are found in wiki markup.
- """
- def fixcodemarkuplinks(matchobj):
- # print 'Inline code: %s' % matchobj.group(0)
- # print 'matcobj1: %s' % matchobj.group(1)
- temp_set_of_codemarkup.add(matchobj.group(0))
- linktext = matchobj.group(1)
- if linktext in mapped_wiki_inline_code:
- logfile.write('Replace: %s \n' % mapped_wiki_inline_code[linktext])
- return mapped_wiki_inline_code[linktext]
-
- return matchobj.group(0) # linktext
- # print 'fixing up code markup to code reference'
- return re.sub(r'``(.+?)``', fixcodemarkuplinks, aOldText)
-
- for file in os.listdir(output_dir):
- if file.endswith(".rst"):
- input_file = output_dir + file
- # print input_file
- textinfile = ''
- with open(input_file) as infile:
- for line in infile:
- textinfile += line
-
- # print textinfile
- # fix up broken wiki-page links in files
- textinfile = fixInternalWikiLinks(textinfile)
-
- # convert codemarkup to links if possible
- textinfile = fixWikiCodeMarkupToCodeLinks(textinfile)
-
- with open(input_file, 'w') as outfile:
- outfile.write(textinfile)
-
- logfile.write('\n\nCODE MARKUP THAT WONT BE LINKED (add entry to mapped_wiki_inline_code if one of these need to be linked. The tool get-api-items.py can be used to generate the list of the documented API items. \n')
- for item in temp_set_of_codemarkup:
- logfile.write('%s\n' % item)
+ logfile.write(
+ '\n\nCODE MARKUP THAT WONT BE LINKED (add entry to mapped_wiki_inline_code if one of these need to be linked. The tool get-api-items.py can be used to generate the list of the documented API items. \n'
+ )
+ for item in temp_set_of_codemarkup:
+ logfile.write('%s\n' % item)
# parser options
def main():
- parser = optparse.OptionParser(version="%prog 0.1.1", usage="Usage: %prog [options] version")
- parser.add_option("-c", "--clonewiki", action="store_true", default=False, dest="clonewiki", help="Clean and clone the latest wiki")
- options, args = parser.parse_args()
+ parser = optparse.OptionParser(version="%prog 0.1.1", usage="Usage: %prog [options] version")
+ parser.add_option(
+ "-c", "--clonewiki", action="store_true", default=False, dest="clonewiki", help="Clean and clone the latest wiki"
+ )
+ options, args = parser.parse_args()
- print('Clone wiki: %s' % options.clonewiki)
- if options.clonewiki:
- CloneWiki()
- # input = raw_input('CHECK ALL files were cloned! (look for "error: unable to create file" )\n')
+ print('Clone wiki: %s' % options.clonewiki)
+ if options.clonewiki:
+ CloneWiki()
+ # input = raw_input('CHECK ALL files were cloned! (look for "error: unable to create file" )\n')
- ConvertFilesToRst()
- FixupConvertedRstFiles()
- print('See LOG for details: %s ' % logfilename)
+ ConvertFilesToRst()
+ FixupConvertedRstFiles()
+ print('See LOG for details: %s ' % logfilename)
if __name__ == '__main__':
- sys.exit(main())
+ sys.exit(main())
diff --git a/system/bin/sdl-config.py b/system/bin/sdl-config.py
index e028a4f7397be..9d1bb92a72622 100755
--- a/system/bin/sdl-config.py
+++ b/system/bin/sdl-config.py
@@ -11,4 +11,3 @@
print('')
elif '--version' in args:
print('1.3.0')
-
diff --git a/system/bin/sdl2-config.py b/system/bin/sdl2-config.py
index 957ef5900a3ec..bb8266c7dabec 100755
--- a/system/bin/sdl2-config.py
+++ b/system/bin/sdl2-config.py
@@ -10,4 +10,3 @@
print('-sUSE_SDL=2')
elif '--version' in args:
print('2.0.10')
-
diff --git a/test/benchmark/benchmark_sse.py b/test/benchmark/benchmark_sse.py
index 65f296c1dafce..e24f60e2e208a 100644
--- a/test/benchmark/benchmark_sse.py
+++ b/test/benchmark/benchmark_sse.py
@@ -34,161 +34,195 @@
def run_benchmark(benchmark_file, results_file, build_args):
- # Run native build
- out_file = os.path.join(temp_dir, 'benchmark_sse_native')
- if WINDOWS:
- out_file += '.exe'
- cmd = [CLANG_CXX] + clang_native.get_clang_native_args() + [benchmark_file, '-O3', '-o', out_file]
- print('Building native version of the benchmark:')
- print(' '.join(cmd))
- run_process(cmd, env=clang_native.get_clang_native_env())
+ # Run native build
+ out_file = os.path.join(temp_dir, 'benchmark_sse_native')
+ if WINDOWS:
+ out_file += '.exe'
+ cmd = [CLANG_CXX] + clang_native.get_clang_native_args() + [benchmark_file, '-O3', '-o', out_file]
+ print('Building native version of the benchmark:')
+ print(' '.join(cmd))
+ run_process(cmd, env=clang_native.get_clang_native_env())
- native_results = Popen([out_file], stdout=PIPE, stderr=PIPE).communicate()
- print(native_results[0])
+ native_results = Popen([out_file], stdout=PIPE, stderr=PIPE).communicate()
+ print(native_results[0])
- # Run emscripten build
- out_file = os.path.join(temp_dir, 'benchmark_sse_html.js')
- cmd = [EMCC, benchmark_file, '-O3', '-sTOTAL_MEMORY=536870912', '-o', out_file] + build_args
- print('Building Emscripten version of the benchmark:')
- print(' '.join(cmd))
- run_process(cmd)
+ # Run emscripten build
+ out_file = os.path.join(temp_dir, 'benchmark_sse_html.js')
+ cmd = [EMCC, benchmark_file, '-O3', '-sTOTAL_MEMORY=536870912', '-o', out_file] + build_args
+ print('Building Emscripten version of the benchmark:')
+ print(' '.join(cmd))
+ run_process(cmd)
- cmd = V8_ENGINE + ['--experimental-wasm-simd', os.path.basename(out_file)]
- print(' '.join(cmd))
- old_dir = os.getcwd()
- os.chdir(os.path.dirname(out_file))
- wasm_results = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
- os.chdir(old_dir)
+ cmd = V8_ENGINE + ['--experimental-wasm-simd', os.path.basename(out_file)]
+ print(' '.join(cmd))
+ old_dir = os.getcwd()
+ os.chdir(os.path.dirname(out_file))
+ wasm_results = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
+ os.chdir(old_dir)
- if not wasm_results:
- raise Exception('Unable to run benchmark in V8!')
+ if not wasm_results:
+ raise Exception('Unable to run benchmark in V8!')
- if not wasm_results[0].strip():
- print(wasm_results[1])
- sys.exit(1)
+ if not wasm_results[0].strip():
+ print(wasm_results[1])
+ sys.exit(1)
- print(wasm_results[0])
+ print(wasm_results[0])
- def strip_comments(text):
- return re.sub('//.*?\n|/\*.*?\*/', '', text, re.S) # noqa
+ def strip_comments(text):
+ return re.sub('//.*?\n|/\*.*?\*/', '', text, re.S) # noqa
- benchmark_results = strip_comments(wasm_results[0])
+ benchmark_results = strip_comments(wasm_results[0])
- # Strip out unwanted print output.
- benchmark_results = benchmark_results[benchmark_results.find('{'):].strip()
- if '*************************' in benchmark_results:
- benchmark_results = benchmark_results[:benchmark_results.find('*************************')].strip()
+ # Strip out unwanted print output.
+ benchmark_results = benchmark_results[benchmark_results.find('{') :].strip()
+ if '*************************' in benchmark_results:
+ benchmark_results = benchmark_results[: benchmark_results.find('*************************')].strip()
- print(benchmark_results)
+ print(benchmark_results)
- shutil.rmtree(temp_dir)
+ shutil.rmtree(temp_dir)
- native_results = json.loads(native_results[0])
- benchmark_results = benchmark_results[benchmark_results.index('{'):benchmark_results.rindex('}') + 1]
- wasm_results = json.loads(benchmark_results)
+ native_results = json.loads(native_results[0])
+ benchmark_results = benchmark_results[benchmark_results.index('{') : benchmark_results.rindex('}') + 1]
+ wasm_results = json.loads(benchmark_results)
- # native_workload = native_results['workload']
- # html_workload = wasm_results['workload']
+ # native_workload = native_results['workload']
+ # html_workload = wasm_results['workload']
- html = '''SSE JavaScript Benchmark
+ html = (
+ '''SSE JavaScript Benchmark
System Info:
- ''' + system_info[0].replace('\n', '
') + '''
+ '''
+ + system_info[0].replace('\n', '
')
+ + '''
Native Clang Compiler:
- ''' + native_info[1].replace('\n', '
') + '''
+ '''
+ + native_info[1].replace('\n', '
')
+ + '''
Emscripten Compiler:
- ''' + emscripten_info[0].replace('\n', '
')
-
- charts_native = {}
- charts_html = {}
- for result in native_results['results']:
- ch = result['chart']
- if ch not in charts_native:
- charts_native[ch] = []
- charts_native[ch] += [result]
- for result in wasm_results['results']:
- ch = result['chart']
- if ch not in charts_html:
- charts_html[ch] = []
- charts_html[ch] += [result]
-
- def find_result_in_category(results, category):
- for result in results:
- if result['category'] == category:
- return result
- return None
-
- def format_comparison(a, b):
- if a < b and a != 0:
- return " {:10.2f}".format(b / a) + 'x FASTER'
- elif b != 0:
- return " {:10.2f}".format(a / b) + 'x SLOWER'
- else:
- return " NaN "
-
- chartNumber = 0
-
- total_time_native_scalar = 0
- total_time_native_simd = 0
- total_time_html_scalar = 0
- total_time_html_simd = 0
-
- for chart_name, chart_native_results in charts_native.items():
- # Extract data for each chart.
- categories = []
- nativeScalarResults = []
- nativeSimdResults = []
- htmlScalarResults = []
- htmlSimdResults = []
- native_results = chart_native_results
- wasm_results = charts_html[chart_name]
- textual_results_native = ''
- textual_results_html = '
'
- textual_results_html2 = '
'
- textual_results_html3 = '
'
- for result in native_results:
- categories += ["'" + result['category'] + "'"]
- nsc = result['scalar']
- nsi = result['simd']
- nativeScalarResults += [str(nsc)]
- nativeSimdResults += [str(nsi)]
- html_result = find_result_in_category(wasm_results, result['category'])
- textual_results_native += 'Native ' + result['category'] + ': ' + "{:10.4f}".format(nsc) + 'ns -> ' + "{:10.4f}".format(nsi) + 'ns. '
- textual_results_native += 'Native SSE is ' + format_comparison(nsi, nsc) + ' than native scalar.
'
-
- if html_result is not None:
- hsc = html_result['scalar']
- htmlScalarResults += [str(hsc)]
- hsi = html_result['simd']
- htmlSimdResults += [str(hsi)]
- textual_results_html += 'JS ' + result['category'] + ': ' + "{:10.4f}".format(hsc) + 'ns -> ' + "{:10.4f}".format(hsi) + 'ns. '
- textual_results_html += 'JS SSE is ' + format_comparison(hsi, hsc) + ' than JS scalar.
'
- textual_results_html2 += 'JS ' + result['category'] + ': JS scalar is ' + format_comparison(hsc, nsc) + ' than native scalar.
'
- textual_results_html3 += 'JS ' + result['category'] + ': JS SSE is ' + format_comparison(hsi, nsi) + ' than native SSE.
'
- total_time_native_scalar += nsc
- total_time_native_simd += nsi
- total_time_html_scalar += hsc
- total_time_html_simd += hsi
- else:
- htmlScalarResults += [str(-1)]
- htmlSimdResults += [str(-1)]
-
- chartNumber += 1
- html += '
'
- html += '''''' + '' + textual_results_native + ' | ' + textual_results_html + ' |
' + textual_results_html2 + ' | ' + textual_results_html3 + ' |
'
-
- # Final overall score
-
- html += ''
- html += ''''''
+ + ''
+ + textual_results_native
+ + ' | '
+ + textual_results_html
+ + ' |
'
+ + textual_results_html2
+ + ' | '
+ + textual_results_html3
+ + ' |
'
+ )
+
+ # Final overall score
+
+ html += ''
+ html += (
+ ''''''
+ )
- html += ''
+ html += ''
- open(results_file, 'w').write(html)
- print('Wrote ' + str(len(html)) + ' bytes to file ' + results_file + '.')
+ open(results_file, 'w').write(html)
+ print('Wrote ' + str(len(html)) + ' bytes to file ' + results_file + '.')
if __name__ == '__main__':
- suite = sys.argv[1].lower() if len(sys.argv) == 2 else None
- if suite in ['sse', 'sse1']:
- run_benchmark(test_file('sse/benchmark_sse1.cpp'), 'results_sse1.html', ['-msse'])
- elif suite == 'sse2':
- run_benchmark(test_file('sse/benchmark_sse2.cpp'), 'results_sse2.html', ['-msse2'])
- elif suite == 'sse3':
- run_benchmark(test_file('sse/benchmark_sse3.cpp'), 'results_sse3.html', ['-msse3'])
- elif suite == 'ssse3':
- run_benchmark(test_file('sse/benchmark_ssse3.cpp'), 'results_ssse3.html', ['-mssse3'])
- else:
- raise Exception('Usage: python test/benchmark_sse.py sse1|sse2|sse3')
+ suite = sys.argv[1].lower() if len(sys.argv) == 2 else None
+ if suite in ['sse', 'sse1']:
+ run_benchmark(test_file('sse/benchmark_sse1.cpp'), 'results_sse1.html', ['-msse'])
+ elif suite == 'sse2':
+ run_benchmark(test_file('sse/benchmark_sse2.cpp'), 'results_sse2.html', ['-msse2'])
+ elif suite == 'sse3':
+ run_benchmark(test_file('sse/benchmark_sse3.cpp'), 'results_sse3.html', ['-msse3'])
+ elif suite == 'ssse3':
+ run_benchmark(test_file('sse/benchmark_ssse3.cpp'), 'results_ssse3.html', ['-mssse3'])
+ else:
+ raise Exception('Usage: python test/benchmark_sse.py sse1|sse2|sse3')
diff --git a/test/clang_native.py b/test/clang_native.py
index 1193eb969bf52..027bd5205f2f5 100644
--- a/test/clang_native.py
+++ b/test/clang_native.py
@@ -15,15 +15,15 @@
def get_native_triple():
arch = {
- 'aarch64': 'arm64',
- 'arm64': 'arm64',
- 'x86_64': 'x86_64',
- 'AMD64': 'x86_64',
+ 'aarch64': 'arm64',
+ 'arm64': 'arm64',
+ 'x86_64': 'x86_64',
+ 'AMD64': 'x86_64',
}[platform.machine()]
OS = {
- 'linux': 'linux',
- 'darwin': 'darwin',
- 'win32': 'windows-msvc',
+ 'linux': 'linux',
+ 'darwin': 'darwin',
+ 'win32': 'windows-msvc',
}[sys.platform]
return f'{arch}-{OS}'
@@ -78,7 +78,11 @@ def get_clang_native_env():
else:
visual_studio_path = 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0'
if not os.path.isdir(visual_studio_path):
- raise Exception('Visual Studio 2015 was not found in "' + visual_studio_path + '"! Run in Visual Studio X64 command prompt to avoid the need to autoguess this location (or set VSINSTALLDIR env var).')
+ raise Exception(
+ 'Visual Studio 2015 was not found in "'
+ + visual_studio_path
+ + '"! Run in Visual Studio X64 command prompt to avoid the need to autoguess this location (or set VSINSTALLDIR env var).'
+ )
# Guess where Program Files (x86) is located
if 'ProgramFiles(x86)' in env:
@@ -98,19 +102,31 @@ def get_clang_native_env():
else:
windows8_sdk_dir = os.path.join(prog_files_x86, 'Windows Kits', '8.1')
if not os.path.isdir(windows8_sdk_dir):
- raise Exception('Windows 8.1 SDK was not found in "' + windows8_sdk_dir + '"! Run in Visual Studio command prompt to avoid the need to autoguess this location (or set WindowsSdkDir env var).')
+ raise Exception(
+ 'Windows 8.1 SDK was not found in "'
+ + windows8_sdk_dir
+ + '"! Run in Visual Studio command prompt to avoid the need to autoguess this location (or set WindowsSdkDir env var).'
+ )
# Guess where Windows 10 SDK is located
if os.path.isdir(os.path.join(prog_files_x86, 'Windows Kits', '10')):
windows10_sdk_dir = os.path.join(prog_files_x86, 'Windows Kits', '10')
if not os.path.isdir(windows10_sdk_dir):
- raise Exception('Windows 10 SDK was not found in "' + windows10_sdk_dir + '"! Run in Visual Studio command prompt to avoid the need to autoguess this location.')
+ raise Exception(
+ 'Windows 10 SDK was not found in "'
+ + windows10_sdk_dir
+ + '"! Run in Visual Studio command prompt to avoid the need to autoguess this location.'
+ )
env.setdefault('VSINSTALLDIR', visual_studio_path)
env.setdefault('VCINSTALLDIR', os.path.join(visual_studio_path, 'VC'))
windows10sdk_kits_include_dir = os.path.join(windows10_sdk_dir, 'Include')
- windows10sdk_kit_version_name = [x for x in os.listdir(windows10sdk_kits_include_dir) if os.path.isdir(os.path.join(windows10sdk_kits_include_dir, x))][0] # e.g. "10.0.10150.0" or "10.0.10240.0"
+ windows10sdk_kit_version_name = [
+ x
+ for x in os.listdir(windows10sdk_kits_include_dir)
+ if os.path.isdir(os.path.join(windows10sdk_kits_include_dir, x))
+ ][0] # e.g. "10.0.10150.0" or "10.0.10240.0"
def append_item(key, item):
if key not in env or len(env[key].strip()) == 0:
diff --git a/test/common.py b/test/common.py
index 541d89aaca73f..02367a76e48f2 100644
--- a/test/common.py
+++ b/test/common.py
@@ -191,6 +191,7 @@ def no_wasm64(note=''):
def decorated(f):
return skip_if(f, 'is_wasm64', note)
+
return decorated
@@ -206,7 +207,9 @@ def decorated(self, *args, **kwargs):
if self.get_setting('INITIAL_MEMORY') == '2200mb':
self.skipTest(note)
f(self, *args, **kwargs)
+
return decorated
+
return decorator
@@ -221,7 +224,9 @@ def decorated(self, *args, **kwargs):
if self.is_4gb():
self.skipTest(note)
f(self, *args, **kwargs)
+
return decorated
+
return decorator
@@ -328,6 +333,7 @@ def node_pthreads(f):
def decorated(self, *args, **kwargs):
self.setup_node_pthreads()
f(self, *args, **kwargs)
+
return decorated
@@ -366,6 +372,7 @@ def decorated(f):
def modified(self, *args, **kwargs):
with env_modify(updates):
return f(self, *args, **kwargs)
+
return modified
return decorated
@@ -384,8 +391,7 @@ def metafunc(self, wasmfs, *args, **kwargs):
self.emcc_args += ['-DMEMFS']
f(self, *args, **kwargs)
- parameterize(metafunc, {'': (False,),
- 'wasmfs': (True,)})
+ parameterize(metafunc, {'': (False,), 'wasmfs': (True,)})
return metafunc
@@ -401,8 +407,13 @@ def metafunc(self, fs, *args, **kwargs):
assert fs is None
func(self, *args, **kwargs)
- parameterize(metafunc, {'': (None,),
- 'nodefs': ('nodefs',)})
+ parameterize(
+ metafunc,
+ {
+ '': (None,),
+ 'nodefs': ('nodefs',),
+ },
+ )
return metafunc
@@ -420,9 +431,14 @@ def metafunc(self, fs, *args, **kwargs):
assert fs is None
func(self, *args, **kwargs)
- parameterize(metafunc, {'': (None,),
- 'nodefs': ('nodefs',),
- 'rawfs': ('rawfs',)})
+ parameterize(
+ metafunc,
+ {
+ '': (None,),
+ 'nodefs': ('nodefs',),
+ 'rawfs': ('rawfs',),
+ },
+ )
return metafunc
@@ -444,10 +460,15 @@ def metafunc(self, fs, *args, **kwargs):
# TODO(sbc): rather than treat WASMFS as orthogonal we should
# probably make it combinatorial with nodefs and noderawfs.
- parameterize(metafunc, {'': (None,),
- 'nodefs': ('nodefs',),
- 'rawfs': ('rawfs',),
- 'wasmfs': ('wasmfs',)})
+ parameterize(
+ metafunc,
+ {
+ '': (None,),
+ 'nodefs': ('nodefs',),
+ 'rawfs': ('rawfs',),
+ 'wasmfs': ('wasmfs',),
+ },
+ )
return metafunc
@@ -464,14 +485,12 @@ def metafunc(self, rawfs, *args, **kwargs):
self.emcc_args += ['-DMEMFS']
func(self, *args, **kwargs)
- parameterize(metafunc, {'': (False,),
- 'rawfs': (True,)})
+ parameterize(metafunc, {'': (False,), 'rawfs': (True,)})
return metafunc
# Decorator version of env_modify
def also_with_env_modify(name_updates_mapping):
-
def decorated(f):
@wraps(f)
def metafunc(self, updates, *args, **kwargs):
@@ -506,8 +525,7 @@ def metafunc(self, with_minimal_runtime, *args, **kwargs):
self.set_setting('MINIMAL_RUNTIME', 1)
f(self, *args, **kwargs)
- parameterize(metafunc, {'': (False,),
- 'minimal_runtime': (True,)})
+ parameterize(metafunc, {'': (False,), 'minimal_runtime': (True,)})
return metafunc
@@ -530,8 +548,7 @@ def metafunc(self, with_bigint, *args, **kwargs):
else:
f(self, *args, **kwargs)
- parameterize(metafunc, {'': (False,),
- 'bigint': (True,)})
+ parameterize(metafunc, {'': (False,), 'bigint': (True,)})
return metafunc
@@ -549,8 +566,7 @@ def metafunc(self, with_wasm64, *args, **kwargs):
else:
f(self, *args, **kwargs)
- parameterize(metafunc, {'': (False,),
- 'wasm64': (True,)})
+ parameterize(metafunc, {'': (False,), 'wasm64': (True,)})
return metafunc
@@ -569,8 +585,7 @@ def metafunc(self, with_wasm2js, *args, **kwargs):
else:
f(self, *args, **kwargs)
- parameterize(metafunc, {'': (False,),
- 'wasm2js': (True,)})
+ parameterize(metafunc, {'': (False,), 'wasm2js': (True,)})
return metafunc
@@ -583,11 +598,13 @@ def can_do_standalone(self, impure=False):
# This is way to detect the core_2gb test mode in test_core.py
if self.get_setting('INITIAL_MEMORY') == '2200mb':
return False
- return self.is_wasm() and \
- self.get_setting('STACK_OVERFLOW_CHECK', 0) < 2 and \
- not self.get_setting('MINIMAL_RUNTIME') and \
- not self.get_setting('SAFE_HEAP') and \
- not any(a.startswith('-fsanitize=') for a in self.emcc_args)
+ return (
+ self.is_wasm()
+ and self.get_setting('STACK_OVERFLOW_CHECK', 0) < 2
+ and not self.get_setting('MINIMAL_RUNTIME')
+ and not self.get_setting('SAFE_HEAP')
+ and not any(a.startswith('-fsanitize=') for a in self.emcc_args)
+ )
# Impure means a test that cannot run in a wasm VM yet, as it is not 100%
@@ -618,8 +635,7 @@ def metafunc(self, standalone):
self.node_args += shared.node_bigint_flags(nodejs)
func(self)
- parameterize(metafunc, {'': (False,),
- 'standalone': (True,)})
+ parameterize(metafunc, {'': (False,), 'standalone': (True,)})
return metafunc
return decorated
@@ -662,9 +678,7 @@ def metafunc(self, mode, *args, **kwargs):
self.set_setting('DEFAULT_TO_CXX')
f(self, *args, **kwargs)
- parameterize(metafunc, {'emscripten': ('emscripten',),
- 'wasm': ('wasm',),
- 'wasm_exnref': ('wasm_exnref',)})
+ parameterize(metafunc, {'emscripten': ('emscripten',), 'wasm': ('wasm',), 'wasm_exnref': ('wasm_exnref',)})
return metafunc
@@ -692,9 +706,7 @@ def metafunc(self, mode, *args, **kwargs):
self.set_setting('SUPPORT_LONGJMP', 'emscripten')
f(self, *args, **kwargs)
- parameterize(metafunc, {'emscripten': ('emscripten',),
- 'wasm': ('wasm',),
- 'wasm_exnref': ('wasm_exnref',)})
+ parameterize(metafunc, {'emscripten': ('emscripten',), 'wasm': ('wasm',), 'wasm_exnref': ('wasm_exnref',)})
return metafunc
@@ -716,11 +728,11 @@ def limit_size(string):
if len(line) > max_line:
lines[i] = line[:max_line] + '[..]'
if len(lines) > maxlines:
- lines = lines[0:maxlines // 2] + ['[..]'] + lines[-maxlines // 2:]
+ lines = lines[0 : maxlines // 2] + ['[..]'] + lines[-maxlines // 2 :]
lines.append('(not all output shown. See `limit_size`)')
string = '\n'.join(lines) + '\n'
if len(string) > maxbytes:
- string = string[0:maxbytes // 2] + '\n[..]\n' + string[-maxbytes // 2:]
+ string = string[0 : maxbytes // 2] + '\n[..]\n' + string[-maxbytes // 2 :]
return string
@@ -765,8 +777,7 @@ def force_delete_contents(dirname):
def find_browser_test_file(filename):
- """Looks for files in test/browser and then in test/
- """
+ """Looks for files in test/browser and then in test/"""
if not os.path.exists(filename):
fullname = test_file('browser', filename)
if not os.path.exists(fullname):
@@ -786,7 +797,8 @@ def parameterize(func, parameters):
if prev:
# If we're parameterizing 2nd time, construct a cartesian product for various combinations.
func._parameterize = {
- '_'.join(filter(None, [k1, k2])): v2 + v1 for (k1, v1), (k2, v2) in itertools.product(prev.items(), parameters.items())
+ '_'.join(filter(None, [k1, k2])): v2 + v1
+ for (k1, v1), (k2, v2) in itertools.product(prev.items(), parameters.items())
}
else:
func._parameterize = parameters
@@ -812,9 +824,11 @@ def test_something_subtest1(self):
def test_something_subtest2(self):
# runs test_something(4, 5, 6)
"""
+
def decorator(func):
parameterize(func, parameters)
return func
+
return decorator
@@ -1109,7 +1123,7 @@ def set_temp_dir(self, temp_dir):
@classmethod
def setUpClass(cls):
super().setUpClass()
- print('(checking sanity from test runner)') # do this after we set env stuff
+ print('(checking sanity from test runner)') # do this after we set env stuff
shared.check_sanity(force=True)
def setUp(self):
@@ -1148,12 +1162,15 @@ def setUp(self):
emcc_min_node_version = (
int(emcc_min_node_version_str[0:2]),
int(emcc_min_node_version_str[2:4]),
- int(emcc_min_node_version_str[4:6])
+ int(emcc_min_node_version_str[4:6]),
)
if node_version < emcc_min_node_version:
self.emcc_args += building.get_emcc_node_flags(node_version)
self.emcc_args.append('-Wno-transpile')
- if node_version[0] < feature_matrix.min_browser_versions[feature_matrix.Feature.JS_BIGINT_INTEGRATION]['node'] / 10000:
+ if (
+ node_version[0]
+ < feature_matrix.min_browser_versions[feature_matrix.Feature.JS_BIGINT_INTEGRATION]['node'] / 10000
+ ):
self.emcc_args.append('-sWASM_BIGINT=0')
self.v8_args = ['--wasm-staging']
@@ -1216,16 +1233,19 @@ def tearDown(self):
# They may not be due to us, but e.g. the browser when running browser
# tests. Until we figure out a proper solution, ignore some temp file
# names that we see on our CI infrastructure.
- ignorable_file_prefixes = [
- '/tmp/tmpaddon',
- '/tmp/circleci-no-output-timeout',
- '/tmp/wasmer'
- ]
+ ignorable_file_prefixes = ['/tmp/tmpaddon', '/tmp/circleci-no-output-timeout', '/tmp/wasmer']
left_over_files = set(temp_files_after_run) - set(self.temp_files_before_run)
- left_over_files = [f for f in left_over_files if not any([f.startswith(prefix) for prefix in ignorable_file_prefixes])]
+ left_over_files = [
+ f for f in left_over_files if not any([f.startswith(prefix) for prefix in ignorable_file_prefixes])
+ ]
if len(left_over_files):
- print('ERROR: After running test, there are ' + str(len(left_over_files)) + ' new temporary files/directories left behind:', file=sys.stderr)
+ print(
+ 'ERROR: After running test, there are '
+ + str(len(left_over_files))
+ + ' new temporary files/directories left behind:',
+ file=sys.stderr,
+ )
for f in left_over_files:
print('leaked file: ' + f, file=sys.stderr)
self.fail('Test leaked ' + str(len(left_over_files)) + ' temporary files!')
@@ -1286,7 +1306,17 @@ def add_on_exit(self, code):
# libraries, for example
def get_emcc_args(self, main_file=False, compile_only=False, asm_only=False):
def is_ldflag(f):
- return any(f.startswith(s) for s in ['-sEXPORT_ES6', '-sPROXY_TO_PTHREAD', '-sENVIRONMENT=', '--pre-js=', '--post-js=', '-sPTHREAD_POOL_SIZE='])
+ return any(
+ f.startswith(s)
+ for s in [
+ '-sEXPORT_ES6',
+ '-sPROXY_TO_PTHREAD',
+ '-sENVIRONMENT=',
+ '--pre-js=',
+ '--post-js=',
+ '-sPTHREAD_POOL_SIZE=',
+ ]
+ )
args = self.serialize_settings(compile_only or asm_only) + self.emcc_args
if asm_only:
@@ -1325,7 +1355,9 @@ def verify_es5(self, filename):
self.fail('es-check failed to verify ES5 output compliance')
# Build JavaScript code from source code
- def build(self, filename, libraries=None, includes=None, force_c=False, js_outfile=True, emcc_args=None, output_basename=None):
+ def build(
+ self, filename, libraries=None, includes=None, force_c=False, js_outfile=True, emcc_args=None, output_basename=None
+ ):
if not os.path.exists(filename):
filename = test_file(filename)
suffix = '.js' if js_outfile else '.wasm'
@@ -1363,7 +1395,7 @@ def get_func(self, src, name):
elif src[t] == '}':
n -= 1
if n == 0:
- return src[start:t + 1]
+ return src[start : t + 1]
t += 1
assert t < len(src)
@@ -1384,7 +1416,9 @@ def count_funcs(self, javascript_file):
return num_funcs
def count_wasm_contents(self, wasm_binary, what):
- out = self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-opt'), wasm_binary, '--metrics'], stdout=PIPE).stdout
+ out = self.run_process(
+ [os.path.join(building.get_binaryen_bin(), 'wasm-opt'), wasm_binary, '--metrics'], stdout=PIPE
+ ).stdout
# output is something like
# [?] : 125
for line in out.splitlines():
@@ -1433,9 +1467,7 @@ def cleanup(line):
assert len(long_lines) == 1
return '\n'.join(lines)
- def run_js(self, filename, engine=None, args=None,
- assert_returncode=0,
- interleaved_output=True):
+ def run_js(self, filename, engine=None, args=None, assert_returncode=0, interleaved_output=True):
# use files, as PIPE can get too full and hang us
stdout_file = self.in_dir('stdout')
stderr_file = None
@@ -1454,10 +1486,7 @@ def run_js(self, filename, engine=None, args=None,
if engine == config.V8_ENGINE:
engine = engine + self.v8_args
try:
- jsrun.run_js(filename, engine, args,
- stdout=stdout,
- stderr=stderr,
- assert_returncode=assert_returncode)
+ jsrun.run_js(filename, engine, args, stdout=stdout, stderr=stderr, assert_returncode=assert_returncode)
except subprocess.TimeoutExpired as e:
timeout_error = e
except subprocess.CalledProcessError as e:
@@ -1491,7 +1520,10 @@ def run_js(self, filename, engine=None, args=None,
if assert_returncode == NON_ZERO:
self.fail('JS subprocess unexpectedly succeeded (%s): Output:\n%s' % (error.cmd, ret))
else:
- self.fail('JS subprocess failed (%s): %s (expected=%s). Output:\n%s' % (error.cmd, error.returncode, assert_returncode, ret))
+ self.fail(
+ 'JS subprocess failed (%s): %s (expected=%s). Output:\n%s'
+ % (error.cmd, error.returncode, assert_returncode, ret)
+ )
# We should pass all strict mode checks
self.assertNotContained('strict warning:', ret)
@@ -1515,21 +1547,18 @@ def assertPathsIdentical(self, path1, path2):
# Tests that the given two multiline text content are identical, modulo line
# ending differences (\r\n on Windows, \n on Unix).
- def assertTextDataIdentical(self, text1, text2, msg=None,
- fromfile='expected', tofile='actual'):
+ def assertTextDataIdentical(self, text1, text2, msg=None, fromfile='expected', tofile='actual'):
text1 = text1.replace('\r\n', '\n')
text2 = text2.replace('\r\n', '\n')
return self.assertIdentical(text1, text2, msg, fromfile, tofile)
- def assertIdentical(self, values, y, msg=None,
- fromfile='expected', tofile='actual'):
+ def assertIdentical(self, values, y, msg=None, fromfile='expected', tofile='actual'):
if type(values) not in (list, tuple):
values = [values]
for x in values:
if x == y:
- return # success
- diff_lines = difflib.unified_diff(x.splitlines(), y.splitlines(),
- fromfile=fromfile, tofile=tofile)
+ return # success
+ diff_lines = difflib.unified_diff(x.splitlines(), y.splitlines(), fromfile=fromfile, tofile=tofile)
diff = ''.join([a.rstrip() + '\n' for a in diff_lines])
if EMTEST_VERBOSE:
print("Expected to have '%s' == '%s'" % (limit_size(values[0]), limit_size(y)))
@@ -1557,12 +1586,10 @@ def assertFileContents(self, filename, contents):
return
if not os.path.exists(filename):
- self.fail('Test expectation file not found: ' + filename + '.\n' +
- 'Run with --rebaseline to generate.')
+ self.fail('Test expectation file not found: ' + filename + '.\n' + 'Run with --rebaseline to generate.')
expected_content = read_file(filename)
message = "Run with --rebaseline to automatically update expectations"
- self.assertTextDataIdentical(expected_content, contents, message,
- filename, filename + '.new')
+ self.assertTextDataIdentical(expected_content, contents, message, filename, filename + '.new')
def assertContained(self, values, string, additional_info='', regex=False):
if callable(string):
@@ -1582,14 +1609,14 @@ def assertContained(self, values, string, additional_info='', regex=False):
if not any(v in string for v in values):
diff = difflib.unified_diff(values[0].split('\n'), string.split('\n'), fromfile='expected', tofile='actual')
diff = ''.join(a.rstrip() + '\n' for a in diff)
- self.fail("Expected to find '%s' in '%s', diff:\n\n%s\n%s" % (
- limit_size(values[0]), limit_size(string), limit_size(diff),
- additional_info
- ))
+ self.fail(
+ "Expected to find '%s' in '%s', diff:\n\n%s\n%s"
+ % (limit_size(values[0]), limit_size(string), limit_size(diff), additional_info)
+ )
def assertNotContained(self, value, string):
if callable(value):
- value = value() # lazy loading
+ value = value() # lazy loading
if callable(string):
string = string()
if value in string:
@@ -1602,10 +1629,8 @@ def assertContainedIf(self, value, string, condition):
self.assertNotContained(value, string)
def assertBinaryEqual(self, file1, file2):
- self.assertEqual(os.path.getsize(file1),
- os.path.getsize(file2))
- self.assertEqual(read_binary(file1),
- read_binary(file2))
+ self.assertEqual(os.path.getsize(file1), os.path.getsize(file2))
+ self.assertEqual(read_binary(file1), read_binary(file2))
def check_expected_size_in_file(self, desc, filename, size):
if EMTEST_REBASELINE:
@@ -1614,7 +1639,9 @@ def check_expected_size_in_file(self, desc, filename, size):
expected_size = int(read_file(filename).strip())
delta = size - expected_size
ratio = abs(delta) / float(expected_size)
- print(' seen %s size: %d (expected: %d) (delta: %d), ratio to expected: %f' % (desc, size, expected_size, delta, ratio))
+ print(
+ ' seen %s size: %d (expected: %d) (delta: %d), ratio to expected: %f' % (desc, size, expected_size, delta, ratio)
+ )
self.assertLess(ratio, size_slack)
library_cache: Dict[str, Tuple[str, object]] = {}
@@ -1624,10 +1651,19 @@ def get_build_dir(self):
ensure_dir(ret)
return ret
- def get_library(self, name, generated_libs, configure=['sh', './configure'], # noqa
- configure_args=None, make=None, make_args=None,
- env_init=None, cache_name_extra='', native=False,
- force_rebuild=False):
+ def get_library(
+ self,
+ name,
+ generated_libs,
+ configure=['sh', './configure'], # noqa
+ configure_args=None,
+ make=None,
+ make_args=None,
+ env_init=None,
+ cache_name_extra='',
+ native=False,
+ force_rebuild=False,
+ ):
if make is None:
make = ['make']
if env_init is None:
@@ -1646,7 +1682,13 @@ def get_library(self, name, generated_libs, configure=['sh', './configure'], #
emcc_args = self.get_emcc_args(compile_only=True)
hash_input = (str(emcc_args) + ' $ ' + str(env_init)).encode('utf-8')
- cache_name = name + ','.join([opt for opt in emcc_args if len(opt) < 7]) + '_' + hashlib.md5(hash_input).hexdigest() + cache_name_extra
+ cache_name = (
+ name
+ + ','.join([opt for opt in emcc_args if len(opt) < 7])
+ + '_'
+ + hashlib.md5(hash_input).hexdigest()
+ + cache_name_extra
+ )
valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
cache_name = ''.join([(c if c in valid_chars else '_') for c in cache_name])
@@ -1669,9 +1711,19 @@ def get_library(self, name, generated_libs, configure=['sh', './configure'], #
cflags = ' '.join(emcc_args)
env_init.setdefault('CFLAGS', cflags)
env_init.setdefault('CXXFLAGS', cflags)
- return build_library(name, build_dir, output_dir, generated_libs, configure,
- make, make_args, self.library_cache,
- cache_name, env_init=env_init, native=native)
+ return build_library(
+ name,
+ build_dir,
+ output_dir,
+ generated_libs,
+ configure,
+ make,
+ make_args,
+ self.library_cache,
+ cache_name,
+ env_init=env_init,
+ native=native,
+ )
def clear(self):
force_delete_contents(self.get_dir())
@@ -1730,7 +1782,9 @@ def expect_fail(self, cmd, expect_traceback=False, **args):
# when run under browser it excercises how dynamic linker handles concurrency
# - because B and C are loaded in parallel.
def _test_dylink_dso_needed(self, do_run):
- create_file('liba.cpp', r'''
+ create_file(
+ 'liba.cpp',
+ r'''
#include
#include
@@ -1752,9 +1806,12 @@ def _test_dylink_dso_needed(self, do_run):
};
static ainit _;
- ''')
+ ''',
+ )
- create_file('libb.c', r'''
+ create_file(
+ 'libb.c',
+ r'''
#include
void afunc(const char *s);
@@ -1762,9 +1819,12 @@ def _test_dylink_dso_needed(self, do_run):
EMSCRIPTEN_KEEPALIVE void bfunc() {
afunc("b");
}
- ''')
+ ''',
+ )
- create_file('libc.c', r'''
+ create_file(
+ 'libc.c',
+ r'''
#include
void afunc(const char *s);
@@ -1772,7 +1832,8 @@ def _test_dylink_dso_needed(self, do_run):
EMSCRIPTEN_KEEPALIVE void cfunc() {
afunc("c");
}
- ''')
+ ''',
+ )
# _test_dylink_dso_needed can be potentially called several times by a test.
# reset dylink-related options first.
@@ -1797,7 +1858,8 @@ def ccshared(src, linkto=None):
self.set_setting('MAIN_MODULE')
extra_args = ['-L.', 'libb' + so, 'libc' + so]
- do_run(r'''
+ do_run(
+ r'''
#ifdef __cplusplus
extern "C" {
#endif
@@ -1813,12 +1875,15 @@ def ccshared(src, linkto=None):
return 0;
}
''',
- 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args)
+ 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n',
+ emcc_args=extra_args,
+ )
extra_args = []
for libname in ('liba', 'libb', 'libc'):
extra_args += ['--embed-file', libname + so]
- do_run(r'''
+ do_run(
+ r'''
#include
#include
#include
@@ -1842,8 +1907,11 @@ def ccshared(src, linkto=None):
cfunc_ptr();
return 0;
}
- ''' % locals(),
- 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args)
+ '''
+ % locals(),
+ 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n',
+ emcc_args=extra_args,
+ )
def do_run(self, src, expected_output=None, force_c=False, **kwargs):
if 'no_build' in kwargs:
@@ -1874,23 +1942,37 @@ def do_run_in_out_file_test(self, srcfile, **kwargs):
return output
## Does a complete test - builds, runs, checks output, etc.
- def _build_and_run(self, filename, expected_output, args=None,
- no_build=False,
- libraries=None,
- includes=None,
- assert_returncode=0, assert_identical=False, assert_all=False,
- check_for_error=True, force_c=False, emcc_args=None,
- interleaved_output=True,
- regex=False,
- output_basename=None):
+ def _build_and_run(
+ self,
+ filename,
+ expected_output,
+ args=None,
+ no_build=False,
+ libraries=None,
+ includes=None,
+ assert_returncode=0,
+ assert_identical=False,
+ assert_all=False,
+ check_for_error=True,
+ force_c=False,
+ emcc_args=None,
+ interleaved_output=True,
+ regex=False,
+ output_basename=None,
+ ):
logger.debug(f'_build_and_run: {filename}')
if no_build:
js_file = filename
else:
- js_file = self.build(filename, libraries=libraries, includes=includes,
- force_c=force_c, emcc_args=emcc_args,
- output_basename=output_basename)
+ js_file = self.build(
+ filename,
+ libraries=libraries,
+ includes=includes,
+ force_c=force_c,
+ emcc_args=emcc_args,
+ output_basename=output_basename,
+ )
self.assertExists(js_file)
engines = self.js_engines.copy()
@@ -1906,9 +1988,9 @@ def _build_and_run(self, filename, expected_output, args=None,
if len(engines) == 0:
self.fail('No JS engine present to run this test with. Check %s and the paths therein.' % config.EM_CONFIG)
for engine in engines:
- js_output = self.run_js(js_file, engine, args,
- assert_returncode=assert_returncode,
- interleaved_output=interleaved_output)
+ js_output = self.run_js(
+ js_file, engine, args, assert_returncode=assert_returncode, interleaved_output=interleaved_output
+ )
js_output = js_output.replace('\r\n', '\n')
if expected_output:
if type(expected_output) not in [list, tuple]:
@@ -1938,16 +2020,18 @@ def get_freetype_library(self):
# And because gnu-offsetof-extensions is a new warning:
'-Wno-unknown-warning-option',
]
- return self.get_library(os.path.join('third_party', 'freetype'),
- os.path.join('objs', '.libs', 'libfreetype.a'),
- configure_args=['--disable-shared', '--without-zlib'])
+ return self.get_library(
+ os.path.join('third_party', 'freetype'),
+ os.path.join('objs', '.libs', 'libfreetype.a'),
+ configure_args=['--disable-shared', '--without-zlib'],
+ )
def get_poppler_library(self, env_init=None):
freetype = self.get_freetype_library()
self.emcc_args += [
'-I' + test_file('third_party/freetype/include'),
- '-I' + test_file('third_party/poppler/include')
+ '-I' + test_file('third_party/poppler/include'),
]
# Poppler has some pretty glaring warning. Suppress them to keep the
@@ -1973,10 +2057,24 @@ def get_poppler_library(self, env_init=None):
env_init['FONTCONFIG_LIBS'] = ' '
poppler = self.get_library(
- os.path.join('third_party', 'poppler'),
- [os.path.join('utils', 'pdftoppm.o'), os.path.join('utils', 'parseargs.o'), os.path.join('poppler', '.libs', 'libpoppler.a')],
- env_init=env_init,
- configure_args=['--disable-libjpeg', '--disable-libpng', '--disable-poppler-qt', '--disable-poppler-qt4', '--disable-cms', '--disable-cairo-output', '--disable-abiword-output', '--disable-shared'])
+ os.path.join('third_party', 'poppler'),
+ [
+ os.path.join('utils', 'pdftoppm.o'),
+ os.path.join('utils', 'parseargs.o'),
+ os.path.join('poppler', '.libs', 'libpoppler.a'),
+ ],
+ env_init=env_init,
+ configure_args=[
+ '--disable-libjpeg',
+ '--disable-libpng',
+ '--disable-poppler-qt',
+ '--disable-poppler-qt4',
+ '--disable-cms',
+ '--disable-cairo-output',
+ '--disable-abiword-output',
+ '--disable-shared',
+ ],
+ )
return poppler + freetype
@@ -1992,10 +2090,13 @@ def get_zlib_library(self, cmake):
# https://github.com/emscripten-core/emscripten/issues/16908 is fixed
self.emcc_args.append('-Wno-pointer-sign')
if cmake:
- rtn = self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'),
- configure=['cmake', '.'],
- make=['cmake', '--build', '.', '--'],
- make_args=[])
+ rtn = self.get_library(
+ os.path.join('third_party', 'zlib'),
+ os.path.join('libz.a'),
+ configure=['cmake', '.'],
+ make=['cmake', '--build', '.', '--'],
+ make_args=[],
+ )
else:
rtn = self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), make_args=['libz.a'])
self.emcc_args = old_args
@@ -2131,7 +2232,7 @@ def log_request(code=0, size=0):
SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm'
httpd = HTTPServer(('localhost', port), TestServerHandler)
- httpd.serve_forever() # test runner will kill us
+ httpd.serve_forever() # test runner will kill us
class Reporting(Enum):
@@ -2139,6 +2240,7 @@ class Reporting(Enum):
code for reporting results back to the browser. This enum allows tests
to decide what type of support code they need/want.
"""
+
NONE = 0
# Include the JS helpers for reporting results
JS_ONLY = 1
@@ -2193,7 +2295,9 @@ def setUpClass(cls):
return
cls.harness_in_queue = multiprocessing.Queue()
cls.harness_out_queue = multiprocessing.Queue()
- cls.harness_server = multiprocessing.Process(target=harness_server_func, args=(cls.harness_in_queue, cls.harness_out_queue, cls.PORT))
+ cls.harness_server = multiprocessing.Process(
+ target=harness_server_func, args=(cls.harness_in_queue, cls.harness_out_queue, cls.PORT)
+ )
cls.harness_server.start()
print('[Browser harness server on process %d]' % cls.harness_server.pid)
cls.browser_open(cls.HARNESS_URL)
@@ -2237,10 +2341,7 @@ def run_browser(self, html_file, expected=None, message=None, timeout=None, extr
assert not (message and expected), 'run_browser expects `expected` or `message`, but not both'
if expected is not None:
try:
- self.harness_in_queue.put((
- 'http://localhost:%s/%s' % (self.PORT, html_file),
- self.get_dir()
- ))
+ self.harness_in_queue.put(('http://localhost:%s/%s' % (self.PORT, html_file), self.get_dir()))
if timeout is None:
timeout = self.BROWSER_TIMEOUT
try:
@@ -2257,7 +2358,7 @@ def run_browser(self, html_file, expected=None, message=None, timeout=None, extr
# us to also fail the test
self.fail('browser harness error')
if output.startswith('/report_result?skipped:'):
- self.skipTest(unquote(output[len('/report_result?skipped:'):]).strip())
+ self.skipTest(unquote(output[len('/report_result?skipped:') :]).strip())
else:
# verify the result, and try again if we should do so
output = unquote(output)
@@ -2271,7 +2372,7 @@ def run_browser(self, html_file, expected=None, message=None, timeout=None, extr
else:
raise e
finally:
- time.sleep(0.1) # see comment about Windows above
+ time.sleep(0.1) # see comment about Windows above
self.assert_out_queue_empty('this test')
else:
webbrowser.open_new(os.path.abspath(html_file))
@@ -2292,8 +2393,11 @@ def compile_btest(self, filename, args, reporting=Reporting.FULL):
if reporting == Reporting.FULL:
# If C reporting (i.e. the REPORT_RESULT macro) is required we
# also include report_result.c and force-include report_result.h
- self.run_process([EMCC, '-c', '-I' + TEST_ROOT,
- test_file('report_result.c')] + self.get_emcc_args(compile_only=True) + (['-fPIC'] if '-fPIC' in args else []))
+ self.run_process(
+ [EMCC, '-c', '-I' + TEST_ROOT, test_file('report_result.c')]
+ + self.get_emcc_args(compile_only=True)
+ + (['-fPIC'] if '-fPIC' in args else [])
+ )
args += ['report_result.o', '-include', test_file('report_result.h')]
if EMTEST_BROWSER == 'node':
args.append('-DEMTEST_NODE')
@@ -2315,12 +2419,18 @@ def btest_exit(self, filename, assert_returncode=0, *args, **kwargs):
kwargs['expected'] = 'exit:%d' % assert_returncode
return self.btest(filename, *args, **kwargs)
- def btest(self, filename, expected=None,
- post_build=None,
- args=None, url_suffix='', timeout=None,
- extra_tries=1,
- reporting=Reporting.FULL,
- output_basename='test'):
+ def btest(
+ self,
+ filename,
+ expected=None,
+ post_build=None,
+ args=None,
+ url_suffix='',
+ timeout=None,
+ extra_tries=1,
+ reporting=Reporting.FULL,
+ output_basename='test',
+ ):
assert expected, 'a btest must have an expected output'
if args is None:
args = []
@@ -2347,23 +2457,20 @@ def btest(self, filename, expected=None,
output = self.run_js('test.js')
self.assertContained('RESULT: ' + expected[0], output)
else:
- self.run_browser(outfile + url_suffix, expected=['/report_result?' + e for e in expected], timeout=timeout, extra_tries=extra_tries)
+ self.run_browser(
+ outfile + url_suffix,
+ expected=['/report_result?' + e for e in expected],
+ timeout=timeout,
+ extra_tries=extra_tries,
+ )
###################################################################################################
-def build_library(name,
- build_dir,
- output_dir,
- generated_libs,
- configure,
- make,
- make_args,
- cache,
- cache_name,
- env_init,
- native):
+def build_library(
+ name, build_dir, output_dir, generated_libs, configure, make, make_args, cache, cache_name, env_init, native
+):
"""Build a library and cache the result. We build the library file
once and cache it for all our tests. (We cache in memory since the test
directory is destroyed and recreated for each test. Note that we cache
@@ -2406,8 +2513,7 @@ def build_library(name,
with open(os.path.join(project_dir, 'configure_err'), 'w') as err:
stdout = out if EMTEST_BUILD_VERBOSE < 2 else None
stderr = err if EMTEST_BUILD_VERBOSE < 1 else None
- shared.run_process(configure, env=env, stdout=stdout, stderr=stderr,
- cwd=project_dir)
+ shared.run_process(configure, env=env, stdout=stdout, stderr=stderr, cwd=project_dir)
except subprocess.CalledProcessError:
print('-- configure stdout --')
print(read_file(Path(project_dir, 'configure_out')))
@@ -2435,8 +2541,7 @@ def open_make_err(mode='r'):
with open_make_err('w') as make_err:
stdout = make_out if EMTEST_BUILD_VERBOSE < 2 else None
stderr = make_err if EMTEST_BUILD_VERBOSE < 1 else None
- shared.run_process(make + make_args, stdout=stdout, stderr=stderr, env=env,
- cwd=project_dir)
+ shared.run_process(make + make_args, stdout=stdout, stderr=stderr, env=env, cwd=project_dir)
except subprocess.CalledProcessError:
with open_make_out() as f:
print('-- make stdout --')
diff --git a/test/gen_large_switchcase.py b/test/gen_large_switchcase.py
index e9f5cef0825f2..e8883a903108f 100755
--- a/test/gen_large_switchcase.py
+++ b/test/gen_large_switchcase.py
@@ -15,7 +15,8 @@
i += incr
incr = (incr % 5) + 1
-print('''#include
+print(
+ '''#include
#include
#include
@@ -23,14 +24,19 @@
{
switch(x)
{
-''' + cases + '''
+'''
+ + cases
+ + '''
default: return "default";
}
}
int main()
{
- for(int i = 0; i < ''' + str((num_cases + 99) // 100) + '''; ++i)
+ for(int i = 0; i < '''
+ + str((num_cases + 99) // 100)
+ + '''; ++i)
printf("%d: %s\\n", i*301, foo(i*301));
printf("Success!\\n");
-}''')
+}'''
+)
diff --git a/test/gen_many_js_functions.py b/test/gen_many_js_functions.py
index dccc74aca2b29..80138cf448796 100644
--- a/test/gen_many_js_functions.py
+++ b/test/gen_many_js_functions.py
@@ -11,7 +11,10 @@
def func_name(i):
- return 'thisIsAFunctionWithVeryLongFunctionNameThatWouldBeGreatToBeMinifiedWhenImportingToAsmJsOrWasmSideCodeToCallOtherwiseCodeSizesWillBeLargeAndNetworkTransfersBecomeVerySlowThatUsersWillGoAwayAndVisitSomeOtherSiteInsteadAndThenWebAssemblyDeveloperIsSadOrEvenWorseNobodyNoticesButInternetPipesWillGetMoreCongestedWhichContributesToGlobalWarmingAndThenEveryoneElseWillBeSadAsWellEspeciallyThePolarBearsAndPenguinsJustThinkAboutThePenguins' + str(i + 1)
+ return (
+ 'thisIsAFunctionWithVeryLongFunctionNameThatWouldBeGreatToBeMinifiedWhenImportingToAsmJsOrWasmSideCodeToCallOtherwiseCodeSizesWillBeLargeAndNetworkTransfersBecomeVerySlowThatUsersWillGoAwayAndVisitSomeOtherSiteInsteadAndThenWebAssemblyDeveloperIsSadOrEvenWorseNobodyNoticesButInternetPipesWillGetMoreCongestedWhichContributesToGlobalWarmingAndThenEveryoneElseWillBeSadAsWellEspeciallyThePolarBearsAndPenguinsJustThinkAboutThePenguins'
+ + str(i + 1)
+ )
def generate_js_library_with_lots_of_functions(out_file):
@@ -38,7 +41,13 @@ def generate_c_program_that_calls_js_library_with_lots_of_functions(out_file):
for i in range(NUM_FUNCS_TO_GENERATE):
f.write(' sum += ' + func_name(i) + '();\n')
- f.write('\n printf("Sum of numbers from 1 to ' + str(NUM_FUNCS_TO_GENERATE) + ': %d (expected ' + str(int((NUM_FUNCS_TO_GENERATE * (NUM_FUNCS_TO_GENERATE + 1)) / 2)) + ')\\n", sum);\n')
+ f.write(
+ '\n printf("Sum of numbers from 1 to '
+ + str(NUM_FUNCS_TO_GENERATE)
+ + ': %d (expected '
+ + str(int((NUM_FUNCS_TO_GENERATE * (NUM_FUNCS_TO_GENERATE + 1)) / 2))
+ + ')\\n", sum);\n'
+ )
f.write('}\n')
diff --git a/test/jsrun.py b/test/jsrun.py
index b918becaed8e0..8f8a58d8e783a 100644
--- a/test/jsrun.py
+++ b/test/jsrun.py
@@ -12,7 +12,7 @@
from tools import shared, utils
-WORKING_ENGINES = {} # Holds all configured engines and whether they work: maps path -> True/False
+WORKING_ENGINES = {} # Holds all configured engines and whether they work: maps path -> True/False
DEFAULT_TIMEOUT = 5 * 60
@@ -83,10 +83,19 @@ def require_engine(engine):
sys.exit(1)
-def run_js(filename, engine, args=None,
- stdin=None, stdout=PIPE, stderr=None, cwd=None,
- full_output=False, assert_returncode=0, skip_check=False,
- timeout=DEFAULT_TIMEOUT):
+def run_js(
+ filename,
+ engine,
+ args=None,
+ stdin=None,
+ stdout=PIPE,
+ stderr=None,
+ cwd=None,
+ full_output=False,
+ assert_returncode=0,
+ skip_check=False,
+ timeout=DEFAULT_TIMEOUT,
+):
"""Execute javascript code generated by tests, with possible timeout."""
# We used to support True here but we no longer do. Assert here just in case.
@@ -100,13 +109,8 @@ def run_js(filename, engine, args=None,
print(f"Running: '{shared.shlex_join(command)}'")
try:
proc = subprocess.run(
- command,
- stdin=stdin,
- stdout=stdout,
- stderr=stderr,
- cwd=cwd,
- timeout=timeout,
- universal_newlines=True)
+ command, stdin=stdin, stdout=stdout, stderr=stderr, cwd=cwd, timeout=timeout, universal_newlines=True
+ )
except Exception:
# the failure may be because the engine is not present. show the proper
# error in that case
diff --git a/test/other/ports/external.py b/test/other/ports/external.py
index 5fb8c8d764f4f..2c5f57915bbad 100644
--- a/test/other/ports/external.py
+++ b/test/other/ports/external.py
@@ -18,12 +18,7 @@
}
# user options (from --use-port)
-opts: Dict[str, Optional[str]] = {
- 'value1': None,
- 'value2': None,
- 'value3': "v3",
- 'dependency': None
-}
+opts: Dict[str, Optional[str]] = {'value1': None, 'value2': None, 'value3': "v3", 'dependency': None}
deps = ['sdl2_image:formats=jpg']
diff --git a/test/parallel_testsuite.py b/test/parallel_testsuite.py
index 05f3717f47f83..013d0490835cc 100644
--- a/test/parallel_testsuite.py
+++ b/test/parallel_testsuite.py
@@ -91,11 +91,12 @@ def combine_results(self, result, buffered_results):
return result
-class BufferedParallelTestResult():
+class BufferedParallelTestResult:
"""A picklable struct used to communicate test results across processes
Fulfills the interface for unittest.TestResult
"""
+
def __init__(self):
self.buffered_result = None
@@ -145,8 +146,9 @@ def addError(self, test, err):
self.buffered_result = BufferedTestError(test, err)
-class BufferedTestBase():
+class BufferedTestBase:
"""Abstract class that holds test result data, split by type of result."""
+
def __init__(self, test, err=None):
self.test = test
if err:
@@ -181,6 +183,7 @@ def fixup_fake_exception(fake_exc):
# the data
def make_wrapper(rtn):
return lambda: rtn
+
ex.tb_frame.f_code.co_positions = make_wrapper(ex.tb_frame.f_code.positions)
ex = ex.tb_next
@@ -209,7 +212,7 @@ def updateResult(self, result):
result.addUnexpectedSuccess(self.test)
-class FakeTraceback():
+class FakeTraceback:
"""A fake version of a traceback object that is picklable across processes.
Python's traceback objects contain hidden stack information that isn't able
@@ -228,14 +231,14 @@ def __init__(self, tb):
self.tb_lasti = tb.tb_lasti
-class FakeFrame():
+class FakeFrame:
def __init__(self, f):
self.f_code = FakeCode(f.f_code)
# f.f_globals is not picklable, not used in stack traces, and needs to be iterable
self.f_globals = []
-class FakeCode():
+class FakeCode:
def __init__(self, co):
self.co_filename = co.co_filename
self.co_name = co.co_name
diff --git a/test/runner.py b/test/runner.py
index 5896fe4f15b9e..5ae1bacbafca6 100755
--- a/test/runner.py
+++ b/test/runner.py
@@ -135,7 +135,7 @@ def get_all_tests(modules):
def get_crossplatform_tests(modules):
- suites = ['core0', 'other', 'sanity'] # We don't need all versions of every test
+ suites = ['core0', 'other', 'sanity'] # We don't need all versions of every test
crossplatform_tests = []
# Walk over the test suites and find the test functions with the
# is_crossplatform_test attribute applied by @crossplatform decorator
@@ -248,15 +248,18 @@ def print_random_test_statistics(num_tests):
std = 0.5 / math.sqrt(num_tests)
expected = 100.0 * (1.0 - std)
print()
- print('running those %d randomly-selected tests. if they all pass, then there is a '
- 'greater than 95%% chance that at least %.2f%% of the test suite will pass'
- % (num_tests, expected))
+ print(
+ 'running those %d randomly-selected tests. if they all pass, then there is a '
+ 'greater than 95%% chance that at least %.2f%% of the test suite will pass' % (num_tests, expected)
+ )
print()
def show():
- print('if all tests passed then there is a greater than 95%% chance that at least '
- '%.2f%% of the test suite will pass'
- % (expected))
+ print(
+ 'if all tests passed then there is a greater than 95%% chance that at least '
+ '%.2f%% of the test suite will pass' % (expected)
+ )
+
atexit.register(show)
@@ -314,6 +317,7 @@ def flattened_tests(loaded_tests):
tests.extend(subsuite)
return tests
+
def suite_for_module(module, tests):
suite_supported = module.__name__ in ('test_core', 'test_other', 'test_posixtest')
if not common.EMTEST_SAVE_DIR and not shared.DEBUG:
@@ -338,9 +342,9 @@ def run_tests(options, suites):
os.makedirs('out', exist_ok=True)
# output fd must remain open until after testRunner.run() below
output = open('out/test-results.xml', 'wb')
- import xmlrunner # type: ignore
- testRunner = xmlrunner.XMLTestRunner(output=output, verbosity=2,
- failfast=options.failfast)
+ import xmlrunner # type: ignore
+
+ testRunner = xmlrunner.XMLTestRunner(output=output, verbosity=2, failfast=options.failfast)
print('Writing XML test output to ' + os.path.abspath(output.name))
else:
testRunner = unittest.TextTestRunner(verbosity=2, failfast=options.failfast)
@@ -348,8 +352,13 @@ def run_tests(options, suites):
for mod_name, suite in suites:
print('Running %s: (%s tests)' % (mod_name, suite.countTestCases()))
res = testRunner.run(suite)
- msg = ('%s: %s run, %s errors, %s failures, %s skipped' %
- (mod_name, res.testsRun, len(res.errors), len(res.failures), len(res.skipped)))
+ msg = '%s: %s run, %s errors, %s failures, %s skipped' % (
+ mod_name,
+ res.testsRun,
+ len(res.errors),
+ len(res.failures),
+ len(res.skipped),
+ )
num_failures += len(res.errors) + len(res.failures) + len(res.unexpectedSuccesses)
resultMessages.append(msg)
@@ -365,32 +374,41 @@ def run_tests(options, suites):
def parse_args(args):
parser = argparse.ArgumentParser(prog='runner.py', description=__doc__)
- parser.add_argument('--save-dir', action='store_true',
- help='Save the temporary directory used during for each '
- 'test. Implies --cores=1. Defaults to true when running a single test')
- parser.add_argument('--no-clean', action='store_true',
- help='Do not clean the temporary directory before each test run')
+ parser.add_argument(
+ '--save-dir',
+ action='store_true',
+ help='Save the temporary directory used during for each '
+ 'test. Implies --cores=1. Defaults to true when running a single test',
+ )
+ parser.add_argument(
+ '--no-clean', action='store_true', help='Do not clean the temporary directory before each test run'
+ )
parser.add_argument('--verbose', '-v', action='store_true')
parser.add_argument('--all-engines', action='store_true')
parser.add_argument('--detect-leaks', action='store_true')
parser.add_argument('--skip-slow', action='store_true', help='Skip tests marked as slow')
- parser.add_argument('--cores', '-j',
- help='Set the number tests to run in parallel. Defaults '
- 'to the number of CPU cores.', default=None)
- parser.add_argument('--rebaseline', action='store_true',
- help='Automatically update test expectations for tests that support it.')
- parser.add_argument('--browser',
- help='Command to launch web browser in which to run browser tests.')
+ parser.add_argument(
+ '--cores',
+ '-j',
+ help='Set the number tests to run in parallel. Defaults ' 'to the number of CPU cores.',
+ default=None,
+ )
+ parser.add_argument(
+ '--rebaseline', action='store_true', help='Automatically update test expectations for tests that support it.'
+ )
+ parser.add_argument('--browser', help='Command to launch web browser in which to run browser tests.')
parser.add_argument('tests', nargs='*')
parser.add_argument('--failfast', action='store_true')
parser.add_argument('--start-at', metavar='NAME', help='Skip all tests up until ')
- parser.add_argument('--continue', dest='_continue', action='store_true',
- help='Resume from the last run test.'
- 'Useful when combined with --failfast')
+ parser.add_argument(
+ '--continue',
+ dest='_continue',
+ action='store_true',
+ help='Resume from the last run test.' 'Useful when combined with --failfast',
+ )
parser.add_argument('--force64', action='store_true')
parser.add_argument('--crossplatform-only', action='store_true')
- parser.add_argument('--repeat', type=int, default=1,
- help='Repeat each test N times (default: 1).')
+ parser.add_argument('--repeat', type=int, default=1, help='Repeat each test N times (default: 1).')
return parser.parse_args()
diff --git a/test/test_benchmark.py b/test/test_benchmark.py
index c0c615fc138e5..bdca3c8138a20 100644
--- a/test/test_benchmark.py
+++ b/test/test_benchmark.py
@@ -56,7 +56,7 @@
EMTEST_BENCHMARKERS = os.getenv('EMTEST_BENCHMARKERS', 'clang,v8,v8-lto,v8-ctors')
-class Benchmarker():
+class Benchmarker:
# Whether to record statistics. Set by SizeBenchmarker.
record_stats = False
@@ -78,7 +78,7 @@ def bench(self, args, output_parser=None, reps=TEST_REPS, expected_output=None):
if expected_output is not None and expected_output not in output:
raise ValueError('Incorrect benchmark output:\n' + output)
- if not output_parser or args == ['0']: # if arg is 0, we are not running code, and have no output to parse
+ if not output_parser or args == ['0']: # if arg is 0, we are not running code, and have no output to parse
curr = time.time() - start
else:
try:
@@ -101,11 +101,15 @@ def display(self, baseline=None):
sorted_times = sorted(self.times)
count = len(sorted_times)
if count % 2 == 0:
- median = sum(sorted_times[count // 2 - 1:count // 2 + 1]) / 2
+ median = sum(sorted_times[count // 2 - 1 : count // 2 + 1]) / 2
else:
median = sorted_times[count // 2]
- print(' %10s: mean: %4.3f (+-%4.3f) secs median: %4.3f range: %4.3f-%4.3f (noise: %4.3f%%) (%d runs)' % (self.name, mean, std, median, min(self.times), max(self.times), 100 * std / mean, self.reps), end=' ')
+ print(
+ ' %10s: mean: %4.3f (+-%4.3f) secs median: %4.3f range: %4.3f-%4.3f (noise: %4.3f%%) (%d runs)'
+ % (self.name, mean, std, median, min(self.times), max(self.times), 100 * std / mean, self.reps),
+ end=' ',
+ )
if baseline:
mean_baseline = sum(baseline.times) / len(baseline.times)
@@ -119,14 +123,18 @@ def display(self, baseline=None):
recorded_stats = []
def add_stat(name, size, gzip_size):
- recorded_stats.append({
- 'value': name,
- 'measurement': size,
- })
- recorded_stats.append({
- 'value': name + ' (gzipped)',
- 'measurement': gzip_size,
- })
+ recorded_stats.append(
+ {
+ 'value': name,
+ 'measurement': size,
+ }
+ )
+ recorded_stats.append(
+ {
+ 'value': name + ' (gzipped)',
+ 'measurement': gzip_size,
+ }
+ )
total_size = 0
total_gzip_size = 0
@@ -160,7 +168,9 @@ def __init__(self, name, cc, cxx, args=None):
self.cxx = cxx
self.args = args or [OPTIMIZATIONS]
- def build(self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser):
+ def build(
+ self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser
+ ):
native_args = native_args or []
shared_args = shared_args or []
self.parent = parent
@@ -170,11 +180,14 @@ def build(self, parent, filename, args, shared_args, emcc_args, native_args, nat
native_args = native_args + lib_builder(self.name, native=True, env_init=env)
if not native_exec:
compiler = self.cxx if filename.endswith('cpp') else self.cc
- cmd = compiler + [
- '-fno-math-errno',
- filename,
- '-o', filename + '.native'
- ] + self.args + shared_args + native_args + clang_native.get_clang_native_args()
+ cmd = (
+ compiler
+ + ['-fno-math-errno', filename, '-o', filename + '.native']
+ + self.args
+ + shared_args
+ + native_args
+ + clang_native.get_clang_native_args()
+ )
# print(cmd)
run_process(cmd, env=clang_native.get_clang_native_env())
else:
@@ -196,11 +209,9 @@ def get_size_text(self):
def run_binaryen_opts(filename, opts):
- run_process([
- os.path.join(building.get_binaryen_bin(), 'wasm-opt', '--all-features'),
- filename,
- '-o', filename
- ] + opts)
+ run_process(
+ [os.path.join(building.get_binaryen_bin(), 'wasm-opt', '--all-features'), filename, '-o', filename] + opts
+ )
class EmscriptenBenchmarker(Benchmarker):
@@ -213,7 +224,9 @@ def __init__(self, name, engine, extra_args=None, env=None, binaryen_opts=None):
self.env.update(env)
self.binaryen_opts = binaryen_opts or []
- def build(self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser):
+ def build(
+ self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser
+ ):
emcc_args = emcc_args or []
self.filename = filename
llvm_root = self.env.get('LLVM') or config.LLVM_ROOT
@@ -226,15 +239,24 @@ def build(self, parent, filename, args, shared_args, emcc_args, native_args, nat
# This shouldn't be 'emcc_args += ...', because emcc_args is passed in as
# a parameter and changes will be visible to the caller.
emcc_args = emcc_args + lib_builder('js_' + llvm_root, native=False, env_init=env_init)
- final = os.path.dirname(filename) + os.path.sep + self.name + ('_' if self.name else '') + os.path.basename(filename) + '.js'
+ final = (
+ os.path.dirname(filename)
+ + os.path.sep
+ + self.name
+ + ('_' if self.name else '')
+ + os.path.basename(filename)
+ + '.js'
+ )
final = final.replace('.cpp', '')
utils.delete_file(final)
cmd = [
- EMCC, filename,
+ EMCC,
+ filename,
OPTIMIZATIONS,
'-sINITIAL_MEMORY=256MB',
'-sENVIRONMENT=node,shell',
- '-o', final
+ '-o',
+ final,
] + LLVM_FEATURE_FLAGS
if shared_args:
cmd += shared_args
@@ -294,7 +316,9 @@ def __init__(self, name, engine, args=None, binaryen_opts=None):
self.args = args or [OPTIMIZATIONS]
self.binaryen_opts = binaryen_opts or []
- def build(self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser):
+ def build(
+ self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser
+ ):
cheerp_args = [
'-fno-math-errno',
]
@@ -303,20 +327,31 @@ def build(self, parent, filename, args, shared_args, emcc_args, native_args, nat
if lib_builder:
# build as "native" (so no emcc env stuff), but with all the cheerp stuff
# set in the env
- cheerp_args = cheerp_args + lib_builder(self.name, native=True, env_init={
- 'CC': CHEERP_BIN + 'clang',
- 'CXX': CHEERP_BIN + 'clang++',
- 'AR': CHEERP_BIN + '../libexec/cheerp-unknown-none-ar',
- 'LD': CHEERP_BIN + 'clang',
- 'NM': CHEERP_BIN + 'llvm-nm',
- 'LDSHARED': CHEERP_BIN + 'clang',
- 'RANLIB': CHEERP_BIN + '../libexec/cheerp-unknown-none-ranlib',
- 'CXXFLAGS': "-Wno-c++11-narrowing",
- 'CHEERP_PREFIX': CHEERP_BIN + '../',
- })
+ cheerp_args = cheerp_args + lib_builder(
+ self.name,
+ native=True,
+ env_init={
+ 'CC': CHEERP_BIN + 'clang',
+ 'CXX': CHEERP_BIN + 'clang++',
+ 'AR': CHEERP_BIN + '../libexec/cheerp-unknown-none-ar',
+ 'LD': CHEERP_BIN + 'clang',
+ 'NM': CHEERP_BIN + 'llvm-nm',
+ 'LDSHARED': CHEERP_BIN + 'clang',
+ 'RANLIB': CHEERP_BIN + '../libexec/cheerp-unknown-none-ranlib',
+ 'CXXFLAGS': "-Wno-c++11-narrowing",
+ 'CHEERP_PREFIX': CHEERP_BIN + '../',
+ },
+ )
if PROFILING:
- cheerp_args += ['-cheerp-pretty-code'] # get function names, like emcc --profiling
- final = os.path.dirname(filename) + os.path.sep + self.name + ('_' if self.name else '') + os.path.basename(filename) + '.js'
+ cheerp_args += ['-cheerp-pretty-code'] # get function names, like emcc --profiling
+ final = (
+ os.path.dirname(filename)
+ + os.path.sep
+ + self.name
+ + ('_' if self.name else '')
+ + os.path.basename(filename)
+ + '.js'
+ )
final = final.replace('.cpp', '')
utils.delete_file(final)
dirs_to_delete = []
@@ -327,12 +362,18 @@ def build(self, parent, filename, args, shared_args, emcc_args, native_args, nat
compiler = CHEERP_BIN + '/clang'
else:
compiler = CHEERP_BIN + '/clang++'
- cmd = [compiler] + cheerp_args + [
- '-cheerp-linear-heap-size=256',
- '-cheerp-secondary-output-file=' + final.replace('.js', '.wasm'),
- filename,
- '-o', final
- ] + shared_args
+ cmd = (
+ [compiler]
+ + cheerp_args
+ + [
+ '-cheerp-linear-heap-size=256',
+ '-cheerp-secondary-output-file=' + final.replace('.js', '.wasm'),
+ filename,
+ '-o',
+ final,
+ ]
+ + shared_args
+ )
# print(' '.join(cmd))
run_process(cmd, stdout=PIPE, stderr=PIPE)
self.filename = final
@@ -360,7 +401,7 @@ def get_output_files(self):
named_benchmarkers = {
'clang': NativeBenchmarker('clang', [CLANG_CC], [CLANG_CXX]),
- 'gcc': NativeBenchmarker('gcc', ['gcc', '-no-pie'], ['g++', '-no-pie']),
+ 'gcc': NativeBenchmarker('gcc', ['gcc', '-no-pie'], ['g++', '-no-pie']),
'size': SizeBenchmarker('size'),
'v8': EmscriptenBenchmarker('v8', aot_v8),
'v8-lto': EmscriptenBenchmarker('v8-lto', aot_v8, ['-flto']),
@@ -371,7 +412,7 @@ def get_output_files(self):
'cherp-v8': CheerpBenchmarker('cheerp-v8-wasm', aot_v8),
# TODO: ensure no baseline compiler is used, see v8
'sm': EmscriptenBenchmarker('sm', config.SPIDERMONKEY_ENGINE),
- 'cherp-sm': CheerpBenchmarker('cheerp-sm-wasm', config.SPIDERMONKEY_ENGINE)
+ 'cherp-sm': CheerpBenchmarker('cheerp-sm-wasm', config.SPIDERMONKEY_ENGINE),
}
for name in EMTEST_BENCHMARKERS.split(','):
@@ -382,7 +423,7 @@ def get_output_files(self):
class benchmark(common.RunnerCore):
save_dir = True
- stats = [] # type: ignore
+ stats = [] # type: ignore
@classmethod
def setUpClass(cls):
@@ -398,7 +439,10 @@ def setUpClass(cls):
pass
try:
with common.chdir(os.path.expanduser('~/Dev/mozilla-central')):
- fingerprint.append('sm: ' + [line for line in run_process(['hg', 'tip'], stdout=PIPE).stdout.splitlines() if 'changeset' in line][0])
+ fingerprint.append(
+ 'sm: '
+ + [line for line in run_process(['hg', 'tip'], stdout=PIPE).stdout.splitlines() if 'changeset' in line][0]
+ )
except Exception:
pass
fingerprint.append('llvm: ' + config.LLVM_ROOT)
@@ -408,11 +452,7 @@ def setUpClass(cls):
def tearDownClass(cls):
super().tearDownClass()
if cls.stats:
- output = {
- 'version': 1,
- 'git_hash': '',
- 'results': cls.stats
- }
+ output = {'version': 1, 'git_hash': '', 'results': cls.stats}
utils.write_file('stats.json', json.dumps(output, indent=2) + '\n')
# avoid depending on argument reception from the commandline
@@ -422,21 +462,36 @@ def hardcode_arguments(self, code):
main_pattern = 'int main(int argc, char **argv)'
assert main_pattern in code
code = code.replace(main_pattern, 'int benchmark_main(int argc, char **argv)')
- code += '''
+ code += (
+ '''
int main() {
int newArgc = 2;
char* newArgv[] = { (char*)"./program.exe", (char*)"%s" };
int ret = benchmark_main(newArgc, newArgv);
return ret;
}
- ''' % DEFAULT_ARG
+ '''
+ % DEFAULT_ARG
+ )
return code
- def do_benchmark(self, name, src, expected_output='FAIL', args=None,
- emcc_args=None, native_args=None, shared_args=None,
- force_c=False, reps=TEST_REPS, native_exec=None,
- output_parser=None, args_processor=None, lib_builder=None,
- skip_native=False):
+ def do_benchmark(
+ self,
+ name,
+ src,
+ expected_output='FAIL',
+ args=None,
+ emcc_args=None,
+ native_args=None,
+ shared_args=None,
+ force_c=False,
+ reps=TEST_REPS,
+ native_exec=None,
+ output_parser=None,
+ args_processor=None,
+ lib_builder=None,
+ skip_native=False,
+ ):
if not benchmarkers:
raise Exception('error, no benchmarkers')
@@ -459,22 +514,24 @@ def do_benchmark(self, name, src, expected_output='FAIL', args=None,
reps = 0
baseline = b
print('Running benchmarker: %s: %s' % (b.__class__.__name__, b.name))
- b.build(self, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser=output_parser is not None)
+ b.build(
+ self,
+ filename,
+ args,
+ shared_args,
+ emcc_args,
+ native_args,
+ native_exec,
+ lib_builder,
+ has_output_parser=output_parser is not None,
+ )
b.bench(args, output_parser, reps, expected_output)
recorded_stats = b.display(baseline)
if recorded_stats:
self.add_stats(name, recorded_stats)
def add_stats(self, name, stats):
- self.stats.append({
- 'key': {
- 'test': name,
- 'units': 'bytes'
- },
- 'measurements': {
- 'stats': stats
- }
- })
+ self.stats.append({'key': {'test': name, 'units': 'bytes'}, 'measurements': {'stats': stats}})
def test_primes(self, check=True):
src = r'''
@@ -516,7 +573,12 @@ def test_primes(self, check=True):
return 0;
}
'''
- self.do_benchmark('primes' if check else 'primes-nocheck', src, 'lastprime:' if check else '', shared_args=['-DCHECK'] if check else [])
+ self.do_benchmark(
+ 'primes' if check else 'primes-nocheck',
+ src,
+ 'lastprime:' if check else '',
+ shared_args=['-DCHECK'] if check else [],
+ )
# Also interesting to test it without the printfs which allow checking the output. Without
# printf, code size is dominated by the runtime itself (the compiled code is just a few lines).
@@ -750,7 +812,7 @@ def test_fannkuch(self):
case 5: n = 12; break;
default: printf("error: %d\\n", arg); return -1;
}
- '''
+ ''',
)
assert 'switch(arg)' in src
self.do_benchmark('fannkuch', src, 'Pfannkuchen(')
@@ -824,7 +886,9 @@ def test_corrections64(self):
def fasta(self, name, double_rep):
src = read_file(test_file('fasta.cpp')).replace('double', double_rep)
- src = src.replace(' const size_t n = ( argc > 1 ) ? atoi( argv[1] ) : 512;', '''
+ src = src.replace(
+ ' const size_t n = ( argc > 1 ) ? atoi( argv[1] ) : 512;',
+ '''
int n;
int arg = argc > 1 ? argv[1][0] - '0' : 3;
switch(arg) {
@@ -836,7 +900,8 @@ def fasta(self, name, double_rep):
case 5: n = 19000000*10; break;
default: printf("error: %d\\n", arg); return -1;
}
- ''')
+ ''',
+ )
assert 'switch(arg)' in src
self.do_benchmark('fasta', src, '')
@@ -854,8 +919,7 @@ def test_skinning(self):
def test_havlak(self):
src = read_file(test_file('havlak.cpp'))
# This runs many recursive calls (DFS) and thus needs a larger stack
- self.do_benchmark('havlak', src, 'Found', shared_args=['-std=c++11'],
- emcc_args=['-sSTACK_SIZE=1MB'])
+ self.do_benchmark('havlak', src, 'Found', shared_args=['-std=c++11'], emcc_args=['-sSTACK_SIZE=1MB'])
def test_base64(self):
src = read_file(test_file('base64.c'))
@@ -870,111 +934,216 @@ def test_zzz_linpack(self):
def output_parser(output):
mflops = re.search(r'Unrolled Double Precision ([\d\.]+) Mflops', output).group(1)
return 10000.0 / float(mflops)
- self.do_benchmark('linpack_double', read_file(test_file('benchmark/linpack2.c')), '''Unrolled Double Precision''', force_c=True, output_parser=output_parser)
+
+ self.do_benchmark(
+ 'linpack_double',
+ read_file(test_file('benchmark/linpack2.c')),
+ '''Unrolled Double Precision''',
+ force_c=True,
+ output_parser=output_parser,
+ )
# Benchmarks the synthetic performance of calling native functions.
@non_core
def test_native_functions(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('native_functions', read_file(test_file('benchmark/benchmark_ffis.cpp')), 'Total time:',
- output_parser=output_parser,
- # Not minimal because this uses functions in library_browsers.js
- emcc_args=['-sMINIMAL_RUNTIME=0'],
- shared_args=['-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'native_functions',
+ read_file(test_file('benchmark/benchmark_ffis.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ # Not minimal because this uses functions in library_browsers.js
+ emcc_args=['-sMINIMAL_RUNTIME=0'],
+ shared_args=['-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
# Benchmarks the synthetic performance of calling function pointers.
@non_core
def test_native_function_pointers(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('native_functions', read_file(test_file('benchmark/benchmark_ffis.cpp')), 'Total time:',
- output_parser=output_parser,
- # Not minimal because this uses functions in library_browsers.js
- emcc_args=['-sMINIMAL_RUNTIME=0'],
- shared_args=['-DBENCHMARK_FUNCTION_POINTER=1', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'native_functions',
+ read_file(test_file('benchmark/benchmark_ffis.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ # Not minimal because this uses functions in library_browsers.js
+ emcc_args=['-sMINIMAL_RUNTIME=0'],
+ shared_args=['-DBENCHMARK_FUNCTION_POINTER=1', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
# Benchmarks the synthetic performance of calling "foreign" JavaScript functions.
@non_core
def test_foreign_functions(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('foreign_functions', read_file(test_file('benchmark/benchmark_ffis.cpp')), 'Total time:',
- output_parser=output_parser,
- # Not minimal because this uses functions in library_browsers.js
- emcc_args=['--js-library', test_file('benchmark/benchmark_ffis.js'), '-sMINIMAL_RUNTIME=0'],
- shared_args=['-DBENCHMARK_FOREIGN_FUNCTION=1', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'foreign_functions',
+ read_file(test_file('benchmark/benchmark_ffis.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ # Not minimal because this uses functions in library_browsers.js
+ emcc_args=['--js-library', test_file('benchmark/benchmark_ffis.js'), '-sMINIMAL_RUNTIME=0'],
+ shared_args=['-DBENCHMARK_FOREIGN_FUNCTION=1', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memcpy_128b(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memcpy_128b', read_file(test_file('benchmark/benchmark_memcpy.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMAX_COPY=128', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memcpy_128b',
+ read_file(test_file('benchmark/benchmark_memcpy.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMAX_COPY=128', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memcpy_4k(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memcpy_4k', read_file(test_file('benchmark/benchmark_memcpy.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMIN_COPY=128', '-DMAX_COPY=4096', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memcpy_4k',
+ read_file(test_file('benchmark/benchmark_memcpy.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMIN_COPY=128', '-DMAX_COPY=4096', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memcpy_16k(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memcpy_16k', read_file(test_file('benchmark/benchmark_memcpy.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMIN_COPY=4096', '-DMAX_COPY=16384', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memcpy_16k',
+ read_file(test_file('benchmark/benchmark_memcpy.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMIN_COPY=4096', '-DMAX_COPY=16384', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memcpy_1mb(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memcpy_1mb', read_file(test_file('benchmark/benchmark_memcpy.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMIN_COPY=16384', '-DMAX_COPY=1048576', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memcpy_1mb',
+ read_file(test_file('benchmark/benchmark_memcpy.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMIN_COPY=16384', '-DMAX_COPY=1048576', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memcpy_16mb(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memcpy_16mb', read_file(test_file('benchmark/benchmark_memcpy.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMIN_COPY=1048576', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memcpy_16mb',
+ read_file(test_file('benchmark/benchmark_memcpy.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMIN_COPY=1048576', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memset_128b(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memset_128b', read_file(test_file('benchmark/benchmark_memset.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMAX_COPY=128', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memset_128b',
+ read_file(test_file('benchmark/benchmark_memset.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMAX_COPY=128', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memset_4k(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memset_4k', read_file(test_file('benchmark/benchmark_memset.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMIN_COPY=128', '-DMAX_COPY=4096', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memset_4k',
+ read_file(test_file('benchmark/benchmark_memset.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMIN_COPY=128', '-DMAX_COPY=4096', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memset_16k(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memset_16k', read_file(test_file('benchmark/benchmark_memset.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMIN_COPY=4096', '-DMAX_COPY=16384', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memset_16k',
+ read_file(test_file('benchmark/benchmark_memset.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMIN_COPY=4096', '-DMAX_COPY=16384', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memset_1mb(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memset_1mb', read_file(test_file('benchmark/benchmark_memset.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMIN_COPY=16384', '-DMAX_COPY=1048576', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memset_1mb',
+ read_file(test_file('benchmark/benchmark_memset.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMIN_COPY=16384', '-DMAX_COPY=1048576', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
@non_core
def test_memset_16mb(self):
def output_parser(output):
return float(re.search(r'Total time: ([\d\.]+)', output).group(1))
- self.do_benchmark('memset_16mb', read_file(test_file('benchmark/benchmark_memset.cpp')), 'Total time:', output_parser=output_parser, shared_args=['-DMIN_COPY=1048576', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'memset_16mb',
+ read_file(test_file('benchmark/benchmark_memset.cpp')),
+ 'Total time:',
+ output_parser=output_parser,
+ shared_args=['-DMIN_COPY=1048576', '-DBUILD_FOR_SHELL', '-I' + test_file('benchmark')],
+ )
def test_malloc_multithreading(self):
# Multithreaded malloc test. For emcc we use mimalloc here.
src = read_file(test_file('other/test_malloc_multithreading.cpp'))
# TODO measure with different numbers of cores and not fixed 4
- self.do_benchmark('malloc_multithreading', src, 'Done.', shared_args=['-DWORKERS=4', '-pthread'], emcc_args=['-sEXIT_RUNTIME', '-sMALLOC=mimalloc'])
+ self.do_benchmark(
+ 'malloc_multithreading',
+ src,
+ 'Done.',
+ shared_args=['-DWORKERS=4', '-pthread'],
+ emcc_args=['-sEXIT_RUNTIME', '-sMALLOC=mimalloc'],
+ )
def test_matrix_multiply(self):
def output_parser(output):
return float(re.search(r'Total elapsed: ([\d\.]+)', output).group(1))
- self.do_benchmark('matrix_multiply', read_file(test_file('matrix_multiply.cpp')), 'Total elapsed:', output_parser=output_parser, shared_args=['-I' + test_file('benchmark')])
+
+ self.do_benchmark(
+ 'matrix_multiply',
+ read_file(test_file('matrix_multiply.cpp')),
+ 'Total elapsed:',
+ output_parser=output_parser,
+ shared_args=['-I' + test_file('benchmark')],
+ )
def lua(self, benchmark, expected, output_parser=None, args_processor=None):
self.emcc_args.remove('-Werror')
@@ -983,13 +1152,34 @@ def lua(self, benchmark, expected, output_parser=None, args_processor=None):
def lib_builder(name, native, env_init):
# We force recomputation for the native benchmarker because this benchmark
# uses native_exec=True, so we need to copy the native executable
- return self.get_library(os.path.join('third_party', 'lua_native' if native else 'lua'), [os.path.join('src', 'lua.o'), os.path.join('src', 'liblua.a')], make=['make', 'generic'], configure=None, native=native, cache_name_extra=name, env_init=env_init, force_rebuild=native)
-
- self.do_benchmark('lua_' + benchmark, '', expected,
- force_c=True, args=[benchmark + '.lua', DEFAULT_ARG],
- emcc_args=['--embed-file', benchmark + '.lua', '-sFORCE_FILESYSTEM', '-sMINIMAL_RUNTIME=0'], # not minimal because of files
- lib_builder=lib_builder, native_exec=os.path.join('building', 'third_party', 'lua_native', 'src', 'lua'),
- output_parser=output_parser, args_processor=args_processor)
+ return self.get_library(
+ os.path.join('third_party', 'lua_native' if native else 'lua'),
+ [os.path.join('src', 'lua.o'), os.path.join('src', 'liblua.a')],
+ make=['make', 'generic'],
+ configure=None,
+ native=native,
+ cache_name_extra=name,
+ env_init=env_init,
+ force_rebuild=native,
+ )
+
+ self.do_benchmark(
+ 'lua_' + benchmark,
+ '',
+ expected,
+ force_c=True,
+ args=[benchmark + '.lua', DEFAULT_ARG],
+ emcc_args=[
+ '--embed-file',
+ benchmark + '.lua',
+ '-sFORCE_FILESYSTEM',
+ '-sMINIMAL_RUNTIME=0',
+ ], # not minimal because of files
+ lib_builder=lib_builder,
+ native_exec=os.path.join('building', 'third_party', 'lua_native', 'src', 'lua'),
+ output_parser=output_parser,
+ args_processor=args_processor,
+ )
def test_zzz_lua_scimark(self):
def output_parser(output):
@@ -1006,30 +1196,62 @@ def test_zzz_zlib(self):
src = read_file(test_file('benchmark/test_zlib_benchmark.c'))
def lib_builder(name, native, env_init):
- return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), make_args=['libz.a'], native=native, cache_name_extra=name, env_init=env_init)
-
- self.do_benchmark('zlib', src, 'ok.',
- force_c=True, shared_args=['-I' + test_file('third_party/zlib')], lib_builder=lib_builder)
+ return self.get_library(
+ os.path.join('third_party', 'zlib'),
+ os.path.join('libz.a'),
+ make_args=['libz.a'],
+ native=native,
+ cache_name_extra=name,
+ env_init=env_init,
+ )
+
+ self.do_benchmark(
+ 'zlib', src, 'ok.', force_c=True, shared_args=['-I' + test_file('third_party/zlib')], lib_builder=lib_builder
+ )
def test_zzz_coremark(self):
src = read_file(test_file('third_party/coremark/core_main.c'))
def lib_builder(name, native, env_init):
- return self.get_library('third_party/coremark', [os.path.join('coremark.a')], configure=None, native=native, cache_name_extra=name, env_init=env_init)
+ return self.get_library(
+ 'third_party/coremark',
+ [os.path.join('coremark.a')],
+ configure=None,
+ native=native,
+ cache_name_extra=name,
+ env_init=env_init,
+ )
def output_parser(output):
iters_sec = re.search(r'Iterations/Sec : ([\d\.]+)', output).group(1)
return 100000.0 / float(iters_sec)
- self.do_benchmark('coremark', src, 'Correct operation validated.', shared_args=['-I' + test_file('third_party/coremark')], lib_builder=lib_builder, output_parser=output_parser, force_c=True)
+ self.do_benchmark(
+ 'coremark',
+ src,
+ 'Correct operation validated.',
+ shared_args=['-I' + test_file('third_party/coremark')],
+ lib_builder=lib_builder,
+ output_parser=output_parser,
+ force_c=True,
+ )
def test_zzz_box2d(self):
src = read_file(test_file('benchmark/test_box2d_benchmark.cpp'))
def lib_builder(name, native, env_init):
- return self.get_library(os.path.join('third_party', 'box2d'), ['box2d.a'], configure=None, native=native, cache_name_extra=name, env_init=env_init)
-
- self.do_benchmark('box2d', src, 'frame averages', shared_args=['-I' + test_file('third_party/box2d')], lib_builder=lib_builder)
+ return self.get_library(
+ os.path.join('third_party', 'box2d'),
+ ['box2d.a'],
+ configure=None,
+ native=native,
+ cache_name_extra=name,
+ env_init=env_init,
+ )
+
+ self.do_benchmark(
+ 'box2d', src, 'frame averages', shared_args=['-I' + test_file('third_party/box2d')], lib_builder=lib_builder
+ )
def test_zzz_bullet(self):
self.emcc_args.remove('-Werror')
@@ -1038,40 +1260,64 @@ def test_zzz_bullet(self):
src += read_file(test_file('third_party/bullet/Demos/Benchmarks/main.cpp'))
def lib_builder(name, native, env_init):
- return self.get_library(str(Path('third_party/bullet')),
- [Path('src/.libs/libBulletDynamics.a'),
- Path('src/.libs/libBulletCollision.a'),
- Path('src/.libs/libLinearMath.a')],
- # The --host parameter is needed for 2 reasons:
- # 1) bullet in it's configure.ac tries to do platform detection and will fail on unknown platforms
- # 2) configure will try to compile and run a test file to check if the C compiler is sane. As Cheerp
- # will generate a wasm file (which cannot be run), configure will fail. Passing `--host` enables
- # cross compile mode, which lets configure complete happily.
- configure_args=['--disable-demos', '--disable-dependency-tracking', '--host=i686-unknown-linux'], native=native, cache_name_extra=name, env_init=env_init)
-
- self.do_benchmark('bullet', src, '\nok.\n',
- shared_args=['-I' + test_file('third_party/bullet/src'), '-I' + test_file('third_party/bullet/Demos/Benchmarks')],
- lib_builder=lib_builder)
+ return self.get_library(
+ str(Path('third_party/bullet')),
+ [
+ Path('src/.libs/libBulletDynamics.a'),
+ Path('src/.libs/libBulletCollision.a'),
+ Path('src/.libs/libLinearMath.a'),
+ ],
+ # The --host parameter is needed for 2 reasons:
+ # 1) bullet in it's configure.ac tries to do platform detection and will fail on unknown platforms
+ # 2) configure will try to compile and run a test file to check if the C compiler is sane. As Cheerp
+ # will generate a wasm file (which cannot be run), configure will fail. Passing `--host` enables
+ # cross compile mode, which lets configure complete happily.
+ configure_args=['--disable-demos', '--disable-dependency-tracking', '--host=i686-unknown-linux'],
+ native=native,
+ cache_name_extra=name,
+ env_init=env_init,
+ )
+
+ self.do_benchmark(
+ 'bullet',
+ src,
+ '\nok.\n',
+ shared_args=['-I' + test_file('third_party/bullet/src'), '-I' + test_file('third_party/bullet/Demos/Benchmarks')],
+ lib_builder=lib_builder,
+ )
def test_zzz_lzma(self):
src = read_file(test_file('benchmark/test_lzma_benchmark.c'))
def lib_builder(name, native, env_init):
- return self.get_library(os.path.join('third_party', 'lzma'), [os.path.join('lzma.a')], configure=None, native=native, cache_name_extra=name, env_init=env_init)
+ return self.get_library(
+ os.path.join('third_party', 'lzma'),
+ [os.path.join('lzma.a')],
+ configure=None,
+ native=native,
+ cache_name_extra=name,
+ env_init=env_init,
+ )
self.do_benchmark('lzma', src, 'ok.', shared_args=['-I' + test_file('third_party/lzma')], lib_builder=lib_builder)
def test_zzz_sqlite(self):
src = read_file(test_file('third_party/sqlite/sqlite3.c')) + read_file(test_file('sqlite/speedtest1.c'))
- self.do_benchmark('sqlite', src, 'TOTAL...',
- native_args=['-ldl', '-pthread'],
- shared_args=['-I' + test_file('third_party/sqlite')],
- # not minimal because of files
- emcc_args=['-sFILESYSTEM', '-sMINIMAL_RUNTIME=0'],
- force_c=True)
+ self.do_benchmark(
+ 'sqlite',
+ src,
+ 'TOTAL...',
+ native_args=['-ldl', '-pthread'],
+ shared_args=['-I' + test_file('third_party/sqlite')],
+ # not minimal because of files
+ emcc_args=['-sFILESYSTEM', '-sMINIMAL_RUNTIME=0'],
+ force_c=True,
+ )
def test_zzz_poppler(self):
- utils.write_file('pre.js', '''
+ utils.write_file(
+ 'pre.js',
+ '''
var benchmarkArgument = %s;
var benchmarkArgumentToPageCount = {
'0': 0,
@@ -1107,17 +1353,27 @@ def test_zzz_poppler(self):
out(files.length + ' files emitted, total output size: ' + totalSize + ', hashed printout: ' + hash);
};
}
- ''' % DEFAULT_ARG)
+ '''
+ % DEFAULT_ARG,
+ )
def lib_builder(name, native, env_init):
return self.get_poppler_library(env_init=env_init)
# TODO: Fix poppler native build and remove skip_native=True
- self.do_benchmark('poppler', '', 'hashed printout',
- shared_args=['-I' + test_file('poppler/include'),
- '-I' + test_file('freetype/include')],
- emcc_args=['-sFILESYSTEM', '--pre-js=pre.js', '--embed-file',
- test_file('poppler/emscripten_html5.pdf') + '@input.pdf',
- '-sERROR_ON_UNDEFINED_SYMBOLS=0',
- '-sMINIMAL_RUNTIME=0'], # not minimal because of files
- lib_builder=lib_builder, skip_native=True)
+ self.do_benchmark(
+ 'poppler',
+ '',
+ 'hashed printout',
+ shared_args=['-I' + test_file('poppler/include'), '-I' + test_file('freetype/include')],
+ emcc_args=[
+ '-sFILESYSTEM',
+ '--pre-js=pre.js',
+ '--embed-file',
+ test_file('poppler/emscripten_html5.pdf') + '@input.pdf',
+ '-sERROR_ON_UNDEFINED_SYMBOLS=0',
+ '-sMINIMAL_RUNTIME=0',
+ ], # not minimal because of files
+ lib_builder=lib_builder,
+ skip_native=True,
+ )
diff --git a/test/test_core.py b/test/test_core.py
index 8075a42ade9bd..6e4fa734e5255 100644
--- a/test/test_core.py
+++ b/test/test_core.py
@@ -28,7 +28,14 @@
from common import read_file, read_binary, requires_v8, requires_node, requires_wasm2js, requires_node_canary
from common import compiler_for, crossplatform, no_4gb, no_2gb, also_with_minimal_runtime
from common import with_all_fs, also_with_nodefs, also_with_nodefs_both, also_with_noderawfs, also_with_wasmfs
-from common import with_all_eh_sjlj, with_all_sjlj, also_with_standalone_wasm, can_do_standalone, no_wasm64, requires_wasm_exnref
+from common import (
+ with_all_eh_sjlj,
+ with_all_sjlj,
+ also_with_standalone_wasm,
+ can_do_standalone,
+ no_wasm64,
+ requires_wasm_exnref,
+)
from common import NON_ZERO, WEBIDL_BINDER, EMBUILDER, PYTHON
import clang_native
@@ -51,11 +58,14 @@ def decorated(self, *args, **kwargs):
if self.is_wasm2js():
self.skipTest('wasm2js only supports MVP for now')
if '-O3' in self.emcc_args:
- self.skipTest('SIMD tests are too slow with -O3 in the new LLVM pass manager, https://github.com/emscripten-core/emscripten/issues/13427')
+ self.skipTest(
+ 'SIMD tests are too slow with -O3 in the new LLVM pass manager, https://github.com/emscripten-core/emscripten/issues/13427'
+ )
self.emcc_args.append('-msimd128')
self.emcc_args.append('-fno-lax-vector-conversions')
self.v8_args.append('--experimental-wasm-simd')
f(self, *args, **kwargs)
+
return decorated
@@ -71,6 +81,7 @@ def decorated(self):
self.skipTest('wasm2js only supports MVP for now')
self.emcc_args.append('-mrelaxed-simd')
f(self)
+
return decorated
@@ -82,6 +93,7 @@ def decorated(self):
if self.is_wasm2js():
self.skipTest('wasm2js only supports MVP for now')
f(self)
+
return decorated
@@ -106,8 +118,7 @@ def decorated(self, dylink_reversed, *args, **kwargs):
return func(self, *args, **kwargs)
- parameterize(decorated, {'': (False,),
- 'reversed': (True,)})
+ parameterize(decorated, {'': (False,), 'reversed': (True,)})
return decorated
@@ -136,6 +147,7 @@ def no_wasm2js(note=''):
def decorated(f):
return skip_if(f, 'is_wasm2js', note)
+
return decorated
@@ -154,6 +166,7 @@ def only_wasm2js(note=''):
def decorated(f):
return skip_if(f, 'is_wasm2js', note, negate=True)
+
return decorated
@@ -170,8 +183,7 @@ def metafunc(self, jspi):
self.set_setting('ASYNCIFY')
f(self)
- parameterize(metafunc, {'': (False,),
- 'jspi': (True,)})
+ parameterize(metafunc, {'': (False,), 'jspi': (True,)})
return metafunc
@@ -186,7 +198,9 @@ def decorated(self):
if self.is_optimizing():
self.skipTest(note)
func(self)
+
return decorated
+
return decorator
@@ -208,7 +222,9 @@ def decorated(self, *args, **kwargs):
if '-fsanitize=address' in self.emcc_args:
self.skipTest(note)
f(self, *args, **kwargs)
+
return decorated
+
return decorator
@@ -223,7 +239,9 @@ def decorated(self, *args, **kwargs):
if '-fsanitize=leak' in self.emcc_args:
self.skipTest(note)
f(self, *args, **kwargs)
+
return decorated
+
return decorator
@@ -238,7 +256,9 @@ def decorated(self, *args, **kwargs):
if '-fsanitize=undefined' in self.emcc_args:
self.skipTest(note)
f(self, *args, **kwargs)
+
return decorated
+
return decorator
@@ -253,7 +273,9 @@ def decorated(self, *args, **kwargs):
if any(a.startswith('-fsanitize=') for a in self.emcc_args):
self.skipTest(note)
f(self, *args, **kwargs)
+
return decorated
+
return decorator
@@ -268,7 +290,9 @@ def decorated(self, *args, **kwargs):
if self.get_setting('WASMFS'):
self.skipTest(note)
f(self, *args, **kwargs)
+
return decorated
+
return decorator
@@ -284,8 +308,11 @@ def decorated(self, *args, **kwargs):
if (name + '=1') in self.emcc_args or self.get_setting(name):
self.skipTest(note)
f(self, *args, **kwargs)
+
return decorated
+
return decorator
+
return outer_decorator
@@ -318,7 +345,7 @@ def maybe_closure(self):
return False
def assertStartswith(self, output, prefix):
- self.assertEqual(prefix, output[:len(prefix)])
+ self.assertEqual(prefix, output[: len(prefix)])
def verify_in_strict_mode(self, filename):
js = read_file(filename)
@@ -332,29 +359,39 @@ def do_core_test(self, testname, **kwargs):
def get_bullet_library(self, use_cmake):
if use_cmake:
configure_commands = ['cmake', '.']
- configure_args = ['-DBUILD_DEMOS=OFF', '-DBUILD_EXTRAS=OFF', '-DUSE_GLUT=OFF',
- '-DCMAKE_CXX_STANDARD=14']
+ configure_args = ['-DBUILD_DEMOS=OFF', '-DBUILD_EXTRAS=OFF', '-DUSE_GLUT=OFF', '-DCMAKE_CXX_STANDARD=14']
# Depending on whether 'configure' or 'cmake' is used to build, Bullet
# places output files in different directory structures.
- generated_libs = [Path('src/BulletDynamics/libBulletDynamics.a'),
- Path('src/BulletCollision/libBulletCollision.a'),
- Path('src/LinearMath/libLinearMath.a')]
+ generated_libs = [
+ Path('src/BulletDynamics/libBulletDynamics.a'),
+ Path('src/BulletCollision/libBulletCollision.a'),
+ Path('src/LinearMath/libLinearMath.a'),
+ ]
else:
configure_commands = ['sh', './configure']
# Force a nondefault --host= so that the configure script will interpret
# that we are doing cross-compilation
# and skip attempting to run the generated executable with './a.out',
# which would fail since we are building a .js file.
- configure_args = ['--disable-shared', '--host=i686-pc-linux-gnu',
- '--disable-demos', '--disable-dependency-tracking']
- generated_libs = [Path('src/.libs/libBulletDynamics.a'),
- Path('src/.libs/libBulletCollision.a'),
- Path('src/.libs/libLinearMath.a')]
+ configure_args = [
+ '--disable-shared',
+ '--host=i686-pc-linux-gnu',
+ '--disable-demos',
+ '--disable-dependency-tracking',
+ ]
+ generated_libs = [
+ Path('src/.libs/libBulletDynamics.a'),
+ Path('src/.libs/libBulletCollision.a'),
+ Path('src/.libs/libLinearMath.a'),
+ ]
- return self.get_library('third_party/bullet', generated_libs,
- configure=configure_commands,
- configure_args=configure_args,
- cache_name_extra=configure_commands[0])
+ return self.get_library(
+ 'third_party/bullet',
+ generated_libs,
+ configure=configure_commands,
+ configure_args=configure_args,
+ cache_name_extra=configure_commands[0],
+ )
def test_hello_world(self):
self.do_core_test('test_hello_world.c')
@@ -388,7 +425,10 @@ def test_int53(self):
def test_int53_convertI32PairToI53Checked(self):
if common.EMTEST_REBASELINE:
- self.run_process([EMCC, test_file('core/test_convertI32PairToI53Checked.cpp'), '-o', 'a.js', '-DGENERATE_ANSWERS'] + self.emcc_args)
+ self.run_process(
+ [EMCC, test_file('core/test_convertI32PairToI53Checked.cpp'), '-o', 'a.js', '-DGENERATE_ANSWERS']
+ + self.emcc_args
+ )
ret = self.run_process(config.NODE_JS + ['a.js'], stdout=PIPE).stdout
write_file(test_file('core/test_convertI32PairToI53Checked.out'), ret)
else:
@@ -545,13 +585,19 @@ def test_cube2md5(self):
@needs_make('make')
def test_cube2hash(self):
# A good test of i64 math
- self.do_run('// empty file', 'Usage: hashstring ',
- libraries=self.get_library('third_party/cube2hash', ['libcube2hash.a'], configure=None),
- includes=[test_file('third_party/cube2hash')], assert_returncode=NON_ZERO)
+ self.do_run(
+ '// empty file',
+ 'Usage: hashstring ',
+ libraries=self.get_library('third_party/cube2hash', ['libcube2hash.a'], configure=None),
+ includes=[test_file('third_party/cube2hash')],
+ assert_returncode=NON_ZERO,
+ )
- for text, output in [('fleefl', '892BDB6FD3F62E863D63DA55851700FDE3ACF30204798CE9'),
- ('fleefl2', 'AA2CC5F96FC9D540CA24FDAF1F71E2942753DB83E8A81B61'),
- ('64bitisslow', '64D8470573635EC354FEE7B7F87C566FCAF1EFB491041670')]:
+ for text, output in [
+ ('fleefl', '892BDB6FD3F62E863D63DA55851700FDE3ACF30204798CE9'),
+ ('fleefl2', 'AA2CC5F96FC9D540CA24FDAF1F71E2942753DB83E8A81B61'),
+ ('64bitisslow', '64D8470573635EC354FEE7B7F87C566FCAF1EFB491041670'),
+ ]:
self.do_run('src.js', 'hash value: ' + output, args=[text], no_build=True)
@only_wasm2js('tests 64-bit alignment of structs')
@@ -597,11 +643,14 @@ def test_align64(self):
}
'''
- self.do_run(src, '''16,32
+ self.do_run(
+ src,
+ '''16,32
0,8,8,8
16,24,24,24
0.00,10,123.46,0.00 : 0.00,10,123.46,0.00
-''')
+''',
+ )
@only_wasm2js('tests signed vs unsigned values')
def test_unsigned(self):
@@ -744,11 +793,16 @@ def test_stack_align(self):
src = test_file('core/test_stack_align.c')
def test():
- self.do_runf(src, ['''align 4: 0
+ self.do_runf(
+ src,
+ [
+ '''align 4: 0
align 8: 0
align 16: 0
align 32: 0
-base align: 0, 0, 0, 0'''])
+base align: 0, 0, 0, 0'''
+ ],
+ )
test()
@@ -774,11 +828,13 @@ def test_mainenv(self):
@no_asan('ASan does not support custom memory allocators')
@no_lsan('LSan does not support custom memory allocators')
- @parameterized({
- 'normal': [],
- 'memvalidate': ['-DEMMALLOC_MEMVALIDATE'],
- 'memvalidate_verbose': ['-DEMMALLOC_MEMVALIDATE', '-DEMMALLOC_VERBOSE', '-DRANDOM_ITERS=130'],
- })
+ @parameterized(
+ {
+ 'normal': [],
+ 'memvalidate': ['-DEMMALLOC_MEMVALIDATE'],
+ 'memvalidate_verbose': ['-DEMMALLOC_MEMVALIDATE', '-DEMMALLOC_VERBOSE', '-DRANDOM_ITERS=130'],
+ }
+ )
def test_emmalloc(self, *args):
self.maybe_closure()
# in newer clang+llvm, the internal calls to malloc in emmalloc may be optimized under
@@ -788,7 +844,7 @@ def test_emmalloc(self, *args):
self.emcc_args += [
'-fno-builtin',
path_from_root('system/lib/libc/sbrk.c'),
- path_from_root('system/lib/emmalloc.c')
+ path_from_root('system/lib/emmalloc.c'),
]
self.emcc_args += args
self.do_run_in_out_file_test('core/test_emmalloc.c')
@@ -859,7 +915,7 @@ def test_longjmp_zero(self):
def test_longjmp_with_and_without_exceptions(self):
# Emscripten SjLj with and without Emscripten EH support
self.set_setting('SUPPORT_LONGJMP', 'emscripten')
- self.set_setting('DEFAULT_TO_CXX') # See comments on @with_all_eh_sjlj
+ self.set_setting('DEFAULT_TO_CXX') # See comments on @with_all_eh_sjlj
for disable_catching in (0, 1):
self.set_setting('DISABLE_EXCEPTION_CATCHING', disable_catching)
self.do_core_test('test_longjmp.c')
@@ -1082,7 +1138,9 @@ class MyException {
}
'''
- self.do_run(src, 'Throw...Construct...Caught...Destruct...Throw...Construct...Copy...Caught...Destruct...Destruct...\n')
+ self.do_run(
+ src, 'Throw...Construct...Caught...Destruct...Throw...Construct...Copy...Caught...Destruct...Destruct...\n'
+ )
@with_all_eh_sjlj
def test_exceptions_2(self):
@@ -1204,12 +1262,18 @@ def test_exceptions_allowed_misuse(self):
# Test old =2 setting for DISABLE_EXCEPTION_CATCHING
self.set_setting('DISABLE_EXCEPTION_CATCHING', 2)
err = self.expect_fail([EMCC, test_file('hello_world.c')] + self.get_emcc_args())
- self.assertContained('error: DISABLE_EXCEPTION_CATCHING=X is no longer needed when specifying EXCEPTION_CATCHING_ALLOWED [-Wdeprecated] [-Werror]', err)
+ self.assertContained(
+ 'error: DISABLE_EXCEPTION_CATCHING=X is no longer needed when specifying EXCEPTION_CATCHING_ALLOWED [-Wdeprecated] [-Werror]',
+ err,
+ )
# =0 should also be a warning
self.set_setting('DISABLE_EXCEPTION_CATCHING', 0)
err = self.expect_fail([EMCC, test_file('hello_world.c')] + self.get_emcc_args())
- self.assertContained('error: DISABLE_EXCEPTION_CATCHING=X is no longer needed when specifying EXCEPTION_CATCHING_ALLOWED [-Wdeprecated] [-Werror]', err)
+ self.assertContained(
+ 'error: DISABLE_EXCEPTION_CATCHING=X is no longer needed when specifying EXCEPTION_CATCHING_ALLOWED [-Wdeprecated] [-Werror]',
+ err,
+ )
# =1 should be a hard error
self.set_setting('DISABLE_EXCEPTION_CATCHING', 1)
@@ -1284,7 +1348,7 @@ def test_exceptions_uncaught_2(self):
def test_exceptions_typed(self):
# Depends on static destructors running
self.set_setting('EXIT_RUNTIME')
- self.clear_setting('SAFE_HEAP') # Throwing null will cause an ignorable null pointer access.
+ self.clear_setting('SAFE_HEAP') # Throwing null will cause an ignorable null pointer access.
self.do_core_test('test_exceptions_typed.cpp')
@with_all_eh_sjlj
@@ -1369,7 +1433,9 @@ def test_EXPORT_EXCEPTION_HANDLING_HELPERS(self):
self.emcc_args.append('-D__USING_EMSCRIPTEN_EXCEPTION__')
self.maybe_closure()
- create_file('main.cpp', '''
+ create_file(
+ 'main.cpp',
+ '''
#include
#include
#include
@@ -1423,7 +1489,8 @@ class myexception : public exception {
}
});
}
- ''')
+ ''',
+ )
expected = '''\
int,
char,
@@ -1436,7 +1503,8 @@ class myexception : public exception {
@with_all_eh_sjlj
def test_bad_typeid(self):
- self.do_run(r'''
+ self.do_run(
+ r'''
// exception example
#include // std::cerr
#include // operator typeid
@@ -1456,12 +1524,15 @@ class Polymorphic {virtual void member(){}};
}
return 0;
}
-''', 'exception caught: std::bad_typeid')
+''',
+ 'exception caught: std::bad_typeid',
+ )
@with_all_eh_sjlj
def test_abort_no_dtors(self):
# abort() should not run destructors
- out = self.do_run(r'''
+ out = self.do_run(
+ r'''
#include
#include
@@ -1473,13 +1544,16 @@ def test_abort_no_dtors(self):
Foo f;
abort();
}
-''', assert_returncode=NON_ZERO)
+''',
+ assert_returncode=NON_ZERO,
+ )
self.assertNotContained('Destructing Foo', out)
def test_iostream_ctors(self):
# iostream stuff must be globally constructed before user global
# constructors, so iostream works in global constructors
- self.do_run(r'''
+ self.do_run(
+ r'''
#include
struct A {
@@ -1491,7 +1565,9 @@ def test_iostream_ctors(self):
std::cout << "free code" << std::endl;
return 0;
}
-''', 'bugfree code')
+''',
+ 'bugfree code',
+ )
@with_all_eh_sjlj
def test_exceptions_longjmp1(self):
@@ -1535,7 +1611,10 @@ def clear_all_relevant_settings(self):
self.set_setting('DISABLE_EXCEPTION_THROWING', 1)
self.set_setting('DISABLE_EXCEPTION_CATCHING', 0)
err = self.expect_fail([EMCC, test_file('hello_world.cpp')] + self.get_emcc_args())
- self.assertContained("error: DISABLE_EXCEPTION_THROWING was set (probably from -fno-exceptions) but is not compatible with enabling exception catching (DISABLE_EXCEPTION_CATCHING=0). If you don't want exceptions, set DISABLE_EXCEPTION_CATCHING to 1; if you do want exceptions, don't link with -fno-exceptions", err)
+ self.assertContained(
+ "error: DISABLE_EXCEPTION_THROWING was set (probably from -fno-exceptions) but is not compatible with enabling exception catching (DISABLE_EXCEPTION_CATCHING=0). If you don't want exceptions, set DISABLE_EXCEPTION_CATCHING to 1; if you do want exceptions, don't link with -fno-exceptions",
+ err,
+ )
clear_all_relevant_settings(self)
# When using Wasm EH, users are not supposed to explicitly pass
@@ -1545,12 +1624,18 @@ def clear_all_relevant_settings(self):
# test setting includes -Werror.
self.set_setting('DISABLE_EXCEPTION_THROWING', 1)
err = self.expect_fail([EMCC, test_file('hello_world.cpp'), '-fwasm-exceptions'] + self.get_emcc_args())
- self.assertContained('error: you no longer need to pass DISABLE_EXCEPTION_CATCHING or DISABLE_EXCEPTION_THROWING when using Wasm exceptions', err)
+ self.assertContained(
+ 'error: you no longer need to pass DISABLE_EXCEPTION_CATCHING or DISABLE_EXCEPTION_THROWING when using Wasm exceptions',
+ err,
+ )
clear_all_relevant_settings(self)
self.set_setting('DISABLE_EXCEPTION_CATCHING', 1)
err = self.expect_fail([EMCC, test_file('hello_world.cpp'), '-fwasm-exceptions'] + self.get_emcc_args())
- self.assertContained('error: you no longer need to pass DISABLE_EXCEPTION_CATCHING or DISABLE_EXCEPTION_THROWING when using Wasm exceptions', err)
+ self.assertContained(
+ 'error: you no longer need to pass DISABLE_EXCEPTION_CATCHING or DISABLE_EXCEPTION_THROWING when using Wasm exceptions',
+ err,
+ )
clear_all_relevant_settings(self)
# Emscripten SjLj and Wasm EH cannot mix
@@ -1575,14 +1660,19 @@ def clear_all_relevant_settings(self):
# Wasm EH does not support ASYNCIFY=1
self.set_setting('ASYNCIFY', 1)
err = self.expect_fail([EMCC, test_file('hello_world.cpp'), '-fwasm-exceptions'] + self.get_emcc_args())
- self.assertContained('error: ASYNCIFY=1 is not compatible with -fwasm-exceptions. Parts of the program that mix ASYNCIFY and exceptions will not compile.', err)
+ self.assertContained(
+ 'error: ASYNCIFY=1 is not compatible with -fwasm-exceptions. Parts of the program that mix ASYNCIFY and exceptions will not compile.',
+ err,
+ )
clear_all_relevant_settings(self)
# EXPORT_EXCEPTION_HANDLING_HELPERS and EXCEPTION_STACK_TRACES requires
# either Emscripten EH or Wasm EH
self.set_setting('EXPORT_EXCEPTION_HANDLING_HELPERS')
err = self.expect_fail([EMCC, test_file('hello_world.cpp')] + self.get_emcc_args())
- self.assertContained('error: EXPORT_EXCEPTION_HANDLING_HELPERS requires either of -fexceptions or -fwasm-exceptions', err)
+ self.assertContained(
+ 'error: EXPORT_EXCEPTION_HANDLING_HELPERS requires either of -fexceptions or -fwasm-exceptions', err
+ )
clear_all_relevant_settings(self)
self.set_setting('EXCEPTION_STACK_TRACES')
@@ -1618,7 +1708,8 @@ def test_segfault(self):
for addr in ('get_null()', 'new D2()'):
print(addr)
- src = r'''
+ src = (
+ r'''
#include
#include
@@ -1651,7 +1742,9 @@ def test_segfault(self):
return 0;
}
- ''' % addr
+ '''
+ % addr
+ )
if 'get_null' in addr:
self.do_run(src, 'segmentation fault', assert_returncode=NON_ZERO)
else:
@@ -1679,7 +1772,7 @@ def test_rename(self):
self.do_run_in_out_file_test('stdio/test_rename.c')
def test_remove(self):
- self.do_run_in_out_file_test('stdio/test_remove.c')
+ self.do_run_in_out_file_test('stdio/test_remove.c')
def test_alloca_stack(self):
self.do_core_test('test_alloca_stack.c')
@@ -1813,7 +1906,8 @@ def test_inlinejs3(self):
self.do_run(src, read_file(output))
def test_inlinejs4(self):
- self.do_run(r'''
+ self.do_run(
+ r'''
#include
#define TO_STRING_INNER(x) #x
@@ -1830,7 +1924,10 @@ def test_inlinejs4(self):
assert(false);
return 0;
}
-''', 'false', assert_returncode=NON_ZERO)
+''',
+ 'false',
+ assert_returncode=NON_ZERO,
+ )
def test_em_asm(self):
self.maybe_closure()
@@ -1853,10 +1950,12 @@ def test_em_asm_2(self):
# test_em_asm_2, just search-replaces EM_ASM to MAIN_THREAD_EM_ASM on the test
# file. That way if new test cases are added to test_em_asm_2.cpp for EM_ASM,
# they will also get tested in MAIN_THREAD_EM_ASM form.
- @parameterized({
- '': ([],),
- 'pthread': (['-pthread', '-sPROXY_TO_PTHREAD', '-sEXIT_RUNTIME'],),
- })
+ @parameterized(
+ {
+ '': ([],),
+ 'pthread': (['-pthread', '-sPROXY_TO_PTHREAD', '-sEXIT_RUNTIME'],),
+ }
+ )
def test_main_thread_em_asm(self, args):
if args:
self.setup_node_pthreads()
@@ -1870,11 +1969,13 @@ def test_main_thread_em_asm(self, args):
self.do_run_in_out_file_test('test.cpp', emcc_args=args, force_c=True)
@needs_dylink
- @parameterized({
- '': ([], False),
- 'relocatable': (['-sMAIN_MODULE=2'], False),
- 'force_c': ([], True),
- })
+ @parameterized(
+ {
+ '': ([], False),
+ 'relocatable': (['-sMAIN_MODULE=2'], False),
+ 'force_c': ([], True),
+ }
+ )
def test_main_thread_async_em_asm(self, args, force_c=False):
self.do_core_test('test_main_thread_async_em_asm.cpp', emcc_args=args, force_c=force_c)
@@ -1912,17 +2013,24 @@ def test_em_asm_direct(self):
@needs_dylink
def test_em_asm_side_module(self):
- self.build(test_file('core/test_em_asm_side.c'), js_outfile=False, emcc_args=['-sSIDE_MODULE'], output_basename='side')
+ self.build(
+ test_file('core/test_em_asm_side.c'), js_outfile=False, emcc_args=['-sSIDE_MODULE'], output_basename='side'
+ )
self.do_core_test('test_em_asm_main.c', emcc_args=['-sMAIN_MODULE=2', 'side.wasm'])
- @parameterized({
- '': ([], False),
- 'pthreads': (['-pthread', '-sPROXY_TO_PTHREAD', '-sEXIT_RUNTIME'], False),
- 'pthreads_dylink': (['-pthread', '-sPROXY_TO_PTHREAD', '-sEXIT_RUNTIME', '-sMAIN_MODULE=2', '-Wno-experimental'], False),
- 'c': ([], True),
- 'dylink': (['-sMAIN_MODULE=2'], False),
- 'dylink_c': (['-sMAIN_MODULE=2'], True),
- })
+ @parameterized(
+ {
+ '': ([], False),
+ 'pthreads': (['-pthread', '-sPROXY_TO_PTHREAD', '-sEXIT_RUNTIME'], False),
+ 'pthreads_dylink': (
+ ['-pthread', '-sPROXY_TO_PTHREAD', '-sEXIT_RUNTIME', '-sMAIN_MODULE=2', '-Wno-experimental'],
+ False,
+ ),
+ 'c': ([], True),
+ 'dylink': (['-sMAIN_MODULE=2'], False),
+ 'dylink_c': (['-sMAIN_MODULE=2'], True),
+ }
+ )
@crossplatform
def test_em_js(self, args, force_c):
if '-sMAIN_MODULE=2' in args:
@@ -1937,7 +2045,9 @@ def test_em_js(self, args, force_c):
@no_wasm2js('test depends on WASM_BIGINT which is not compatible with wasm2js')
def test_em_js_i64(self):
err = self.expect_fail([EMCC, '-Werror', '-sWASM_BIGINT=0', test_file('core/test_em_js_i64.c')])
- self.assertContained('emcc: error: using 64-bit arguments in EM_JS function without WASM_BIGINT is not yet fully supported: `foo`', err)
+ self.assertContained(
+ 'emcc: error: using 64-bit arguments in EM_JS function without WASM_BIGINT is not yet fully supported: `foo`', err
+ )
self.node_args += shared.node_bigint_flags(self.get_nodejs())
self.do_core_test('test_em_js_i64.c')
@@ -1990,9 +2100,11 @@ def test_memorygrowth(self):
# Make sure ALLOW_MEMORY_GROWTH generates different code (should be less optimized)
code_start = '// EMSCRIPTEN_START_FUNCS'
self.assertContained(code_start, fail)
- fail = fail[fail.find(code_start):]
- win = win[win.find(code_start):]
- assert len(fail) < len(win), 'failing code - without memory growth on - is more optimized, and smaller' + str([len(fail), len(win)])
+ fail = fail[fail.find(code_start) :]
+ win = win[win.find(code_start) :]
+ assert len(fail) < len(win), 'failing code - without memory growth on - is more optimized, and smaller' + str(
+ [len(fail), len(win)]
+ )
# Tracing of memory growths should work
# (SAFE_HEAP would instrument the tracing code itself, leading to recursion)
@@ -2021,7 +2133,9 @@ def test_memorygrowth_2(self):
if '-O2' in self.emcc_args and self.is_wasm2js():
# Make sure ALLOW_MEMORY_GROWTH generates different code (should be less optimized)
- assert len(fail) < len(win), 'failing code - without memory growth on - is more optimized, and smaller' + str([len(fail), len(win)])
+ assert len(fail) < len(win), 'failing code - without memory growth on - is more optimized, and smaller' + str(
+ [len(fail), len(win)]
+ )
def test_memorygrowth_3(self):
if self.has_changed_setting('ALLOW_MEMORY_GROWTH'):
@@ -2054,7 +2168,13 @@ def test_memorygrowth_linear_step(self):
self.skipTest('wasm memory specific test')
# check that memory growth does not exceed the wasm mem max limit and is exactly or one step below the wasm mem max
- self.emcc_args += ['-sALLOW_MEMORY_GROWTH', '-sSTACK_SIZE=1Mb', '-sINITIAL_MEMORY=64Mb', '-sMAXIMUM_MEMORY=130Mb', '-sMEMORY_GROWTH_LINEAR_STEP=1Mb']
+ self.emcc_args += [
+ '-sALLOW_MEMORY_GROWTH',
+ '-sSTACK_SIZE=1Mb',
+ '-sINITIAL_MEMORY=64Mb',
+ '-sMAXIMUM_MEMORY=130Mb',
+ '-sMEMORY_GROWTH_LINEAR_STEP=1Mb',
+ ]
self.do_core_test('test_memorygrowth_linear_step.c')
@no_ubsan('UBSan seems to effect the precise memory usage')
@@ -2066,7 +2186,12 @@ def test_memorygrowth_geometric_step(self):
if self.is_wasm2js():
self.skipTest('wasm memory specific test')
- self.emcc_args += ['-sINITIAL_MEMORY=16MB', '-sALLOW_MEMORY_GROWTH', '-sMEMORY_GROWTH_GEOMETRIC_STEP=8.5', '-sMEMORY_GROWTH_GEOMETRIC_CAP=32MB']
+ self.emcc_args += [
+ '-sINITIAL_MEMORY=16MB',
+ '-sALLOW_MEMORY_GROWTH',
+ '-sMEMORY_GROWTH_GEOMETRIC_STEP=8.5',
+ '-sMEMORY_GROWTH_GEOMETRIC_CAP=32MB',
+ ]
self.do_core_test('test_memorygrowth_geometric_step.c')
def test_memorygrowth_3_force_fail_reallocBuffer(self):
@@ -2078,10 +2203,7 @@ def test_memorygrowth_3_force_fail_reallocBuffer(self):
self.add_pre_run('growMemory = (size) => false;')
self.do_core_test('test_memorygrowth_3.c')
- @parameterized({
- 'nogrow': ([],),
- 'grow': (['-sALLOW_MEMORY_GROWTH', '-sMAXIMUM_MEMORY=18MB'],)
- })
+ @parameterized({'nogrow': ([],), 'grow': (['-sALLOW_MEMORY_GROWTH', '-sMAXIMUM_MEMORY=18MB'],)})
@no_asan('requires more memory when growing')
@no_lsan('requires more memory when growing')
@no_4gb('depends on MAXIMUM_MEMORY')
@@ -2092,10 +2214,12 @@ def test_aborting_new(self, args):
self.emcc_args += args
self.do_core_test('test_aborting_new.cpp')
- @parameterized({
- 'nogrow': (['-sABORTING_MALLOC=0'],),
- 'grow': (['-sABORTING_MALLOC=0', '-sALLOW_MEMORY_GROWTH', '-sMAXIMUM_MEMORY=18MB'],)
- })
+ @parameterized(
+ {
+ 'nogrow': (['-sABORTING_MALLOC=0'],),
+ 'grow': (['-sABORTING_MALLOC=0', '-sALLOW_MEMORY_GROWTH', '-sMAXIMUM_MEMORY=18MB'],),
+ }
+ )
@no_asan('requires more memory when growing')
@no_lsan('requires more memory when growing')
@no_4gb('depends on MAXIMUM_MEMORY')
@@ -2116,7 +2240,7 @@ def test_module_wasm_memory(self):
self.set_setting('INCOMING_MODULE_JS_API', ['wasmMemory'])
self.do_runf('core/test_module_wasm_memory.c', 'success')
- def test_ssr(self): # struct self-ref
+ def test_ssr(self): # struct self-ref
src = '''
#include
@@ -2158,11 +2282,15 @@ def test_bigswitch(self):
if not self.is_optimizing():
self.skipTest('nodejs takes ~4GB to compile this if the wasm is not optimized, which OOMs')
self.set_setting('USE_SDL')
- self.do_runf('bigswitch.cpp', '''34962: GL_ARRAY_BUFFER (0x8892)
+ self.do_runf(
+ 'bigswitch.cpp',
+ '''34962: GL_ARRAY_BUFFER (0x8892)
26214: what?
35040: GL_STREAM_DRAW (0x88E0)
3060: what?
-''', args=['34962', '26214', '35040', str(0xbf4)])
+''',
+ args=['34962', '26214', '35040', str(0xBF4)],
+ )
@no_wasm2js('massive switches can break js engines')
@is_slow_test
@@ -2170,14 +2298,21 @@ def test_biggerswitch(self):
if self.is_optimizing():
self.skipTest('https://github.com/emscripten-core/emscripten/issues/22179')
if not self.is_optimizing():
- self.skipTest('nodejs takes >6GB to compile this if the wasm is not optimized, which OOMs, see https://github.com/emscripten-core/emscripten/issues/7928#issuecomment-458308453')
+ self.skipTest(
+ 'nodejs takes >6GB to compile this if the wasm is not optimized, which OOMs, see https://github.com/emscripten-core/emscripten/issues/7928#issuecomment-458308453'
+ )
num_cases = 20000
- switch_case = self.run_process([PYTHON, test_file('gen_large_switchcase.py'), str(num_cases)], stdout=PIPE, stderr=PIPE).stdout
- self.do_run(switch_case, '''58996: 589965899658996
+ switch_case = self.run_process(
+ [PYTHON, test_file('gen_large_switchcase.py'), str(num_cases)], stdout=PIPE, stderr=PIPE
+ ).stdout
+ self.do_run(
+ switch_case,
+ '''58996: 589965899658996
59297: 592975929759297
59598: default
59899: 598995989959899
-Success!''')
+Success!''',
+ )
@no_ubsan('local count too large for VMs')
def test_indirectbr(self):
@@ -2190,7 +2325,9 @@ def test_indirectbr(self):
@no_wasm2js('extremely deep nesting, hits stack limit on some VMs')
def test_indirectbr_many(self):
if not self.is_optimizing():
- self.skipTest('nodejs takes ~1.8GB to compile this if the wasm is not optimized, which can cause OOM on the test runners')
+ self.skipTest(
+ 'nodejs takes ~1.8GB to compile this if the wasm is not optimized, which can cause OOM on the test runners'
+ )
self.do_core_test('test_indirectbr_many.c')
def test_pack(self):
@@ -2293,11 +2430,14 @@ def test_varargs_byval(self):
printf("The current type of b is: %d\n", b.tt);
}
'''
- self.do_run(src, '''The original address of a is: 0x12345678
+ self.do_run(
+ src,
+ '''The original address of a is: 0x12345678
The original type of b is: 9
The current address of a is: 0x12345678
The current type of b is: 9
-''')
+''',
+ )
def test_functionpointer_libfunc_varargs(self):
self.do_core_test('test_functionpointer_libfunc_varargs.c')
@@ -2354,7 +2494,9 @@ def test_stdlibs(self):
self.do_core_test('test_stdlibs.c', out_suffix=out_suffix)
def test_stdbool(self):
- create_file('test_stdbool.c', r'''
+ create_file(
+ 'test_stdbool.c',
+ r'''
#include
#include
@@ -2364,7 +2506,8 @@ def test_stdbool(self):
printf("*%d*\n", x != y);
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('test_stdbool.c', '*1*')
@@ -2435,10 +2578,12 @@ def test_pthread_equal(self):
self.do_run_in_out_file_test('pthread/test_pthread_equal.cpp')
@node_pthreads
- @parameterized({
+ @parameterized(
+ {
'': (False,),
'modularize': (True,),
- })
+ }
+ )
def test_pthread_proxying(self, modularize):
if modularize and self.get_setting('WASM') == 0:
self.skipTest('MODULARIZE + WASM=0 + pthreads does not work (#16794)')
@@ -2451,16 +2596,14 @@ def test_pthread_proxying(self, modularize):
self.set_setting('MODULARIZE')
self.set_setting('EXPORT_NAME=ModuleFactory')
args = ['--extern-post-js', test_file('modularize_post_js.js')]
- self.do_run_in_out_file_test('pthread/test_pthread_proxying.c',
- interleaved_output=False, emcc_args=args)
+ self.do_run_in_out_file_test('pthread/test_pthread_proxying.c', interleaved_output=False, emcc_args=args)
@node_pthreads
def test_pthread_proxying_cpp(self):
self.set_setting('PROXY_TO_PTHREAD')
if not self.has_changed_setting('INITIAL_MEMORY'):
self.set_setting('INITIAL_MEMORY=32mb')
- self.do_run_in_out_file_test('pthread/test_pthread_proxying_cpp.cpp',
- interleaved_output=False)
+ self.do_run_in_out_file_test('pthread/test_pthread_proxying_cpp.cpp', interleaved_output=False)
@node_pthreads
def test_pthread_proxying_dropped_work(self):
@@ -2470,9 +2613,7 @@ def test_pthread_proxying_dropped_work(self):
@node_pthreads
def test_pthread_proxying_canceled_work(self):
self.set_setting('PROXY_TO_PTHREAD')
- self.do_run_in_out_file_test(
- 'pthread/test_pthread_proxying_canceled_work.c',
- interleaved_output=False)
+ self.do_run_in_out_file_test('pthread/test_pthread_proxying_canceled_work.c', interleaved_output=False)
@node_pthreads
@flaky('https://github.com/emscripten-core/emscripten/issues/19795')
@@ -2622,10 +2763,12 @@ def test_copyop(self):
# (llvm-gcc copies items one by one).
self.do_core_test('test_copyop.cpp')
- @parameterized({
- '': ([],),
- 'bulkmem': (['-mbulk-memory'],),
- })
+ @parameterized(
+ {
+ '': ([],),
+ 'bulkmem': (['-mbulk-memory'],),
+ }
+ )
def test_memcpy_zero_bytes(self, args):
self.do_core_test('test_memcpy_zero_bytes.c', emcc_args=['-fno-builtin'] + args)
@@ -2678,7 +2821,9 @@ def test_legacy_stack_deps(self):
# functions that must be $-prefixed in `__deps` lists. However,
# to support legacy code we continue to support the non-prefixed
# versions in `__deps` lists.
- create_file('lib.js', '''
+ create_file(
+ 'lib.js',
+ '''
addToLibrary({
foo__deps: ['stackSave', 'stackRestore'],
foo: () => {
@@ -2686,13 +2831,17 @@ def test_legacy_stack_deps(self):
stackRestore(a);
return 0;
}
- })''')
- create_file('main.c', '''
+ })''',
+ )
+ create_file(
+ 'main.c',
+ '''
int foo();
int main() {
return foo();
- }''')
+ }''',
+ )
self.do_runf('main.c', emcc_args=['--js-library=lib.js'])
def test_nestedstructs(self):
@@ -2838,15 +2987,19 @@ def test_dlfcn_missing(self):
self.do_run(src, expected)
@needs_dylink
- @parameterized({
- '': ([],),
- 'pthreads': (['-pthread', '-sEXIT_RUNTIME', '-sPROXY_TO_PTHREAD', '-Wno-experimental'],),
- })
+ @parameterized(
+ {
+ '': ([],),
+ 'pthreads': (['-pthread', '-sEXIT_RUNTIME', '-sPROXY_TO_PTHREAD', '-Wno-experimental'],),
+ }
+ )
def test_dlfcn_basic(self, args):
if args:
self.setup_node_pthreads()
self.emcc_args += args
- create_file('liblib.cpp', '''
+ create_file(
+ 'liblib.cpp',
+ '''
#include
class Foo {
@@ -2857,7 +3010,8 @@ class Foo {
};
Foo side_global;
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.cpp')
self.prep_dlfcn_main()
@@ -2883,13 +3037,16 @@ class Bar {
@needs_dylink
def test_dlfcn_i64(self):
- create_file('liblib.c', '''
+ create_file(
+ 'liblib.c',
+ '''
#include
int64_t foo(int x) {
return (long long)x / (long long)1234;
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
@@ -2922,7 +3079,9 @@ def test_dlfcn_i64(self):
@needs_dylink
def test_dlfcn_em_asm(self):
- create_file('liblib.cpp', '''
+ create_file(
+ 'liblib.cpp',
+ '''
#include
class Foo {
public:
@@ -2931,7 +3090,8 @@ class Foo {
}
};
Foo side_global;
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.cpp')
self.prep_dlfcn_main()
@@ -2955,7 +3115,9 @@ class Bar {
@needs_dylink
def test_dlfcn_qsort(self):
- create_file('liblib.c', '''
+ create_file(
+ 'liblib.c',
+ '''
int lib_cmp(const void* left, const void* right) {
const int* a = (const int*) left;
const int* b = (const int*) right;
@@ -2969,7 +3131,8 @@ def test_dlfcn_qsort(self):
CMP_TYPE get_cmp() {
return lib_cmp;
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
@@ -3026,7 +3189,9 @@ def test_dlfcn_qsort(self):
@needs_dylink
def test_dlfcn_data_and_fptr(self):
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
#include
int theglobal = 42;
@@ -3051,7 +3216,8 @@ def test_dlfcn_data_and_fptr(self):
fptr();
return lib_fptr;
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
@@ -3108,26 +3274,33 @@ def test_dlfcn_data_and_fptr(self):
return 0;
}
'''
- self.do_run(src, '''\
+ self.do_run(
+ src,
+ '''\
In func: 13
First calling main_fptr from lib.
Second calling lib_fptr from main.
parent_func called from child
parent_func called from child
Var: 42
-''', force_c=True)
+''',
+ force_c=True,
+ )
@needs_dylink
def test_dlfcn_varargs(self):
# this test is not actually valid - it fails natively. the child should fail
# to be loaded, not load and successfully see the parent print_ints func
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
void print_ints(int n, ...);
void func() {
print_ints(2, 13, 42);
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
@@ -3168,11 +3341,14 @@ def test_dlfcn_varargs(self):
@no_4gb('output is sensitive to absolute data layout')
def test_dlfcn_alignment_and_zeroing(self):
self.set_setting('INITIAL_MEMORY', '16mb')
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
int prezero = 0;
__attribute__((aligned(1024))) int superAligned = 12345;
int postzero = 0;
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
for i in range(10):
curr = '%d.so' % i
@@ -3180,7 +3356,9 @@ def test_dlfcn_alignment_and_zeroing(self):
self.prep_dlfcn_main()
self.set_setting('INITIAL_MEMORY', '128mb')
- create_file('src.c', r'''
+ create_file(
+ 'src.c',
+ r'''
#include
#include
#include
@@ -3235,7 +3413,8 @@ def test_dlfcn_alignment_and_zeroing(self):
printf("success.\n");
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('src.c', 'success.\n')
@needs_dylink
@@ -3273,17 +3452,22 @@ def get_data_exports(wasm):
@needs_dylink
def test_dlfcn_unique_sig(self):
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
#include
int myfunc(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m) {
return 13;
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
#include
@@ -3305,22 +3489,28 @@ def test_dlfcn_unique_sig(self):
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('main.c', 'success')
@needs_dylink
def test_dlfcn_info(self):
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
#include
int myfunc(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m) {
return 13;
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
- create_file('main.c', '''
+ create_file(
+ 'main.c',
+ '''
#include
#include
#include
@@ -3352,12 +3542,15 @@ def test_dlfcn_info(self):
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('main.c', 'success')
@needs_dylink
def test_dlfcn_stacks(self):
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
#include
#include
#include
@@ -3371,11 +3564,14 @@ def test_dlfcn_stacks(self):
snprintf(bigstack, sizeof(bigstack), "%s", input);
return strlen(bigstack);
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
- create_file('main.c', '''
+ create_file(
+ 'main.c',
+ '''
#include
#include
#include
@@ -3405,12 +3601,15 @@ def test_dlfcn_stacks(self):
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('main.c', 'success')
@needs_dylink
def test_dlfcn_funcs(self):
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
#include
#include
#include
@@ -3440,11 +3639,14 @@ def test_dlfcn_funcs(self):
default: return NULL;
}
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
#include
@@ -3490,8 +3692,11 @@ def test_dlfcn_funcs(self):
puts("ok");
return 0;
}
- ''')
- self.do_runf('main.c', '''go
+ ''',
+ )
+ self.do_runf(
+ 'main.c',
+ '''go
void_main.
int_main 201
void 0
@@ -3499,11 +3704,14 @@ def test_dlfcn_funcs(self):
int 0 54
int 1 9000
ok
-''')
+''',
+ )
@needs_dylink
def test_dlfcn_longjmp(self):
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
#include
#include
@@ -3513,11 +3721,14 @@ def test_dlfcn_longjmp(self):
if (i == 10) longjmp(buf, i);
printf("pre %d\n", i);
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
#include
@@ -3545,8 +3756,11 @@ def test_dlfcn_longjmp(self):
return 0;
}
- ''')
- self.do_runf('main.c', '''go!
+ ''',
+ )
+ self.do_runf(
+ 'main.c',
+ '''go!
pre 1
pre 2
pre 3
@@ -3557,7 +3771,8 @@ def test_dlfcn_longjmp(self):
pre 8
pre 9
out!
-''')
+''',
+ )
# TODO: make this work. need to forward tempRet0 across modules
# TODO Enable @with_all_eh_sjlj (the test is not working now)
@@ -3565,7 +3780,9 @@ def test_dlfcn_longjmp(self):
def zzztest_dlfcn_exceptions(self):
self.set_setting('DISABLE_EXCEPTION_CATCHING', 0)
- create_file('liblib.cpp', r'''
+ create_file(
+ 'liblib.cpp',
+ r'''
extern "C" {
int ok() {
return 65;
@@ -3574,7 +3791,8 @@ def zzztest_dlfcn_exceptions(self):
throw 123;
}
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.cpp')
self.prep_dlfcn_main()
@@ -3617,11 +3835,14 @@ def zzztest_dlfcn_exceptions(self):
return 0;
}
'''
- self.do_run(src, '''go!
+ self.do_run(
+ src,
+ '''go!
ok: 65
int 123
ok
-''')
+''',
+ )
@needs_dylink
def test_dlfcn_handle_alloc(self):
@@ -3631,7 +3852,9 @@ def test_dlfcn_handle_alloc(self):
def indir(name):
return os.path.join(dirname, name)
- create_file('a.cpp', r'''
+ create_file(
+ 'a.cpp',
+ r'''
#include
static class A {
@@ -3640,9 +3863,12 @@ def indir(name):
puts("a: loaded");
}
} _;
- ''')
+ ''',
+ )
- create_file('b.cpp', r'''
+ create_file(
+ 'b.cpp',
+ r'''
#include
static class B {
@@ -3651,7 +3877,8 @@ def indir(name):
puts("b: loaded");
}
} _;
- ''')
+ ''',
+ )
self.build_dlfcn_lib('a.cpp', outfile='liba.so')
self.build_dlfcn_lib('b.cpp', outfile='libb.so')
@@ -3659,7 +3886,9 @@ def indir(name):
self.set_setting('MAIN_MODULE')
self.clear_setting('SIDE_MODULE')
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
#include
@@ -3685,7 +3914,8 @@ def indir(name):
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('main.c', 'a: loaded\nb: loaded\n')
@needs_dylink
@@ -3693,11 +3923,14 @@ def indir(name):
def test_dlfcn_feature_in_lib(self):
self.emcc_args.append('-mnontrapping-fptoint')
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
int magic(float x) {
return __builtin_wasm_trunc_saturate_s_i32_f32(x);
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
@@ -3729,7 +3962,9 @@ def test_dlfcn_feature_in_lib(self):
def test_dlfcn_asyncify(self):
self.set_setting('ASYNCIFY')
- create_file('liblib.c', r'''
+ create_file(
+ 'liblib.c',
+ r'''
#include
#include
@@ -3739,7 +3974,8 @@ def test_dlfcn_asyncify(self):
printf("after sleep\n");
return 42;
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liblib.c')
self.prep_dlfcn_main()
@@ -3763,7 +3999,9 @@ def test_dlfcn_rtld_local(self):
# Create two shared libraries that both depend on a third.
# liba.so -> libsub.so
# libb.so -> libsub.so
- create_file('liba.c', r'''
+ create_file(
+ 'liba.c',
+ r'''
#include
void func_sub();
@@ -3774,9 +4012,12 @@ def test_dlfcn_rtld_local(self):
// be available here even though liba itself is loaded with RTLD_LOCAL.
func_sub();
}
- ''')
+ ''',
+ )
- create_file('libb.c', r'''
+ create_file(
+ 'libb.c',
+ r'''
#include
void func_sub();
@@ -3787,22 +4028,28 @@ def test_dlfcn_rtld_local(self):
// be available here even though liba itself is loaded with RTLD_LOCAL.
func_sub();
}
- ''')
+ ''',
+ )
- create_file('libsub.c', r'''
+ create_file(
+ 'libsub.c',
+ r'''
#include
void func_sub() {
printf("func_sub\n");
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('libsub.c', outfile='libsub.so')
self.build_dlfcn_lib('libb.c', outfile='libb.so', emcc_args=['libsub.so'])
self.build_dlfcn_lib('liba.c', outfile='liba.so', emcc_args=['libsub.so'])
self.prep_dlfcn_main(['liba.so', 'libb.so', '-L.'])
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
#include
@@ -3840,7 +4087,8 @@ def test_dlfcn_rtld_local(self):
printf("done\n");
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('main.c', 'main\nfunc_a\nfunc_sub\nfunc_b\nfunc_sub\ndone\n')
@@ -3848,26 +4096,36 @@ def test_dlfcn_rtld_local(self):
def test_dlfcn_preload(self):
# Create chain of dependencies and load the first libary with preload plugin.
# main -> libb.so -> liba.so
- create_file('liba.c', r'''
+ create_file(
+ 'liba.c',
+ r'''
#include
int liba_fun() {
return 23;
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('liba.c', outfile='liba.so')
- create_file('libb.c', r'''
+ create_file(
+ 'libb.c',
+ r'''
#include
int liba_fun();
int libb_fun() {
return liba_fun()*2;
}
- ''')
+ ''',
+ )
self.build_dlfcn_lib('libb.c', outfile='libb.so', emcc_args=['liba.so'])
- self.prep_dlfcn_main(['--preload-file', 'libb.so', '--use-preload-plugins', '-L.', '-sAUTOLOAD_DYLIBS=0', 'libb.so'])
- create_file('main.c', r'''
+ self.prep_dlfcn_main(
+ ['--preload-file', 'libb.so', '--use-preload-plugins', '-L.', '-sAUTOLOAD_DYLIBS=0', 'libb.so']
+ )
+ create_file(
+ 'main.c',
+ r'''
#include
#include
#include
@@ -3887,11 +4145,11 @@ def test_dlfcn_preload(self):
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('main.c', 'done\n')
- def dylink_test(self, main, side, expected=None, header=None, force_c=False,
- main_module=2, **kwargs):
+ def dylink_test(self, main, side, expected=None, header=None, force_c=False, main_module=2, **kwargs):
# Same as dylink_testf but take source code in string form
if not isinstance(side, list):
side_file = 'liblib.cpp' if not force_c else 'liblib.c'
@@ -3906,11 +4164,18 @@ def dylink_test(self, main, side, expected=None, header=None, force_c=False,
return self.dylink_testf(main, side, expected, main_module=main_module, **kwargs)
- def dylink_testf(self, main, side=None, expected=None, force_c=False, main_emcc_args=None,
- main_module=2,
- so_dir='',
- so_name='liblib.so',
- **kwargs):
+ def dylink_testf(
+ self,
+ main,
+ side=None,
+ expected=None,
+ force_c=False,
+ main_emcc_args=None,
+ main_module=2,
+ so_dir='',
+ so_name='liblib.so',
+ **kwargs,
+ ):
main_emcc_args = main_emcc_args or []
if getattr(self, 'dylink_reversed', False):
# Test the reverse case. There we flip the role of the side module and main module.
@@ -3961,7 +4226,8 @@ def dylink_testf(self, main, side=None, expected=None, force_c=False, main_emcc_
self.emcc_args = old_args
def do_basic_dylink_test(self, **kwargs):
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
#include "header.h"
@@ -3969,13 +4235,19 @@ def do_basic_dylink_test(self, **kwargs):
printf("other says %d.\n", sidey());
return 0;
}
- ''', '''
+ ''',
+ '''
#include "header.h"
int sidey() {
return 11;
}
- ''', 'other says 11.', 'int sidey();', force_c=True, **kwargs)
+ ''',
+ 'other says 11.',
+ 'int sidey();',
+ force_c=True,
+ **kwargs,
+ )
@needs_dylink
@crossplatform
@@ -4015,7 +4287,9 @@ def test_dylink_locate_file(self):
so_dir = 'so_dir'
so_name = 'liblib.so'
os.mkdir(so_dir)
- create_file('pre.js', '''
+ create_file(
+ 'pre.js',
+ '''
Module['locateFile'] = function(f) {
if (f === '%s') {
return '%s/' + f;
@@ -4023,12 +4297,15 @@ def test_dylink_locate_file(self):
return f;
}
};
- ''' % (so_name, so_dir))
+ '''
+ % (so_name, so_dir),
+ )
self.do_basic_dylink_test(so_dir=so_dir, so_name=so_name, main_emcc_args=['--pre-js', 'pre.js'])
@with_dylink_reversed
def test_dylink_function_pointer_equality(self):
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
#include "header.h"
@@ -4042,31 +4319,42 @@ def test_dylink_function_pointer_equality(self):
printf("failure\n");
return 0;
}
- ''', '''
+ ''',
+ '''
#include
#include "header.h"
void* get_address() {
return (void*)&puts;
}
- ''', 'success', header='void* get_address();', force_c=True)
+ ''',
+ 'success',
+ header='void* get_address();',
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_floats(self):
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
extern float sidey();
int main() {
printf("other says %.2f.\n", sidey()+1);
return 0;
}
- ''', '''
+ ''',
+ '''
float sidey() { return 11.5; }
- ''', 'other says 12.50', force_c=True)
+ ''',
+ 'other says 12.50',
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_printf(self):
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
void sidey();
int main() {
@@ -4074,12 +4362,16 @@ def test_dylink_printf(self):
sidey();
return 0;
}
- ''', r'''
+ ''',
+ r'''
#include
void sidey() {
printf("hello from side\n");
}
- ''', 'hello from main\nhello from side\n', force_c=True)
+ ''',
+ 'hello from main\nhello from side\n',
+ force_c=True,
+ )
# Verify that a function pointer can be passed back and forth and invoked
# on both sides.
@@ -4104,7 +4396,9 @@ def test_dylink_funcpointer(self):
intfunc sidey(intfunc f) { f(1); return f; }
''',
expected='hello from funcptr: 1\nhello from funcptr: 0\n',
- header='typedef void (*intfunc)(int );', force_c=True)
+ header='typedef void (*intfunc)(int );',
+ force_c=True,
+ )
@with_dylink_reversed
# test dynamic linking of a module with multiple function pointers, stored
@@ -4130,7 +4424,9 @@ def test_dylink_static_funcpointers(self):
void sidey(voidfunc f) { f(); }
''',
expected='hello 0\nhello 1\nhello 2\n',
- header='typedef void (*voidfunc)(); void sidey(voidfunc f);', force_c=True)
+ header='typedef void (*voidfunc)(); void sidey(voidfunc f);',
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_funcpointers_wrapper(self):
@@ -4157,7 +4453,9 @@ def test_dylink_funcpointers_wrapper(self):
#include
typedef void (*charfunc)(const char*);
extern charfunc get();
- ''', force_c=True)
+ ''',
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_static_funcpointer_float(self):
@@ -4179,11 +4477,14 @@ def test_dylink_static_funcpointer_float(self):
int sidey(floatfunc f) { f(56.78); return 1; }
''',
expected='hello 1: 56.779999\ngot: 1\nhello 1: 12.340000\n',
- header='typedef float (*floatfunc)(float);', force_c=True)
+ header='typedef float (*floatfunc)(float);',
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_global_init(self):
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
struct Class {
Class() { printf("a new Class\n"); }
@@ -4192,28 +4493,37 @@ def test_dylink_global_init(self):
int main() {
return 0;
}
- ''', r'''
+ ''',
+ r'''
void nothing() {}
- ''', 'a new Class\n')
+ ''',
+ 'a new Class\n',
+ )
@with_dylink_reversed
def test_dylink_global_inits(self):
def test():
- self.dylink_test(header=r'''
+ self.dylink_test(
+ header=r'''
#include
struct Class {
Class(const char *name) { printf("new %s\n", name); }
};
- ''', main=r'''
+ ''',
+ main=r'''
#include "header.h"
static Class c("main");
int main() {
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include "header.h"
static Class c("side");
- ''', expected=['new main\nnew side\n', 'new side\nnew main\n'])
+ ''',
+ expected=['new main\nnew side\n', 'new side\nnew main\n'],
+ )
+
test()
print('check warnings')
@@ -4225,7 +4535,8 @@ def test():
@with_dylink_reversed
def test_dylink_i64(self):
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
#include
extern int64_t sidey();
@@ -4233,17 +4544,22 @@ def test_dylink_i64(self):
printf("other says %lld.\n", sidey());
return 0;
}
- ''', '''
+ ''',
+ '''
#include
int64_t sidey() {
return 42;
}
- ''', 'other says 42.', force_c=True)
+ ''',
+ 'other says 42.',
+ force_c=True,
+ )
@with_dylink_reversed
@all_engines
def test_dylink_i64_b(self):
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
#include
extern int64_t sidey();
@@ -4264,7 +4580,8 @@ def test_dylink_i64_b(self):
int64_t rb = hb(42);
printf("my second fp says: %lld.\n", r);
}
- ''', '''
+ ''',
+ '''
#include
int64_t sidey() {
volatile int64_t x = 0x12345678abcdef12LL;
@@ -4272,12 +4589,16 @@ def test_dylink_i64_b(self):
x = 18 - x;
return x;
}
- ''', 'other says -1311768467750121224.\nmy fp says: 43.\nmy second fp says: 43.', force_c=True)
+ ''',
+ 'other says -1311768467750121224.\nmy fp says: 43.\nmy second fp says: 43.',
+ force_c=True,
+ )
@with_dylink_reversed
@also_with_wasm_bigint
def test_dylink_i64_c(self):
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
#include
#include "header.h"
@@ -4308,7 +4629,8 @@ def test_dylink_i64_c(self):
printf("res64 - external %" PRId64 "\n", eres64);
return 0;
}
- ''', '''\
+ ''',
+ '''\
#include "header.h"
int32_t function_ret_32(int32_t i, int32_t j, int32_t k) {
return 32;
@@ -4316,21 +4638,27 @@ def test_dylink_i64_c(self):
int64_t function_ret_64(int32_t i, int32_t j, int32_t k) {
return 64;
}
- ''', '''\
+ ''',
+ '''\
res32 - internal 32
res32 - external 32
res64 - internal 64
-res64 - external 64\n''', header='''\
+res64 - external 64\n''',
+ header='''\
#include
#include
EMSCRIPTEN_KEEPALIVE int32_t function_ret_32(int32_t i, int32_t j, int32_t k);
EMSCRIPTEN_KEEPALIVE int64_t function_ret_64(int32_t i, int32_t j, int32_t k);
- ''', force_c=True)
+ ''',
+ force_c=True,
+ )
- @parameterized({
- '': (False,),
- 'rtld_local': (True,),
- })
+ @parameterized(
+ {
+ '': (False,),
+ 'rtld_local': (True,),
+ }
+ )
@needs_dylink
@also_with_wasm_bigint
def test_dylink_i64_invoke(self, rtld_local):
@@ -4338,7 +4666,8 @@ def test_dylink_i64_invoke(self, rtld_local):
self.set_setting('NO_AUTOLOAD_DYLIBS')
self.emcc_args.append('-DUSE_DLOPEN')
self.set_setting('DISABLE_EXCEPTION_CATCHING', 0)
- self.dylink_test(r'''\
+ self.dylink_test(
+ r'''\
#include
#include
#include
@@ -4362,7 +4691,8 @@ def test_dylink_i64_invoke(self, rtld_local):
printf("got %lld\n", sidey(temp));
printf("got %lld\n", sidey(0));
return 0;
- }''', r'''\
+ }''',
+ r'''\
#include
#include
#include
@@ -4382,42 +4712,55 @@ def test_dylink_i64_invoke(self, rtld_local):
return 0;
}
}
- }''', 'got 84\ngot 0')
+ }''',
+ 'got 84\ngot 0',
+ )
@with_dylink_reversed
def test_dylink_class(self):
- self.dylink_test(header=r'''
+ self.dylink_test(
+ header=r'''
#include
struct Class {
Class(const char *name);
};
- ''', main=r'''
+ ''',
+ main=r'''
#include "header.h"
int main() {
Class c("main");
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include "header.h"
Class::Class(const char *name) { printf("new %s\n", name); }
- ''', expected=['new main\n'])
+ ''',
+ expected=['new main\n'],
+ )
@with_dylink_reversed
def test_dylink_global_var(self):
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
extern int x;
int main() {
printf("extern is %d.\n", x);
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
int x = 123;
- ''', expected=['extern is 123.\n'], force_c=True)
+ ''',
+ expected=['extern is 123.\n'],
+ force_c=True,
+ )
@needs_dylink
def test_dylink_global_var_export(self):
- self.do_run(r'''
+ self.do_run(
+ r'''
#include
#include
#include
@@ -4434,34 +4777,43 @@ def test_dylink_global_var_export(self):
assert(js_address == &my_number);
return 0;
}
- ''', emcc_args=['-sMAIN_MODULE'], force_c=True)
+ ''',
+ emcc_args=['-sMAIN_MODULE'],
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_global_var_modded(self):
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
extern int x;
int main() {
printf("extern is %d.\n", x);
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
int x = 123;
struct Initter {
Initter() { x = 456; }
};
Initter initter;
- ''', expected=['extern is 456.\n'])
-
+ ''',
+ expected=['extern is 456.\n'],
+ )
+
@with_dylink_reversed
def test_dylink_stdlib(self):
- self.dylink_test(header=r'''
+ self.dylink_test(
+ header=r'''
#include
#include
#include
char *side(const char *data);
double pow_two(double x);
- ''', main=r'''
+ ''',
+ main=r'''
#include
#include "header.h"
int main() {
@@ -4475,7 +4827,8 @@ def test_dylink_stdlib(self):
free(temp);
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include "header.h"
char *side(const char *data) {
char *ret = (char*)malloc(strlen(data)+1);
@@ -4485,20 +4838,28 @@ def test_dylink_stdlib(self):
double pow_two(double x) {
return pow(2, x);
}
- ''', expected=['hello through side\n\npow_two: 59.'], force_c=True)
+ ''',
+ expected=['hello through side\n\npow_two: 59.'],
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_jslib(self):
- create_file('lib.js', r'''
+ create_file(
+ 'lib.js',
+ r'''
addToLibrary({
test_lib_func: function(x) {
return x + 17.2;
}
});
- ''')
- self.dylink_test(header=r'''
+ ''',
+ )
+ self.dylink_test(
+ header=r'''
extern double test_lib_func(int input);
- ''', main=r'''
+ ''',
+ main=r'''
#include
#include "header.h"
extern double sidey();
@@ -4510,7 +4871,8 @@ def test_dylink_jslib(self):
printf("more: %.5f, %d\n", temp, input);
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include
#include "header.h"
extern int main2();
@@ -4520,44 +4882,62 @@ def test_dylink_jslib(self):
printf("main2 sed: %u, %c\n", temp, temp/2);
return test_lib_func(temp);
}
- ''', expected='other says 45.2', main_emcc_args=['--js-library', 'lib.js'], force_c=True)
+ ''',
+ expected='other says 45.2',
+ main_emcc_args=['--js-library', 'lib.js'],
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_many_postsets(self):
NUM = 1234
- self.dylink_test(header=r'''
+ self.dylink_test(
+ header=r'''
#include
typedef void (*voidfunc)();
static void simple() {
printf("simple.\n");
}
- static volatile voidfunc funcs[''' + str(NUM) + '] = { ' + ','.join(['simple'] * NUM) + r''' };
+ static volatile voidfunc funcs['''
+ + str(NUM)
+ + '] = { '
+ + ','.join(['simple'] * NUM)
+ + r''' };
static void test() {
- volatile int i = ''' + str(NUM - 1) + r''';
+ volatile int i = '''
+ + str(NUM - 1)
+ + r''';
funcs[i]();
i = 0;
funcs[i]();
}
extern void more();
- ''', main=r'''
+ ''',
+ main=r'''
#include "header.h"
int main() {
test();
more();
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include "header.h"
void more() {
test();
}
- ''', expected=['simple.\nsimple.\nsimple.\nsimple.\n'], force_c=True)
+ ''',
+ expected=['simple.\nsimple.\nsimple.\nsimple.\n'],
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_postsets_chunking(self):
- self.dylink_test(header=r'''
+ self.dylink_test(
+ header=r'''
extern int global_var;
- ''', main=r'''
+ ''',
+ main=r'''
#include
#include "header.h"
@@ -4581,19 +4961,25 @@ def test_dylink_postsets_chunking(self):
int main(int argc, char *argv[]) {
printf("%d\n", *ptr);
}
- ''', side=r'''
+ ''',
+ side=r'''
#include "header.h"
int global_var = 12345;
- ''', expected=['12345\n'], force_c=True)
+ ''',
+ expected=['12345\n'],
+ force_c=True,
+ )
@with_dylink_reversed
- @parameterized({
- 'libcxx': ('libc,libc++,libmalloc,libc++abi',),
- 'all': ('1',),
- 'missing': ('libc,libmalloc,libc++abi', False, False, False),
- 'missing_assertions': ('libc,libmalloc,libc++abi', False, False, True),
- })
+ @parameterized(
+ {
+ 'libcxx': ('libc,libc++,libmalloc,libc++abi',),
+ 'all': ('1',),
+ 'missing': ('libc,libmalloc,libc++abi', False, False, False),
+ 'missing_assertions': ('libc,libmalloc,libc++abi', False, False, True),
+ }
+ )
def test_dylink_syslibs(self, syslibs, expect_pass=True, with_reversed=True, assertions=True):
# one module uses libcxx, need to force its inclusion when it isn't the main
if not with_reversed and self.dylink_reversed:
@@ -4615,38 +5001,50 @@ def test_dylink_syslibs(self, syslibs, expect_pass=True, with_reversed=True, ass
assert_returncode = NON_ZERO
with env_modify({'EMCC_FORCE_STDLIBS': syslibs, 'EMCC_ONLY_FORCED_STDLIBS': '1'}):
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
void side();
int main() {
side();
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include
void side() { std::cout << "cout hello from side\n"; }
- ''', expected=expected, main_module=1, assert_returncode=assert_returncode)
+ ''',
+ expected=expected,
+ main_module=1,
+ assert_returncode=assert_returncode,
+ )
@with_dylink_reversed
@with_env_modify({'EMCC_FORCE_STDLIBS': 'libc++'})
def test_dylink_iostream(self):
- self.dylink_test(header=r'''
+ self.dylink_test(
+ header=r'''
#include
#include
std::string side();
- ''', main=r'''
+ ''',
+ main=r'''
#include "header.h"
int main() {
std::cout << "hello from main " << side() << std::endl;
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include "header.h"
std::string side() { return "and hello from side"; }
- ''', expected=['hello from main and hello from side\n'])
+ ''',
+ expected=['hello from main and hello from side\n'],
+ )
@with_dylink_reversed
- def test_dylink_dynamic_cast(self): # issue 3465
- self.dylink_test(header=r'''
+ def test_dylink_dynamic_cast(self): # issue 3465
+ self.dylink_test(
+ header=r'''
class Base {
public:
virtual void printName();
@@ -4656,7 +5054,8 @@ class Derived : public Base {
public:
void printName();
};
- ''', main=r'''
+ ''',
+ main=r'''
#include "header.h"
#include
@@ -4678,7 +5077,8 @@ class Derived : public Base {
delete derived;
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include "header.h"
#include
@@ -4689,18 +5089,22 @@ class Derived : public Base {
void Derived::printName() {
printf("Derived\n");
}
- ''', expected=['starting main\nBase\nDerived\nOK'])
+ ''',
+ expected=['starting main\nBase\nDerived\nOK'],
+ )
@with_all_eh_sjlj
@with_dylink_reversed
def test_dylink_raii_exceptions(self):
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
extern int side();
int main() {
printf("from side: %d.\n", side());
}
- ''', side=r'''
+ ''',
+ side=r'''
#include
typedef int (*ifdi)(float, double, int);
int func_with_special_sig(float a, double b, int c) {
@@ -4720,12 +5124,15 @@ def test_dylink_raii_exceptions(self):
volatile ifdi p = func_with_special_sig;
return p(2.18281, 3.14159, 42);
}
- ''', expected=['special 2.182810 3.141590 42\ndestroy\nfrom side: 1337.\n'])
+ ''',
+ expected=['special 2.182810 3.141590 42\ndestroy\nfrom side: 1337.\n'],
+ )
@with_all_eh_sjlj
@with_dylink_reversed
def test_dylink_exceptions_try_catch(self):
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
extern void side();
int main() {
@@ -4737,7 +5144,8 @@ def test_dylink_exceptions_try_catch(self):
side();
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include
void side() {
try {
@@ -4746,12 +5154,15 @@ def test_dylink_exceptions_try_catch(self):
printf("side: caught %.1f\n", f);
}
}
- ''', expected=['main: caught 3\nside: caught 5.3\n'])
+ ''',
+ expected=['main: caught 3\nside: caught 5.3\n'],
+ )
@with_all_eh_sjlj
@with_dylink_reversed
def test_dylink_exceptions_try_catch_2(self):
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
extern void side_throw_int();
int main() {
@@ -4765,7 +5176,8 @@ def test_dylink_exceptions_try_catch_2(self):
void main_throw_float() {
throw 5.3f;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include
extern void main_throw_float();
void side_throw_int() {
@@ -4776,12 +5188,16 @@ def test_dylink_exceptions_try_catch_2(self):
}
throw 3;
}
- ''', expected=['side: caught 5.3\nmain: caught 3\n'])
+ ''',
+ expected=['side: caught 5.3\nmain: caught 3\n'],
+ )
@with_all_eh_sjlj
@needs_dylink
def test_dylink_exceptions_try_catch_6(self):
- create_file('main.cpp', r'''
+ create_file(
+ 'main.cpp',
+ r'''
#include
int main() {
void* handle = dlopen("liblib.so", RTLD_LAZY);
@@ -4789,14 +5205,17 @@ def test_dylink_exceptions_try_catch_6(self):
(side)();
return 0;
}
- ''')
+ ''',
+ )
# Create a dependency on __cxa_find_matching_catch_6 (6 = num clauses + 2)
# which is one higher than the default set of __cxa_find_matching_catch
# functions created in library_exceptions.js.
# This means we end up depending on dynamic linking code to redirect
# __cxa_find_matching_catch_6 to __cxa_find_matching_catch.
- create_file('liblib.cpp', r'''
+ create_file(
+ 'liblib.cpp',
+ r'''
#include
extern "C" void side() {
try {
@@ -4811,7 +5230,8 @@ def test_dylink_exceptions_try_catch_6(self):
printf("side: caught short %hd\n", x);
}
}
- ''')
+ ''',
+ )
self.maybe_closure()
@@ -4834,7 +5254,9 @@ def test_dylink_hyper_dupe(self):
self.set_setting('ASSERTIONS', 2)
# test hyper-dynamic linking, and test duplicate warnings
- create_file('third.cpp', r'''
+ create_file(
+ 'third.cpp',
+ r'''
#include
int sidef() { return 36; }
int sideg = 49;
@@ -4853,9 +5275,11 @@ def test_dylink_hyper_dupe(self):
void only_in_third_1(int x) {
printf("only_in_third_1: %d, %d, %d, %d\n", sidef(), sideg, second_to_third, x);
}
- ''')
+ ''',
+ )
self.run_process([EMCC, 'third.cpp', '-o', 'third.wasm', '-sSIDE_MODULE'] + self.get_emcc_args())
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
#include
extern int sidef();
@@ -4874,7 +5298,7 @@ def test_dylink_hyper_dupe(self):
only_in_third_0();
}
''',
- side=r'''
+ side=r'''
#include
int sidef() { return 10; } // third will try to override these, but fail!
int sideg = 20;
@@ -4891,7 +5315,10 @@ def test_dylink_hyper_dupe(self):
printf("only_in_second_1: %d, %d, %d, %d\n", sidef(), sideg, third_to_second, x);
}
''',
- expected=['sidef: 10, sideg: 20.\nbsidef: 536.\nonly_in_second_0: 10, 20, 1337\nonly_in_third_1: 36, 49, 500, 1221\nonly_in_third_0: 36, 49, 500\nonly_in_second_1: 10, 20, 1337, 2112\n'])
+ expected=[
+ 'sidef: 10, sideg: 20.\nbsidef: 536.\nonly_in_second_0: 10, 20, 1337\nonly_in_third_1: 36, 49, 500, 1221\nonly_in_third_0: 36, 49, 500\nonly_in_second_1: 10, 20, 1337, 2112\n'
+ ],
+ )
print('check warnings')
full = self.run_js('src.js')
@@ -4909,7 +5336,8 @@ def test_dylink_load_compiled_side_module(self):
# startup.
self.set_setting('NO_AUTOLOAD_DYLIBS')
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
#include
extern int sidef();
@@ -4926,16 +5354,19 @@ def test_dylink_load_compiled_side_module(self):
printf("sidef: %d.\n", sidef());
}
''',
- side=r'''
+ side=r'''
#include
int sidef() { return 10; }
- ''', expected=['sidef: 10'])
+ ''',
+ expected=['sidef: 10'],
+ )
@needs_dylink
def test_dylink_dso_needed(self):
def do_run(src, expected_output, emcc_args=None):
create_file('main.c', src + 'int main() { return test_main(); }')
self.do_runf('main.c', expected_output, emcc_args=emcc_args)
+
self._test_dylink_dso_needed(do_run)
@with_dylink_reversed
@@ -4948,7 +5379,8 @@ def test_dylink_dot_a(self):
self.run_process([EMCC, '-fPIC', '-c', 'fourth.c', '-o', 'fourth.o'] + self.get_emcc_args(compile_only=True))
self.run_process([EMAR, 'rc', 'libfourth.a', 'fourth.o'])
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
#include
int sidef();
@@ -4957,13 +5389,16 @@ def test_dylink_dot_a(self):
printf("sidef: %d, sideg: %d.\n", sidef(), sideg());
}
''',
- # contents of libfourth.a must be included, even if they aren't referred to!
- side=['libfourth.a', 'third.o'],
- expected=['sidef: 36, sideg: 17.\n'], force_c=True)
+ # contents of libfourth.a must be included, even if they aren't referred to!
+ side=['libfourth.a', 'third.o'],
+ expected=['sidef: 36, sideg: 17.\n'],
+ force_c=True,
+ )
@with_dylink_reversed
def test_dylink_spaghetti(self):
- self.dylink_test(main=r'''
+ self.dylink_test(
+ main=r'''
#include
int main_x = 72;
extern int side_x;
@@ -4979,7 +5414,8 @@ def test_dylink_spaghetti(self):
printf("main main sees %d, %d, %d.\n", adjust, *ptr, main_x);
return 0;
}
- ''', side=r'''
+ ''',
+ side=r'''
#include
extern int main_x;
int side_x = -534;
@@ -4991,15 +5427,20 @@ def test_dylink_spaghetti(self):
}
};
SideClass cs;
- ''', expected=['''\
+ ''',
+ expected=[
+ '''\
side init sees 82, 72, -534.
main init sees -524, -534, 72.
main main sees -524, -534, 72.
-''', '''\
+''',
+ '''\
main init sees -524, -534, 72.
side init sees 82, 72, -534.
main main sees -524, -534, 72.
-'''])
+''',
+ ],
+ )
@needs_make('mingw32-make')
@with_dylink_reversed
@@ -5009,10 +5450,12 @@ def test_dylink_zlib(self):
# example.c uses K&R style function declarations
self.emcc_args.append('-Wno-deprecated-non-prototype')
self.emcc_args.append('-I' + test_file('third_party/zlib'))
- self.dylink_test(main=read_file(test_file('third_party/zlib/example.c')),
- side=zlib_archive,
- expected=read_file(test_file('core/test_zlib.out')),
- force_c=True)
+ self.dylink_test(
+ main=read_file(test_file('third_party/zlib/example.c')),
+ side=zlib_archive,
+ expected=read_file(test_file('core/test_zlib.out')),
+ force_c=True,
+ )
# @with_dylink_reversed
# def test_dylink_bullet(self):
@@ -5069,10 +5512,7 @@ class Bar : public Foo {
}
'''
- self.dylink_test(main=main,
- side=side,
- header=header,
- expected='success')
+ self.dylink_test(main=main, side=side, header=header, expected='success')
@needs_dylink
def test_dylink_argv_argc(self):
@@ -5080,12 +5520,15 @@ def test_dylink_argv_argc(self):
self.emcc_args += ['--extern-pre-js', 'pre.js']
- create_file('pre.js', '''
+ create_file(
+ 'pre.js',
+ '''
var Module = { arguments: ['hello', 'world!'] }
- ''')
+ ''',
+ )
self.dylink_test(
- '', # main module is empty.
+ '', # main module is empty.
r'''
#include
int main(int argc, char const *argv[]) {
@@ -5095,7 +5538,8 @@ def test_dylink_argv_argc(self):
return 0;
}
''',
- expected='3 hello world!')
+ expected='3 hello world!',
+ )
@needs_dylink
def test_dylink_weak(self):
@@ -5153,7 +5597,7 @@ def test_strtol(self):
def test_transtrcase(self):
self.do_core_test('test_transtrcase.c')
- @also_with_wasmfs # tests EXIT_RUNTIME flushing
+ @also_with_wasmfs # tests EXIT_RUNTIME flushing
@no_wasm2js('very slow to compile: https://github.com/emscripten-core/emscripten/issues/21048')
@is_slow_test
def test_printf(self):
@@ -5246,17 +5690,23 @@ def test_sscanf_2(self):
}
'''
if ftype == 'float':
- self.do_run(src.replace('%lf', '%f').replace('double', 'float'), '''Pass: 1.234568 1.234568
+ self.do_run(
+ src.replace('%lf', '%f').replace('double', 'float'),
+ '''Pass: 1.234568 1.234568
Pass: 123456.789062 123456.789062
Pass: 123456.789062 123456.789062
Pass: 0.000012 0.000012
-Pass: 0.000012 0.000012''')
+Pass: 0.000012 0.000012''',
+ )
else:
- self.do_run(src, '''Pass: 1.234568 1.234568
+ self.do_run(
+ src,
+ '''Pass: 1.234568 1.234568
Pass: 123456.789000 123456.789000
Pass: 123456.789000 123456.789000
Pass: 0.000012 0.000012
-Pass: 0.000012 0.000012''')
+Pass: 0.000012 0.000012''',
+ )
def test_sscanf_n(self):
self.do_core_test('test_sscanf_n.c')
@@ -5300,7 +5750,7 @@ def test_files(self):
# Use closure here, to test we don't break FS stuff
if '-O3' in self.emcc_args and self.is_wasm2js():
print('closure 2')
- self.emcc_args += ['--closure', '2'] # Use closure 2 here for some additional coverage
+ self.emcc_args += ['--closure', '2'] # Use closure 2 here for some additional coverage
# Sadly --closure=2 is not yet free of closure warnings
# FIXME(https://github.com/emscripten-core/emscripten/issues/17080)
self.ldflags.append('-Wno-error=closure')
@@ -5310,7 +5760,9 @@ def test_files(self):
self.emcc_args += ['--pre-js', 'pre.js']
self.set_setting('FORCE_FILESYSTEM')
- create_file('pre.js', '''
+ create_file(
+ 'pre.js',
+ '''
/** @suppress{checkTypes}*/
Module = {
'noFSInit': true,
@@ -5325,20 +5777,24 @@ def test_files(self):
});
}
};
-''')
+''',
+ )
create_file('test.file', 'some data')
self.do_run_in_out_file_test('test_files.c')
def test_module_stdin(self):
- create_file('pre.js', '''
+ create_file(
+ 'pre.js',
+ '''
var data = [10, 20, 40, 30];
Module = {
stdin: () => { return data.pop() || null },
stdout: (x) => out('got: ' + x)
};
- ''')
+ ''',
+ )
self.emcc_args += ['--pre-js', 'pre.js']
src = r'''
@@ -5356,13 +5812,16 @@ def test_module_stdin(self):
}
'''
- self.do_run(src, '''\
+ self.do_run(
+ src,
+ '''\
isatty? in=0,out=0,err=1
got: 30
got: 40
got: 20
got: 10
-''')
+''',
+ )
def test_mount(self):
self.set_setting('FORCE_FILESYSTEM')
@@ -5453,7 +5912,8 @@ def test_fscanf(self):
def test_fscanf_2(self):
create_file('a.txt', '1/2/3 4/5/6 7/8/9\n')
self.emcc_args += ['--embed-file', 'a.txt']
- self.do_run(r'''\
+ self.do_run(
+ r'''\
#include
int main(int argv, char** argc) {
@@ -5474,7 +5934,9 @@ def test_fscanf_2(self):
printf("matches: %d\n", matches);
return 0;
}
- ''', 'fscanf test\nmatches: 9\n')
+ ''',
+ 'fscanf test\nmatches: 9\n',
+ )
def test_fileno(self):
create_file('empty.txt', '')
@@ -5575,7 +6037,9 @@ def test_utime(self):
def test_futimens(self):
self.do_runf('utime/test_futimens.c', 'success')
- @no_minimal_runtime('MINIMAL_RUNTIME does not have getValue() and setValue() (TODO add it to a JS library function to get it in)')
+ @no_minimal_runtime(
+ 'MINIMAL_RUNTIME does not have getValue() and setValue() (TODO add it to a JS library function to get it in)'
+ )
@requires_node # only node handles utf well
def test_utf(self):
self.set_setting('EXPORTED_FUNCTIONS', ['_main', '_malloc', '_free'])
@@ -5604,19 +6068,23 @@ def test_utf8_textdecoder(self):
self.do_runf('benchmark/benchmark_utf8.c', 'OK.')
# Test that invalid character in UTF8 does not cause decoding to crash.
- @parameterized({
- '': [[]],
- 'textdecoder': [['-sTEXTDECODER']],
- })
+ @parameterized(
+ {
+ '': [[]],
+ 'textdecoder': [['-sTEXTDECODER']],
+ }
+ )
def test_utf8_invalid(self, args):
self.do_runf('utf8_invalid.cpp', 'OK.', emcc_args=args)
# Test that invalid character in UTF8 does not cause decoding to crash.
@no_asan('TODO: ASan support in minimal runtime')
- @parameterized({
- '': [[]],
- 'textdecoder': [['-sTEXTDECODER']],
- })
+ @parameterized(
+ {
+ '': [[]],
+ 'textdecoder': [['-sTEXTDECODER']],
+ }
+ )
def test_minimal_runtime_utf8_invalid(self, args):
self.set_setting('MINIMAL_RUNTIME')
self.emcc_args += ['--pre-js', test_file('minimal_runtime_exit_handling.js')]
@@ -5640,7 +6108,7 @@ def test_std_function_incomplete_return(self):
self.do_core_test('test_std_function_incomplete_return.cpp')
def test_istream(self):
- for linkable in [0]: # , 1]:
+ for linkable in [0]: # , 1]:
print(linkable)
# regression check for issue #273
self.set_setting('LINKABLE', linkable)
@@ -5775,14 +6243,13 @@ def test_fs_mmap(self):
self.do_run_in_out_file_test('fs/test_mmap.c')
@no_wasmfs('wasmfs will (?) need a non-JS mechanism to ignore permissions during startup')
- @parameterized({
- '': [],
- 'minimal_runtime': ['-sMINIMAL_RUNTIME=1']
- })
+ @parameterized({'': [], 'minimal_runtime': ['-sMINIMAL_RUNTIME=1']})
def test_fs_no_main(self, *args):
# library_fs.js uses hooks to enable ignoring of permisions up until ATMAINs are run. This
# test verified that they work correctly, even in programs without a main function.
- create_file('pre.js', '''
+ create_file(
+ 'pre.js',
+ '''
Module.preRun = () => {
assert(FS.ignorePermissions, "ignorePermissions not set during preRun");
}
@@ -5790,7 +6257,8 @@ def test_fs_no_main(self, *args):
assert(!FS.ignorePermissions, "ignorePermissions not unset during onRuntimeInitialized");
assert(_foo() == 42);
}
-''')
+''',
+ )
self.set_setting('EXPORTED_FUNCTIONS', '_foo')
self.set_setting('FORCE_FILESYSTEM')
self.emcc_args += ['--pre-js', 'pre.js'] + list(args)
@@ -5805,7 +6273,8 @@ def test_fs_errorstack(self):
self.set_setting('FORCE_FILESYSTEM')
self.set_setting('ASSERTIONS')
- self.do_run(r'''
+ self.do_run(
+ r'''
#include
#include
int main(void) {
@@ -5820,7 +6289,10 @@ def test_fs_errorstack(self):
);
return 0;
}
- ''', 'at Object.readFile', assert_returncode=NON_ZERO) # engines has different error stack format
+ ''',
+ 'at Object.readFile',
+ assert_returncode=NON_ZERO,
+ ) # engines has different error stack format
@also_with_noderawfs
def test_fs_llseek(self):
@@ -5888,10 +6360,7 @@ def test_sigalrm(self):
def test_signals(self):
self.do_core_test('test_signals.c')
- @parameterized({
- 'sigint': (EM_SIGINT, 128 + EM_SIGINT, True),
- 'sigabrt': (EM_SIGABRT, 1, False)
- })
+ @parameterized({'sigint': (EM_SIGINT, 128 + EM_SIGINT, True), 'sigabrt': (EM_SIGABRT, 1, False)})
@crossplatform
def test_sigaction_default(self, signal, exit_code, assert_identical):
self.set_setting('EXIT_RUNTIME')
@@ -5901,7 +6370,7 @@ def test_sigaction_default(self, signal, exit_code, assert_identical):
test_file('test_sigaction_default.c'),
args=[str(signal)],
assert_identical=assert_identical,
- assert_returncode=exit_code
+ assert_returncode=exit_code,
)
@crossplatform
@@ -6006,7 +6475,9 @@ def test_unistd_unlink(self):
def test_unistd_links(self):
nodefs = '-DNODEFS' in self.emcc_args
if nodefs and WINDOWS:
- self.skipTest('Skipping NODEFS part of this test for test_unistd_links on Windows, since it would require administrative privileges.')
+ self.skipTest(
+ 'Skipping NODEFS part of this test for test_unistd_links on Windows, since it would require administrative privileges.'
+ )
# Also, other detected discrepancies if you do end up running this test on NODEFS:
# test expects /, but Windows gives \ as path slashes.
# Calling readlink() on a non-link gives error 22 EINVAL on Unix, but simply error 0 OK on Windows.
@@ -6086,10 +6557,13 @@ def test_nl_types(self):
def test_799(self):
src = test_file('799.cpp')
- self.do_runf(src, '''Set PORT family: 0, port: 3979
+ self.do_runf(
+ src,
+ '''Set PORT family: 0, port: 3979
Get PORT family: 0
PORT: 3979
-''')
+''',
+ )
def test_ctype(self):
self.do_core_test('test_ctype.c')
@@ -6121,14 +6595,17 @@ def test_main_module_static_align(self):
# libc++ tests
def test_iostream_and_determinism(self):
- create_file('src.cpp', '''
+ create_file(
+ 'src.cpp',
+ '''
#include
int main() {
std::cout << "hello world" << std::endl << 77 << "." << std::endl;
return 0;
}
- ''')
+ ''',
+ )
num = 5
for i in range(num):
@@ -6161,7 +6638,9 @@ def test_reinterpreted_ptrs(self):
self.do_core_test('test_reinterpreted_ptrs.cpp')
def test_js_libraries(self):
- create_file('main.cpp', '''
+ create_file(
+ 'main.cpp',
+ '''
#include
extern "C" {
extern void printey();
@@ -6172,17 +6651,24 @@ def test_js_libraries(self):
printf("*%d*\\n", calcey(10, 22));
return 0;
}
- ''')
- create_file('mylib1.js', '''
+ ''',
+ )
+ create_file(
+ 'mylib1.js',
+ '''
addToLibrary({
printey: () => out('hello from lib!')
});
- ''')
- create_file('mylib2.js', '''
+ ''',
+ )
+ create_file(
+ 'mylib2.js',
+ '''
addToLibrary({
calcey: (x, y) => x + y
});
- ''')
+ ''',
+ )
self.emcc_args += ['--js-library', 'mylib1.js', '--js-library', 'mylib2.js']
self.do_runf('main.cpp', 'hello from lib!\n*32*\n')
@@ -6199,7 +6685,15 @@ def test_unicode_js_library(self):
err = self.expect_fail([PYTHON, 'expect_fail.py'], expect_traceback=True)
self.assertContained('UnicodeDecodeError', err)
- self.emcc_args += ['-sMODULARIZE', '--js-library', test_file('unicode_library.js'), '--extern-post-js', test_file('modularize_post_js.js'), '--post-js', test_file('unicode_postjs.js')]
+ self.emcc_args += [
+ '-sMODULARIZE',
+ '--js-library',
+ test_file('unicode_library.js'),
+ '--extern-post-js',
+ test_file('modularize_post_js.js'),
+ '--post-js',
+ test_file('unicode_postjs.js'),
+ ]
self.do_run_in_out_file_test('test_unicode_js_library.c')
def test_funcptr_import_type(self):
@@ -6210,7 +6704,8 @@ def test_funcptr_import_type(self):
def test_constglobalunion(self):
self.set_setting('EXPORT_ALL')
- self.do_run(r'''
+ self.do_run(
+ r'''
#include
struct one_const {
@@ -6239,7 +6734,9 @@ def test_constglobalunion(self):
printf("%li\n", (long)!!addr_of_my_consts.a);
return 0;
}
- ''', '1')
+ ''',
+ '1',
+ )
### 'Medium' tests
@@ -6258,14 +6755,24 @@ def test_raytrace(self):
output = read_file(test_file('raytrace.ppm'))
self.do_run(src, output, args=['3', '16'])
- @parameterized({
- '': ('double',),
- 'float': ('float',),
- })
+ @parameterized(
+ {
+ '': ('double',),
+ 'float': ('float',),
+ }
+ )
def test_fasta(self, float_type):
- results = [('1', '''GG\nctt\n\ntgagc\n'''),
- ('20', '''GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTT\ncttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg\n\ntacgtgtagcctagtgtttgtgttgcgttatagtctatttgtggacacagtatggtcaaa\n\ntgacgtcttttgatctgacggcgttaacaaagatactctg\n'''),
- ('50', '''GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA\nTCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACAT\ncttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg\n\ntactDtDagcctatttSVHtHttKtgtHMaSattgWaHKHttttagacatWatgtRgaaa\n\nNtactMcSMtYtcMgRtacttctWBacgaa\n\nagatactctgggcaacacacatacttctctcatgttgtttcttcggacctttcataacct\n\nttcctggcacatggttagctgcacatcacaggattgtaagggtctagtggttcagtgagc\n\nggaatatcattcgtcggtggtgttaatctatctcggtgtagcttataaatgcatccgtaa\n\ngaatattatgtttatttgtcggtacgttcatggtagtggtgtcgccgatttagacgtaaa\n\nggcatgtatg\n''')]
+ results = [
+ ('1', '''GG\nctt\n\ntgagc\n'''),
+ (
+ '20',
+ '''GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTT\ncttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg\n\ntacgtgtagcctagtgtttgtgttgcgttatagtctatttgtggacacagtatggtcaaa\n\ntgacgtcttttgatctgacggcgttaacaaagatactctg\n''',
+ ),
+ (
+ '50',
+ '''GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA\nTCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACAT\ncttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg\n\ntactDtDagcctatttSVHtHttKtgtHMaSattgWaHKHttttagacatWatgtRgaaa\n\nNtactMcSMtYtcMgRtacttctWBacgaa\n\nagatactctgggcaacacacatacttctctcatgttgtttcttcggacctttcataacct\n\nttcctggcacatggttagctgcacatcacaggattgtaagggtctagtggttcagtgagc\n\nggaatatcattcgtcggtggtgttaatctatctcggtgtagcttataaatgcatccgtaa\n\ngaatattatgtttatttgtcggtacgttcatggtagtggtgtcgccgatttagacgtaaa\n\nggcatgtatg\n''',
+ ),
+ ]
orig_src = read_file(test_file('fasta.cpp'))
@@ -6314,7 +6821,11 @@ def test_dlmalloc(self):
# emcc should build in dlmalloc automatically, and do all the sign correction etc. for it
delete_file('src.js')
- self.run_process([EMCC, test_file('dlmalloc_test.c'), '-sINITIAL_MEMORY=128MB', '-o', 'src.js'], stdout=PIPE, stderr=self.stderr_redirect)
+ self.run_process(
+ [EMCC, test_file('dlmalloc_test.c'), '-sINITIAL_MEMORY=128MB', '-o', 'src.js'],
+ stdout=PIPE,
+ stderr=self.stderr_redirect,
+ )
self.do_run(None, '*1,0*', ['200', '1'], no_build=True)
self.do_run(None, '*400,0*', ['400', '400'], no_build=True)
@@ -6343,7 +6854,9 @@ def test_dlmalloc_large(self):
@no_lsan('lsan also changes malloc, and that ends up linking in new twice')
def test_dlmalloc_partial(self):
# present part of the symbols of dlmalloc, not all
- src = read_file(test_file('new.cpp')).replace('{{{ NEW }}}', 'new int').replace('{{{ DELETE }}}', 'delete') + '''
+ src = (
+ read_file(test_file('new.cpp')).replace('{{{ NEW }}}', 'new int').replace('{{{ DELETE }}}', 'delete')
+ + '''
#include
#include
@@ -6352,6 +6865,7 @@ def test_dlmalloc_partial(self):
return malloc(size);
}
'''
+ )
self.do_run(src, 'new!\n*1,0*')
@no_asan('asan also changes malloc, and that ends up linking in new twice')
@@ -6363,10 +6877,13 @@ def test_dlmalloc_partial_2(self):
self.do_core_test('test_dlmalloc_partial_2.c', assert_returncode=NON_ZERO)
def test_libcxx(self):
- self.do_runf('core/test_libcxx_hash.cpp',
- 'june -> 30\nPrevious (in alphabetical order) is july\nNext (in alphabetical order) is march')
+ self.do_runf(
+ 'core/test_libcxx_hash.cpp',
+ 'june -> 30\nPrevious (in alphabetical order) is july\nNext (in alphabetical order) is march',
+ )
- self.do_run('''
+ self.do_run(
+ '''
#include
#include
int main() {
@@ -6375,7 +6892,9 @@ def test_libcxx(self):
printf("hello world\\n");
return 0;
}
- ''', 'hello world')
+ ''',
+ 'hello world',
+ )
def test_typeid(self):
self.do_core_test('test_typeid.cpp')
@@ -6407,11 +6926,13 @@ def test_mmap_anon_pthreads(self):
self.do_core_test('test_mmap_anon.c')
@no_lsan('Test code contains memory leaks')
- @parameterized({
+ @parameterized(
+ {
'': (0,),
'asyncify': (1,),
'jspi': (2,),
- })
+ }
+ )
def test_cubescript(self, asyncify):
# uses register keyword
self.emcc_args += ['-std=c++03', '-Wno-dynamic-class-memaccess']
@@ -6439,6 +6960,7 @@ def test_relocatable_void_function(self):
def test_wasm_intrinsics_simd(self):
def run():
self.do_runf('test_wasm_intrinsics_simd.c', 'Success!')
+
# Improves test readability
self.emcc_args.append('-Wno-c++11-narrowing')
self.emcc_args = ['-Wpedantic', '-Werror', '-Wall', '-xc++'] + self.emcc_args
@@ -6460,13 +6982,14 @@ def test_neon_wasm_simd(self):
@requires_native_clang
@no_safe_heap('has unaligned 64-bit operations in wasm')
@no_ubsan('test contains UB')
- @parameterized({
- '': ([],),
- 'nontrapping': (['-mnontrapping-fptoint'],)
- })
+ @parameterized({'': ([],), 'nontrapping': (['-mnontrapping-fptoint'],)})
def test_sse1(self, args):
src = test_file('sse/test_sse1.cpp')
- self.run_process([shared.CLANG_CXX, src, '-msse', '-o', 'test_sse1', '-D_CRT_SECURE_NO_WARNINGS=1'] + clang_native.get_clang_native_args(), stdout=PIPE)
+ self.run_process(
+ [shared.CLANG_CXX, src, '-msse', '-o', 'test_sse1', '-D_CRT_SECURE_NO_WARNINGS=1']
+ + clang_native.get_clang_native_args(),
+ stdout=PIPE,
+ )
native_result = self.run_process('./test_sse1', stdout=PIPE).stdout
self.emcc_args += ['-I' + test_file('sse'), '-msse'] + args
@@ -6481,15 +7004,16 @@ def test_sse1(self, args):
@is_slow_test
@no_ubsan('https://github.com/emscripten-core/emscripten/issues/19688')
@no_asan('local count too large')
- @parameterized({
- '': ([],),
- 'nontrapping': (['-mnontrapping-fptoint'],)
- })
+ @parameterized({'': ([],), 'nontrapping': (['-mnontrapping-fptoint'],)})
def test_sse2(self, args):
if self.is_wasm64():
self.require_node_canary()
src = test_file('sse/test_sse2.cpp')
- self.run_process([shared.CLANG_CXX, src, '-msse2', '-Wno-argument-outside-range', '-o', 'test_sse2', '-D_CRT_SECURE_NO_WARNINGS=1'] + clang_native.get_clang_native_args(), stdout=PIPE)
+ self.run_process(
+ [shared.CLANG_CXX, src, '-msse2', '-Wno-argument-outside-range', '-o', 'test_sse2', '-D_CRT_SECURE_NO_WARNINGS=1']
+ + clang_native.get_clang_native_args(),
+ stdout=PIPE,
+ )
native_result = self.run_process('./test_sse2', stdout=PIPE).stdout
self.emcc_args += ['-I' + test_file('sse'), '-msse2', '-Wno-argument-outside-range', '-sSTACK_SIZE=1MB'] + args
@@ -6501,7 +7025,11 @@ def test_sse2(self, args):
@requires_native_clang
def test_sse3(self):
src = test_file('sse/test_sse3.cpp')
- self.run_process([shared.CLANG_CXX, src, '-msse3', '-Wno-argument-outside-range', '-o', 'test_sse3', '-D_CRT_SECURE_NO_WARNINGS=1'] + clang_native.get_clang_native_args(), stdout=PIPE)
+ self.run_process(
+ [shared.CLANG_CXX, src, '-msse3', '-Wno-argument-outside-range', '-o', 'test_sse3', '-D_CRT_SECURE_NO_WARNINGS=1']
+ + clang_native.get_clang_native_args(),
+ stdout=PIPE,
+ )
native_result = self.run_process('./test_sse3', stdout=PIPE).stdout
self.emcc_args += ['-I' + test_file('sse'), '-msse3', '-Wno-argument-outside-range']
@@ -6513,7 +7041,19 @@ def test_sse3(self):
@requires_native_clang
def test_ssse3(self):
src = test_file('sse/test_ssse3.cpp')
- self.run_process([shared.CLANG_CXX, src, '-mssse3', '-Wno-argument-outside-range', '-o', 'test_ssse3', '-D_CRT_SECURE_NO_WARNINGS=1'] + clang_native.get_clang_native_args(), stdout=PIPE)
+ self.run_process(
+ [
+ shared.CLANG_CXX,
+ src,
+ '-mssse3',
+ '-Wno-argument-outside-range',
+ '-o',
+ 'test_ssse3',
+ '-D_CRT_SECURE_NO_WARNINGS=1',
+ ]
+ + clang_native.get_clang_native_args(),
+ stdout=PIPE,
+ )
native_result = self.run_process('./test_ssse3', stdout=PIPE).stdout
self.emcc_args += ['-I' + test_file('sse'), '-mssse3', '-Wno-argument-outside-range']
@@ -6533,7 +7073,19 @@ def test_sse4_1(self):
# ASan with -O0 fails with:
# Compiling function #69:"__original_main" failed: local count too large
self.emcc_args.append('-O1')
- self.run_process([shared.CLANG_CXX, src, '-msse4.1', '-Wno-argument-outside-range', '-o', 'test_sse4_1', '-D_CRT_SECURE_NO_WARNINGS=1'] + clang_native.get_clang_native_args(), stdout=PIPE)
+ self.run_process(
+ [
+ shared.CLANG_CXX,
+ src,
+ '-msse4.1',
+ '-Wno-argument-outside-range',
+ '-o',
+ 'test_sse4_1',
+ '-D_CRT_SECURE_NO_WARNINGS=1',
+ ]
+ + clang_native.get_clang_native_args(),
+ stdout=PIPE,
+ )
native_result = self.run_process('./test_sse4_1', stdout=PIPE).stdout
self.emcc_args += ['-I' + test_file('sse'), '-msse4.1', '-Wno-argument-outside-range', '-sSTACK_SIZE=1MB']
@@ -6543,14 +7095,15 @@ def test_sse4_1(self):
# Tests invoking the SIMD API via x86 SSE4.2 nmmintrin.h header (_mm_x() functions)
@wasm_simd
@requires_native_clang
- @parameterized({
- '': (False,),
- '2': (True,)
- })
+ @parameterized({'': (False,), '2': (True,)})
def test_sse4(self, use_4_2):
msse4 = '-msse4.2' if use_4_2 else '-msse4'
src = test_file('sse/test_sse4_2.cpp')
- self.run_process([shared.CLANG_CXX, src, msse4, '-Wno-argument-outside-range', '-o', 'test_sse4_2', '-D_CRT_SECURE_NO_WARNINGS=1'] + clang_native.get_clang_native_args(), stdout=PIPE)
+ self.run_process(
+ [shared.CLANG_CXX, src, msse4, '-Wno-argument-outside-range', '-o', 'test_sse4_2', '-D_CRT_SECURE_NO_WARNINGS=1']
+ + clang_native.get_clang_native_args(),
+ stdout=PIPE,
+ )
native_result = self.run_process('./test_sse4_2', stdout=PIPE).stdout
self.emcc_args += ['-I' + test_file('sse'), msse4, '-Wno-argument-outside-range']
@@ -6563,13 +7116,23 @@ def test_sse4(self, use_4_2):
@is_slow_test
@no_asan('local count too large')
@no_ubsan('local count too large')
- @parameterized({
- '': ([],),
- 'nontrapping': (['-mnontrapping-fptoint'],)
- })
+ @parameterized({'': ([],), 'nontrapping': (['-mnontrapping-fptoint'],)})
def test_avx(self, args):
src = test_file('sse/test_avx.cpp')
- self.run_process([shared.CLANG_CXX, src, '-mavx', '-Wno-argument-outside-range', '-Wpedantic', '-o', 'test_avx', '-D_CRT_SECURE_NO_WARNINGS=1'] + clang_native.get_clang_native_args(), stdout=PIPE)
+ self.run_process(
+ [
+ shared.CLANG_CXX,
+ src,
+ '-mavx',
+ '-Wno-argument-outside-range',
+ '-Wpedantic',
+ '-o',
+ 'test_avx',
+ '-D_CRT_SECURE_NO_WARNINGS=1',
+ ]
+ + clang_native.get_clang_native_args(),
+ stdout=PIPE,
+ )
native_result = self.run_process('./test_avx', stdout=PIPE).stdout
self.emcc_args += ['-I' + test_file('sse'), '-mavx', '-Wno-argument-outside-range', '-sSTACK_SIZE=1MB'] + args
@@ -6581,9 +7144,7 @@ def test_sse_diagnostics(self):
self.emcc_args.remove('-Werror')
src = test_file('sse/test_sse_diagnostic.cpp')
- p = self.run_process(
- [shared.EMXX, src, '-msse', '-DWASM_SIMD_COMPAT_SLOW'] + self.get_emcc_args(),
- stderr=PIPE)
+ p = self.run_process([shared.EMXX, src, '-msse', '-DWASM_SIMD_COMPAT_SLOW'] + self.get_emcc_args(), stderr=PIPE)
self.assertContained('Instruction emulated via slow path.', p.stderr)
@requires_native_clang
@@ -6596,7 +7157,11 @@ def test_relaxed_simd_implies_simd128(self):
def test_gcc_unmangler(self):
self.emcc_args += ['-I' + test_file('third_party/libiberty')]
- self.do_runf('third_party/libiberty/cp-demangle.c', '*d_demangle(char const*, int, unsigned int*)*', args=['_ZL10d_demanglePKciPj'])
+ self.do_runf(
+ 'third_party/libiberty/cp-demangle.c',
+ '*d_demangle(char const*, int, unsigned int*)*',
+ args=['_ZL10d_demanglePKciPj'],
+ )
@needs_make('make')
@crossplatform
@@ -6604,18 +7169,22 @@ def test_lua(self):
self.emcc_args.remove('-Werror')
env_init = {
'SYSCFLAGS': ' '.join(self.get_emcc_args(compile_only=True)),
- 'SYSLDFLAGS': ' '.join(self.get_emcc_args())
+ 'SYSLDFLAGS': ' '.join(self.get_emcc_args()),
}
- libs = self.get_library('third_party/lua',
- [Path('src/lua.o'), Path('src/liblua.a')],
- make=['make', 'echo', 'generic'],
- env_init=env_init,
- configure=None)
- self.do_run('',
- 'hello lua world!\n17\n1\n2\n3\n4\n7',
- args=['-e', '''print("hello lua world!");print(17);for x = 1,4 do print(x) end;print(10-3)'''],
- libraries=libs,
- includes=[test_file('lua')])
+ libs = self.get_library(
+ 'third_party/lua',
+ [Path('src/lua.o'), Path('src/liblua.a')],
+ make=['make', 'echo', 'generic'],
+ env_init=env_init,
+ configure=None,
+ )
+ self.do_run(
+ '',
+ 'hello lua world!\n17\n1\n2\n3\n4\n7',
+ args=['-e', '''print("hello lua world!");print(17);for x = 1,4 do print(x) end;print(10-3)'''],
+ libraries=libs,
+ includes=[test_file('lua')],
+ )
@no_asan('issues with freetype itself')
@needs_make('configure script')
@@ -6624,47 +7193,58 @@ def test_freetype(self):
if self.get_setting('WASMFS'):
self.emcc_args += ['-sFORCE_FILESYSTEM']
- self.add_pre_run("FS.createDataFile('/', 'font.ttf', %s, true, false, false);" % str(
- list(bytearray(read_binary(test_file('freetype/LiberationSansBold.ttf'))))
- ))
+ self.add_pre_run(
+ "FS.createDataFile('/', 'font.ttf', %s, true, false, false);"
+ % str(list(bytearray(read_binary(test_file('freetype/LiberationSansBold.ttf')))))
+ )
# Not needed for js, but useful for debugging
shutil.copy(test_file('freetype/LiberationSansBold.ttf'), 'font.ttf')
ftlib = self.get_freetype_library()
# Main
- self.do_run_in_out_file_test('freetype/main.c',
- args=['font.ttf', 'test!', '150', '120', '25'],
- libraries=ftlib,
- includes=[test_file('third_party/freetype/include')])
+ self.do_run_in_out_file_test(
+ 'freetype/main.c',
+ args=['font.ttf', 'test!', '150', '120', '25'],
+ libraries=ftlib,
+ includes=[test_file('third_party/freetype/include')],
+ )
# github issue 324
print('[issue 324]')
- self.do_run_in_out_file_test('freetype/main_2.c',
- args=['font.ttf', 'w', '32', '32', '25'],
- libraries=ftlib,
- includes=[test_file('third_party/freetype/include')])
+ self.do_run_in_out_file_test(
+ 'freetype/main_2.c',
+ args=['font.ttf', 'w', '32', '32', '25'],
+ libraries=ftlib,
+ includes=[test_file('third_party/freetype/include')],
+ )
print('[issue 324 case 2]')
- self.do_run_in_out_file_test('freetype/main_3.c',
- args=['font.ttf', 'W', '32', '32', '0'],
- libraries=ftlib,
- includes=[test_file('third_party/freetype/include')])
+ self.do_run_in_out_file_test(
+ 'freetype/main_3.c',
+ args=['font.ttf', 'W', '32', '32', '0'],
+ libraries=ftlib,
+ includes=[test_file('third_party/freetype/include')],
+ )
print('[issue 324 case 3]')
- self.do_run_in_out_file_test('freetype/main_3.c',
- out_suffix='_alt',
- args=['font.ttf', 'ea', '40', '32', '0'],
- libraries=ftlib,
- includes=[test_file('third_party/freetype/include')])
+ self.do_run_in_out_file_test(
+ 'freetype/main_3.c',
+ out_suffix='_alt',
+ args=['font.ttf', 'ea', '40', '32', '0'],
+ libraries=ftlib,
+ includes=[test_file('third_party/freetype/include')],
+ )
@no_asan('local count too large for VMs')
@no_ubsan('local count too large for VMs')
@is_slow_test
- @parameterized({
- '': (False,),
- 'pthreads': (True,),
- })
+ @parameterized(
+ {
+ '': (False,),
+ 'pthreads': (True,),
+ }
+ )
def test_sqlite(self, use_pthreads):
if use_pthreads:
self.emcc_args.append('-pthread')
@@ -6674,17 +7254,14 @@ def test_sqlite(self, use_pthreads):
@needs_make('mingw32-make')
@is_slow_test
- @parameterized({
- 'cmake': (True,),
- 'configure': (False,)
- })
+ @parameterized({'cmake': (True,), 'configure': (False,)})
def test_zlib(self, use_cmake):
if WINDOWS and not use_cmake:
self.skipTest("Windows cannot run configure sh scripts")
self.maybe_closure()
if '-g' in self.emcc_args:
- self.emcc_args.append('-gsource-map') # more source maps coverage
+ self.emcc_args.append('-gsource-map') # more source maps coverage
zlib = self.get_zlib_library(use_cmake)
@@ -6695,10 +7272,7 @@ def test_zlib(self, use_cmake):
@needs_make('make')
@is_slow_test
@no_ubsan('it seems that bullet contains UB')
- @parameterized({
- 'cmake': (True,),
- 'autoconf': (False,)
- })
+ @parameterized({'cmake': (True,), 'autoconf': (False,)})
# Called thus so it runs late in the alphabetical cycle... it is long
def test_bullet(self, use_cmake):
if WINDOWS and not use_cmake:
@@ -6720,13 +7294,17 @@ def test_bullet(self, use_cmake):
self.set_setting('ASSERTIONS', 2)
self.emcc_args.append('-Wno-unused-command-line-argument')
- self.do_runf('third_party/bullet/Demos/HelloWorld/HelloWorld.cpp',
- [read_file(test_file('bullet/output.txt')), # different roundings
- read_file(test_file('bullet/output2.txt')),
- read_file(test_file('bullet/output3.txt')),
- read_file(test_file('bullet/output4.txt'))],
- libraries=self.get_bullet_library(use_cmake),
- includes=[test_file('third_party/bullet/src')])
+ self.do_runf(
+ 'third_party/bullet/Demos/HelloWorld/HelloWorld.cpp',
+ [
+ read_file(test_file('bullet/output.txt')), # different roundings
+ read_file(test_file('bullet/output2.txt')),
+ read_file(test_file('bullet/output3.txt')),
+ read_file(test_file('bullet/output4.txt')),
+ ],
+ libraries=self.get_bullet_library(use_cmake),
+ includes=[test_file('third_party/bullet/src')],
+ )
@no_asan('issues with freetype itself')
@no_ubsan('local count too large')
@@ -6740,7 +7318,9 @@ def test_poppler(self):
poppler = self.get_poppler_library()
shutil.copy(test_file('poppler/paper.pdf'), '.')
- create_file('pre.js', '''
+ create_file(
+ 'pre.js',
+ '''
Module.preRun = () => {
FS.createDataFile('/', 'paper.pdf', readBinary('paper.pdf'), true, false, false);
};
@@ -6748,13 +7328,12 @@ def test_poppler(self):
var FileData = Array.from(MEMFS.getFileDataAsTypedArray(FS.root.contents['filename-1.ppm']));
out("Data: " + JSON.stringify(FileData.map(function(x) { return unSign(x, 8) })));
};
- ''')
+ ''',
+ )
self.emcc_args += ['--pre-js', 'pre.js', '-sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE=$unSign']
ppm_data = str(list(bytearray(read_binary(test_file('poppler/ref.ppm')))))
- self.do_run('', ppm_data.replace(' ', ''),
- libraries=poppler,
- args=['-scale-to', '512', 'paper.pdf', 'filename'])
+ self.do_run('', ppm_data.replace(' ', ''), libraries=poppler, args=['-scale-to', '512', 'paper.pdf', 'filename'])
@needs_make('make')
@is_slow_test
@@ -6778,12 +7357,16 @@ def line_splitter(data):
original_j2k = test_file('openjpeg/syntensity_lobby_s.j2k')
image_bytes = list(bytearray(read_binary(original_j2k)))
- create_file('pre.js', """
+ create_file(
+ 'pre.js',
+ """
Module.preRun = () => FS.createDataFile('/', 'image.j2k', %s, true, false, false);
Module.postRun = () => {
out('Data: ' + JSON.stringify(Array.from(FS.readFile('image.raw'))));
};
- """ % line_splitter(str(image_bytes)))
+ """
+ % line_splitter(str(image_bytes)),
+ )
# ensure libpng is built so that openjpeg's configure step can detect it.
# If we don't do this then we don't know what the state of the cache will be
@@ -6794,15 +7377,19 @@ def line_splitter(data):
builder_cmd.append('--wasm64')
self.emcc_args.append('-Wno-pointer-to-int-cast')
self.run_process(builder_cmd)
- lib = self.get_library('third_party/openjpeg',
- [Path('codec/CMakeFiles/j2k_to_image.dir/index.c.o'),
- Path('codec/CMakeFiles/j2k_to_image.dir/convert.c.o'),
- Path('codec/CMakeFiles/j2k_to_image.dir/__/common/color.c.o'),
- Path('codec/CMakeFiles/j2k_to_image.dir/__/common/getopt.c.o'),
- Path('bin/libopenjpeg.a')],
- configure=['cmake', '.'],
- # configure_args=['--enable-tiff=no', '--enable-jp3d=no', '--enable-png=no'],
- make_args=[]) # no -j 2, since parallel builds can fail
+ lib = self.get_library(
+ 'third_party/openjpeg',
+ [
+ Path('codec/CMakeFiles/j2k_to_image.dir/index.c.o'),
+ Path('codec/CMakeFiles/j2k_to_image.dir/convert.c.o'),
+ Path('codec/CMakeFiles/j2k_to_image.dir/__/common/color.c.o'),
+ Path('codec/CMakeFiles/j2k_to_image.dir/__/common/getopt.c.o'),
+ Path('bin/libopenjpeg.a'),
+ ],
+ configure=['cmake', '.'],
+ # configure_args=['--enable-tiff=no', '--enable-jp3d=no', '--enable-png=no'],
+ make_args=[],
+ ) # no -j 2, since parallel builds can fail
# We use doubles in JS, so we get slightly different values than native code. So we
# check our output by comparing the average pixel difference
@@ -6814,7 +7401,7 @@ def image_compare(output):
# Evaluate the output as a python array
js_data = eval(m.group(0))
- js_data = [x if x >= 0 else 256 + x for x in js_data] # Our output may be signed, so unsign it
+ js_data = [x if x >= 0 else 256 + x for x in js_data] # Our output may be signed, so unsign it
# Get the correct output
true_data = bytearray(read_binary(test_file('openjpeg/syntensity_lobby_s.raw')))
@@ -6836,18 +7423,22 @@ def image_compare(output):
assert abs(true_mean - image_mean) < 0.01, [true_mean, image_mean]
assert diff_mean < 0.01, diff_mean
- self.emcc_args += ['--minify=0'] # to compare the versions
+ self.emcc_args += ['--minify=0'] # to compare the versions
self.emcc_args += ['--pre-js', 'pre.js']
- output = self.do_runf('third_party/openjpeg/codec/j2k_to_image.c',
- 'Successfully generated', # The real test for valid output is in image_compare
- args='-i image.j2k -o image.raw'.split(),
- emcc_args=['-sUSE_LIBPNG'],
- libraries=lib,
- includes=[test_file('third_party/openjpeg/libopenjpeg'),
- test_file('third_party/openjpeg/codec'),
- test_file('third_party/openjpeg/common'),
- Path(self.get_build_dir(), 'third_party/openjpeg')])
+ output = self.do_runf(
+ 'third_party/openjpeg/codec/j2k_to_image.c',
+ 'Successfully generated', # The real test for valid output is in image_compare
+ args='-i image.j2k -o image.raw'.split(),
+ emcc_args=['-sUSE_LIBPNG'],
+ libraries=lib,
+ includes=[
+ test_file('third_party/openjpeg/libopenjpeg'),
+ test_file('third_party/openjpeg/codec'),
+ test_file('third_party/openjpeg/common'),
+ Path(self.get_build_dir(), 'third_party/openjpeg'),
+ ],
+ )
image_compare(output)
@also_with_standalone_wasm(impure=True)
@@ -6875,7 +7466,9 @@ def test_ccall(self):
self.emcc_args.append('-Wno-return-stack-address')
self.set_setting('EXPORTED_RUNTIME_METHODS', ['ccall', 'cwrap', 'STACK_SIZE'])
self.set_setting('WASM_ASYNC_COMPILATION', 0)
- create_file('post.js', '''
+ create_file(
+ 'post.js',
+ '''
out('*');
var ret;
ret = Module['ccall']('get_int', 'number'); out([typeof ret, ret].join(','));
@@ -6906,10 +7499,27 @@ def test_ccall(self):
}
out('stack is ok.');
ccall('call_ccall_again', null);
- ''')
+ ''',
+ )
self.emcc_args += ['--post-js', 'post.js']
- self.set_setting('EXPORTED_FUNCTIONS', ['_get_int', '_get_float', '_get_bool', '_get_string', '_print_int', '_print_float', '_print_bool', '_print_string', '_multi', '_pointer', '_call_ccall_again', '_malloc'])
+ self.set_setting(
+ 'EXPORTED_FUNCTIONS',
+ [
+ '_get_int',
+ '_get_float',
+ '_get_bool',
+ '_get_string',
+ '_print_int',
+ '_print_float',
+ '_print_bool',
+ '_print_string',
+ '_multi',
+ '_pointer',
+ '_call_ccall_again',
+ '_malloc',
+ ],
+ )
self.do_core_test('test_ccall.cpp')
if self.maybe_closure():
@@ -6920,10 +7530,13 @@ def test_ccall_cwrap_fast_path(self):
self.set_setting('EXPORTED_RUNTIME_METHODS', ['ccall', 'cwrap'])
self.set_setting('WASM_ASYNC_COMPILATION', 0)
self.set_setting('ASSERTIONS', 0)
- create_file('post.js', '''
+ create_file(
+ 'post.js',
+ '''
var printBool = Module['cwrap']('print_bool', null, ['boolean']);
out(Module['_print_bool'] === printBool); // the function should be the exact raw function in the module rather than a wrapped one
- ''')
+ ''',
+ )
self.emcc_args += ['--post-js', 'post.js']
self.set_setting('EXPORTED_FUNCTIONS', ['_print_bool'])
@@ -6934,13 +7547,12 @@ def test_EXPORTED_RUNTIME_METHODS(self):
self.do_core_test('EXPORTED_RUNTIME_METHODS.c')
# test dyncall (and other runtime methods) can be exported
self.emcc_args += ['-DEXPORTED']
- self.set_setting('EXPORTED_RUNTIME_METHODS', ['dynCall', 'addFunction', 'lengthBytesUTF8', 'getTempRet0', 'setTempRet0'])
+ self.set_setting(
+ 'EXPORTED_RUNTIME_METHODS', ['dynCall', 'addFunction', 'lengthBytesUTF8', 'getTempRet0', 'setTempRet0']
+ )
self.do_core_test('EXPORTED_RUNTIME_METHODS.c')
- @parameterized({
- '': [],
- 'minimal_runtime': ['-sMINIMAL_RUNTIME=1']
- })
+ @parameterized({'': [], 'minimal_runtime': ['-sMINIMAL_RUNTIME=1']})
def test_dyncall_specific(self, *args):
if self.get_setting('MEMORY64'):
self.skipTest('not compatible with MEMORY64')
@@ -6950,26 +7562,28 @@ def test_dyncall_specific(self, *args):
# more without them - we don't need to legalize)
args = list(args) + ['-sDYNCALLS', '-DWASM_BIGINT']
cases = [
- ('DIRECT', []),
- ('DYNAMIC_SIG', ['-sDYNCALLS']),
- ]
+ ('DIRECT', []),
+ ('DYNAMIC_SIG', ['-sDYNCALLS']),
+ ]
if '-sMINIMAL_RUNTIME=1' in args:
self.emcc_args += ['--pre-js', test_file('minimal_runtime_exit_handling.js')]
else:
cases += [
('EXPORTED', []),
('EXPORTED_DYNAMIC_SIG', ['-sDYNCALLS', '-sEXPORTED_RUNTIME_METHODS=dynCall']),
- ('FROM_OUTSIDE', ['-sEXPORTED_RUNTIME_METHODS=dynCall_iiji'])
+ ('FROM_OUTSIDE', ['-sEXPORTED_RUNTIME_METHODS=dynCall_iiji']),
]
for which, extra_args in cases:
print(str(args) + ' ' + which)
self.do_core_test('test_dyncall_specific.c', emcc_args=['-D' + which] + list(args) + extra_args)
- @parameterized({
- '': ([],),
- 'legacy': (['-sDYNCALLS'],),
- })
+ @parameterized(
+ {
+ '': ([],),
+ 'legacy': (['-sDYNCALLS'],),
+ }
+ )
def test_dyncall_pointers(self, args):
self.do_core_test('test_dyncall_pointers.c', emcc_args=args)
@@ -6986,10 +7600,9 @@ def test(args=None, asserts=False):
if self.get_setting('WASM_BIGINT'):
out_suffix += '_bigint'
assert_returncode = 0 if not asserts else NON_ZERO
- self.do_run_in_out_file_test('core/test_getValue_setValue.cpp',
- out_suffix=out_suffix,
- assert_returncode=assert_returncode,
- emcc_args=args)
+ self.do_run_in_out_file_test(
+ 'core/test_getValue_setValue.cpp', out_suffix=out_suffix, assert_returncode=assert_returncode, emcc_args=args
+ )
if self.get_setting('WASM_BIGINT'):
self.emcc_args += ['-DWASM_BIGINT']
@@ -7012,19 +7625,21 @@ def test(args=None, asserts=False):
self.set_setting('EXPORTED_RUNTIME_METHODS', ['getValue', 'setValue'])
test()
- @parameterized({
- '': ([],),
- '_files': (['-DUSE_FILES'],)
- })
+ @parameterized({'': ([],), '_files': (['-DUSE_FILES'],)})
def test_FS_exports(self, extra_args):
# these used to be exported, but no longer are by default
def test(output_prefix='', args=None, assert_returncode=0):
args += extra_args
print(args)
- self.do_runf('core/FS_exports.cpp',
- (read_file(test_file('core/FS_exports' + output_prefix + '.out')),
- read_file(test_file('core/FS_exports' + output_prefix + '_2.out'))),
- assert_returncode=assert_returncode, emcc_args=args)
+ self.do_runf(
+ 'core/FS_exports.cpp',
+ (
+ read_file(test_file('core/FS_exports' + output_prefix + '.out')),
+ read_file(test_file('core/FS_exports' + output_prefix + '_2.out')),
+ ),
+ assert_returncode=assert_returncode,
+ emcc_args=args,
+ )
# see that direct usage (not on module) works. we don't export, but the use
# keeps it alive through JSDCE
@@ -7041,8 +7656,9 @@ def test(output_prefix='', args=None, assert_returncode=0):
def test_legacy_exported_runtime_numbers(self):
# these used to be exported, but no longer are by default
def test(expected, args=None, assert_returncode=0):
- self.do_runf('core/legacy_exported_runtime_numbers.cpp', expected,
- assert_returncode=assert_returncode, emcc_args=args)
+ self.do_runf(
+ 'core/legacy_exported_runtime_numbers.cpp', expected, assert_returncode=assert_returncode, emcc_args=args
+ )
# Without assertion indirect usages (via Module) result in `undefined` and direct usage
# generates a builtin (not very helpful) JS error.
@@ -7052,7 +7668,9 @@ def test(expected, args=None, assert_returncode=0):
test('ALLOC_STACK is not defined', args=['-DDIRECT'], assert_returncode=NON_ZERO)
# When assertions are enabled direct and indirect usage both abort with a useful error message.
- not_exported = "Aborted('ALLOC_STACK' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ))"
+ not_exported = (
+ "Aborted('ALLOC_STACK' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ))"
+ )
not_included = "`ALLOC_STACK` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='$ALLOC_STACK')"
self.set_setting('ASSERTIONS')
test(not_exported, assert_returncode=NON_ZERO)
@@ -7155,10 +7773,7 @@ def test_emulate_function_pointer_casts(self):
self.do_core_test('test_emulate_function_pointer_casts.cpp')
@no_wasm2js('TODO: nicely printed names in wasm2js')
- @parameterized({
- 'normal': ([],),
- 'noexcept': (['-fno-exceptions'],)
- })
+ @parameterized({'normal': ([],), 'noexcept': (['-fno-exceptions'],)})
def test_demangle_stacks(self, extra_args):
self.emcc_args += extra_args
self.set_setting('ASSERTIONS')
@@ -7205,7 +7820,11 @@ def test_demangle_stacks_symbol_map(self):
# we may see the full one, if -g, or the short one if not
if ' ' + short_aborter + ' ' not in output and ' ' + full_aborter + ' ' not in output:
# stack traces may also be ' name ' or 'name@' etc
- if '\n' + short_aborter + ' ' not in output and '\n' + full_aborter + ' ' not in output and 'wasm-function[' + short_aborter + ']' not in output:
+ if (
+ '\n' + short_aborter + ' ' not in output
+ and '\n' + full_aborter + ' ' not in output
+ and 'wasm-function[' + short_aborter + ']' not in output
+ ):
if '\n' + short_aborter + '@' not in output and '\n' + full_aborter + '@' not in output:
self.assertContained(' ' + short_aborter + ' ' + '\n' + ' ' + full_aborter + ' ', output)
@@ -7222,14 +7841,17 @@ def test_eval_ctors(self):
print('leave printf in ctor')
self.set_setting('EVAL_CTORS')
- self.do_run(r'''
+ self.do_run(
+ r'''
#include
struct C {
C() { printf("constructing!\n"); } // don't remove this!
};
C c;
int main() {}
- ''', "constructing!\n")
+ ''',
+ "constructing!\n",
+ )
def do_test(test, level=1, prefix='src'):
def get_code_size():
@@ -7252,7 +7874,8 @@ def get_code_size():
print('remove ctor of just assigns to memory')
def test1():
- self.do_run(r'''
+ self.do_run(
+ r'''
#include
struct C {
int x;
@@ -7266,7 +7889,9 @@ def test1():
int main() {
printf("x: %d\n", c.x);
}
- ''', "x: 11\n")
+ ''',
+ "x: 11\n",
+ )
do_test(test1)
@@ -7284,13 +7909,17 @@ def test2():
do_test(test2, level=2, prefix='hello_libcxx')
- @parameterized({
- '': (['-lembind', '-sDYNAMIC_EXECUTION=0'],),
- 'flag': (['--bind'],),
- })
+ @parameterized(
+ {
+ '': (['-lembind', '-sDYNAMIC_EXECUTION=0'],),
+ 'flag': (['--bind'],),
+ }
+ )
def test_embind_val_basics(self, args):
self.maybe_closure()
- create_file('test.cpp', r'''
+ create_file(
+ 'test.cpp',
+ r'''
#include
#include
@@ -7305,23 +7934,33 @@ def test_embind_val_basics(self, args):
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('test.cpp', 'abs(-10): 10\nabs(-11): 11', emcc_args=args)
@node_pthreads
def test_embind_basics(self):
self.maybe_closure()
self.emcc_args += [
- '-lembind', '--post-js', 'post.js',
+ '-lembind',
+ '--post-js',
+ 'post.js',
# for extra coverage, test using pthreads
- '-pthread', '-sPROXY_TO_PTHREAD', '-sEXIT_RUNTIME'
+ '-pthread',
+ '-sPROXY_TO_PTHREAD',
+ '-sEXIT_RUNTIME',
]
- create_file('post.js', '''
+ create_file(
+ 'post.js',
+ '''
function printLerp() {
out('lerp ' + Module['lerp'](100, 200, 66) + '.');
}
- ''')
- create_file('test.cpp', r'''
+ ''',
+ )
+ create_file(
+ 'test.cpp',
+ r'''
#include
#include
#include
@@ -7338,12 +7977,15 @@ def test_embind_basics(self):
EM_ASM(printLerp());
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('test.cpp', 'lerp 166')
def test_embind_unbound_types(self):
self.emcc_args += ['-lembind', '--post-js', 'post.js']
- create_file('post.js', '''
+ create_file(
+ 'post.js',
+ '''
function ready() {
try {
Module['compute'](new Uint8Array([1,2,3]));
@@ -7351,8 +7993,11 @@ def test_embind_unbound_types(self):
out(e);
}
}
- ''')
- create_file('test.cpp', r'''
+ ''',
+ )
+ create_file(
+ 'test.cpp',
+ r'''
#include
#include
using namespace emscripten;
@@ -7366,17 +8011,23 @@ def test_embind_unbound_types(self):
EM_ASM(ready());
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('test.cpp', 'UnboundTypeError: Cannot call compute due to unbound types: Pi')
def test_embind_memory_view(self):
self.emcc_args += ['-lembind', '--post-js', 'post.js']
- create_file('post.js', '''
+ create_file(
+ 'post.js',
+ '''
function printFirstElement() {
out(Module['getBufferView']()[0]);
}
- ''')
- create_file('test.cpp', r'''
+ ''',
+ )
+ create_file(
+ 'test.cpp',
+ r'''
#include
#include
#include
@@ -7398,7 +8049,8 @@ def test_embind_memory_view(self):
EM_ASM(printFirstElement());
return 0;
}
- ''')
+ ''',
+ )
self.do_runf('test.cpp', '107')
def test_embind_inheritance(self):
@@ -7431,7 +8083,9 @@ def test_embind_val_assignment(self):
@node_pthreads
def test_embind_val_cross_thread(self):
self.emcc_args += ['--bind']
- create_file('test_embind_val_cross_thread.cpp', r'''
+ create_file(
+ 'test_embind_val_cross_thread.cpp',
+ r'''
#include
#include
#include
@@ -7452,13 +8106,16 @@ def test_embind_val_cross_thread(self):
// resolves to different values on different threads.
printf("%d\n", value.as());
}
- ''')
+ ''',
+ )
self.do_runf('test_embind_val_cross_thread.cpp', 'val accessed from wrong thread', assert_returncode=NON_ZERO)
@node_pthreads
def test_embind_val_cross_thread_deleted(self):
self.emcc_args += ['--bind']
- create_file('test_embind_val_cross_thread.cpp', r'''
+ create_file(
+ 'test_embind_val_cross_thread.cpp',
+ r'''
#include
#include
#include
@@ -7480,24 +8137,31 @@ def test_embind_val_cross_thread_deleted(self):
// There should be no cross-thread error here when it tries to free that value,
// because the value has already been deleted on the correct thread.
}
- ''')
+ ''',
+ )
self.do_runf('test_embind_val_cross_thread.cpp')
def test_embind_val_coro(self):
- create_file('post.js', r'''Module.onRuntimeInitialized = () => {
+ create_file(
+ 'post.js',
+ r'''Module.onRuntimeInitialized = () => {
Module.asyncCoro().then(console.log);
- }''')
+ }''',
+ )
self.emcc_args += ['-std=c++20', '--bind', '--post-js=post.js']
self.do_runf('embind/test_val_coro.cpp', '34\n')
def test_embind_val_coro_caught(self):
self.set_setting('EXCEPTION_STACK_TRACES')
- create_file('post.js', r'''Module.onRuntimeInitialized = () => {
+ create_file(
+ 'post.js',
+ r'''Module.onRuntimeInitialized = () => {
Module.throwingCoro().then(
console.log,
err => console.error(`rejected with: ${err.stack}`)
);
- }''')
+ }''',
+ )
self.emcc_args += ['-std=c++20', '--bind', '--post-js=post.js', '-fexceptions']
self.do_runf('embind/test_val_coro.cpp', 'rejected with: std::runtime_error: bang from throwingCoro!\n')
@@ -7520,7 +8184,9 @@ def test_embind_i64_binding(self):
self.do_run_in_out_file_test('embind/test_i64_binding.cpp', assert_identical=True)
def test_embind_no_rtti(self):
- create_file('main.cpp', r'''
+ create_file(
+ 'main.cpp',
+ r'''
#include
#include
#include
@@ -7543,14 +8209,17 @@ def test_embind_no_rtti(self):
EMSCRIPTEN_BINDINGS(my_module) {
emscripten::function("dotest", &test);
}
- ''')
+ ''',
+ )
self.emcc_args += ['-lembind', '-fno-rtti', '-DEMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=0']
self.do_runf('main.cpp', '418\ndotest returned: 42\n')
- @parameterized({
- '': ([],),
- 'no_rtti': (['-fno-rtti', '-DEMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=0'],),
- })
+ @parameterized(
+ {
+ '': ([],),
+ 'no_rtti': (['-fno-rtti', '-DEMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=0'],),
+ }
+ )
def test_embind_polymorphic_class(self, args):
self.do_core_test('test_embind_polymorphic_class_no_rtti.cpp', emcc_args=args + ['-lembind'])
@@ -7582,13 +8251,15 @@ def test_embind_no_rtti_followed_by_rtti(self):
self.emcc_args += ['-lembind', '-fno-rtti', '-frtti']
self.do_run(src, '418\ndotest returned: 42\n')
- @parameterized({
- '': ('DEFAULT', False),
- 'all': ('ALL', False),
- 'fast': ('FAST', False),
- 'default': ('DEFAULT', False),
- 'all_growth': ('ALL', True),
- })
+ @parameterized(
+ {
+ '': ('DEFAULT', False),
+ 'all': ('ALL', False),
+ 'fast': ('FAST', False),
+ 'default': ('DEFAULT', False),
+ 'all_growth': ('ALL', True),
+ }
+ )
def test_webidl(self, mode, allow_memory_growth):
self.set_setting('WASM_ASYNC_COMPILATION', 0)
if self.maybe_closure():
@@ -7625,7 +8296,12 @@ def test_webidl(self, mode, allow_memory_growth):
# Export things on "TheModule". This matches the typical use pattern of
# the bound library being used as Box2D.* or Ammo.*, and we cannot rely
# on "Module" being always present (closure may remove it).
- self.emcc_args += ['-sEXPORTED_FUNCTIONS=_malloc,_free', '-sEXPORTED_RUNTIME_METHODS=stringToUTF8', '--post-js=glue.js', '--extern-post-js=extern-post.js']
+ self.emcc_args += [
+ '-sEXPORTED_FUNCTIONS=_malloc,_free',
+ '-sEXPORTED_RUNTIME_METHODS=stringToUTF8',
+ '--post-js=glue.js',
+ '--extern-post-js=extern-post.js',
+ ]
if mode == 'ALL':
self.emcc_args += ['-sASSERTIONS']
if allow_memory_growth:
@@ -7650,10 +8326,12 @@ def test_embind_sync_if_pthread_delayed(self):
### Tests for tools
@no_wasm2js('TODO: source maps in wasm2js')
- @parameterized({
- '': ([],),
- 'minimal_runtime': (['-sMINIMAL_RUNTIME'],),
- })
+ @parameterized(
+ {
+ '': ([],),
+ 'minimal_runtime': (['-sMINIMAL_RUNTIME'],),
+ }
+ )
@requires_node
def test_source_map(self, args):
if '-g' not in self.emcc_args:
@@ -7690,9 +8368,7 @@ def test_source_map(self, args):
no_maps_file = re.sub(' *//[@#].*$', '', no_maps_file, flags=re.MULTILINE)
self.emcc_args.append('-gsource-map')
- self.emcc(os.path.abspath('src.cpp'),
- self.get_emcc_args(),
- out_filename)
+ self.emcc(os.path.abspath('src.cpp'), self.get_emcc_args(), out_filename)
map_referent = out_filename if self.is_wasm2js() else wasm_filename
# after removing the @line and @sourceMappingURL comments, the build
# result should be identical to the non-source-mapped debug version.
@@ -7713,9 +8389,7 @@ def test_source_map(self, args):
# the sourcesContent attribute is optional, but if it is present it
# needs to containt valid source text.
self.assertTextDataIdentical(src, data['sourcesContent'][src_index])
- mappings = json.loads(self.run_js(
- path_from_root('test/sourcemap2json.js'),
- args=[map_filename]))
+ mappings = json.loads(self.run_js(path_from_root('test/sourcemap2json.js'), args=[map_filename]))
seen_lines = set()
for m in mappings:
if m['source'] == 'src.cpp':
@@ -7806,8 +8480,9 @@ def get_dwarf_addr(line, col):
self.assertLess(get_dwarf_addr(7, 3), get_dwarf_addr(8, 3))
# Get the wat, printing with -g which has binary offsets
- wat = self.run_process([Path(building.get_binaryen_bin(), 'wasm-opt'),
- wasm_filename, '-g', '--print'], stdout=PIPE).stdout
+ wat = self.run_process(
+ [Path(building.get_binaryen_bin(), 'wasm-opt'), wasm_filename, '-g', '--print'], stdout=PIPE
+ ).stdout
# We expect to see a pattern like this in optimized builds (there isn't
# much that can change with such calls to JS (they can't be reordered or
@@ -7875,8 +8550,10 @@ def test_modularize_closure_pre(self):
self.ldflags.append('-Wno-error=closure')
self.emcc_args += [
- '--pre-js', test_file('core/modularize_closure_pre.js'),
- '--extern-post-js', test_file('modularize_post_js.js'),
+ '--pre-js',
+ test_file('core/modularize_closure_pre.js'),
+ '--extern-post-js',
+ test_file('modularize_post_js.js'),
'--closure=1',
'-g1',
'-sMODULARIZE',
@@ -7892,7 +8569,7 @@ def test_emscripten_log(self):
self.do_run_in_out_file_test('emscripten_log/emscripten_log.cpp', interleaved_output=False)
# test closure compiler as well
if self.maybe_closure():
- self.emcc_args += ['-g1'] # extra testing
+ self.emcc_args += ['-g1'] # extra testing
self.do_run_in_out_file_test('emscripten_log/emscripten_log_with_closure.cpp', interleaved_output=False)
def test_float_literals(self):
@@ -7901,7 +8578,9 @@ def test_float_literals(self):
def test_exit_status(self):
# needs to flush stdio streams
self.set_setting('EXIT_RUNTIME')
- create_file('exit.c', r'''
+ create_file(
+ 'exit.c',
+ r'''
#include
#include
#include
@@ -7926,17 +8605,23 @@ def test_exit_status(self):
_Exit(119);
#endif
}
- ''')
- create_file('pre.js', '''
+ ''',
+ )
+ create_file(
+ 'pre.js',
+ '''
Module.onExit = (status) => {
out('I see exit status: ' + status);
// The EXITSTATUS global should match what we are passed
assert(status == EXITSTATUS);
};
- ''')
+ ''',
+ )
self.emcc_args += ['--pre-js', 'pre.js']
print('.. exit')
- self.do_runf('exit.c', 'hello, world!\ncleanup\nI see exit status: 117', assert_returncode=117, emcc_args=['-DNORMAL_EXIT'])
+ self.do_runf(
+ 'exit.c', 'hello, world!\ncleanup\nI see exit status: 117', assert_returncode=117, emcc_args=['-DNORMAL_EXIT']
+ )
print('.. _exit')
self.do_runf('exit.c', 'hello, world!\nI see exit status: 118', assert_returncode=118, emcc_args=['-DUNDER_EXIT'])
print('.. _Exit')
@@ -7967,14 +8652,17 @@ def test_asyncify_longjmp(self):
# Test that a main with arguments is automatically asyncified.
@with_asyncify_and_jspi
def test_async_main(self):
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
int main(int argc, char **argv) {
emscripten_sleep(1);
printf("argc=%d argv=%s\n", argc, argv[1]);
}
-''')
+''',
+ )
self.do_runf('main.c', 'argc=2 argv=hello', args=['hello'])
@@ -7983,7 +8671,9 @@ def test_async_hello(self):
# needs to flush stdio streams
self.set_setting('EXIT_RUNTIME')
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
void f(void *p) {
@@ -7998,13 +8688,16 @@ def test_async_hello(self):
emscripten_sleep(100);
printf("%d\n", i);
}
-''')
+''',
+ )
self.do_runf('main.c', 'HelloWorld!99')
@with_asyncify_and_jspi
def test_async_loop(self):
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
int main() {
@@ -8013,7 +8706,8 @@ def test_async_loop(self):
printf("hello %d\n", i);
}
}
-''')
+''',
+ )
self.do_runf('main.c', 'hello 0\nhello 1\nhello 2\nhello 3\nhello 4\n')
@@ -8028,7 +8722,9 @@ def test_async_ccall_bad(self):
self.set_setting('ASYNCIFY')
self.set_setting('ASSERTIONS')
self.set_setting('INVOKE_RUN', 0)
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
int main() {
@@ -8036,8 +8732,11 @@ def test_async_ccall_bad(self):
emscripten_sleep(100);
printf("World\n");
}
-''')
- create_file('pre.js', '''
+''',
+ )
+ create_file(
+ 'pre.js',
+ '''
Module.onRuntimeInitialized = () => {
try {
ccall('main', 'number', ['number', 'string'], [2, 'waka']);
@@ -8047,7 +8746,8 @@ def test_async_ccall_bad(self):
assert(!never);
}
};
-''')
+''',
+ )
self.emcc_args += ['--pre-js', 'pre.js']
self.do_runf('main.c', 'The call to main is running asynchronously.')
@@ -8058,7 +8758,9 @@ def test_async_ccall_good(self):
self.set_setting('ASSERTIONS')
self.set_setting('INVOKE_RUN', 0)
self.set_setting('DEFAULT_LIBRARY_FUNCS_TO_INCLUDE', ['$ccall'])
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
int main() {
@@ -8066,21 +8768,27 @@ def test_async_ccall_good(self):
emscripten_sleep(100);
printf("World\n");
}
-''')
- create_file('pre.js', '''
+''',
+ )
+ create_file(
+ 'pre.js',
+ '''
Module.onRuntimeInitialized = () => {
ccall('main', null, ['number', 'string'], [2, 'waka'], { async: true });
};
-''')
+''',
+ )
self.emcc_args += ['--pre-js', 'pre.js']
self.do_runf('main.c', 'HelloWorld')
- @parameterized({
- 'asyncify': (False, 1),
- 'exit_runtime_asyncify': (True, 1),
- 'jspi': (False, 2),
- 'exit_runtime_jspi': (True, 2),
- })
+ @parameterized(
+ {
+ 'asyncify': (False, 1),
+ 'exit_runtime_asyncify': (True, 1),
+ 'jspi': (False, 2),
+ 'exit_runtime_jspi': (True, 2),
+ }
+ )
def test_async_ccall_promise(self, exit_runtime, asyncify):
if asyncify == 2:
self.require_jspi()
@@ -8091,7 +8799,9 @@ def test_async_ccall_promise(self, exit_runtime, asyncify):
self.set_setting('EXIT_RUNTIME', exit_runtime)
self.set_setting('EXPORTED_FUNCTIONS', ['_stringf', '_floatf'])
self.set_setting('DEFAULT_LIBRARY_FUNCS_TO_INCLUDE', ['$maybeExit', '$ccall'])
- create_file('main.c', r'''
+ create_file(
+ 'main.c',
+ r'''
#include
#include
const char* stringf(char* param) {
@@ -8104,8 +8814,11 @@ def test_async_ccall_promise(self, exit_runtime, asyncify):
emscripten_sleep(20);
return 6.4;
}
-''')
- create_file('pre.js', r'''
+''',
+ )
+ create_file(
+ 'pre.js',
+ r'''
Module.onRuntimeInitialized = () => {
runtimeKeepalivePush();
ccall('stringf', 'string', ['string'], ['first\n'], { async: true })
@@ -8118,7 +8831,8 @@ def test_async_ccall_promise(self, exit_runtime, asyncify):
});
});
};
-''')
+''',
+ )
self.emcc_args += ['--pre-js', 'pre.js']
self.do_runf('main.c', 'stringf: first\nsecond\n6.4')
@@ -8132,18 +8846,26 @@ def test_asyncify_unused(self):
# test a program not using asyncify, but the pref is set
self.do_core_test('test_hello_world.c')
- @parameterized({
- 'normal': ([], True),
- 'removelist_a': (['-sASYNCIFY_REMOVE=["foo(int, double)"]'], False),
- 'removelist_b': (['-sASYNCIFY_REMOVE=["bar()"]'], True),
- 'removelist_c': (['-sASYNCIFY_REMOVE=["baz()"]'], False),
- 'onlylist_a': (['-sASYNCIFY_ONLY=["main","__original_main","foo(int, double)","baz()","c_baz","Structy::funcy()","bar()"]'], True),
- 'onlylist_b': (['-sASYNCIFY_ONLY=["main","__original_main","foo(int, double)","baz()","c_baz","Structy::funcy()"]'], True),
- 'onlylist_c': (['-sASYNCIFY_ONLY=["main","__original_main","foo(int, double)","baz()","c_baz"]'], False),
- 'onlylist_d': (['-sASYNCIFY_ONLY=["foo(int, double)","baz()","c_baz","Structy::funcy()"]'], False),
- 'onlylist_b_response': ([], True, 'main\n__original_main\nfoo(int, double)\nbaz()\nc_baz\nStructy::funcy()\n'),
- 'onlylist_c_response': ([], False, 'main\n__original_main\nfoo(int, double)\nbaz()\nc_baz\n'),
- })
+ @parameterized(
+ {
+ 'normal': ([], True),
+ 'removelist_a': (['-sASYNCIFY_REMOVE=["foo(int, double)"]'], False),
+ 'removelist_b': (['-sASYNCIFY_REMOVE=["bar()"]'], True),
+ 'removelist_c': (['-sASYNCIFY_REMOVE=["baz()"]'], False),
+ 'onlylist_a': (
+ ['-sASYNCIFY_ONLY=["main","__original_main","foo(int, double)","baz()","c_baz","Structy::funcy()","bar()"]'],
+ True,
+ ),
+ 'onlylist_b': (
+ ['-sASYNCIFY_ONLY=["main","__original_main","foo(int, double)","baz()","c_baz","Structy::funcy()"]'],
+ True,
+ ),
+ 'onlylist_c': (['-sASYNCIFY_ONLY=["main","__original_main","foo(int, double)","baz()","c_baz"]'], False),
+ 'onlylist_d': (['-sASYNCIFY_ONLY=["foo(int, double)","baz()","c_baz","Structy::funcy()"]'], False),
+ 'onlylist_b_response': ([], True, 'main\n__original_main\nfoo(int, double)\nbaz()\nc_baz\nStructy::funcy()\n'),
+ 'onlylist_c_response': ([], False, 'main\n__original_main\nfoo(int, double)\nbaz()\nc_baz\n'),
+ }
+ )
def test_asyncify_lists(self, args, should_pass, response=None):
if response is not None:
create_file('response.file', response)
@@ -8154,7 +8876,7 @@ def test_asyncify_lists(self, args, should_pass, response=None):
if should_pass:
self.do_core_test('test_asyncify_lists.cpp', assert_identical=True)
else:
- self.do_runf('core/test_asyncify_lists.cpp', ('RuntimeError', 'Thrown at'), assert_returncode=NON_ZERO)
+ self.do_runf('core/test_asyncify_lists.cpp', ('RuntimeError', 'Thrown at'), assert_returncode=NON_ZERO)
# use of ASYNCIFY_* options may require intermediate debug info. that should
# not end up emitted in the final binary
@@ -8170,14 +8892,23 @@ def test_asyncify_lists(self, args, should_pass, response=None):
binary = read_binary(filename)
self.assertFalse(b'main' in binary)
- @parameterized({
- 'normal': ([], True),
- 'ignoreindirect': (['-sASYNCIFY_IGNORE_INDIRECT'], False),
- 'add': (['-sASYNCIFY_IGNORE_INDIRECT', '-sASYNCIFY_ADD=["virt()"]'], True),
- # If ASYNCIFY_PROPAGATE_ADD is disabled then we must specify the callers of
- # virt() manually, rather than have them inferred automatically.
- 'add_no_prop': (['-sASYNCIFY_IGNORE_INDIRECT', '-sASYNCIFY_ADD=["__original_main","main","virt()"]', '-sASYNCIFY_PROPAGATE_ADD=0'], True),
- })
+ @parameterized(
+ {
+ 'normal': ([], True),
+ 'ignoreindirect': (['-sASYNCIFY_IGNORE_INDIRECT'], False),
+ 'add': (['-sASYNCIFY_IGNORE_INDIRECT', '-sASYNCIFY_ADD=["virt()"]'], True),
+ # If ASYNCIFY_PROPAGATE_ADD is disabled then we must specify the callers of
+ # virt() manually, rather than have them inferred automatically.
+ 'add_no_prop': (
+ [
+ '-sASYNCIFY_IGNORE_INDIRECT',
+ '-sASYNCIFY_ADD=["__original_main","main","virt()"]',
+ '-sASYNCIFY_PROPAGATE_ADD=0',
+ ],
+ True,
+ ),
+ }
+ )
def test_asyncify_indirect_lists(self, args, should_pass):
self.set_setting('ASYNCIFY')
self.emcc_args += args
@@ -8198,7 +8929,8 @@ def test_asyncify_indirect_lists(self, args, should_pass):
def test_asyncify_side_module(self):
self.set_setting('ASYNCIFY')
self.set_setting('ASYNCIFY_IMPORTS', ['my_sleep'])
- self.dylink_test(r'''
+ self.dylink_test(
+ r'''
#include
#include "header.h"
@@ -8208,7 +8940,8 @@ def test_asyncify_side_module(self):
printf("after sleep\n");
return 0;
}
- ''', r'''
+ ''',
+ r'''
#include
#include
#include "header.h"
@@ -8221,7 +8954,11 @@ def test_asyncify_side_module(self):
// variable on stack in side module function should be restored.
printf("%d\n", value);
}
- ''', 'before sleep\n42\n42\nafter sleep\n', header='void my_sleep(int);', force_c=True)
+ ''',
+ 'before sleep\n42\n42\nafter sleep\n',
+ header='void my_sleep(int);',
+ force_c=True,
+ )
@no_asan('asyncify stack operations confuse asan')
def test_emscripten_scan_registers(self):
@@ -8259,24 +8996,27 @@ def test_asyncify_main_module(self):
def test_pthread_join_and_asyncify(self):
# TODO Test with ASYNCIFY=1 https://github.com/emscripten-core/emscripten/issues/17552
self.require_jspi()
- self.do_runf('core/test_pthread_join_and_asyncify.c', 'joining thread!\njoined thread!',
- emcc_args=['-sJSPI',
- '-sEXIT_RUNTIME=1',
- '-pthread', '-sPROXY_TO_PTHREAD'])
+ self.do_runf(
+ 'core/test_pthread_join_and_asyncify.c',
+ 'joining thread!\njoined thread!',
+ emcc_args=['-sJSPI', '-sEXIT_RUNTIME=1', '-pthread', '-sPROXY_TO_PTHREAD'],
+ )
@no_asan('asyncify stack operations confuse asan')
@no_wasm2js('TODO: lazy loading in wasm2js')
- @parameterized({
- 'conditional': (True,),
- 'unconditional': (False,),
- })
+ @parameterized(
+ {
+ 'conditional': (True,),
+ 'unconditional': (False,),
+ }
+ )
def test_emscripten_lazy_load_code(self, conditional):
if self.get_setting('STACK_OVERFLOW_CHECK'):
self.skipTest('https://github.com/emscripten-core/emscripten/issues/16828')
self.set_setting('ASYNCIFY_LAZY_LOAD_CODE')
self.set_setting('ASYNCIFY_IGNORE_INDIRECT')
self.set_setting('MALLOC', 'emmalloc')
- self.emcc_args += ['--profiling-funcs'] # so that we can find the functions for the changes below
+ self.emcc_args += ['--profiling-funcs'] # so that we can find the functions for the changes below
if conditional:
self.emcc_args += ['-DCONDITIONAL']
self.do_core_test('emscripten_lazy_load_code.cpp', args=['0'])
@@ -8289,10 +9029,13 @@ def test_emscripten_lazy_load_code(self, conditional):
# For the purposes of this test we don't consider O1 to be optimizing
is_optimizing = self.is_optimizing() and '-O1' not in self.emcc_args
- if not conditional and is_optimizing and \
- '-g' not in self.emcc_args and \
- '-fsanitize=leak' not in self.emcc_args and \
- not self.get_setting('WASMFS'):
+ if (
+ not conditional
+ and is_optimizing
+ and '-g' not in self.emcc_args
+ and '-fsanitize=leak' not in self.emcc_args
+ and not self.get_setting('WASMFS')
+ ):
# TODO: WasmFS has not yet been optimized for code size, and the general
# increase it causes mixes up code size measurements like this.
# See https://github.com/emscripten-core/emscripten/issues/16005
@@ -8331,7 +9074,9 @@ def verify_working(args):
self.assertContained('foo_end\n', self.run_js('emscripten_lazy_load_code.js', args=args))
def verify_broken(args):
- self.assertNotContained('foo_end\n', self.run_js('emscripten_lazy_load_code.js', args=args, assert_returncode=NON_ZERO))
+ self.assertNotContained(
+ 'foo_end\n', self.run_js('emscripten_lazy_load_code.js', args=args, assert_returncode=NON_ZERO)
+ )
# the first-loaded wasm will not reach the second call, since we call it after lazy-loading.
# verify that by changing the first wasm to throw in that function
@@ -8388,10 +9133,12 @@ def test_maybe_wasm2js(self):
@no_asan('no wasm2js support yet in asan')
@requires_wasm2js
- @parameterized({
- '': ([],),
- 'minimal_runtime': (['-sMINIMAL_RUNTIME'],),
- })
+ @parameterized(
+ {
+ '': ([],),
+ 'minimal_runtime': (['-sMINIMAL_RUNTIME'],),
+ }
+ )
def test_wasm2js_fallback(self, args):
if self.is_wasm2js():
self.skipTest('redundant to test wasm2js in wasm2js* mode')
@@ -8407,12 +9154,13 @@ def test_wasm2js_fallback(self, args):
# Then disable WebAssembly support in VM, and try again.. Should still work with Wasm2JS fallback.
create_file('b.out.js', 'WebAssembly = undefined;\n' + read_file('a.out.js'))
- os.remove('a.out.wasm') # Also delete the Wasm file to test that it is not attempted to be loaded.
+ os.remove('a.out.wasm') # Also delete the Wasm file to test that it is not attempted to be loaded.
self.assertContained('hello!', self.run_js('b.out.js'))
def test_cxx_self_assign(self):
# See https://github.com/emscripten-core/emscripten/pull/2688 and http://llvm.org/bugs/show_bug.cgi?id=18735
- self.do_run(r'''
+ self.do_run(
+ r'''
#include