Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/tools/minimal_runtime_shell.py
6170 views
1
import logging
2
import os
3
import re
4
import sys
5
6
__scriptdir__ = os.path.dirname(os.path.abspath(__file__))
7
__rootdir__ = os.path.dirname(__scriptdir__)
8
sys.path.insert(0, __rootdir__)
9
10
from . import building, shared, utils
11
from .settings import settings
12
13
logger = logging.getLogger('minimal_runtime_shell')
14
15
16
def generate_minimal_runtime_load_statement(target_basename):
17
# Extra code to appear before the loader
18
prefix_statements = []
19
# Statements to appear inside a Promise .then() block after loading has finished
20
then_statements = []
21
# Import parameters to call the main JS runtime function with
22
modularize_imports = []
23
24
# Depending on whether streaming Wasm compilation is enabled or not, the minimal sized code to
25
# download Wasm looks a bit different.
26
# Expand {{{ DOWNLOAD_WASM }}} block from here (if we added #define support, this could be done in
27
# the template directly)
28
if settings.MINIMAL_RUNTIME_STREAMING_WASM_COMPILATION:
29
if settings.MIN_SAFARI_VERSION < 150000 or settings.MIN_NODE_VERSION < 180100 or settings.MIN_FIREFOX_VERSION < 58:
30
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming
31
download_wasm = f"WebAssembly.compileStreaming ? WebAssembly.compileStreaming(fetch('{target_basename}.wasm')) : binary('{target_basename}.wasm')"
32
else:
33
# WebAssembly.compileStreaming() is unconditionally supported:
34
download_wasm = f"WebAssembly.compileStreaming(fetch('{target_basename}.wasm'))"
35
elif settings.MINIMAL_RUNTIME_STREAMING_WASM_INSTANTIATION:
36
# Same compatibility story as above for
37
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming
38
if settings.MIN_SAFARI_VERSION < 150000 or settings.MIN_NODE_VERSION < 180100 or settings.MIN_FIREFOX_VERSION < 58:
39
download_wasm = f"!WebAssembly.instantiateStreaming && binary('{target_basename}.wasm')"
40
else:
41
# WebAssembly.instantiateStreaming() is unconditionally supported, so we do not download wasm
42
# in the .html file, but leave it to the .js file to download
43
download_wasm = None
44
else:
45
download_wasm = f"binary('{target_basename}.wasm')"
46
47
# Main JS file always in first entry
48
files_to_load = [f"script('{settings.TARGET_JS_NAME}')"]
49
50
# Download .wasm file
51
if (settings.WASM == 1 and settings.WASM2JS == 0) or not download_wasm:
52
if settings.MODULARIZE:
53
modularize_imports += [f'wasm: r[{len(files_to_load)}]']
54
else:
55
then_statements += [f"{settings.EXPORT_NAME}.wasm = r[{len(files_to_load)}];"]
56
if download_wasm:
57
files_to_load += [download_wasm]
58
59
# Download wasm_worker file
60
if settings.WASM_WORKERS and settings.MODULARIZE:
61
modularize_imports += ['js: js']
62
63
# Download Wasm2JS code if target browser does not support WebAssembly
64
if settings.WASM == 2:
65
if settings.MODULARIZE:
66
modularize_imports += [f'wasm: supportsWasm ? r[{len(files_to_load)}] : 0']
67
else:
68
then_statements += [f"if (supportsWasm) {settings.EXPORT_NAME}.wasm = r[{len(files_to_load)}];"]
69
files_to_load += [f"supportsWasm ? {download_wasm} : script('{target_basename}.wasm.js')"]
70
71
# Execute compiled output when building with MODULARIZE
72
if settings.MODULARIZE:
73
modularize_imports = ',\n '.join(modularize_imports)
74
if settings.WASM_WORKERS:
75
then_statements += ['''\
76
// Detour the JS code to a separate variable to avoid instantiating with 'r' array as "this"
77
// directly to avoid strict ECMAScript/Firefox GC problems that cause a leak, see
78
// https://bugzil.la/1540101
79
var js = URL.createObjectURL(new Blob([r[0]], { type: \'application/javascript\' }));
80
script(js).then((c) => c({
81
%s
82
}));''' % modularize_imports]
83
else:
84
then_statements += ['''\
85
// Detour the JS code to a separate variable to avoid instantiating with 'r' array as "this"
86
// directly to avoid strict ECMAScript/Firefox GC problems that cause a leak, see
87
// https://bugzil.la/1540101
88
var js = r[0];
89
js({
90
%s
91
});''' % modularize_imports]
92
93
binary_xhr = ' var binary = (url) => fetch(url).then((rsp) => rsp.arrayBuffer());'
94
95
script_xhr = '''\
96
function script(url) { // Downloads a script file and adds it to DOM
97
return new Promise((ok) => {
98
var s = document.createElement('script');
99
s.src = url;
100
s.onload = () => {
101
#if MODULARIZE
102
#if WASM == 2
103
// In MODULARIZEd WASM==2 builds, we use this same function to download
104
// both .js and .asm.js that are structured with {{{ EXPORT_NAME }}}
105
// at the top level, but also use this function to download the Wasm2JS
106
// file that does not have an {{{ EXPORT_NAME }}} function, hence the
107
// variable typeof check:
108
if (typeof {{{ EXPORT_NAME }}} !== 'undefined') {
109
var c = {{{ EXPORT_NAME }}};
110
delete {{{ EXPORT_NAME }}};
111
ok(c);
112
} else {
113
ok();
114
}
115
#else
116
var c = {{{ EXPORT_NAME }}};
117
delete {{{ EXPORT_NAME }}};
118
ok(c);
119
#endif
120
#else
121
ok();
122
#endif
123
};
124
document.body.appendChild(s);
125
});
126
}
127
'''
128
129
# Only one file to download - no need to use Promise.all()
130
if len(files_to_load) == 1:
131
if settings.MODULARIZE:
132
return script_xhr + files_to_load[0] + ".then(js);"
133
else:
134
return script_xhr + files_to_load[0] + ";"
135
136
if not settings.MODULARIZE or settings.WASM_WORKERS:
137
# If downloading multiple files like .wasm or .mem, those need to be loaded in
138
# before we can add the main runtime script to the DOM, so convert the main .js
139
# script load from direct script() load to a binary() load so we can still
140
# immediately start the download, but can control when we add the script to the
141
# DOM.
142
if settings.PTHREADS or settings.WASM_WORKERS:
143
script_load = "script(url)"
144
else:
145
script_load = "script(url).then(() => URL.revokeObjectURL(url));"
146
147
if settings.WASM_WORKERS:
148
save_js = f'{settings.EXPORT_NAME}.js = '
149
else:
150
save_js = ''
151
152
files_to_load[0] = f"binary('{settings.TARGET_JS_NAME}')"
153
if not settings.MODULARIZE:
154
then_statements += ["var url = %sURL.createObjectURL(new Blob([r[0]], { type: 'application/javascript' }));" % save_js,
155
script_load]
156
157
# Add in binary() XHR loader if used:
158
if any("binary(" in s for s in files_to_load + then_statements):
159
prefix_statements += [binary_xhr]
160
if any("script(" in s for s in files_to_load + then_statements):
161
prefix_statements += [script_xhr]
162
163
# Several files to download, go via Promise.all()
164
load = '\n'.join(prefix_statements)
165
load += "Promise.all([" + ', '.join(files_to_load) + "])"
166
if len(then_statements) > 0:
167
load += '.then((r) => {\n %s\n});' % '\n '.join(then_statements)
168
return load
169
170
171
def generate_minimal_runtime_html(target, options, js_target, target_basename):
172
logger.debug('generating HTML for minimal runtime')
173
shell = utils.read_file(options.shell_html)
174
if settings.SINGLE_FILE:
175
# No extra files needed to download in a SINGLE_FILE build.
176
shell = shell.replace('{{{ DOWNLOAD_JS_AND_WASM_FILES }}}', '')
177
else:
178
shell = shell.replace('{{{ DOWNLOAD_JS_AND_WASM_FILES }}}', generate_minimal_runtime_load_statement(target_basename))
179
180
temp_files = shared.get_temp_files()
181
with temp_files.get_file(suffix='.js') as shell_temp:
182
utils.write_file(shell_temp, shell)
183
shell = building.read_and_preprocess(shell_temp)
184
185
if re.search(r'{{{\s*SCRIPT\s*}}}', shell):
186
utils.exit_with_error(f'--shell-file "{options.shell_html}": MINIMAL_RUNTIME uses a different kind of HTML page shell file than the traditional runtime! Please see $EMSCRIPTEN/html/shell_minimal_runtime.html for a template to use as a basis.')
187
188
shell = shell.replace('{{{ TARGET_BASENAME }}}', settings.TARGET_BASENAME)
189
shell = shell.replace('{{{ EXPORT_NAME }}}', settings.EXPORT_NAME)
190
shell = shell.replace('{{{ TARGET_JS_NAME }}}', settings.TARGET_JS_NAME)
191
192
# In SINGLE_FILE build, embed the main .js file into the .html output
193
if settings.SINGLE_FILE:
194
js_contents = utils.read_file(js_target)
195
utils.delete_file(js_target)
196
else:
197
js_contents = ''
198
shell = shell.replace('{{{ JS_CONTENTS_IN_SINGLE_FILE_BUILD }}}', js_contents)
199
utils.write_file(target, shell, options.output_eol)
200
201