aboutsummaryrefslogtreecommitdiff
path: root/src/talks/wasm/examples/2-sum
diff options
context:
space:
mode:
authorSebastiano Tronto <sebastiano@tronto.net>2025-11-22 15:34:30 +0100
committerSebastiano Tronto <sebastiano@tronto.net>2025-11-22 15:42:12 +0100
commita4d6defa1722d52bf0f5bb2f3abf1443c4b6509c (patch)
treefc6bda84afeca68fe84d2e56119db107e2c509f1 /src/talks/wasm/examples/2-sum
parente855546ab1df31131b906d6cabed91409daf922d (diff)
downloadsebastiano.tronto.net-a4d6defa1722d52bf0f5bb2f3abf1443c4b6509c.tar.gz
sebastiano.tronto.net-a4d6defa1722d52bf0f5bb2f3abf1443c4b6509c.zip
Added talk
Diffstat (limited to 'src/talks/wasm/examples/2-sum')
-rw-r--r--src/talks/wasm/examples/2-sum/index.html.raw16
-rw-r--r--src/talks/wasm/examples/2-sum/mime.txt1
-rw-r--r--src/talks/wasm/examples/2-sum/script.js14
-rw-r--r--src/talks/wasm/examples/2-sum/sum_library.c3
-rw-r--r--src/talks/wasm/examples/2-sum/sum_library.mjs1531
-rwxr-xr-xsrc/talks/wasm/examples/2-sum/sum_library.wasmbin0 -> 1116 bytes
6 files changed, 1565 insertions, 0 deletions
diff --git a/src/talks/wasm/examples/2-sum/index.html.raw b/src/talks/wasm/examples/2-sum/index.html.raw
new file mode 100644
index 0000000..b0a7c38
--- /dev/null
+++ b/src/talks/wasm/examples/2-sum/index.html.raw
@@ -0,0 +1,16 @@
1<!doctype html>
2<html lang="en-US">
3<head>
4 <meta charset="utf-8" />
5 <meta name="viewport" content="width=device-width" />
6 <title>Sum two numbers</title>
7 <script src="./script.js" type="module" defer></script>
8</head>
9
10<body>
11 <input id="aInput" /> + <br />
12 <input id="bInput" /> <button id="goButton">=</button> <br />
13 <p id="resultText"></p>
14</body>
15
16</html>
diff --git a/src/talks/wasm/examples/2-sum/mime.txt b/src/talks/wasm/examples/2-sum/mime.txt
new file mode 100644
index 0000000..6a9a425
--- /dev/null
+++ b/src/talks/wasm/examples/2-sum/mime.txt
@@ -0,0 +1 @@
text/javascript mjs
diff --git a/src/talks/wasm/examples/2-sum/script.js b/src/talks/wasm/examples/2-sum/script.js
new file mode 100644
index 0000000..4b05824
--- /dev/null
+++ b/src/talks/wasm/examples/2-sum/script.js
@@ -0,0 +1,14 @@
1import SumLibrary from "./sum_library.mjs";
2
3var sumLibraryInstance = await SumLibrary();
4
5var aInput = document.getElementById("aInput");
6var bInput = document.getElementById("bInput");
7var button = document.getElementById("goButton");
8var resultText = document.getElementById("resultText");
9
10button.addEventListener("click", () => {
11 var a = Number(aInput.value);
12 var b = Number(bInput.value);
13 resultText.innerText = sumLibraryInstance._sum(a, b);
14});
diff --git a/src/talks/wasm/examples/2-sum/sum_library.c b/src/talks/wasm/examples/2-sum/sum_library.c
new file mode 100644
index 0000000..aba9411
--- /dev/null
+++ b/src/talks/wasm/examples/2-sum/sum_library.c
@@ -0,0 +1,3 @@
1int sum(int a, int b) {
2 return a + b;
3}
diff --git a/src/talks/wasm/examples/2-sum/sum_library.mjs b/src/talks/wasm/examples/2-sum/sum_library.mjs
new file mode 100644
index 0000000..298c30e
--- /dev/null
+++ b/src/talks/wasm/examples/2-sum/sum_library.mjs
@@ -0,0 +1,1531 @@
1// This code implements the `-sMODULARIZE` settings by taking the generated
2// JS program code (INNER_JS_CODE) and wrapping it in a factory function.
3
4// When targetting node and ES6 we use `await import ..` in the generated code
5// so the outer function needs to be marked as async.
6async function SumLibrary(moduleArg = {}) {
7 var moduleRtn;
8
9// include: shell.js
10// The Module object: Our interface to the outside world. We import
11// and export values on it. There are various ways Module can be used:
12// 1. Not defined. We create it here
13// 2. A function parameter, function(moduleArg) => Promise<Module>
14// 3. pre-run appended it, var Module = {}; ..generated code..
15// 4. External script tag defines var Module.
16// We need to check if Module already exists (e.g. case 3 above).
17// Substitution will be replaced with actual code on later stage of the build,
18// this way Closure Compiler will not mangle it (e.g. case 4. above).
19// Note that if you want to run closure, and also to use Module
20// after the generated code, you will need to define var Module = {};
21// before the code. Then that object will be used in the code, and you
22// can continue to use Module afterwards as well.
23var Module = moduleArg;
24
25// Determine the runtime environment we are in. You can customize this by
26// setting the ENVIRONMENT setting at compile time (see settings.js).
27
28// Attempt to auto-detect the environment
29var ENVIRONMENT_IS_WEB = typeof window == 'object';
30var ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != 'undefined';
31// N.b. Electron.js environment is simultaneously a NODE-environment, but
32// also a web environment.
33var ENVIRONMENT_IS_NODE = typeof process == 'object' && process.versions?.node && process.type != 'renderer';
34var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
35
36if (ENVIRONMENT_IS_NODE) {
37 // When building an ES module `require` is not normally available.
38 // We need to use `createRequire()` to construct the require()` function.
39 const { createRequire } = await import('module');
40 /** @suppress{duplicate} */
41 var require = createRequire(import.meta.url);
42
43}
44
45// --pre-jses are emitted after the Module integration code, so that they can
46// refer to Module (if they choose; they can also define Module)
47
48
49var arguments_ = [];
50var thisProgram = './this.program';
51var quit_ = (status, toThrow) => {
52 throw toThrow;
53};
54
55var _scriptName = import.meta.url;
56
57// `/` should be present at the end if `scriptDirectory` is not empty
58var scriptDirectory = '';
59function locateFile(path) {
60 if (Module['locateFile']) {
61 return Module['locateFile'](path, scriptDirectory);
62 }
63 return scriptDirectory + path;
64}
65
66// Hooks that are implemented differently in different runtime environments.
67var readAsync, readBinary;
68
69if (ENVIRONMENT_IS_NODE) {
70 const isNode = typeof process == 'object' && process.versions?.node && process.type != 'renderer';
71 if (!isNode) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
72
73 var nodeVersion = process.versions.node;
74 var numericVersion = nodeVersion.split('.').slice(0, 3);
75 numericVersion = (numericVersion[0] * 10000) + (numericVersion[1] * 100) + (numericVersion[2].split('-')[0] * 1);
76 if (numericVersion < 160000) {
77 throw new Error('This emscripten-generated code requires node v16.0.0 (detected v' + nodeVersion + ')');
78 }
79
80 // These modules will usually be used on Node.js. Load them eagerly to avoid
81 // the complexity of lazy-loading.
82 var fs = require('fs');
83
84 if (_scriptName.startsWith('file:')) {
85 scriptDirectory = require('path').dirname(require('url').fileURLToPath(_scriptName)) + '/';
86 }
87
88// include: node_shell_read.js
89readBinary = (filename) => {
90 // We need to re-wrap `file://` strings to URLs.
91 filename = isFileURI(filename) ? new URL(filename) : filename;
92 var ret = fs.readFileSync(filename);
93 assert(Buffer.isBuffer(ret));
94 return ret;
95};
96
97readAsync = async (filename, binary = true) => {
98 // See the comment in the `readBinary` function.
99 filename = isFileURI(filename) ? new URL(filename) : filename;
100 var ret = fs.readFileSync(filename, binary ? undefined : 'utf8');
101 assert(binary ? Buffer.isBuffer(ret) : typeof ret == 'string');
102 return ret;
103};
104// end include: node_shell_read.js
105 if (process.argv.length > 1) {
106 thisProgram = process.argv[1].replace(/\\/g, '/');
107 }
108
109 arguments_ = process.argv.slice(2);
110
111 quit_ = (status, toThrow) => {
112 process.exitCode = status;
113 throw toThrow;
114 };
115
116} else
117if (ENVIRONMENT_IS_SHELL) {
118
119 const isNode = typeof process == 'object' && process.versions?.node && process.type != 'renderer';
120 if (isNode || typeof window == 'object' || typeof WorkerGlobalScope != 'undefined') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
121
122} else
123
124// Note that this includes Node.js workers when relevant (pthreads is enabled).
125// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
126// ENVIRONMENT_IS_NODE.
127if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
128 try {
129 scriptDirectory = new URL('.', _scriptName).href; // includes trailing slash
130 } catch {
131 // Must be a `blob:` or `data:` URL (e.g. `blob:http://site.com/etc/etc`), we cannot
132 // infer anything from them.
133 }
134
135 if (!(typeof window == 'object' || typeof WorkerGlobalScope != 'undefined')) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
136
137 {
138// include: web_or_worker_shell_read.js
139if (ENVIRONMENT_IS_WORKER) {
140 readBinary = (url) => {
141 var xhr = new XMLHttpRequest();
142 xhr.open('GET', url, false);
143 xhr.responseType = 'arraybuffer';
144 xhr.send(null);
145 return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
146 };
147 }
148
149 readAsync = async (url) => {
150 // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.
151 // See https://github.com/github/fetch/pull/92#issuecomment-140665932
152 // Cordova or Electron apps are typically loaded from a file:// url.
153 // So use XHR on webview if URL is a file URL.
154 if (isFileURI(url)) {
155 return new Promise((resolve, reject) => {
156 var xhr = new XMLHttpRequest();
157 xhr.open('GET', url, true);
158 xhr.responseType = 'arraybuffer';
159 xhr.onload = () => {
160 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
161 resolve(xhr.response);
162 return;
163 }
164 reject(xhr.status);
165 };
166 xhr.onerror = reject;
167 xhr.send(null);
168 });
169 }
170 var response = await fetch(url, { credentials: 'same-origin' });
171 if (response.ok) {
172 return response.arrayBuffer();
173 }
174 throw new Error(response.status + ' : ' + response.url);
175 };
176// end include: web_or_worker_shell_read.js
177 }
178} else
179{
180 throw new Error('environment detection error');
181}
182
183var out = console.log.bind(console);
184var err = console.error.bind(console);
185
186var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';
187var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';
188var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';
189var FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js';
190var ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js';
191var JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js';
192var OPFS = 'OPFS is no longer included by default; build with -lopfs.js';
193
194var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';
195
196// perform assertions in shell.js after we set up out() and err(), as otherwise
197// if an assertion fails it cannot print the message
198
199assert(!ENVIRONMENT_IS_SHELL, 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.');
200
201// end include: shell.js
202
203// include: preamble.js
204// === Preamble library stuff ===
205
206// Documentation for the public APIs defined in this file must be updated in:
207// site/source/docs/api_reference/preamble.js.rst
208// A prebuilt local version of the documentation is available at:
209// site/build/text/docs/api_reference/preamble.js.txt
210// You can also build docs locally as HTML or other formats in site/
211// An online HTML version (which may be of a different version of Emscripten)
212// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
213
214var wasmBinary;
215
216if (typeof WebAssembly != 'object') {
217 err('no native wasm support detected');
218}
219
220// Wasm globals
221
222//========================================
223// Runtime essentials
224//========================================
225
226// whether we are quitting the application. no code should run after this.
227// set in exit() and abort()
228var ABORT = false;
229
230// set by exit() and abort(). Passed to 'onExit' handler.
231// NOTE: This is also used as the process return code code in shell environments
232// but only when noExitRuntime is false.
233var EXITSTATUS;
234
235// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we
236// don't define it at all in release modes. This matches the behaviour of
237// MINIMAL_RUNTIME.
238// TODO(sbc): Make this the default even without STRICT enabled.
239/** @type {function(*, string=)} */
240function assert(condition, text) {
241 if (!condition) {
242 abort('Assertion failed' + (text ? ': ' + text : ''));
243 }
244}
245
246// We used to include malloc/free by default in the past. Show a helpful error in
247// builds with assertions.
248function _malloc() {
249 abort('malloc() called but not included in the build - add `_malloc` to EXPORTED_FUNCTIONS');
250}
251function _free() {
252 // Show a helpful error since we used to include free by default in the past.
253 abort('free() called but not included in the build - add `_free` to EXPORTED_FUNCTIONS');
254}
255
256/**
257 * Indicates whether filename is delivered via file protocol (as opposed to http/https)
258 * @noinline
259 */
260var isFileURI = (filename) => filename.startsWith('file://');
261
262// include: runtime_common.js
263// include: runtime_stack_check.js
264// Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
265function writeStackCookie() {
266 var max = _emscripten_stack_get_end();
267 assert((max & 3) == 0);
268 // If the stack ends at address zero we write our cookies 4 bytes into the
269 // stack. This prevents interference with SAFE_HEAP and ASAN which also
270 // monitor writes to address zero.
271 if (max == 0) {
272 max += 4;
273 }
274 // The stack grow downwards towards _emscripten_stack_get_end.
275 // We write cookies to the final two words in the stack and detect if they are
276 // ever overwritten.
277 HEAPU32[((max)>>2)] = 0x02135467;
278 HEAPU32[(((max)+(4))>>2)] = 0x89BACDFE;
279 // Also test the global address 0 for integrity.
280 HEAPU32[((0)>>2)] = 1668509029;
281}
282
283function checkStackCookie() {
284 if (ABORT) return;
285 var max = _emscripten_stack_get_end();
286 // See writeStackCookie().
287 if (max == 0) {
288 max += 4;
289 }
290 var cookie1 = HEAPU32[((max)>>2)];
291 var cookie2 = HEAPU32[(((max)+(4))>>2)];
292 if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) {
293 abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`);
294 }
295 // Also test the global address 0 for integrity.
296 if (HEAPU32[((0)>>2)] != 0x63736d65 /* 'emsc' */) {
297 abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
298 }
299}
300// end include: runtime_stack_check.js
301// include: runtime_exceptions.js
302// end include: runtime_exceptions.js
303// include: runtime_debug.js
304var runtimeDebug = true; // Switch to false at runtime to disable logging at the right times
305
306// Used by XXXXX_DEBUG settings to output debug messages.
307function dbg(...args) {
308 if (!runtimeDebug && typeof runtimeDebug != 'undefined') return;
309 // TODO(sbc): Make this configurable somehow. Its not always convenient for
310 // logging to show up as warnings.
311 console.warn(...args);
312}
313
314// Endianness check
315(() => {
316 var h16 = new Int16Array(1);
317 var h8 = new Int8Array(h16.buffer);
318 h16[0] = 0x6373;
319 if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)';
320})();
321
322function consumedModuleProp(prop) {
323 if (!Object.getOwnPropertyDescriptor(Module, prop)) {
324 Object.defineProperty(Module, prop, {
325 configurable: true,
326 set() {
327 abort(`Attempt to set \`Module.${prop}\` after it has already been processed. This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`);
328
329 }
330 });
331 }
332}
333
334function makeInvalidEarlyAccess(name) {
335 return () => assert(false, `call to '${name}' via reference taken before Wasm module initialization`);
336
337}
338
339function ignoredModuleProp(prop) {
340 if (Object.getOwnPropertyDescriptor(Module, prop)) {
341 abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`);
342 }
343}
344
345// forcing the filesystem exports a few things by default
346function isExportedByForceFilesystem(name) {
347 return name === 'FS_createPath' ||
348 name === 'FS_createDataFile' ||
349 name === 'FS_createPreloadedFile' ||
350 name === 'FS_unlink' ||
351 name === 'addRunDependency' ||
352 // The old FS has some functionality that WasmFS lacks.
353 name === 'FS_createLazyFile' ||
354 name === 'FS_createDevice' ||
355 name === 'removeRunDependency';
356}
357
358/**
359 * Intercept access to a global symbol. This enables us to give informative
360 * warnings/errors when folks attempt to use symbols they did not include in
361 * their build, or no symbols that no longer exist.
362 */
363function hookGlobalSymbolAccess(sym, func) {
364 if (typeof globalThis != 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) {
365 Object.defineProperty(globalThis, sym, {
366 configurable: true,
367 get() {
368 func();
369 return undefined;
370 }
371 });
372 }
373}
374
375function missingGlobal(sym, msg) {
376 hookGlobalSymbolAccess(sym, () => {
377 warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`);
378 });
379}
380
381missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer');
382missingGlobal('asm', 'Please use wasmExports instead');
383
384function missingLibrarySymbol(sym) {
385 hookGlobalSymbolAccess(sym, () => {
386 // Can't `abort()` here because it would break code that does runtime
387 // checks. e.g. `if (typeof SDL === 'undefined')`.
388 var msg = `\`${sym}\` 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`;
389 // DEFAULT_LIBRARY_FUNCS_TO_INCLUDE requires the name as it appears in
390 // library.js, which means $name for a JS name with no prefix, or name
391 // for a JS name like _name.
392 var librarySymbol = sym;
393 if (!librarySymbol.startsWith('_')) {
394 librarySymbol = '$' + sym;
395 }
396 msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`;
397 if (isExportedByForceFilesystem(sym)) {
398 msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';
399 }
400 warnOnce(msg);
401 });
402
403 // Any symbol that is not included from the JS library is also (by definition)
404 // not exported on the Module object.
405 unexportedRuntimeSymbol(sym);
406}
407
408function unexportedRuntimeSymbol(sym) {
409 if (!Object.getOwnPropertyDescriptor(Module, sym)) {
410 Object.defineProperty(Module, sym, {
411 configurable: true,
412 get() {
413 var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;
414 if (isExportedByForceFilesystem(sym)) {
415 msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';
416 }
417 abort(msg);
418 }
419 });
420 }
421}
422
423// end include: runtime_debug.js
424var readyPromiseResolve, readyPromiseReject;
425
426// Memory management
427
428var wasmMemory;
429
430var
431/** @type {!Int8Array} */
432 HEAP8,
433/** @type {!Uint8Array} */
434 HEAPU8,
435/** @type {!Int16Array} */
436 HEAP16,
437/** @type {!Uint16Array} */
438 HEAPU16,
439/** @type {!Int32Array} */
440 HEAP32,
441/** @type {!Uint32Array} */
442 HEAPU32,
443/** @type {!Float32Array} */
444 HEAPF32,
445/** @type {!Float64Array} */
446 HEAPF64;
447
448// BigInt64Array type is not correctly defined in closure
449var
450/** not-@type {!BigInt64Array} */
451 HEAP64,
452/* BigUint64Array type is not correctly defined in closure
453/** not-@type {!BigUint64Array} */
454 HEAPU64;
455
456var runtimeInitialized = false;
457
458
459
460function updateMemoryViews() {
461 var b = wasmMemory.buffer;
462 HEAP8 = new Int8Array(b);
463 HEAP16 = new Int16Array(b);
464 HEAPU8 = new Uint8Array(b);
465 HEAPU16 = new Uint16Array(b);
466 HEAP32 = new Int32Array(b);
467 HEAPU32 = new Uint32Array(b);
468 HEAPF32 = new Float32Array(b);
469 HEAPF64 = new Float64Array(b);
470 HEAP64 = new BigInt64Array(b);
471 HEAPU64 = new BigUint64Array(b);
472}
473
474// include: memoryprofiler.js
475// end include: memoryprofiler.js
476// end include: runtime_common.js
477assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined,
478 'JS engine does not provide full typed array support');
479
480function preRun() {
481 if (Module['preRun']) {
482 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
483 while (Module['preRun'].length) {
484 addOnPreRun(Module['preRun'].shift());
485 }
486 }
487 consumedModuleProp('preRun');
488 // Begin ATPRERUNS hooks
489 callRuntimeCallbacks(onPreRuns);
490 // End ATPRERUNS hooks
491}
492
493function initRuntime() {
494 assert(!runtimeInitialized);
495 runtimeInitialized = true;
496
497 checkStackCookie();
498
499 // No ATINITS hooks
500
501 wasmExports['__wasm_call_ctors']();
502
503 // No ATPOSTCTORS hooks
504}
505
506function postRun() {
507 checkStackCookie();
508 // PThreads reuse the runtime from the main thread.
509
510 if (Module['postRun']) {
511 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
512 while (Module['postRun'].length) {
513 addOnPostRun(Module['postRun'].shift());
514 }
515 }
516 consumedModuleProp('postRun');
517
518 // Begin ATPOSTRUNS hooks
519 callRuntimeCallbacks(onPostRuns);
520 // End ATPOSTRUNS hooks
521}
522
523// A counter of dependencies for calling run(). If we need to
524// do asynchronous work before running, increment this and
525// decrement it. Incrementing must happen in a place like
526// Module.preRun (used by emcc to add file preloading).
527// Note that you can add dependencies in preRun, even though
528// it happens right before run - run will be postponed until
529// the dependencies are met.
530var runDependencies = 0;
531var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
532var runDependencyTracking = {};
533var runDependencyWatcher = null;
534
535function addRunDependency(id) {
536 runDependencies++;
537
538 Module['monitorRunDependencies']?.(runDependencies);
539
540 if (id) {
541 assert(!runDependencyTracking[id]);
542 runDependencyTracking[id] = 1;
543 if (runDependencyWatcher === null && typeof setInterval != 'undefined') {
544 // Check for missing dependencies every few seconds
545 runDependencyWatcher = setInterval(() => {
546 if (ABORT) {
547 clearInterval(runDependencyWatcher);
548 runDependencyWatcher = null;
549 return;
550 }
551 var shown = false;
552 for (var dep in runDependencyTracking) {
553 if (!shown) {
554 shown = true;
555 err('still waiting on run dependencies:');
556 }
557 err(`dependency: ${dep}`);
558 }
559 if (shown) {
560 err('(end of list)');
561 }
562 }, 10000);
563 }
564 } else {
565 err('warning: run dependency added without ID');
566 }
567}
568
569function removeRunDependency(id) {
570 runDependencies--;
571
572 Module['monitorRunDependencies']?.(runDependencies);
573
574 if (id) {
575 assert(runDependencyTracking[id]);
576 delete runDependencyTracking[id];
577 } else {
578 err('warning: run dependency removed without ID');
579 }
580 if (runDependencies == 0) {
581 if (runDependencyWatcher !== null) {
582 clearInterval(runDependencyWatcher);
583 runDependencyWatcher = null;
584 }
585 if (dependenciesFulfilled) {
586 var callback = dependenciesFulfilled;
587 dependenciesFulfilled = null;
588 callback(); // can add another dependenciesFulfilled
589 }
590 }
591}
592
593/** @param {string|number=} what */
594function abort(what) {
595 Module['onAbort']?.(what);
596
597 what = 'Aborted(' + what + ')';
598 // TODO(sbc): Should we remove printing and leave it up to whoever
599 // catches the exception?
600 err(what);
601
602 ABORT = true;
603
604 // Use a wasm runtime error, because a JS error might be seen as a foreign
605 // exception, which means we'd run destructors on it. We need the error to
606 // simply make the program stop.
607 // FIXME This approach does not work in Wasm EH because it currently does not assume
608 // all RuntimeErrors are from traps; it decides whether a RuntimeError is from
609 // a trap or not based on a hidden field within the object. So at the moment
610 // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that
611 // allows this in the wasm spec.
612
613 // Suppress closure compiler warning here. Closure compiler's builtin extern
614 // definition for WebAssembly.RuntimeError claims it takes no arguments even
615 // though it can.
616 // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.
617 /** @suppress {checkTypes} */
618 var e = new WebAssembly.RuntimeError(what);
619
620 readyPromiseReject?.(e);
621 // Throw the error whether or not MODULARIZE is set because abort is used
622 // in code paths apart from instantiation where an exception is expected
623 // to be thrown when abort is called.
624 throw e;
625}
626
627// show errors on likely calls to FS when it was not included
628var FS = {
629 error() {
630 abort('Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM');
631 },
632 init() { FS.error() },
633 createDataFile() { FS.error() },
634 createPreloadedFile() { FS.error() },
635 createLazyFile() { FS.error() },
636 open() { FS.error() },
637 mkdev() { FS.error() },
638 registerDevice() { FS.error() },
639 analyzePath() { FS.error() },
640
641 ErrnoError() { FS.error() },
642};
643
644
645function createExportWrapper(name, nargs) {
646 return (...args) => {
647 assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`);
648 var f = wasmExports[name];
649 assert(f, `exported native function \`${name}\` not found`);
650 // Only assert for too many arguments. Too few can be valid since the missing arguments will be zero filled.
651 assert(args.length <= nargs, `native function \`${name}\` called with ${args.length} args but expects ${nargs}`);
652 return f(...args);
653 };
654}
655
656var wasmBinaryFile;
657
658function findWasmBinary() {
659 if (Module['locateFile']) {
660 return locateFile('sum_library.wasm');
661 }
662 // Use bundler-friendly `new URL(..., import.meta.url)` pattern; works in browsers too.
663 return new URL('sum_library.wasm', import.meta.url).href;
664}
665
666function getBinarySync(file) {
667 if (file == wasmBinaryFile && wasmBinary) {
668 return new Uint8Array(wasmBinary);
669 }
670 if (readBinary) {
671 return readBinary(file);
672 }
673 throw 'both async and sync fetching of the wasm failed';
674}
675
676async function getWasmBinary(binaryFile) {
677 // If we don't have the binary yet, load it asynchronously using readAsync.
678 if (!wasmBinary) {
679 // Fetch the binary using readAsync
680 try {
681 var response = await readAsync(binaryFile);
682 return new Uint8Array(response);
683 } catch {
684 // Fall back to getBinarySync below;
685 }
686 }
687
688 // Otherwise, getBinarySync should be able to get it synchronously
689 return getBinarySync(binaryFile);
690}
691
692async function instantiateArrayBuffer(binaryFile, imports) {
693 try {
694 var binary = await getWasmBinary(binaryFile);
695 var instance = await WebAssembly.instantiate(binary, imports);
696 return instance;
697 } catch (reason) {
698 err(`failed to asynchronously prepare wasm: ${reason}`);
699
700 // Warn on some common problems.
701 if (isFileURI(wasmBinaryFile)) {
702 err(`warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`);
703 }
704 abort(reason);
705 }
706}
707
708async function instantiateAsync(binary, binaryFile, imports) {
709 if (!binary && typeof WebAssembly.instantiateStreaming == 'function'
710 // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.
711 && !isFileURI(binaryFile)
712 // Avoid instantiateStreaming() on Node.js environment for now, as while
713 // Node.js v18.1.0 implements it, it does not have a full fetch()
714 // implementation yet.
715 //
716 // Reference:
717 // https://github.com/emscripten-core/emscripten/pull/16917
718 && !ENVIRONMENT_IS_NODE
719 ) {
720 try {
721 var response = fetch(binaryFile, { credentials: 'same-origin' });
722 var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);
723 return instantiationResult;
724 } catch (reason) {
725 // We expect the most common failure cause to be a bad MIME type for the binary,
726 // in which case falling back to ArrayBuffer instantiation should work.
727 err(`wasm streaming compile failed: ${reason}`);
728 err('falling back to ArrayBuffer instantiation');
729 // fall back of instantiateArrayBuffer below
730 };
731 }
732 return instantiateArrayBuffer(binaryFile, imports);
733}
734
735function getWasmImports() {
736 // prepare imports
737 return {
738 'env': wasmImports,
739 'wasi_snapshot_preview1': wasmImports,
740 }
741}
742
743// Create the wasm instance.
744// Receives the wasm imports, returns the exports.
745async function createWasm() {
746 // Load the wasm module and create an instance of using native support in the JS engine.
747 // handle a generated wasm instance, receiving its exports and
748 // performing other necessary setup
749 /** @param {WebAssembly.Module=} module*/
750 function receiveInstance(instance, module) {
751 wasmExports = instance.exports;
752
753
754
755 wasmMemory = wasmExports['memory'];
756
757 assert(wasmMemory, 'memory not found in wasm exports');
758 updateMemoryViews();
759
760 assignWasmExports(wasmExports);
761 removeRunDependency('wasm-instantiate');
762 return wasmExports;
763 }
764 // wait for the pthread pool (if any)
765 addRunDependency('wasm-instantiate');
766
767 // Prefer streaming instantiation if available.
768 // Async compilation can be confusing when an error on the page overwrites Module
769 // (for example, if the order of elements is wrong, and the one defining Module is
770 // later), so we save Module and check it later.
771 var trueModule = Module;
772 function receiveInstantiationResult(result) {
773 // 'result' is a ResultObject object which has both the module and instance.
774 // receiveInstance() will swap in the exports (to Module.asm) so they can be called
775 assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
776 trueModule = null;
777 // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.
778 // When the regression is fixed, can restore the above PTHREADS-enabled path.
779 return receiveInstance(result['instance']);
780 }
781
782 var info = getWasmImports();
783
784 // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
785 // to manually instantiate the Wasm module themselves. This allows pages to
786 // run the instantiation parallel to any other async startup actions they are
787 // performing.
788 // Also pthreads and wasm workers initialize the wasm instance through this
789 // path.
790 if (Module['instantiateWasm']) {
791 return new Promise((resolve, reject) => {
792 try {
793 Module['instantiateWasm'](info, (mod, inst) => {
794 resolve(receiveInstance(mod, inst));
795 });
796 } catch(e) {
797 err(`Module.instantiateWasm callback failed with error: ${e}`);
798 reject(e);
799 }
800 });
801 }
802
803 wasmBinaryFile ??= findWasmBinary();
804 var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);
805 var exports = receiveInstantiationResult(result);
806 return exports;
807}
808
809// end include: preamble.js
810
811// Begin JS library code
812
813
814 class ExitStatus {
815 name = 'ExitStatus';
816 constructor(status) {
817 this.message = `Program terminated with exit(${status})`;
818 this.status = status;
819 }
820 }
821
822 var callRuntimeCallbacks = (callbacks) => {
823 while (callbacks.length > 0) {
824 // Pass the module as the first argument.
825 callbacks.shift()(Module);
826 }
827 };
828 var onPostRuns = [];
829 var addOnPostRun = (cb) => onPostRuns.push(cb);
830
831 var onPreRuns = [];
832 var addOnPreRun = (cb) => onPreRuns.push(cb);
833
834
835
836 /**
837 * @param {number} ptr
838 * @param {string} type
839 */
840 function getValue(ptr, type = 'i8') {
841 if (type.endsWith('*')) type = '*';
842 switch (type) {
843 case 'i1': return HEAP8[ptr];
844 case 'i8': return HEAP8[ptr];
845 case 'i16': return HEAP16[((ptr)>>1)];
846 case 'i32': return HEAP32[((ptr)>>2)];
847 case 'i64': return HEAP64[((ptr)>>3)];
848 case 'float': return HEAPF32[((ptr)>>2)];
849 case 'double': return HEAPF64[((ptr)>>3)];
850 case '*': return HEAPU32[((ptr)>>2)];
851 default: abort(`invalid type for getValue: ${type}`);
852 }
853 }
854
855 var noExitRuntime = true;
856
857 var ptrToString = (ptr) => {
858 assert(typeof ptr === 'number');
859 // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
860 ptr >>>= 0;
861 return '0x' + ptr.toString(16).padStart(8, '0');
862 };
863
864
865 /**
866 * @param {number} ptr
867 * @param {number} value
868 * @param {string} type
869 */
870 function setValue(ptr, value, type = 'i8') {
871 if (type.endsWith('*')) type = '*';
872 switch (type) {
873 case 'i1': HEAP8[ptr] = value; break;
874 case 'i8': HEAP8[ptr] = value; break;
875 case 'i16': HEAP16[((ptr)>>1)] = value; break;
876 case 'i32': HEAP32[((ptr)>>2)] = value; break;
877 case 'i64': HEAP64[((ptr)>>3)] = BigInt(value); break;
878 case 'float': HEAPF32[((ptr)>>2)] = value; break;
879 case 'double': HEAPF64[((ptr)>>3)] = value; break;
880 case '*': HEAPU32[((ptr)>>2)] = value; break;
881 default: abort(`invalid type for setValue: ${type}`);
882 }
883 }
884
885 var stackRestore = (val) => __emscripten_stack_restore(val);
886
887 var stackSave = () => _emscripten_stack_get_current();
888
889 var warnOnce = (text) => {
890 warnOnce.shown ||= {};
891 if (!warnOnce.shown[text]) {
892 warnOnce.shown[text] = 1;
893 if (ENVIRONMENT_IS_NODE) text = 'warning: ' + text;
894 err(text);
895 }
896 };
897// End JS library code
898
899// include: postlibrary.js
900// This file is included after the automatically-generated JS library code
901// but before the wasm module is created.
902
903{
904
905 // Begin ATMODULES hooks
906 if (Module['noExitRuntime']) noExitRuntime = Module['noExitRuntime'];
907if (Module['print']) out = Module['print'];
908if (Module['printErr']) err = Module['printErr'];
909if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];
910
911Module['FS_createDataFile'] = FS.createDataFile;
912Module['FS_createPreloadedFile'] = FS.createPreloadedFile;
913
914 // End ATMODULES hooks
915
916 checkIncomingModuleAPI();
917
918 if (Module['arguments']) arguments_ = Module['arguments'];
919 if (Module['thisProgram']) thisProgram = Module['thisProgram'];
920
921 // Assertions on removed incoming Module JS APIs.
922 assert(typeof Module['memoryInitializerPrefixURL'] == 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
923 assert(typeof Module['pthreadMainPrefixURL'] == 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
924 assert(typeof Module['cdInitializerPrefixURL'] == 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
925 assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
926 assert(typeof Module['read'] == 'undefined', 'Module.read option was removed');
927 assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
928 assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
929 assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)');
930 assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY');
931 assert(typeof Module['ENVIRONMENT'] == 'undefined', 'Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)');
932 assert(typeof Module['STACK_SIZE'] == 'undefined', 'STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time')
933 // If memory is defined in wasm, the user can't provide it, or set INITIAL_MEMORY
934 assert(typeof Module['wasmMemory'] == 'undefined', 'Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally');
935 assert(typeof Module['INITIAL_MEMORY'] == 'undefined', 'Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically');
936
937}
938
939// Begin runtime exports
940 var missingLibrarySymbols = [
941 'writeI53ToI64',
942 'writeI53ToI64Clamped',
943 'writeI53ToI64Signaling',
944 'writeI53ToU64Clamped',
945 'writeI53ToU64Signaling',
946 'readI53FromI64',
947 'readI53FromU64',
948 'convertI32PairToI53',
949 'convertI32PairToI53Checked',
950 'convertU32PairToI53',
951 'bigintToI53Checked',
952 'stackAlloc',
953 'getTempRet0',
954 'setTempRet0',
955 'zeroMemory',
956 'exitJS',
957 'getHeapMax',
958 'abortOnCannotGrowMemory',
959 'growMemory',
960 'withStackSave',
961 'strError',
962 'inetPton4',
963 'inetNtop4',
964 'inetPton6',
965 'inetNtop6',
966 'readSockaddr',
967 'writeSockaddr',
968 'readEmAsmArgs',
969 'jstoi_q',
970 'getExecutableName',
971 'autoResumeAudioContext',
972 'getDynCaller',
973 'dynCall',
974 'handleException',
975 'keepRuntimeAlive',
976 'runtimeKeepalivePush',
977 'runtimeKeepalivePop',
978 'callUserCallback',
979 'maybeExit',
980 'asmjsMangle',
981 'asyncLoad',
982 'alignMemory',
983 'mmapAlloc',
984 'HandleAllocator',
985 'getNativeTypeSize',
986 'getUniqueRunDependency',
987 'addOnInit',
988 'addOnPostCtor',
989 'addOnPreMain',
990 'addOnExit',
991 'STACK_SIZE',
992 'STACK_ALIGN',
993 'POINTER_SIZE',
994 'ASSERTIONS',
995 'ccall',
996 'cwrap',
997 'convertJsFunctionToWasm',
998 'getEmptyTableSlot',
999 'updateTableMap',
1000 'getFunctionAddress',
1001 'addFunction',
1002 'removeFunction',
1003 'UTF8ArrayToString',
1004 'UTF8ToString',
1005 'stringToUTF8Array',
1006 'stringToUTF8',
1007 'lengthBytesUTF8',
1008 'intArrayFromString',
1009 'intArrayToString',
1010 'AsciiToString',
1011 'stringToAscii',
1012 'UTF16ToString',
1013 'stringToUTF16',
1014 'lengthBytesUTF16',
1015 'UTF32ToString',
1016 'stringToUTF32',
1017 'lengthBytesUTF32',
1018 'stringToNewUTF8',
1019 'stringToUTF8OnStack',
1020 'writeArrayToMemory',
1021 'registerKeyEventCallback',
1022 'maybeCStringToJsString',
1023 'findEventTarget',
1024 'getBoundingClientRect',
1025 'fillMouseEventData',
1026 'registerMouseEventCallback',
1027 'registerWheelEventCallback',
1028 'registerUiEventCallback',
1029 'registerFocusEventCallback',
1030 'fillDeviceOrientationEventData',
1031 'registerDeviceOrientationEventCallback',
1032 'fillDeviceMotionEventData',
1033 'registerDeviceMotionEventCallback',
1034 'screenOrientation',
1035 'fillOrientationChangeEventData',
1036 'registerOrientationChangeEventCallback',
1037 'fillFullscreenChangeEventData',
1038 'registerFullscreenChangeEventCallback',
1039 'JSEvents_requestFullscreen',
1040 'JSEvents_resizeCanvasForFullscreen',
1041 'registerRestoreOldStyle',
1042 'hideEverythingExceptGivenElement',
1043 'restoreHiddenElements',
1044 'setLetterbox',
1045 'softFullscreenResizeWebGLRenderTarget',
1046 'doRequestFullscreen',
1047 'fillPointerlockChangeEventData',
1048 'registerPointerlockChangeEventCallback',
1049 'registerPointerlockErrorEventCallback',
1050 'requestPointerLock',
1051 'fillVisibilityChangeEventData',
1052 'registerVisibilityChangeEventCallback',
1053 'registerTouchEventCallback',
1054 'fillGamepadEventData',
1055 'registerGamepadEventCallback',
1056 'registerBeforeUnloadEventCallback',
1057 'fillBatteryEventData',
1058 'registerBatteryEventCallback',
1059 'setCanvasElementSize',
1060 'getCanvasElementSize',
1061 'jsStackTrace',
1062 'getCallstack',
1063 'convertPCtoSourceLocation',
1064 'getEnvStrings',
1065 'checkWasiClock',
1066 'flush_NO_FILESYSTEM',
1067 'wasiRightsToMuslOFlags',
1068 'wasiOFlagsToMuslOFlags',
1069 'initRandomFill',
1070 'randomFill',
1071 'safeSetTimeout',
1072 'setImmediateWrapped',
1073 'safeRequestAnimationFrame',
1074 'clearImmediateWrapped',
1075 'registerPostMainLoop',
1076 'registerPreMainLoop',
1077 'getPromise',
1078 'makePromise',
1079 'idsToPromises',
1080 'makePromiseCallback',
1081 'ExceptionInfo',
1082 'findMatchingCatch',
1083 'Browser_asyncPrepareDataCounter',
1084 'isLeapYear',
1085 'ydayFromDate',
1086 'arraySum',
1087 'addDays',
1088 'getSocketFromFD',
1089 'getSocketAddress',
1090 'FS_createPreloadedFile',
1091 'FS_modeStringToFlags',
1092 'FS_getMode',
1093 'FS_stdin_getChar',
1094 'FS_mkdirTree',
1095 '_setNetworkCallback',
1096 'heapObjectForWebGLType',
1097 'toTypedArrayIndex',
1098 'webgl_enable_ANGLE_instanced_arrays',
1099 'webgl_enable_OES_vertex_array_object',
1100 'webgl_enable_WEBGL_draw_buffers',
1101 'webgl_enable_WEBGL_multi_draw',
1102 'webgl_enable_EXT_polygon_offset_clamp',
1103 'webgl_enable_EXT_clip_control',
1104 'webgl_enable_WEBGL_polygon_mode',
1105 'emscriptenWebGLGet',
1106 'computeUnpackAlignedImageSize',
1107 'colorChannelsInGlTextureFormat',
1108 'emscriptenWebGLGetTexPixelData',
1109 'emscriptenWebGLGetUniform',
1110 'webglGetUniformLocation',
1111 'webglPrepareUniformLocationsBeforeFirstUse',
1112 'webglGetLeftBracePos',
1113 'emscriptenWebGLGetVertexAttrib',
1114 '__glGetActiveAttribOrUniform',
1115 'writeGLArray',
1116 'registerWebGlEventCallback',
1117 'runAndAbortIfError',
1118 'ALLOC_NORMAL',
1119 'ALLOC_STACK',
1120 'allocate',
1121 'writeStringToMemory',
1122 'writeAsciiToMemory',
1123 'demangle',
1124 'stackTrace',
1125];
1126missingLibrarySymbols.forEach(missingLibrarySymbol)
1127
1128 var unexportedSymbols = [
1129 'run',
1130 'addRunDependency',
1131 'removeRunDependency',
1132 'out',
1133 'err',
1134 'callMain',
1135 'abort',
1136 'wasmMemory',
1137 'wasmExports',
1138 'HEAPF32',
1139 'HEAPF64',
1140 'HEAP8',
1141 'HEAPU8',
1142 'HEAP16',
1143 'HEAPU16',
1144 'HEAP32',
1145 'HEAPU32',
1146 'HEAP64',
1147 'HEAPU64',
1148 'writeStackCookie',
1149 'checkStackCookie',
1150 'INT53_MAX',
1151 'INT53_MIN',
1152 'stackSave',
1153 'stackRestore',
1154 'ptrToString',
1155 'ENV',
1156 'ERRNO_CODES',
1157 'DNS',
1158 'Protocols',
1159 'Sockets',
1160 'timers',
1161 'warnOnce',
1162 'readEmAsmArgsArray',
1163 'wasmTable',
1164 'noExitRuntime',
1165 'addOnPreRun',
1166 'addOnPostRun',
1167 'freeTableIndexes',
1168 'functionsInTableMap',
1169 'setValue',
1170 'getValue',
1171 'PATH',
1172 'PATH_FS',
1173 'UTF8Decoder',
1174 'UTF16Decoder',
1175 'JSEvents',
1176 'specialHTMLTargets',
1177 'findCanvasEventTarget',
1178 'currentFullscreenStrategy',
1179 'restoreOldWindowedStyle',
1180 'UNWIND_CACHE',
1181 'ExitStatus',
1182 'emSetImmediate',
1183 'emClearImmediate_deps',
1184 'emClearImmediate',
1185 'promiseMap',
1186 'uncaughtExceptionCount',
1187 'exceptionLast',
1188 'exceptionCaught',
1189 'Browser',
1190 'requestFullscreen',
1191 'requestFullScreen',
1192 'setCanvasSize',
1193 'getUserMedia',
1194 'createContext',
1195 'getPreloadedImageData__data',
1196 'wget',
1197 'MONTH_DAYS_REGULAR',
1198 'MONTH_DAYS_LEAP',
1199 'MONTH_DAYS_REGULAR_CUMULATIVE',
1200 'MONTH_DAYS_LEAP_CUMULATIVE',
1201 'SYSCALLS',
1202 'preloadPlugins',
1203 'FS_stdin_getChar_buffer',
1204 'FS_unlink',
1205 'FS_createPath',
1206 'FS_createDevice',
1207 'FS_readFile',
1208 'FS',
1209 'FS_root',
1210 'FS_mounts',
1211 'FS_devices',
1212 'FS_streams',
1213 'FS_nextInode',
1214 'FS_nameTable',
1215 'FS_currentPath',
1216 'FS_initialized',
1217 'FS_ignorePermissions',
1218 'FS_filesystems',
1219 'FS_syncFSRequests',
1220 'FS_readFiles',
1221 'FS_lookupPath',
1222 'FS_getPath',
1223 'FS_hashName',
1224 'FS_hashAddNode',
1225 'FS_hashRemoveNode',
1226 'FS_lookupNode',
1227 'FS_createNode',
1228 'FS_destroyNode',
1229 'FS_isRoot',
1230 'FS_isMountpoint',
1231 'FS_isFile',
1232 'FS_isDir',
1233 'FS_isLink',
1234 'FS_isChrdev',
1235 'FS_isBlkdev',
1236 'FS_isFIFO',
1237 'FS_isSocket',
1238 'FS_flagsToPermissionString',
1239 'FS_nodePermissions',
1240 'FS_mayLookup',
1241 'FS_mayCreate',
1242 'FS_mayDelete',
1243 'FS_mayOpen',
1244 'FS_checkOpExists',
1245 'FS_nextfd',
1246 'FS_getStreamChecked',
1247 'FS_getStream',
1248 'FS_createStream',
1249 'FS_closeStream',
1250 'FS_dupStream',
1251 'FS_doSetAttr',
1252 'FS_chrdev_stream_ops',
1253 'FS_major',
1254 'FS_minor',
1255 'FS_makedev',
1256 'FS_registerDevice',
1257 'FS_getDevice',
1258 'FS_getMounts',
1259 'FS_syncfs',
1260 'FS_mount',
1261 'FS_unmount',
1262 'FS_lookup',
1263 'FS_mknod',
1264 'FS_statfs',
1265 'FS_statfsStream',
1266 'FS_statfsNode',
1267 'FS_create',
1268 'FS_mkdir',
1269 'FS_mkdev',
1270 'FS_symlink',
1271 'FS_rename',
1272 'FS_rmdir',
1273 'FS_readdir',
1274 'FS_readlink',
1275 'FS_stat',
1276 'FS_fstat',
1277 'FS_lstat',
1278 'FS_doChmod',
1279 'FS_chmod',
1280 'FS_lchmod',
1281 'FS_fchmod',
1282 'FS_doChown',
1283 'FS_chown',
1284 'FS_lchown',
1285 'FS_fchown',
1286 'FS_doTruncate',
1287 'FS_truncate',
1288 'FS_ftruncate',
1289 'FS_utime',
1290 'FS_open',
1291 'FS_close',
1292 'FS_isClosed',
1293 'FS_llseek',
1294 'FS_read',
1295 'FS_write',
1296 'FS_mmap',
1297 'FS_msync',
1298 'FS_ioctl',
1299 'FS_writeFile',
1300 'FS_cwd',
1301 'FS_chdir',
1302 'FS_createDefaultDirectories',
1303 'FS_createDefaultDevices',
1304 'FS_createSpecialDirectories',
1305 'FS_createStandardStreams',
1306 'FS_staticInit',
1307 'FS_init',
1308 'FS_quit',
1309 'FS_findObject',
1310 'FS_analyzePath',
1311 'FS_createFile',
1312 'FS_createDataFile',
1313 'FS_forceLoadFile',
1314 'FS_createLazyFile',
1315 'FS_absolutePath',
1316 'FS_createFolder',
1317 'FS_createLink',
1318 'FS_joinPath',
1319 'FS_mmapAlloc',
1320 'FS_standardizePath',
1321 'MEMFS',
1322 'TTY',
1323 'PIPEFS',
1324 'SOCKFS',
1325 'tempFixedLengthArray',
1326 'miniTempWebGLFloatBuffers',
1327 'miniTempWebGLIntBuffers',
1328 'GL',
1329 'AL',
1330 'GLUT',
1331 'EGL',
1332 'GLEW',
1333 'IDBStore',
1334 'SDL',
1335 'SDL_gfx',
1336 'allocateUTF8',
1337 'allocateUTF8OnStack',
1338 'print',
1339 'printErr',
1340 'jstoi_s',
1341];
1342unexportedSymbols.forEach(unexportedRuntimeSymbol);
1343
1344 // End runtime exports
1345 // Begin JS library exports
1346 // End JS library exports
1347
1348// end include: postlibrary.js
1349
1350function checkIncomingModuleAPI() {
1351 ignoredModuleProp('fetchSettings');
1352}
1353
1354// Imports from the Wasm binary.
1355var _sum = Module['_sum'] = makeInvalidEarlyAccess('_sum');
1356var _fflush = makeInvalidEarlyAccess('_fflush');
1357var _emscripten_stack_init = makeInvalidEarlyAccess('_emscripten_stack_init');
1358var _emscripten_stack_get_free = makeInvalidEarlyAccess('_emscripten_stack_get_free');
1359var _emscripten_stack_get_base = makeInvalidEarlyAccess('_emscripten_stack_get_base');
1360var _emscripten_stack_get_end = makeInvalidEarlyAccess('_emscripten_stack_get_end');
1361var __emscripten_stack_restore = makeInvalidEarlyAccess('__emscripten_stack_restore');
1362var __emscripten_stack_alloc = makeInvalidEarlyAccess('__emscripten_stack_alloc');
1363var _emscripten_stack_get_current = makeInvalidEarlyAccess('_emscripten_stack_get_current');
1364
1365function assignWasmExports(wasmExports) {
1366 Module['_sum'] = _sum = createExportWrapper('sum', 2);
1367 _fflush = createExportWrapper('fflush', 1);
1368 _emscripten_stack_init = wasmExports['emscripten_stack_init'];
1369 _emscripten_stack_get_free = wasmExports['emscripten_stack_get_free'];
1370 _emscripten_stack_get_base = wasmExports['emscripten_stack_get_base'];
1371 _emscripten_stack_get_end = wasmExports['emscripten_stack_get_end'];
1372 __emscripten_stack_restore = wasmExports['_emscripten_stack_restore'];
1373 __emscripten_stack_alloc = wasmExports['_emscripten_stack_alloc'];
1374 _emscripten_stack_get_current = wasmExports['emscripten_stack_get_current'];
1375}
1376var wasmImports = {
1377
1378};
1379var wasmExports = await createWasm();
1380
1381
1382// include: postamble.js
1383// === Auto-generated postamble setup entry stuff ===
1384
1385var calledRun;
1386
1387function stackCheckInit() {
1388 // This is normally called automatically during __wasm_call_ctors but need to
1389 // get these values before even running any of the ctors so we call it redundantly
1390 // here.
1391 _emscripten_stack_init();
1392 // TODO(sbc): Move writeStackCookie to native to to avoid this.
1393 writeStackCookie();
1394}
1395
1396function run() {
1397
1398 if (runDependencies > 0) {
1399 dependenciesFulfilled = run;
1400 return;
1401 }
1402
1403 stackCheckInit();
1404
1405 preRun();
1406
1407 // a preRun added a dependency, run will be called later
1408 if (runDependencies > 0) {
1409 dependenciesFulfilled = run;
1410 return;
1411 }
1412
1413 function doRun() {
1414 // run may have just been called through dependencies being fulfilled just in this very frame,
1415 // or while the async setStatus time below was happening
1416 assert(!calledRun);
1417 calledRun = true;
1418 Module['calledRun'] = true;
1419
1420 if (ABORT) return;
1421
1422 initRuntime();
1423
1424 readyPromiseResolve?.(Module);
1425 Module['onRuntimeInitialized']?.();
1426 consumedModuleProp('onRuntimeInitialized');
1427
1428 assert(!Module['_main'], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]');
1429
1430 postRun();
1431 }
1432
1433 if (Module['setStatus']) {
1434 Module['setStatus']('Running...');
1435 setTimeout(() => {
1436 setTimeout(() => Module['setStatus'](''), 1);
1437 doRun();
1438 }, 1);
1439 } else
1440 {
1441 doRun();
1442 }
1443 checkStackCookie();
1444}
1445
1446function checkUnflushedContent() {
1447 // Compiler settings do not allow exiting the runtime, so flushing
1448 // the streams is not possible. but in ASSERTIONS mode we check
1449 // if there was something to flush, and if so tell the user they
1450 // should request that the runtime be exitable.
1451 // Normally we would not even include flush() at all, but in ASSERTIONS
1452 // builds we do so just for this check, and here we see if there is any
1453 // content to flush, that is, we check if there would have been
1454 // something a non-ASSERTIONS build would have not seen.
1455 // How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0
1456 // mode (which has its own special function for this; otherwise, all
1457 // the code is inside libc)
1458 var oldOut = out;
1459 var oldErr = err;
1460 var has = false;
1461 out = err = (x) => {
1462 has = true;
1463 }
1464 try { // it doesn't matter if it fails
1465 _fflush(0);
1466 } catch(e) {}
1467 out = oldOut;
1468 err = oldErr;
1469 if (has) {
1470 warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the Emscripten FAQ), or make sure to emit a newline when you printf etc.');
1471 warnOnce('(this may also be due to not including full filesystem support - try building with -sFORCE_FILESYSTEM)');
1472 }
1473}
1474
1475function preInit() {
1476 if (Module['preInit']) {
1477 if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
1478 while (Module['preInit'].length > 0) {
1479 Module['preInit'].shift()();
1480 }
1481 }
1482 consumedModuleProp('preInit');
1483}
1484
1485preInit();
1486run();
1487
1488// end include: postamble.js
1489
1490// include: postamble_modularize.js
1491// In MODULARIZE mode we wrap the generated code in a factory function
1492// and return either the Module itself, or a promise of the module.
1493//
1494// We assign to the `moduleRtn` global here and configure closure to see
1495// this as and extern so it won't get minified.
1496
1497if (runtimeInitialized) {
1498 moduleRtn = Module;
1499} else {
1500 // Set up the promise that indicates the Module is initialized
1501 moduleRtn = new Promise((resolve, reject) => {
1502 readyPromiseResolve = resolve;
1503 readyPromiseReject = reject;
1504 });
1505}
1506
1507// Assertion for attempting to access module properties on the incoming
1508// moduleArg. In the past we used this object as the prototype of the module
1509// and assigned properties to it, but now we return a distinct object. This
1510// keeps the instance private until it is ready (i.e the promise has been
1511// resolved).
1512for (const prop of Object.keys(Module)) {
1513 if (!(prop in moduleArg)) {
1514 Object.defineProperty(moduleArg, prop, {
1515 configurable: true,
1516 get() {
1517 abort(`Access to module property ('${prop}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`)
1518 }
1519 });
1520 }
1521}
1522// end include: postamble_modularize.js
1523
1524
1525
1526 return moduleRtn;
1527}
1528
1529// Export using a UMD style export, or ES6 exports if selected
1530export default SumLibrary;
1531
diff --git a/src/talks/wasm/examples/2-sum/sum_library.wasm b/src/talks/wasm/examples/2-sum/sum_library.wasm
new file mode 100755
index 0000000..f3d3cc0
--- /dev/null
+++ b/src/talks/wasm/examples/2-sum/sum_library.wasm
Binary files differ

Generated with cgit - Back to sebastiano.tronto.net