· 6 years ago · Aug 13, 2019, 03:00 AM
1// Copyright 2010 The Emscripten Authors. All rights reserved.
2// Emscripten is available under two separate licenses, the MIT license and the
3// University of Illinois/NCSA Open Source License. Both these licenses can be
4// found in the LICENSE file.
5
6// The Module object: Our interface to the outside world. We import
7// and export values on it. There are various ways Module can be used:
8// 1. Not defined. We create it here
9// 2. A function parameter, function(Module) { ..generated code.. }
10// 3. pre-run appended it, var Module = {}; ..generated code..
11// 4. External script tag defines var Module.
12// We need to check if Module already exists (e.g. case 3 above).
13// Substitution will be replaced with actual code on later stage of the build,
14// this way Closure Compiler will not mangle it (e.g. case 4. above).
15// Note that if you want to run closure, and also to use Module
16// after the generated code, you will need to define var Module = {};
17// before the code. Then that object will be used in the code, and you
18// can continue to use Module afterwards as well.
19var Module = typeof Module !== 'undefined' ? Module : {};
20
21// --pre-jses are emitted after the Module integration code, so that they can
22// refer to Module (if they choose; they can also define Module)
23// {{PRE_JSES}}
24
25// Sometimes an existing Module object exists with properties
26// meant to overwrite the default module functionality. Here
27// we collect those properties and reapply _after_ we configure
28// the current environment's defaults to avoid having to be so
29// defensive during initialization.
30var moduleOverrides = {};
31var key;
32for (key in Module) {
33 if (Module.hasOwnProperty(key)) {
34 moduleOverrides[key] = Module[key];
35 }
36}
37
38var arguments_ = [];
39var thisProgram = './this.program';
40var quit_ = function(status, toThrow) {
41 throw toThrow;
42};
43
44// Determine the runtime environment we are in. You can customize this by
45// setting the ENVIRONMENT setting at compile time (see settings.js).
46
47var ENVIRONMENT_IS_WEB = false;
48var ENVIRONMENT_IS_WORKER = false;
49var ENVIRONMENT_IS_NODE = false;
50var ENVIRONMENT_HAS_NODE = false;
51var ENVIRONMENT_IS_SHELL = false;
52ENVIRONMENT_IS_WEB = typeof window === 'object';
53ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
54// A web environment like Electron.js can have Node enabled, so we must
55// distinguish between Node-enabled environments and Node environments per se.
56// This will allow the former to do things like mount NODEFS.
57// Extended check using process.versions fixes issue #8816.
58// (Also makes redundant the original check that 'require' is a function.)
59ENVIRONMENT_HAS_NODE = typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string';
60ENVIRONMENT_IS_NODE = ENVIRONMENT_HAS_NODE && !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER;
61ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
62
63if (Module['ENVIRONMENT']) {
64 throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -s ENVIRONMENT=web or -s ENVIRONMENT=node)');
65}
66
67
68// Three configurations we can be running in:
69// 1) We could be the application main() thread running in the main JS UI thread. (ENVIRONMENT_IS_WORKER == false and ENVIRONMENT_IS_PTHREAD == false)
70// 2) We could be the application main() thread proxied to worker. (with Emscripten -s PROXY_TO_WORKER=1) (ENVIRONMENT_IS_WORKER == true, ENVIRONMENT_IS_PTHREAD == false)
71// 3) We could be an application pthread running in a worker. (ENVIRONMENT_IS_WORKER == true and ENVIRONMENT_IS_PTHREAD == true)
72
73
74
75
76// `/` should be present at the end if `scriptDirectory` is not empty
77var scriptDirectory = '';
78function locateFile(path) {
79 if (Module['locateFile']) {
80 return Module['locateFile'](path, scriptDirectory);
81 }
82 return scriptDirectory + path;
83}
84
85// Hooks that are implemented differently in different runtime environments.
86var read_,
87 readAsync,
88 readBinary,
89 setWindowTitle;
90
91if (ENVIRONMENT_IS_NODE) {
92 scriptDirectory = __dirname + '/';
93
94 // Expose functionality in the same simple way that the shells work
95 // Note that we pollute the global namespace here, otherwise we break in node
96 var nodeFS;
97 var nodePath;
98
99 read_ = function shell_read(filename, binary) {
100 var ret;
101 if (!nodeFS) nodeFS = require('fs');
102 if (!nodePath) nodePath = require('path');
103 filename = nodePath['normalize'](filename);
104 ret = nodeFS['readFileSync'](filename);
105 return binary ? ret : ret.toString();
106 };
107
108 readBinary = function readBinary(filename) {
109 var ret = read_(filename, true);
110 if (!ret.buffer) {
111 ret = new Uint8Array(ret);
112 }
113 assert(ret.buffer);
114 return ret;
115 };
116
117 if (process['argv'].length > 1) {
118 thisProgram = process['argv'][1].replace(/\\/g, '/');
119 }
120
121 arguments_ = process['argv'].slice(2);
122
123 if (typeof module !== 'undefined') {
124 module['exports'] = Module;
125 }
126
127 process['on']('uncaughtException', function(ex) {
128 // suppress ExitStatus exceptions from showing an error
129 if (!(ex instanceof ExitStatus)) {
130 throw ex;
131 }
132 });
133
134 process['on']('unhandledRejection', abort);
135
136 quit_ = function(status) {
137 process['exit'](status);
138 };
139
140 Module['inspect'] = function () { return '[Emscripten Module object]'; };
141} else
142if (ENVIRONMENT_IS_SHELL) {
143
144
145 if (typeof read != 'undefined') {
146 read_ = function shell_read(f) {
147 return read(f);
148 };
149 }
150
151 readBinary = function readBinary(f) {
152 var data;
153 if (typeof readbuffer === 'function') {
154 return new Uint8Array(readbuffer(f));
155 }
156 data = read(f, 'binary');
157 assert(typeof data === 'object');
158 return data;
159 };
160
161 if (typeof scriptArgs != 'undefined') {
162 arguments_ = scriptArgs;
163 } else if (typeof arguments != 'undefined') {
164 arguments_ = arguments;
165 }
166
167 if (typeof quit === 'function') {
168 quit_ = function(status) {
169 quit(status);
170 };
171 }
172
173 if (typeof print !== 'undefined') {
174 // Prefer to use print/printErr where they exist, as they usually work better.
175 if (typeof console === 'undefined') console = {};
176 console.log = print;
177 console.warn = console.error = typeof printErr !== 'undefined' ? printErr : print;
178 }
179} else
180if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
181 if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled
182 scriptDirectory = self.location.href;
183 } else if (document.currentScript) { // web
184 scriptDirectory = document.currentScript.src;
185 }
186 // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
187 // otherwise, slice off the final part of the url to find the script directory.
188 // if scriptDirectory does not contain a slash, lastIndexOf will return -1,
189 // and scriptDirectory will correctly be replaced with an empty string.
190 if (scriptDirectory.indexOf('blob:') !== 0) {
191 scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf('/')+1);
192 } else {
193 scriptDirectory = '';
194 }
195
196
197 read_ = function shell_read(url) {
198 var xhr = new XMLHttpRequest();
199 xhr.open('GET', url, false);
200 xhr.send(null);
201 return xhr.responseText;
202 };
203
204 if (ENVIRONMENT_IS_WORKER) {
205 readBinary = function readBinary(url) {
206 var xhr = new XMLHttpRequest();
207 xhr.open('GET', url, false);
208 xhr.responseType = 'arraybuffer';
209 xhr.send(null);
210 return new Uint8Array(xhr.response);
211 };
212 }
213
214 readAsync = function readAsync(url, onload, onerror) {
215 var xhr = new XMLHttpRequest();
216 xhr.open('GET', url, true);
217 xhr.responseType = 'arraybuffer';
218 xhr.onload = function xhr_onload() {
219 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
220 onload(xhr.response);
221 return;
222 }
223 onerror();
224 };
225 xhr.onerror = onerror;
226 xhr.send(null);
227 };
228
229 setWindowTitle = function(title) { document.title = title };
230} else
231{
232 throw new Error('environment detection error');
233}
234
235// Set up the out() and err() hooks, which are how we can print to stdout or
236// stderr, respectively.
237var out = Module['print'] || console.log.bind(console);
238var err = Module['printErr'] || console.warn.bind(console);
239
240// Merge back in the overrides
241for (key in moduleOverrides) {
242 if (moduleOverrides.hasOwnProperty(key)) {
243 Module[key] = moduleOverrides[key];
244 }
245}
246// Free the object hierarchy contained in the overrides, this lets the GC
247// reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
248moduleOverrides = null;
249
250// Emit code to handle expected values on the Module object. This applies Module.x
251// to the proper local x. This has two benefits: first, we only emit it if it is
252// expected to arrive, and second, by using a local everywhere else that can be
253// minified.
254if (Module['arguments']) arguments_ = Module['arguments'];if (!Object.getOwnPropertyDescriptor(Module, 'arguments')) Object.defineProperty(Module, 'arguments', { get: function() { abort('Module.arguments has been replaced with plain arguments_') } });
255if (Module['thisProgram']) thisProgram = Module['thisProgram'];if (!Object.getOwnPropertyDescriptor(Module, 'thisProgram')) Object.defineProperty(Module, 'thisProgram', { get: function() { abort('Module.thisProgram has been replaced with plain thisProgram') } });
256if (Module['quit']) quit_ = Module['quit'];if (!Object.getOwnPropertyDescriptor(Module, 'quit')) Object.defineProperty(Module, 'quit', { get: function() { abort('Module.quit has been replaced with plain quit_') } });
257
258// perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
259// Assertions on removed incoming Module JS APIs.
260assert(typeof Module['memoryInitializerPrefixURL'] === 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
261assert(typeof Module['pthreadMainPrefixURL'] === 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
262assert(typeof Module['cdInitializerPrefixURL'] === 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
263assert(typeof Module['filePackagePrefixURL'] === 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
264assert(typeof Module['read'] === 'undefined', 'Module.read option was removed (modify read_ in JS)');
265assert(typeof Module['readAsync'] === 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
266assert(typeof Module['readBinary'] === 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
267assert(typeof Module['setWindowTitle'] === 'undefined', 'Module.setWindowTitle option was removed (modify setWindowTitle in JS)');
268if (!Object.getOwnPropertyDescriptor(Module, 'read')) Object.defineProperty(Module, 'read', { get: function() { abort('Module.read has been replaced with plain read_') } });
269if (!Object.getOwnPropertyDescriptor(Module, 'readAsync')) Object.defineProperty(Module, 'readAsync', { get: function() { abort('Module.readAsync has been replaced with plain readAsync') } });
270if (!Object.getOwnPropertyDescriptor(Module, 'readBinary')) Object.defineProperty(Module, 'readBinary', { get: function() { abort('Module.readBinary has been replaced with plain readBinary') } });
271// TODO: add when SDL2 is fixed if (!Object.getOwnPropertyDescriptor(Module, 'setWindowTitle')) Object.defineProperty(Module, 'setWindowTitle', { get: function() { abort('Module.setWindowTitle has been replaced with plain setWindowTitle') } });
272
273
274// TODO remove when SDL2 is fixed (also see above)
275
276
277
278// Copyright 2017 The Emscripten Authors. All rights reserved.
279// Emscripten is available under two separate licenses, the MIT license and the
280// University of Illinois/NCSA Open Source License. Both these licenses can be
281// found in the LICENSE file.
282
283// {{PREAMBLE_ADDITIONS}}
284
285var STACK_ALIGN = 16;
286
287// stack management, and other functionality that is provided by the compiled code,
288// should not be used before it is ready
289stackSave = stackRestore = stackAlloc = function() {
290 abort('cannot use the stack before compiled code is ready to run, and has provided stack access');
291};
292
293function staticAlloc(size) {
294 abort('staticAlloc is no longer available at runtime; instead, perform static allocations at compile time (using makeStaticAlloc)');
295}
296
297function dynamicAlloc(size) {
298 assert(DYNAMICTOP_PTR);
299 var ret = HEAP32[DYNAMICTOP_PTR>>2];
300 var end = (ret + size + 15) & -16;
301 if (end > _emscripten_get_heap_size()) {
302 abort('failure to dynamicAlloc - memory growth etc. is not supported there, call malloc/sbrk directly');
303 }
304 HEAP32[DYNAMICTOP_PTR>>2] = end;
305 return ret;
306}
307
308function alignMemory(size, factor) {
309 if (!factor) factor = STACK_ALIGN; // stack alignment (16-byte) by default
310 return Math.ceil(size / factor) * factor;
311}
312
313function getNativeTypeSize(type) {
314 switch (type) {
315 case 'i1': case 'i8': return 1;
316 case 'i16': return 2;
317 case 'i32': return 4;
318 case 'i64': return 8;
319 case 'float': return 4;
320 case 'double': return 8;
321 default: {
322 if (type[type.length-1] === '*') {
323 return 4; // A pointer
324 } else if (type[0] === 'i') {
325 var bits = parseInt(type.substr(1));
326 assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type);
327 return bits / 8;
328 } else {
329 return 0;
330 }
331 }
332 }
333}
334
335function warnOnce(text) {
336 if (!warnOnce.shown) warnOnce.shown = {};
337 if (!warnOnce.shown[text]) {
338 warnOnce.shown[text] = 1;
339 err(text);
340 }
341}
342
343var asm2wasmImports = { // special asm2wasm imports
344 "f64-rem": function(x, y) {
345 return x % y;
346 },
347 "debugger": function() {
348 debugger;
349 }
350};
351
352
353
354var jsCallStartIndex = 1;
355var functionPointers = new Array(0);
356
357// Wraps a JS function as a wasm function with a given signature.
358// In the future, we may get a WebAssembly.Function constructor. Until then,
359// we create a wasm module that takes the JS function as an import with a given
360// signature, and re-exports that as a wasm function.
361function convertJsFunctionToWasm(func, sig) {
362
363 // The module is static, with the exception of the type section, which is
364 // generated based on the signature passed in.
365 var typeSection = [
366 0x01, // id: section,
367 0x00, // length: 0 (placeholder)
368 0x01, // count: 1
369 0x60, // form: func
370 ];
371 var sigRet = sig.slice(0, 1);
372 var sigParam = sig.slice(1);
373 var typeCodes = {
374 'i': 0x7f, // i32
375 'j': 0x7e, // i64
376 'f': 0x7d, // f32
377 'd': 0x7c, // f64
378 };
379
380 // Parameters, length + signatures
381 typeSection.push(sigParam.length);
382 for (var i = 0; i < sigParam.length; ++i) {
383 typeSection.push(typeCodes[sigParam[i]]);
384 }
385
386 // Return values, length + signatures
387 // With no multi-return in MVP, either 0 (void) or 1 (anything else)
388 if (sigRet == 'v') {
389 typeSection.push(0x00);
390 } else {
391 typeSection = typeSection.concat([0x01, typeCodes[sigRet]]);
392 }
393
394 // Write the overall length of the type section back into the section header
395 // (excepting the 2 bytes for the section id and length)
396 typeSection[1] = typeSection.length - 2;
397
398 // Rest of the module is static
399 var bytes = new Uint8Array([
400 0x00, 0x61, 0x73, 0x6d, // magic ("\0asm")
401 0x01, 0x00, 0x00, 0x00, // version: 1
402 ].concat(typeSection, [
403 0x02, 0x07, // import section
404 // (import "e" "f" (func 0 (type 0)))
405 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
406 0x07, 0x05, // export section
407 // (export "f" (func 0 (type 0)))
408 0x01, 0x01, 0x66, 0x00, 0x00,
409 ]));
410
411 // We can compile this wasm module synchronously because it is very small.
412 // This accepts an import (at "e.f"), that it reroutes to an export (at "f")
413 var module = new WebAssembly.Module(bytes);
414 var instance = new WebAssembly.Instance(module, {
415 e: {
416 f: func
417 }
418 });
419 var wrappedFunc = instance.exports.f;
420 return wrappedFunc;
421}
422
423// Add a wasm function to the table.
424function addFunctionWasm(func, sig) {
425 var table = wasmTable;
426 var ret = table.length;
427
428 // Grow the table
429 try {
430 table.grow(1);
431 } catch (err) {
432 if (!err instanceof RangeError) {
433 throw err;
434 }
435 throw 'Unable to grow wasm table. Use a higher value for RESERVED_FUNCTION_POINTERS or set ALLOW_TABLE_GROWTH.';
436 }
437
438 // Insert new element
439 try {
440 // Attempting to call this with JS function will cause of table.set() to fail
441 table.set(ret, func);
442 } catch (err) {
443 if (!err instanceof TypeError) {
444 throw err;
445 }
446 assert(typeof sig !== 'undefined', 'Missing signature argument to addFunction');
447 var wrapped = convertJsFunctionToWasm(func, sig);
448 table.set(ret, wrapped);
449 }
450
451 return ret;
452}
453
454function removeFunctionWasm(index) {
455 // TODO(sbc): Look into implementing this to allow re-using of table slots
456}
457
458// 'sig' parameter is required for the llvm backend but only when func is not
459// already a WebAssembly function.
460function addFunction(func, sig) {
461
462
463 var base = 0;
464 for (var i = base; i < base + 0; i++) {
465 if (!functionPointers[i]) {
466 functionPointers[i] = func;
467 return jsCallStartIndex + i;
468 }
469 }
470 throw 'Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.';
471
472}
473
474function removeFunction(index) {
475
476 functionPointers[index-jsCallStartIndex] = null;
477}
478
479var funcWrappers = {};
480
481function getFuncWrapper(func, sig) {
482 if (!func) return; // on null pointer, return undefined
483 assert(sig);
484 if (!funcWrappers[sig]) {
485 funcWrappers[sig] = {};
486 }
487 var sigCache = funcWrappers[sig];
488 if (!sigCache[func]) {
489 // optimize away arguments usage in common cases
490 if (sig.length === 1) {
491 sigCache[func] = function dynCall_wrapper() {
492 return dynCall(sig, func);
493 };
494 } else if (sig.length === 2) {
495 sigCache[func] = function dynCall_wrapper(arg) {
496 return dynCall(sig, func, [arg]);
497 };
498 } else {
499 // general case
500 sigCache[func] = function dynCall_wrapper() {
501 return dynCall(sig, func, Array.prototype.slice.call(arguments));
502 };
503 }
504 }
505 return sigCache[func];
506}
507
508
509function makeBigInt(low, high, unsigned) {
510 return unsigned ? ((+((low>>>0)))+((+((high>>>0)))*4294967296.0)) : ((+((low>>>0)))+((+((high|0)))*4294967296.0));
511}
512
513function dynCall(sig, ptr, args) {
514 if (args && args.length) {
515 assert(args.length == sig.length-1);
516 assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
517 return Module['dynCall_' + sig].apply(null, [ptr].concat(args));
518 } else {
519 assert(sig.length == 1);
520 assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
521 return Module['dynCall_' + sig].call(null, ptr);
522 }
523}
524
525var tempRet0 = 0;
526
527var setTempRet0 = function(value) {
528 tempRet0 = value;
529};
530
531var getTempRet0 = function() {
532 return tempRet0;
533};
534
535function getCompilerSetting(name) {
536 throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for getCompilerSetting or emscripten_get_compiler_setting to work';
537}
538
539var Runtime = {
540 // helpful errors
541 getTempRet0: function() { abort('getTempRet0() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
542 staticAlloc: function() { abort('staticAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
543 stackAlloc: function() { abort('stackAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
544};
545
546// The address globals begin at. Very low in memory, for code size and optimization opportunities.
547// Above 0 is static memory, starting with globals.
548// Then the stack.
549// Then 'dynamic' memory for sbrk.
550var GLOBAL_BASE = 1024;
551
552
553
554
555// === Preamble library stuff ===
556
557// Documentation for the public APIs defined in this file must be updated in:
558// site/source/docs/api_reference/preamble.js.rst
559// A prebuilt local version of the documentation is available at:
560// site/build/text/docs/api_reference/preamble.js.txt
561// You can also build docs locally as HTML or other formats in site/
562// An online HTML version (which may be of a different version of Emscripten)
563// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
564
565
566var wasmBinary;if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];if (!Object.getOwnPropertyDescriptor(Module, 'wasmBinary')) Object.defineProperty(Module, 'wasmBinary', { get: function() { abort('Module.wasmBinary has been replaced with plain wasmBinary') } });
567
568
569if (typeof WebAssembly !== 'object') {
570 abort('No WebAssembly support found. Build with -s WASM=0 to target JavaScript instead.');
571}
572
573
574// In MINIMAL_RUNTIME, setValue() and getValue() are only available when building with safe heap enabled, for heap safety checking.
575// In traditional runtime, setValue() and getValue() are always available (although their use is highly discouraged due to perf penalties)
576
577/** @type {function(number, number, string, boolean=)} */
578function setValue(ptr, value, type, noSafe) {
579 type = type || 'i8';
580 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
581 switch(type) {
582 case 'i1': HEAP8[((ptr)>>0)]=value; break;
583 case 'i8': HEAP8[((ptr)>>0)]=value; break;
584 case 'i16': HEAP16[((ptr)>>1)]=value; break;
585 case 'i32': HEAP32[((ptr)>>2)]=value; break;
586 case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math_abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math_min((+(Math_floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((ptr)>>2)]=tempI64[0],HEAP32[(((ptr)+(4))>>2)]=tempI64[1]); break;
587 case 'float': HEAPF32[((ptr)>>2)]=value; break;
588 case 'double': HEAPF64[((ptr)>>3)]=value; break;
589 default: abort('invalid type for setValue: ' + type);
590 }
591}
592
593/** @type {function(number, string, boolean=)} */
594function getValue(ptr, type, noSafe) {
595 type = type || 'i8';
596 if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
597 switch(type) {
598 case 'i1': return HEAP8[((ptr)>>0)];
599 case 'i8': return HEAP8[((ptr)>>0)];
600 case 'i16': return HEAP16[((ptr)>>1)];
601 case 'i32': return HEAP32[((ptr)>>2)];
602 case 'i64': return HEAP32[((ptr)>>2)];
603 case 'float': return HEAPF32[((ptr)>>2)];
604 case 'double': return HEAPF64[((ptr)>>3)];
605 default: abort('invalid type for getValue: ' + type);
606 }
607 return null;
608}
609
610
611
612
613
614// Wasm globals
615
616var wasmMemory;
617
618// Potentially used for direct table calls.
619var wasmTable;
620
621
622//========================================
623// Runtime essentials
624//========================================
625
626// whether we are quitting the application. no code should run after this.
627// set in exit() and abort()
628var ABORT = false;
629
630// set by exit() and abort(). Passed to 'onExit' handler.
631// NOTE: This is also used as the process return code code in shell environments
632// but only when noExitRuntime is false.
633var EXITSTATUS = 0;
634
635/** @type {function(*, string=)} */
636function assert(condition, text) {
637 if (!condition) {
638 abort('Assertion failed: ' + text);
639 }
640}
641
642// Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
643function getCFunc(ident) {
644 var func = Module['_' + ident]; // closure exported function
645 assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported');
646 return func;
647}
648
649// C calling interface.
650function ccall(ident, returnType, argTypes, args, opts) {
651 // For fast lookup of conversion functions
652 var toC = {
653 'string': function(str) {
654 var ret = 0;
655 if (str !== null && str !== undefined && str !== 0) { // null string
656 // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
657 var len = (str.length << 2) + 1;
658 ret = stackAlloc(len);
659 stringToUTF8(str, ret, len);
660 }
661 return ret;
662 },
663 'array': function(arr) {
664 var ret = stackAlloc(arr.length);
665 writeArrayToMemory(arr, ret);
666 return ret;
667 }
668 };
669
670 function convertReturnValue(ret) {
671 if (returnType === 'string') return UTF8ToString(ret);
672 if (returnType === 'boolean') return Boolean(ret);
673 return ret;
674 }
675
676 var func = getCFunc(ident);
677 var cArgs = [];
678 var stack = 0;
679 assert(returnType !== 'array', 'Return type should not be "array".');
680 if (args) {
681 for (var i = 0; i < args.length; i++) {
682 var converter = toC[argTypes[i]];
683 if (converter) {
684 if (stack === 0) stack = stackSave();
685 cArgs[i] = converter(args[i]);
686 } else {
687 cArgs[i] = args[i];
688 }
689 }
690 }
691 var ret = func.apply(null, cArgs);
692 assert(!(opts && opts.async), 'async call is only supported with Emterpretify for now, see #9029');
693
694 ret = convertReturnValue(ret);
695 if (stack !== 0) stackRestore(stack);
696 return ret;
697}
698
699function cwrap(ident, returnType, argTypes, opts) {
700 return function() {
701 return ccall(ident, returnType, argTypes, arguments, opts);
702 }
703}
704
705var ALLOC_NORMAL = 0; // Tries to use _malloc()
706var ALLOC_STACK = 1; // Lives for the duration of the current function call
707var ALLOC_DYNAMIC = 2; // Cannot be freed except through sbrk
708var ALLOC_NONE = 3; // Do not allocate
709
710// allocate(): This is for internal use. You can use it yourself as well, but the interface
711// is a little tricky (see docs right below). The reason is that it is optimized
712// for multiple syntaxes to save space in generated code. So you should
713// normally not use allocate(), and instead allocate memory using _malloc(),
714// initialize it with setValue(), and so forth.
715// @slab: An array of data, or a number. If a number, then the size of the block to allocate,
716// in *bytes* (note that this is sometimes confusing: the next parameter does not
717// affect this!)
718// @types: Either an array of types, one for each byte (or 0 if no type at that position),
719// or a single type which is used for the entire block. This only matters if there
720// is initial data - if @slab is a number, then this does not matter at all and is
721// ignored.
722// @allocator: How to allocate memory, see ALLOC_*
723/** @type {function((TypedArray|Array<number>|number), string, number, number=)} */
724function allocate(slab, types, allocator, ptr) {
725 var zeroinit, size;
726 if (typeof slab === 'number') {
727 zeroinit = true;
728 size = slab;
729 } else {
730 zeroinit = false;
731 size = slab.length;
732 }
733
734 var singleType = typeof types === 'string' ? types : null;
735
736 var ret;
737 if (allocator == ALLOC_NONE) {
738 ret = ptr;
739 } else {
740 ret = [_malloc,
741 stackAlloc,
742 dynamicAlloc][allocator](Math.max(size, singleType ? 1 : types.length));
743 }
744
745 if (zeroinit) {
746 var stop;
747 ptr = ret;
748 assert((ret & 3) == 0);
749 stop = ret + (size & ~3);
750 for (; ptr < stop; ptr += 4) {
751 HEAP32[((ptr)>>2)]=0;
752 }
753 stop = ret + size;
754 while (ptr < stop) {
755 HEAP8[((ptr++)>>0)]=0;
756 }
757 return ret;
758 }
759
760 if (singleType === 'i8') {
761 if (slab.subarray || slab.slice) {
762 HEAPU8.set(/** @type {!Uint8Array} */ (slab), ret);
763 } else {
764 HEAPU8.set(new Uint8Array(slab), ret);
765 }
766 return ret;
767 }
768
769 var i = 0, type, typeSize, previousType;
770 while (i < size) {
771 var curr = slab[i];
772
773 type = singleType || types[i];
774 if (type === 0) {
775 i++;
776 continue;
777 }
778 assert(type, 'Must know what type to store in allocate!');
779
780 if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
781
782 setValue(ret+i, curr, type);
783
784 // no need to look up size unless type changes, so cache it
785 if (previousType !== type) {
786 typeSize = getNativeTypeSize(type);
787 previousType = type;
788 }
789 i += typeSize;
790 }
791
792 return ret;
793}
794
795// Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready
796function getMemory(size) {
797 if (!runtimeInitialized) return dynamicAlloc(size);
798 return _malloc(size);
799}
800
801
802
803
804/** @type {function(number, number=)} */
805function Pointer_stringify(ptr, length) {
806 abort("this function has been removed - you should use UTF8ToString(ptr, maxBytesToRead) instead!");
807}
808
809// Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns
810// a copy of that string as a Javascript String object.
811
812function AsciiToString(ptr) {
813 var str = '';
814 while (1) {
815 var ch = HEAPU8[((ptr++)>>0)];
816 if (!ch) return str;
817 str += String.fromCharCode(ch);
818 }
819}
820
821// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
822// null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP.
823
824function stringToAscii(str, outPtr) {
825 return writeAsciiToMemory(str, outPtr, false);
826}
827
828
829// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns
830// a copy of that string as a Javascript String object.
831
832var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
833
834/**
835 * @param {number} idx
836 * @param {number=} maxBytesToRead
837 * @return {string}
838 */
839function UTF8ArrayToString(u8Array, idx, maxBytesToRead) {
840 var endIdx = idx + maxBytesToRead;
841 var endPtr = idx;
842 // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
843 // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
844 // (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity)
845 while (u8Array[endPtr] && !(endPtr >= endIdx)) ++endPtr;
846
847 if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) {
848 return UTF8Decoder.decode(u8Array.subarray(idx, endPtr));
849 } else {
850 var str = '';
851 // If building with TextDecoder, we have already computed the string length above, so test loop end condition against that
852 while (idx < endPtr) {
853 // For UTF8 byte structure, see:
854 // http://en.wikipedia.org/wiki/UTF-8#Description
855 // https://www.ietf.org/rfc/rfc2279.txt
856 // https://tools.ietf.org/html/rfc3629
857 var u0 = u8Array[idx++];
858 if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
859 var u1 = u8Array[idx++] & 63;
860 if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
861 var u2 = u8Array[idx++] & 63;
862 if ((u0 & 0xF0) == 0xE0) {
863 u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
864 } else {
865 if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte 0x' + u0.toString(16) + ' encountered when deserializing a UTF-8 string on the asm.js/wasm heap to a JS string!');
866 u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (u8Array[idx++] & 63);
867 }
868
869 if (u0 < 0x10000) {
870 str += String.fromCharCode(u0);
871 } else {
872 var ch = u0 - 0x10000;
873 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
874 }
875 }
876 }
877 return str;
878}
879
880// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a
881// copy of that string as a Javascript String object.
882// maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit
883// this parameter to scan the string until the first \0 byte. If maxBytesToRead is
884// passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the
885// middle, then the string will cut short at that byte index (i.e. maxBytesToRead will
886// not produce a string of exact length [ptr, ptr+maxBytesToRead[)
887// N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may
888// throw JS JIT optimizations off, so it is worth to consider consistently using one
889// style or the other.
890/**
891 * @param {number} ptr
892 * @param {number=} maxBytesToRead
893 * @return {string}
894 */
895function UTF8ToString(ptr, maxBytesToRead) {
896 return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
897}
898
899// Copies the given Javascript String object 'str' to the given byte array at address 'outIdx',
900// encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP.
901// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
902// Parameters:
903// str: the Javascript string to copy.
904// outU8Array: the array to copy to. Each index in this array is assumed to be one 8-byte element.
905// outIdx: The starting offset in the array to begin the copying.
906// maxBytesToWrite: The maximum number of bytes this function can write to the array.
907// This count should include the null terminator,
908// i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else.
909// maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator.
910// Returns the number of bytes written, EXCLUDING the null terminator.
911
912function stringToUTF8Array(str, outU8Array, outIdx, maxBytesToWrite) {
913 if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes.
914 return 0;
915
916 var startIdx = outIdx;
917 var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
918 for (var i = 0; i < str.length; ++i) {
919 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
920 // See http://unicode.org/faq/utf_bom.html#utf16-3
921 // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
922 var u = str.charCodeAt(i); // possibly a lead surrogate
923 if (u >= 0xD800 && u <= 0xDFFF) {
924 var u1 = str.charCodeAt(++i);
925 u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF);
926 }
927 if (u <= 0x7F) {
928 if (outIdx >= endIdx) break;
929 outU8Array[outIdx++] = u;
930 } else if (u <= 0x7FF) {
931 if (outIdx + 1 >= endIdx) break;
932 outU8Array[outIdx++] = 0xC0 | (u >> 6);
933 outU8Array[outIdx++] = 0x80 | (u & 63);
934 } else if (u <= 0xFFFF) {
935 if (outIdx + 2 >= endIdx) break;
936 outU8Array[outIdx++] = 0xE0 | (u >> 12);
937 outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
938 outU8Array[outIdx++] = 0x80 | (u & 63);
939 } else {
940 if (outIdx + 3 >= endIdx) break;
941 if (u >= 0x200000) warnOnce('Invalid Unicode code point 0x' + u.toString(16) + ' encountered when serializing a JS string to an UTF-8 string on the asm.js/wasm heap! (Valid unicode code points should be in range 0-0x1FFFFF).');
942 outU8Array[outIdx++] = 0xF0 | (u >> 18);
943 outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
944 outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
945 outU8Array[outIdx++] = 0x80 | (u & 63);
946 }
947 }
948 // Null-terminate the pointer to the buffer.
949 outU8Array[outIdx] = 0;
950 return outIdx - startIdx;
951}
952
953// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
954// null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP.
955// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
956// Returns the number of bytes written, EXCLUDING the null terminator.
957
958function stringToUTF8(str, outPtr, maxBytesToWrite) {
959 assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
960 return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite);
961}
962
963// Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte.
964function lengthBytesUTF8(str) {
965 var len = 0;
966 for (var i = 0; i < str.length; ++i) {
967 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
968 // See http://unicode.org/faq/utf_bom.html#utf16-3
969 var u = str.charCodeAt(i); // possibly a lead surrogate
970 if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
971 if (u <= 0x7F) ++len;
972 else if (u <= 0x7FF) len += 2;
973 else if (u <= 0xFFFF) len += 3;
974 else len += 4;
975 }
976 return len;
977}
978
979
980// Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
981// a copy of that string as a Javascript String object.
982
983var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
984function UTF16ToString(ptr) {
985 assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!');
986 var endPtr = ptr;
987 // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
988 // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
989 var idx = endPtr >> 1;
990 while (HEAP16[idx]) ++idx;
991 endPtr = idx << 1;
992
993 if (endPtr - ptr > 32 && UTF16Decoder) {
994 return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
995 } else {
996 var i = 0;
997
998 var str = '';
999 while (1) {
1000 var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
1001 if (codeUnit == 0) return str;
1002 ++i;
1003 // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
1004 str += String.fromCharCode(codeUnit);
1005 }
1006 }
1007}
1008
1009// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
1010// null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP.
1011// Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write.
1012// Parameters:
1013// str: the Javascript string to copy.
1014// outPtr: Byte address in Emscripten HEAP where to write the string to.
1015// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
1016// terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else.
1017// maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator.
1018// Returns the number of bytes written, EXCLUDING the null terminator.
1019
1020function stringToUTF16(str, outPtr, maxBytesToWrite) {
1021 assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
1022 assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
1023 // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
1024 if (maxBytesToWrite === undefined) {
1025 maxBytesToWrite = 0x7FFFFFFF;
1026 }
1027 if (maxBytesToWrite < 2) return 0;
1028 maxBytesToWrite -= 2; // Null terminator.
1029 var startPtr = outPtr;
1030 var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
1031 for (var i = 0; i < numCharsToWrite; ++i) {
1032 // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
1033 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
1034 HEAP16[((outPtr)>>1)]=codeUnit;
1035 outPtr += 2;
1036 }
1037 // Null-terminate the pointer to the HEAP.
1038 HEAP16[((outPtr)>>1)]=0;
1039 return outPtr - startPtr;
1040}
1041
1042// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
1043
1044function lengthBytesUTF16(str) {
1045 return str.length*2;
1046}
1047
1048function UTF32ToString(ptr) {
1049 assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!');
1050 var i = 0;
1051
1052 var str = '';
1053 while (1) {
1054 var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
1055 if (utf32 == 0)
1056 return str;
1057 ++i;
1058 // Gotcha: fromCharCode constructs a character from a UTF-16 encoded code (pair), not from a Unicode code point! So encode the code point to UTF-16 for constructing.
1059 // See http://unicode.org/faq/utf_bom.html#utf16-3
1060 if (utf32 >= 0x10000) {
1061 var ch = utf32 - 0x10000;
1062 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
1063 } else {
1064 str += String.fromCharCode(utf32);
1065 }
1066 }
1067}
1068
1069// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
1070// null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP.
1071// Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write.
1072// Parameters:
1073// str: the Javascript string to copy.
1074// outPtr: Byte address in Emscripten HEAP where to write the string to.
1075// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
1076// terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else.
1077// maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator.
1078// Returns the number of bytes written, EXCLUDING the null terminator.
1079
1080function stringToUTF32(str, outPtr, maxBytesToWrite) {
1081 assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!');
1082 assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
1083 // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
1084 if (maxBytesToWrite === undefined) {
1085 maxBytesToWrite = 0x7FFFFFFF;
1086 }
1087 if (maxBytesToWrite < 4) return 0;
1088 var startPtr = outPtr;
1089 var endPtr = startPtr + maxBytesToWrite - 4;
1090 for (var i = 0; i < str.length; ++i) {
1091 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
1092 // See http://unicode.org/faq/utf_bom.html#utf16-3
1093 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
1094 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
1095 var trailSurrogate = str.charCodeAt(++i);
1096 codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
1097 }
1098 HEAP32[((outPtr)>>2)]=codeUnit;
1099 outPtr += 4;
1100 if (outPtr + 4 > endPtr) break;
1101 }
1102 // Null-terminate the pointer to the HEAP.
1103 HEAP32[((outPtr)>>2)]=0;
1104 return outPtr - startPtr;
1105}
1106
1107// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
1108
1109function lengthBytesUTF32(str) {
1110 var len = 0;
1111 for (var i = 0; i < str.length; ++i) {
1112 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
1113 // See http://unicode.org/faq/utf_bom.html#utf16-3
1114 var codeUnit = str.charCodeAt(i);
1115 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate.
1116 len += 4;
1117 }
1118
1119 return len;
1120}
1121
1122// Allocate heap space for a JS string, and write it there.
1123// It is the responsibility of the caller to free() that memory.
1124function allocateUTF8(str) {
1125 var size = lengthBytesUTF8(str) + 1;
1126 var ret = _malloc(size);
1127 if (ret) stringToUTF8Array(str, HEAP8, ret, size);
1128 return ret;
1129}
1130
1131// Allocate stack space for a JS string, and write it there.
1132function allocateUTF8OnStack(str) {
1133 var size = lengthBytesUTF8(str) + 1;
1134 var ret = stackAlloc(size);
1135 stringToUTF8Array(str, HEAP8, ret, size);
1136 return ret;
1137}
1138
1139// Deprecated: This function should not be called because it is unsafe and does not provide
1140// a maximum length limit of how many bytes it is allowed to write. Prefer calling the
1141// function stringToUTF8Array() instead, which takes in a maximum length that can be used
1142// to be secure from out of bounds writes.
1143/** @deprecated */
1144function writeStringToMemory(string, buffer, dontAddNull) {
1145 warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!');
1146
1147 var /** @type {number} */ lastChar, /** @type {number} */ end;
1148 if (dontAddNull) {
1149 // stringToUTF8Array always appends null. If we don't want to do that, remember the
1150 // character that existed at the location where the null will be placed, and restore
1151 // that after the write (below).
1152 end = buffer + lengthBytesUTF8(string);
1153 lastChar = HEAP8[end];
1154 }
1155 stringToUTF8(string, buffer, Infinity);
1156 if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character.
1157}
1158
1159function writeArrayToMemory(array, buffer) {
1160 assert(array.length >= 0, 'writeArrayToMemory array must have a length (should be an array or typed array)')
1161 HEAP8.set(array, buffer);
1162}
1163
1164function writeAsciiToMemory(str, buffer, dontAddNull) {
1165 for (var i = 0; i < str.length; ++i) {
1166 assert(str.charCodeAt(i) === str.charCodeAt(i)&0xff);
1167 HEAP8[((buffer++)>>0)]=str.charCodeAt(i);
1168 }
1169 // Null-terminate the pointer to the HEAP.
1170 if (!dontAddNull) HEAP8[((buffer)>>0)]=0;
1171}
1172
1173
1174
1175
1176// Memory management
1177
1178var PAGE_SIZE = 16384;
1179var WASM_PAGE_SIZE = 65536;
1180var ASMJS_PAGE_SIZE = 16777216;
1181
1182function alignUp(x, multiple) {
1183 if (x % multiple > 0) {
1184 x += multiple - (x % multiple);
1185 }
1186 return x;
1187}
1188
1189var HEAP,
1190/** @type {ArrayBuffer} */
1191 buffer,
1192/** @type {Int8Array} */
1193 HEAP8,
1194/** @type {Uint8Array} */
1195 HEAPU8,
1196/** @type {Int16Array} */
1197 HEAP16,
1198/** @type {Uint16Array} */
1199 HEAPU16,
1200/** @type {Int32Array} */
1201 HEAP32,
1202/** @type {Uint32Array} */
1203 HEAPU32,
1204/** @type {Float32Array} */
1205 HEAPF32,
1206/** @type {Float64Array} */
1207 HEAPF64;
1208
1209function updateGlobalBufferViews() {
1210 Module['HEAP8'] = HEAP8 = new Int8Array(buffer);
1211 Module['HEAP16'] = HEAP16 = new Int16Array(buffer);
1212 Module['HEAP32'] = HEAP32 = new Int32Array(buffer);
1213 Module['HEAPU8'] = HEAPU8 = new Uint8Array(buffer);
1214 Module['HEAPU16'] = HEAPU16 = new Uint16Array(buffer);
1215 Module['HEAPU32'] = HEAPU32 = new Uint32Array(buffer);
1216 Module['HEAPF32'] = HEAPF32 = new Float32Array(buffer);
1217 Module['HEAPF64'] = HEAPF64 = new Float64Array(buffer);
1218}
1219
1220
1221var STATIC_BASE = 1024,
1222 STACK_BASE = 4832,
1223 STACKTOP = STACK_BASE,
1224 STACK_MAX = 5247712,
1225 DYNAMIC_BASE = 5247712,
1226 DYNAMICTOP_PTR = 4800;
1227
1228assert(STACK_BASE % 16 === 0, 'stack must start aligned');
1229assert(DYNAMIC_BASE % 16 === 0, 'heap must start aligned');
1230
1231
1232
1233var TOTAL_STACK = 5242880;
1234if (Module['TOTAL_STACK']) assert(TOTAL_STACK === Module['TOTAL_STACK'], 'the stack size can no longer be determined at runtime')
1235
1236var INITIAL_TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 16777216;if (!Object.getOwnPropertyDescriptor(Module, 'TOTAL_MEMORY')) Object.defineProperty(Module, 'TOTAL_MEMORY', { get: function() { abort('Module.TOTAL_MEMORY has been replaced with plain INITIAL_TOTAL_MEMORY') } });
1237
1238assert(INITIAL_TOTAL_MEMORY >= TOTAL_STACK, 'TOTAL_MEMORY should be larger than TOTAL_STACK, was ' + INITIAL_TOTAL_MEMORY + '! (TOTAL_STACK=' + TOTAL_STACK + ')');
1239
1240// check for full engine support (use string 'subarray' to avoid closure compiler confusion)
1241assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray !== undefined && Int32Array.prototype.set !== undefined,
1242 'JS engine does not provide full typed array support');
1243
1244
1245
1246
1247
1248
1249
1250 if (Module['wasmMemory']) {
1251 wasmMemory = Module['wasmMemory'];
1252 } else
1253 {
1254 wasmMemory = new WebAssembly.Memory({
1255 'initial': INITIAL_TOTAL_MEMORY / WASM_PAGE_SIZE
1256 ,
1257 'maximum': INITIAL_TOTAL_MEMORY / WASM_PAGE_SIZE
1258 });
1259 }
1260
1261
1262if (wasmMemory) {
1263 buffer = wasmMemory.buffer;
1264}
1265
1266// If the user provides an incorrect length, just use that length instead rather than providing the user to
1267// specifically provide the memory length with Module['TOTAL_MEMORY'].
1268INITIAL_TOTAL_MEMORY = buffer.byteLength;
1269assert(INITIAL_TOTAL_MEMORY % WASM_PAGE_SIZE === 0);
1270updateGlobalBufferViews();
1271
1272HEAP32[DYNAMICTOP_PTR>>2] = DYNAMIC_BASE;
1273
1274
1275// Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
1276function writeStackCookie() {
1277 assert((STACK_MAX & 3) == 0);
1278 HEAPU32[(STACK_MAX >> 2)-1] = 0x02135467;
1279 HEAPU32[(STACK_MAX >> 2)-2] = 0x89BACDFE;
1280}
1281
1282function checkStackCookie() {
1283 var cookie1 = HEAPU32[(STACK_MAX >> 2)-1];
1284 var cookie2 = HEAPU32[(STACK_MAX >> 2)-2];
1285 if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) {
1286 abort('Stack overflow! Stack cookie has been overwritten, expected hex dwords 0x89BACDFE and 0x02135467, but received 0x' + cookie2.toString(16) + ' ' + cookie1.toString(16));
1287 }
1288 // Also test the global address 0 for integrity.
1289 // We don't do this with ASan because ASan does its own checks for this.
1290 if (HEAP32[0] !== 0x63736d65 /* 'emsc' */) abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
1291}
1292
1293function abortStackOverflow(allocSize) {
1294 abort('Stack overflow! Attempted to allocate ' + allocSize + ' bytes on the stack, but stack has only ' + (STACK_MAX - stackSave() + allocSize) + ' bytes available!');
1295}
1296
1297
1298 HEAP32[0] = 0x63736d65; /* 'emsc' */
1299
1300
1301
1302// Endianness check (note: assumes compiler arch was little-endian)
1303HEAP16[1] = 0x6373;
1304if (HEAPU8[2] !== 0x73 || HEAPU8[3] !== 0x63) throw 'Runtime error: expected the system to be little-endian!';
1305
1306function abortFnPtrError(ptr, sig) {
1307 abort("Invalid function pointer " + ptr + " called with signature '" + sig + "'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this). Build with ASSERTIONS=2 for more info.");
1308}
1309
1310
1311
1312function callRuntimeCallbacks(callbacks) {
1313 while(callbacks.length > 0) {
1314 var callback = callbacks.shift();
1315 if (typeof callback == 'function') {
1316 callback();
1317 continue;
1318 }
1319 var func = callback.func;
1320 if (typeof func === 'number') {
1321 if (callback.arg === undefined) {
1322 Module['dynCall_v'](func);
1323 } else {
1324 Module['dynCall_vi'](func, callback.arg);
1325 }
1326 } else {
1327 func(callback.arg === undefined ? null : callback.arg);
1328 }
1329 }
1330}
1331
1332var __ATPRERUN__ = []; // functions called before the runtime is initialized
1333var __ATINIT__ = []; // functions called during startup
1334var __ATMAIN__ = []; // functions called when main() is to be run
1335var __ATEXIT__ = []; // functions called during shutdown
1336var __ATPOSTRUN__ = []; // functions called after the main() is called
1337
1338var runtimeInitialized = false;
1339var runtimeExited = false;
1340
1341
1342function preRun() {
1343
1344 if (Module['preRun']) {
1345 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
1346 while (Module['preRun'].length) {
1347 addOnPreRun(Module['preRun'].shift());
1348 }
1349 }
1350
1351 callRuntimeCallbacks(__ATPRERUN__);
1352}
1353
1354function initRuntime() {
1355 checkStackCookie();
1356 assert(!runtimeInitialized);
1357 runtimeInitialized = true;
1358
1359 callRuntimeCallbacks(__ATINIT__);
1360}
1361
1362function preMain() {
1363 checkStackCookie();
1364
1365 callRuntimeCallbacks(__ATMAIN__);
1366}
1367
1368function exitRuntime() {
1369 checkStackCookie();
1370 runtimeExited = true;
1371}
1372
1373function postRun() {
1374 checkStackCookie();
1375
1376 if (Module['postRun']) {
1377 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
1378 while (Module['postRun'].length) {
1379 addOnPostRun(Module['postRun'].shift());
1380 }
1381 }
1382
1383 callRuntimeCallbacks(__ATPOSTRUN__);
1384}
1385
1386function addOnPreRun(cb) {
1387 __ATPRERUN__.unshift(cb);
1388}
1389
1390function addOnInit(cb) {
1391 __ATINIT__.unshift(cb);
1392}
1393
1394function addOnPreMain(cb) {
1395 __ATMAIN__.unshift(cb);
1396}
1397
1398function addOnExit(cb) {
1399}
1400
1401function addOnPostRun(cb) {
1402 __ATPOSTRUN__.unshift(cb);
1403}
1404
1405function unSign(value, bits, ignore) {
1406 if (value >= 0) {
1407 return value;
1408 }
1409 return bits <= 32 ? 2*Math.abs(1 << (bits-1)) + value // Need some trickery, since if bits == 32, we are right at the limit of the bits JS uses in bitshifts
1410 : Math.pow(2, bits) + value;
1411}
1412function reSign(value, bits, ignore) {
1413 if (value <= 0) {
1414 return value;
1415 }
1416 var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
1417 : Math.pow(2, bits-1);
1418 if (value >= half && (bits <= 32 || value > half)) { // for huge values, we can hit the precision limit and always get true here. so don't do that
1419 // but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
1420 // TODO: In i64 mode 1, resign the two parts separately and safely
1421 value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
1422 }
1423 return value;
1424}
1425
1426
1427assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
1428assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
1429assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
1430assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
1431
1432var Math_abs = Math.abs;
1433var Math_cos = Math.cos;
1434var Math_sin = Math.sin;
1435var Math_tan = Math.tan;
1436var Math_acos = Math.acos;
1437var Math_asin = Math.asin;
1438var Math_atan = Math.atan;
1439var Math_atan2 = Math.atan2;
1440var Math_exp = Math.exp;
1441var Math_log = Math.log;
1442var Math_sqrt = Math.sqrt;
1443var Math_ceil = Math.ceil;
1444var Math_floor = Math.floor;
1445var Math_pow = Math.pow;
1446var Math_imul = Math.imul;
1447var Math_fround = Math.fround;
1448var Math_round = Math.round;
1449var Math_min = Math.min;
1450var Math_max = Math.max;
1451var Math_clz32 = Math.clz32;
1452var Math_trunc = Math.trunc;
1453
1454
1455
1456// A counter of dependencies for calling run(). If we need to
1457// do asynchronous work before running, increment this and
1458// decrement it. Incrementing must happen in a place like
1459// Module.preRun (used by emcc to add file preloading).
1460// Note that you can add dependencies in preRun, even though
1461// it happens right before run - run will be postponed until
1462// the dependencies are met.
1463var runDependencies = 0;
1464var runDependencyWatcher = null;
1465var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
1466var runDependencyTracking = {};
1467
1468function getUniqueRunDependency(id) {
1469 var orig = id;
1470 while (1) {
1471 if (!runDependencyTracking[id]) return id;
1472 id = orig + Math.random();
1473 }
1474 return id;
1475}
1476
1477function addRunDependency(id) {
1478 runDependencies++;
1479
1480 if (Module['monitorRunDependencies']) {
1481 Module['monitorRunDependencies'](runDependencies);
1482 }
1483
1484 if (id) {
1485 assert(!runDependencyTracking[id]);
1486 runDependencyTracking[id] = 1;
1487 if (runDependencyWatcher === null && typeof setInterval !== 'undefined') {
1488 // Check for missing dependencies every few seconds
1489 runDependencyWatcher = setInterval(function() {
1490 if (ABORT) {
1491 clearInterval(runDependencyWatcher);
1492 runDependencyWatcher = null;
1493 return;
1494 }
1495 var shown = false;
1496 for (var dep in runDependencyTracking) {
1497 if (!shown) {
1498 shown = true;
1499 err('still waiting on run dependencies:');
1500 }
1501 err('dependency: ' + dep);
1502 }
1503 if (shown) {
1504 err('(end of list)');
1505 }
1506 }, 10000);
1507 }
1508 } else {
1509 err('warning: run dependency added without ID');
1510 }
1511}
1512
1513function removeRunDependency(id) {
1514 runDependencies--;
1515
1516 if (Module['monitorRunDependencies']) {
1517 Module['monitorRunDependencies'](runDependencies);
1518 }
1519
1520 if (id) {
1521 assert(runDependencyTracking[id]);
1522 delete runDependencyTracking[id];
1523 } else {
1524 err('warning: run dependency removed without ID');
1525 }
1526 if (runDependencies == 0) {
1527 if (runDependencyWatcher !== null) {
1528 clearInterval(runDependencyWatcher);
1529 runDependencyWatcher = null;
1530 }
1531 if (dependenciesFulfilled) {
1532 var callback = dependenciesFulfilled;
1533 dependenciesFulfilled = null;
1534 callback(); // can add another dependenciesFulfilled
1535 }
1536 }
1537}
1538
1539Module["preloadedImages"] = {}; // maps url to image data
1540Module["preloadedAudios"] = {}; // maps url to audio data
1541
1542
1543var memoryInitializer = null;
1544
1545
1546
1547
1548// show errors on likely calls to FS when it was not included
1549var FS = {
1550 error: function() {
1551 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 -s FORCE_FILESYSTEM=1');
1552 },
1553 init: function() { FS.error() },
1554 createDataFile: function() { FS.error() },
1555 createPreloadedFile: function() { FS.error() },
1556 createLazyFile: function() { FS.error() },
1557 open: function() { FS.error() },
1558 mkdev: function() { FS.error() },
1559 registerDevice: function() { FS.error() },
1560 analyzePath: function() { FS.error() },
1561 loadFilesFromDB: function() { FS.error() },
1562
1563 ErrnoError: function ErrnoError() { FS.error() },
1564};
1565Module['FS_createDataFile'] = FS.createDataFile;
1566Module['FS_createPreloadedFile'] = FS.createPreloadedFile;
1567
1568
1569
1570// Copyright 2017 The Emscripten Authors. All rights reserved.
1571// Emscripten is available under two separate licenses, the MIT license and the
1572// University of Illinois/NCSA Open Source License. Both these licenses can be
1573// found in the LICENSE file.
1574
1575// Prefix of data URIs emitted by SINGLE_FILE and related options.
1576var dataURIPrefix = 'data:application/octet-stream;base64,';
1577
1578// Indicates whether filename is a base64 data URI.
1579function isDataURI(filename) {
1580 return String.prototype.startsWith ?
1581 filename.startsWith(dataURIPrefix) :
1582 filename.indexOf(dataURIPrefix) === 0;
1583}
1584
1585
1586
1587
1588var wasmBinaryFile = 'a.out.wasm';
1589if (!isDataURI(wasmBinaryFile)) {
1590 wasmBinaryFile = locateFile(wasmBinaryFile);
1591}
1592
1593function getBinary() {
1594 try {
1595 if (wasmBinary) {
1596 return new Uint8Array(wasmBinary);
1597 }
1598
1599 if (readBinary) {
1600 return readBinary(wasmBinaryFile);
1601 } else {
1602 throw "both async and sync fetching of the wasm failed";
1603 }
1604 }
1605 catch (err) {
1606 abort(err);
1607 }
1608}
1609
1610function getBinaryPromise() {
1611 // if we don't have the binary yet, and have the Fetch api, use that
1612 // in some environments, like Electron's render process, Fetch api may be present, but have a different context than expected, let's only use it on the Web
1613 if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && typeof fetch === 'function') {
1614 return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) {
1615 if (!response['ok']) {
1616 throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
1617 }
1618 return response['arrayBuffer']();
1619 }).catch(function () {
1620 return getBinary();
1621 });
1622 }
1623 // Otherwise, getBinary should be able to get it synchronously
1624 return new Promise(function(resolve, reject) {
1625 resolve(getBinary());
1626 });
1627}
1628
1629
1630
1631// Create the wasm instance.
1632// Receives the wasm imports, returns the exports.
1633function createWasm(env) {
1634
1635 // prepare imports
1636 var info = {
1637 'env': env
1638 ,
1639 'global': {
1640 'NaN': NaN,
1641 'Infinity': Infinity
1642 },
1643 'global.Math': Math,
1644 'asm2wasm': asm2wasmImports
1645 };
1646 // Load the wasm module and create an instance of using native support in the JS engine.
1647 // handle a generated wasm instance, receiving its exports and
1648 // performing other necessary setup
1649 function receiveInstance(instance, module) {
1650 var exports = instance.exports;
1651 Module['asm'] = exports;
1652 removeRunDependency('wasm-instantiate');
1653 }
1654 // we can't run yet (except in a pthread, where we have a custom sync instantiator)
1655 addRunDependency('wasm-instantiate');
1656
1657
1658 // Async compilation can be confusing when an error on the page overwrites Module
1659 // (for example, if the order of elements is wrong, and the one defining Module is
1660 // later), so we save Module and check it later.
1661 var trueModule = Module;
1662 function receiveInstantiatedSource(output) {
1663 // 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.
1664 // receiveInstance() will swap in the exports (to Module.asm) so they can be called
1665 assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
1666 trueModule = null;
1667 // 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.
1668 // When the regression is fixed, can restore the above USE_PTHREADS-enabled path.
1669 receiveInstance(output['instance']);
1670 }
1671
1672
1673 function instantiateArrayBuffer(receiver) {
1674 return getBinaryPromise().then(function(binary) {
1675 return WebAssembly.instantiate(binary, info);
1676 }).then(receiver, function(reason) {
1677 err('failed to asynchronously prepare wasm: ' + reason);
1678 abort(reason);
1679 });
1680 }
1681
1682 // Prefer streaming instantiation if available.
1683 function instantiateAsync() {
1684 if (!wasmBinary &&
1685 typeof WebAssembly.instantiateStreaming === 'function' &&
1686 !isDataURI(wasmBinaryFile) &&
1687 typeof fetch === 'function') {
1688 fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) {
1689 var result = WebAssembly.instantiateStreaming(response, info);
1690 return result.then(receiveInstantiatedSource, function(reason) {
1691 // We expect the most common failure cause to be a bad MIME type for the binary,
1692 // in which case falling back to ArrayBuffer instantiation should work.
1693 err('wasm streaming compile failed: ' + reason);
1694 err('falling back to ArrayBuffer instantiation');
1695 instantiateArrayBuffer(receiveInstantiatedSource);
1696 });
1697 });
1698 } else {
1699 return instantiateArrayBuffer(receiveInstantiatedSource);
1700 }
1701 }
1702 // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
1703 // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
1704 // to any other async startup actions they are performing.
1705 if (Module['instantiateWasm']) {
1706 try {
1707 var exports = Module['instantiateWasm'](info, receiveInstance);
1708 return exports;
1709 } catch(e) {
1710 err('Module.instantiateWasm callback failed with error: ' + e);
1711 return false;
1712 }
1713 }
1714
1715 instantiateAsync();
1716 return {}; // no exports yet; we'll fill them in later
1717}
1718
1719// Provide an "asm.js function" for the application, called to "link" the asm.js module. We instantiate
1720// the wasm module at that time, and it receives imports and provides exports and so forth, the app
1721// doesn't need to care that it is wasm or asm.js.
1722
1723Module['asm'] = function(global, env, providedBuffer) {
1724 // memory was already allocated (so js could use the buffer)
1725 env['memory'] = wasmMemory
1726 ;
1727 // import table
1728 env['table'] = wasmTable = new WebAssembly.Table({
1729 'initial': 30,
1730 'maximum': 30,
1731 'element': 'anyfunc'
1732 });
1733 // With the wasm backend __memory_base and __table_base and only needed for
1734 // relocatable output.
1735 env['__memory_base'] = 1024; // tell the memory segments where to place themselves
1736 // table starts at 0 by default (even in dynamic linking, for the main module)
1737 env['__table_base'] = 0;
1738
1739 var exports = createWasm(env);
1740 assert(exports, 'binaryen setup failed (no wasm support?)');
1741 return exports;
1742};
1743
1744// Globals used by JS i64 conversions
1745var tempDouble;
1746var tempI64;
1747
1748// === Body ===
1749
1750var ASM_CONSTS = [];
1751
1752
1753
1754
1755
1756// STATICTOP = STATIC_BASE + 3808;
1757/* global initializers */ /*__ATINIT__.push();*/
1758
1759
1760
1761
1762
1763
1764
1765
1766/* no memory initializer */
1767var tempDoublePtr = 4816
1768assert(tempDoublePtr % 8 == 0);
1769
1770function copyTempFloat(ptr) { // functions, because inlining this code increases code size too much
1771 HEAP8[tempDoublePtr] = HEAP8[ptr];
1772 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1773 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1774 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1775}
1776
1777function copyTempDouble(ptr) {
1778 HEAP8[tempDoublePtr] = HEAP8[ptr];
1779 HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
1780 HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
1781 HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
1782 HEAP8[tempDoublePtr+4] = HEAP8[ptr+4];
1783 HEAP8[tempDoublePtr+5] = HEAP8[ptr+5];
1784 HEAP8[tempDoublePtr+6] = HEAP8[ptr+6];
1785 HEAP8[tempDoublePtr+7] = HEAP8[ptr+7];
1786}
1787
1788// {{PRE_LIBRARY}}
1789
1790
1791 function demangle(func) {
1792 warnOnce('warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling');
1793 return func;
1794 }
1795
1796 function demangleAll(text) {
1797 var regex =
1798 /__Z[\w\d_]+/g;
1799 return text.replace(regex,
1800 function(x) {
1801 var y = demangle(x);
1802 return x === y ? x : (y + ' [' + x + ']');
1803 });
1804 }
1805
1806 function jsStackTrace() {
1807 var err = new Error();
1808 if (!err.stack) {
1809 // IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown,
1810 // so try that as a special-case.
1811 try {
1812 throw new Error(0);
1813 } catch(e) {
1814 err = e;
1815 }
1816 if (!err.stack) {
1817 return '(no stack trace available)';
1818 }
1819 }
1820 return err.stack.toString();
1821 }
1822
1823 function stackTrace() {
1824 var js = jsStackTrace();
1825 if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']();
1826 return demangleAll(js);
1827 }
1828
1829 function ___lock() {}
1830
1831
1832
1833 var PATH={splitPath:function (filename) {
1834 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
1835 return splitPathRe.exec(filename).slice(1);
1836 },normalizeArray:function (parts, allowAboveRoot) {
1837 // if the path tries to go above the root, `up` ends up > 0
1838 var up = 0;
1839 for (var i = parts.length - 1; i >= 0; i--) {
1840 var last = parts[i];
1841 if (last === '.') {
1842 parts.splice(i, 1);
1843 } else if (last === '..') {
1844 parts.splice(i, 1);
1845 up++;
1846 } else if (up) {
1847 parts.splice(i, 1);
1848 up--;
1849 }
1850 }
1851 // if the path is allowed to go above the root, restore leading ..s
1852 if (allowAboveRoot) {
1853 for (; up; up--) {
1854 parts.unshift('..');
1855 }
1856 }
1857 return parts;
1858 },normalize:function (path) {
1859 var isAbsolute = path.charAt(0) === '/',
1860 trailingSlash = path.substr(-1) === '/';
1861 // Normalize the path
1862 path = PATH.normalizeArray(path.split('/').filter(function(p) {
1863 return !!p;
1864 }), !isAbsolute).join('/');
1865 if (!path && !isAbsolute) {
1866 path = '.';
1867 }
1868 if (path && trailingSlash) {
1869 path += '/';
1870 }
1871 return (isAbsolute ? '/' : '') + path;
1872 },dirname:function (path) {
1873 var result = PATH.splitPath(path),
1874 root = result[0],
1875 dir = result[1];
1876 if (!root && !dir) {
1877 // No dirname whatsoever
1878 return '.';
1879 }
1880 if (dir) {
1881 // It has a dirname, strip trailing slash
1882 dir = dir.substr(0, dir.length - 1);
1883 }
1884 return root + dir;
1885 },basename:function (path) {
1886 // EMSCRIPTEN return '/'' for '/', not an empty string
1887 if (path === '/') return '/';
1888 var lastSlash = path.lastIndexOf('/');
1889 if (lastSlash === -1) return path;
1890 return path.substr(lastSlash+1);
1891 },extname:function (path) {
1892 return PATH.splitPath(path)[3];
1893 },join:function () {
1894 var paths = Array.prototype.slice.call(arguments, 0);
1895 return PATH.normalize(paths.join('/'));
1896 },join2:function (l, r) {
1897 return PATH.normalize(l + '/' + r);
1898 }};var SYSCALLS={buffers:[null,[],[]],printChar:function (stream, curr) {
1899 var buffer = SYSCALLS.buffers[stream];
1900 assert(buffer);
1901 if (curr === 0 || curr === 10) {
1902 (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0));
1903 buffer.length = 0;
1904 } else {
1905 buffer.push(curr);
1906 }
1907 },varargs:0,get:function (varargs) {
1908 SYSCALLS.varargs += 4;
1909 var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)];
1910 return ret;
1911 },getStr:function () {
1912 var ret = UTF8ToString(SYSCALLS.get());
1913 return ret;
1914 },get64:function () {
1915 var low = SYSCALLS.get(), high = SYSCALLS.get();
1916 if (low >= 0) assert(high === 0);
1917 else assert(high === -1);
1918 return low;
1919 },getZero:function () {
1920 assert(SYSCALLS.get() === 0);
1921 }};function ___syscall140(which, varargs) {SYSCALLS.varargs = varargs;
1922 try {
1923 // llseek
1924 var stream = SYSCALLS.getStreamFromFD(), offset_high = SYSCALLS.get(), offset_low = SYSCALLS.get(), result = SYSCALLS.get(), whence = SYSCALLS.get();
1925 abort('it should not be possible to operate on streams when !SYSCALLS_REQUIRE_FILESYSTEM');
1926 return 0;
1927 } catch (e) {
1928 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
1929 return -e.errno;
1930 }
1931 }
1932
1933
1934 function flush_NO_FILESYSTEM() {
1935 // flush anything remaining in the buffers during shutdown
1936 var fflush = Module["_fflush"];
1937 if (fflush) fflush(0);
1938 var buffers = SYSCALLS.buffers;
1939 if (buffers[1].length) SYSCALLS.printChar(1, 10);
1940 if (buffers[2].length) SYSCALLS.printChar(2, 10);
1941 }function ___syscall146(which, varargs) {SYSCALLS.varargs = varargs;
1942 try {
1943 // writev
1944 // hack to support printf in SYSCALLS_REQUIRE_FILESYSTEM=0
1945 var stream = SYSCALLS.get(), iov = SYSCALLS.get(), iovcnt = SYSCALLS.get();
1946 var ret = 0;
1947 for (var i = 0; i < iovcnt; i++) {
1948 var ptr = HEAP32[(((iov)+(i*8))>>2)];
1949 var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
1950 for (var j = 0; j < len; j++) {
1951 SYSCALLS.printChar(stream, HEAPU8[ptr+j]);
1952 }
1953 ret += len;
1954 }
1955 return ret;
1956 } catch (e) {
1957 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
1958 return -e.errno;
1959 }
1960 }
1961
1962 function ___syscall54(which, varargs) {SYSCALLS.varargs = varargs;
1963 try {
1964 // ioctl
1965 return 0;
1966 } catch (e) {
1967 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
1968 return -e.errno;
1969 }
1970 }
1971
1972 function ___syscall6(which, varargs) {SYSCALLS.varargs = varargs;
1973 try {
1974 // close
1975 var stream = SYSCALLS.getStreamFromFD();
1976 abort('it should not be possible to operate on streams when !SYSCALLS_REQUIRE_FILESYSTEM');
1977 return 0;
1978 } catch (e) {
1979 if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
1980 return -e.errno;
1981 }
1982 }
1983
1984 function ___unlock() {}
1985
1986 function _emscripten_get_heap_size() {
1987 return HEAP8.length;
1988 }
1989
1990
1991 function _emscripten_memcpy_big(dest, src, num) {
1992 HEAPU8.set(HEAPU8.subarray(src, src+num), dest);
1993 }
1994
1995
1996
1997
1998
1999
2000 function ___setErrNo(value) {
2001 if (Module['___errno_location']) HEAP32[((Module['___errno_location']())>>2)]=value;
2002 else err('failed to set errno from JS');
2003 return value;
2004 }
2005
2006
2007 function abortOnCannotGrowMemory(requestedSize) {
2008 abort('Cannot enlarge memory arrays to size ' + requestedSize + ' bytes (OOM). Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value ' + HEAP8.length + ', (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ');
2009 }function _emscripten_resize_heap(requestedSize) {
2010 abortOnCannotGrowMemory(requestedSize);
2011 }
2012var ASSERTIONS = true;
2013
2014// Copyright 2017 The Emscripten Authors. All rights reserved.
2015// Emscripten is available under two separate licenses, the MIT license and the
2016// University of Illinois/NCSA Open Source License. Both these licenses can be
2017// found in the LICENSE file.
2018
2019/** @type {function(string, boolean=, number=)} */
2020function intArrayFromString(stringy, dontAddNull, length) {
2021 var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
2022 var u8array = new Array(len);
2023 var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
2024 if (dontAddNull) u8array.length = numBytesWritten;
2025 return u8array;
2026}
2027
2028function intArrayToString(array) {
2029 var ret = [];
2030 for (var i = 0; i < array.length; i++) {
2031 var chr = array[i];
2032 if (chr > 0xFF) {
2033 if (ASSERTIONS) {
2034 assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.');
2035 }
2036 chr &= 0xFF;
2037 }
2038 ret.push(String.fromCharCode(chr));
2039 }
2040 return ret.join('');
2041}
2042
2043
2044// ASM_LIBRARY EXTERN PRIMITIVES: Int8Array,Int32Array
2045
2046function nullFunc_ii(x) { abortFnPtrError(x, 'ii'); }
2047function nullFunc_iidiiii(x) { abortFnPtrError(x, 'iidiiii'); }
2048function nullFunc_iiii(x) { abortFnPtrError(x, 'iiii'); }
2049function nullFunc_jiji(x) { abortFnPtrError(x, 'jiji'); }
2050function nullFunc_vii(x) { abortFnPtrError(x, 'vii'); }
2051
2052var asmGlobalArg = {};
2053
2054var asmLibraryArg = {
2055 "abort": abort,
2056 "setTempRet0": setTempRet0,
2057 "getTempRet0": getTempRet0,
2058 "abortStackOverflow": abortStackOverflow,
2059 "nullFunc_ii": nullFunc_ii,
2060 "nullFunc_iidiiii": nullFunc_iidiiii,
2061 "nullFunc_iiii": nullFunc_iiii,
2062 "nullFunc_jiji": nullFunc_jiji,
2063 "nullFunc_vii": nullFunc_vii,
2064 "___lock": ___lock,
2065 "___setErrNo": ___setErrNo,
2066 "___syscall140": ___syscall140,
2067 "___syscall146": ___syscall146,
2068 "___syscall54": ___syscall54,
2069 "___syscall6": ___syscall6,
2070 "___unlock": ___unlock,
2071 "_emscripten_get_heap_size": _emscripten_get_heap_size,
2072 "_emscripten_memcpy_big": _emscripten_memcpy_big,
2073 "_emscripten_resize_heap": _emscripten_resize_heap,
2074 "abortOnCannotGrowMemory": abortOnCannotGrowMemory,
2075 "demangle": demangle,
2076 "demangleAll": demangleAll,
2077 "flush_NO_FILESYSTEM": flush_NO_FILESYSTEM,
2078 "jsStackTrace": jsStackTrace,
2079 "stackTrace": stackTrace,
2080 "tempDoublePtr": tempDoublePtr,
2081 "DYNAMICTOP_PTR": DYNAMICTOP_PTR
2082};
2083// EMSCRIPTEN_START_ASM
2084var asm =Module["asm"]// EMSCRIPTEN_END_ASM
2085(asmGlobalArg, asmLibraryArg, buffer);
2086
2087Module["asm"] = asm;
2088var ___errno_location = Module["___errno_location"] = function() {
2089 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2090 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2091 return Module["asm"]["___errno_location"].apply(null, arguments)
2092};
2093
2094var _fflush = Module["_fflush"] = function() {
2095 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2096 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2097 return Module["asm"]["_fflush"].apply(null, arguments)
2098};
2099
2100var _free = Module["_free"] = function() {
2101 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2102 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2103 return Module["asm"]["_free"].apply(null, arguments)
2104};
2105
2106var _main = Module["_main"] = function() {
2107 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2108 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2109 return Module["asm"]["_main"].apply(null, arguments)
2110};
2111
2112var _malloc = Module["_malloc"] = function() {
2113 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2114 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2115 return Module["asm"]["_malloc"].apply(null, arguments)
2116};
2117
2118var _memcpy = Module["_memcpy"] = function() {
2119 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2120 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2121 return Module["asm"]["_memcpy"].apply(null, arguments)
2122};
2123
2124var _memset = Module["_memset"] = function() {
2125 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2126 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2127 return Module["asm"]["_memset"].apply(null, arguments)
2128};
2129
2130var _sbrk = Module["_sbrk"] = function() {
2131 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2132 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2133 return Module["asm"]["_sbrk"].apply(null, arguments)
2134};
2135
2136var establishStackSpace = Module["establishStackSpace"] = function() {
2137 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2138 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2139 return Module["asm"]["establishStackSpace"].apply(null, arguments)
2140};
2141
2142var stackAlloc = Module["stackAlloc"] = function() {
2143 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2144 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2145 return Module["asm"]["stackAlloc"].apply(null, arguments)
2146};
2147
2148var stackRestore = Module["stackRestore"] = function() {
2149 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2150 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2151 return Module["asm"]["stackRestore"].apply(null, arguments)
2152};
2153
2154var stackSave = Module["stackSave"] = function() {
2155 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2156 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2157 return Module["asm"]["stackSave"].apply(null, arguments)
2158};
2159
2160var dynCall_ii = Module["dynCall_ii"] = function() {
2161 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2162 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2163 return Module["asm"]["dynCall_ii"].apply(null, arguments)
2164};
2165
2166var dynCall_iidiiii = Module["dynCall_iidiiii"] = function() {
2167 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2168 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2169 return Module["asm"]["dynCall_iidiiii"].apply(null, arguments)
2170};
2171
2172var dynCall_iiii = Module["dynCall_iiii"] = function() {
2173 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2174 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2175 return Module["asm"]["dynCall_iiii"].apply(null, arguments)
2176};
2177
2178var dynCall_jiji = Module["dynCall_jiji"] = function() {
2179 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2180 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2181 return Module["asm"]["dynCall_jiji"].apply(null, arguments)
2182};
2183
2184var dynCall_vii = Module["dynCall_vii"] = function() {
2185 assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
2186 assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
2187 return Module["asm"]["dynCall_vii"].apply(null, arguments)
2188};
2189;
2190
2191
2192
2193// === Auto-generated postamble setup entry stuff ===
2194
2195Module['asm'] = asm;
2196
2197if (!Object.getOwnPropertyDescriptor(Module, "intArrayFromString")) Module["intArrayFromString"] = function() { abort("'intArrayFromString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2198if (!Object.getOwnPropertyDescriptor(Module, "intArrayToString")) Module["intArrayToString"] = function() { abort("'intArrayToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2199if (!Object.getOwnPropertyDescriptor(Module, "ccall")) Module["ccall"] = function() { abort("'ccall' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2200if (!Object.getOwnPropertyDescriptor(Module, "cwrap")) Module["cwrap"] = function() { abort("'cwrap' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2201if (!Object.getOwnPropertyDescriptor(Module, "setValue")) Module["setValue"] = function() { abort("'setValue' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2202if (!Object.getOwnPropertyDescriptor(Module, "getValue")) Module["getValue"] = function() { abort("'getValue' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2203if (!Object.getOwnPropertyDescriptor(Module, "allocate")) Module["allocate"] = function() { abort("'allocate' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2204if (!Object.getOwnPropertyDescriptor(Module, "getMemory")) Module["getMemory"] = function() { abort("'getMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2205if (!Object.getOwnPropertyDescriptor(Module, "AsciiToString")) Module["AsciiToString"] = function() { abort("'AsciiToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2206if (!Object.getOwnPropertyDescriptor(Module, "stringToAscii")) Module["stringToAscii"] = function() { abort("'stringToAscii' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2207if (!Object.getOwnPropertyDescriptor(Module, "UTF8ArrayToString")) Module["UTF8ArrayToString"] = function() { abort("'UTF8ArrayToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2208if (!Object.getOwnPropertyDescriptor(Module, "UTF8ToString")) Module["UTF8ToString"] = function() { abort("'UTF8ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2209if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8Array")) Module["stringToUTF8Array"] = function() { abort("'stringToUTF8Array' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2210if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8")) Module["stringToUTF8"] = function() { abort("'stringToUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2211if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF8")) Module["lengthBytesUTF8"] = function() { abort("'lengthBytesUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2212if (!Object.getOwnPropertyDescriptor(Module, "UTF16ToString")) Module["UTF16ToString"] = function() { abort("'UTF16ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2213if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF16")) Module["stringToUTF16"] = function() { abort("'stringToUTF16' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2214if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF16")) Module["lengthBytesUTF16"] = function() { abort("'lengthBytesUTF16' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2215if (!Object.getOwnPropertyDescriptor(Module, "UTF32ToString")) Module["UTF32ToString"] = function() { abort("'UTF32ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2216if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF32")) Module["stringToUTF32"] = function() { abort("'stringToUTF32' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2217if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF32")) Module["lengthBytesUTF32"] = function() { abort("'lengthBytesUTF32' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2218if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8")) Module["allocateUTF8"] = function() { abort("'allocateUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2219if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() { abort("'stackTrace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2220if (!Object.getOwnPropertyDescriptor(Module, "addOnPreRun")) Module["addOnPreRun"] = function() { abort("'addOnPreRun' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2221if (!Object.getOwnPropertyDescriptor(Module, "addOnInit")) Module["addOnInit"] = function() { abort("'addOnInit' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2222if (!Object.getOwnPropertyDescriptor(Module, "addOnPreMain")) Module["addOnPreMain"] = function() { abort("'addOnPreMain' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2223if (!Object.getOwnPropertyDescriptor(Module, "addOnExit")) Module["addOnExit"] = function() { abort("'addOnExit' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2224if (!Object.getOwnPropertyDescriptor(Module, "addOnPostRun")) Module["addOnPostRun"] = function() { abort("'addOnPostRun' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2225if (!Object.getOwnPropertyDescriptor(Module, "writeStringToMemory")) Module["writeStringToMemory"] = function() { abort("'writeStringToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2226if (!Object.getOwnPropertyDescriptor(Module, "writeArrayToMemory")) Module["writeArrayToMemory"] = function() { abort("'writeArrayToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2227if (!Object.getOwnPropertyDescriptor(Module, "writeAsciiToMemory")) Module["writeAsciiToMemory"] = function() { abort("'writeAsciiToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2228if (!Object.getOwnPropertyDescriptor(Module, "addRunDependency")) Module["addRunDependency"] = function() { abort("'addRunDependency' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2229if (!Object.getOwnPropertyDescriptor(Module, "removeRunDependency")) Module["removeRunDependency"] = function() { abort("'removeRunDependency' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2230if (!Object.getOwnPropertyDescriptor(Module, "ENV")) Module["ENV"] = function() { abort("'ENV' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2231if (!Object.getOwnPropertyDescriptor(Module, "FS")) Module["FS"] = function() { abort("'FS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2232if (!Object.getOwnPropertyDescriptor(Module, "FS_createFolder")) Module["FS_createFolder"] = function() { abort("'FS_createFolder' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2233if (!Object.getOwnPropertyDescriptor(Module, "FS_createPath")) Module["FS_createPath"] = function() { abort("'FS_createPath' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2234if (!Object.getOwnPropertyDescriptor(Module, "FS_createDataFile")) Module["FS_createDataFile"] = function() { abort("'FS_createDataFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2235if (!Object.getOwnPropertyDescriptor(Module, "FS_createPreloadedFile")) Module["FS_createPreloadedFile"] = function() { abort("'FS_createPreloadedFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2236if (!Object.getOwnPropertyDescriptor(Module, "FS_createLazyFile")) Module["FS_createLazyFile"] = function() { abort("'FS_createLazyFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2237if (!Object.getOwnPropertyDescriptor(Module, "FS_createLink")) Module["FS_createLink"] = function() { abort("'FS_createLink' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2238if (!Object.getOwnPropertyDescriptor(Module, "FS_createDevice")) Module["FS_createDevice"] = function() { abort("'FS_createDevice' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2239if (!Object.getOwnPropertyDescriptor(Module, "FS_unlink")) Module["FS_unlink"] = function() { abort("'FS_unlink' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
2240if (!Object.getOwnPropertyDescriptor(Module, "GL")) Module["GL"] = function() { abort("'GL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2241if (!Object.getOwnPropertyDescriptor(Module, "dynamicAlloc")) Module["dynamicAlloc"] = function() { abort("'dynamicAlloc' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2242if (!Object.getOwnPropertyDescriptor(Module, "warnOnce")) Module["warnOnce"] = function() { abort("'warnOnce' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2243if (!Object.getOwnPropertyDescriptor(Module, "loadDynamicLibrary")) Module["loadDynamicLibrary"] = function() { abort("'loadDynamicLibrary' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2244if (!Object.getOwnPropertyDescriptor(Module, "loadWebAssemblyModule")) Module["loadWebAssemblyModule"] = function() { abort("'loadWebAssemblyModule' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2245if (!Object.getOwnPropertyDescriptor(Module, "getLEB")) Module["getLEB"] = function() { abort("'getLEB' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2246if (!Object.getOwnPropertyDescriptor(Module, "getFunctionTables")) Module["getFunctionTables"] = function() { abort("'getFunctionTables' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2247if (!Object.getOwnPropertyDescriptor(Module, "alignFunctionTables")) Module["alignFunctionTables"] = function() { abort("'alignFunctionTables' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2248if (!Object.getOwnPropertyDescriptor(Module, "registerFunctions")) Module["registerFunctions"] = function() { abort("'registerFunctions' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2249if (!Object.getOwnPropertyDescriptor(Module, "addFunction")) Module["addFunction"] = function() { abort("'addFunction' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2250if (!Object.getOwnPropertyDescriptor(Module, "removeFunction")) Module["removeFunction"] = function() { abort("'removeFunction' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2251if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = function() { abort("'getFuncWrapper' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2252if (!Object.getOwnPropertyDescriptor(Module, "prettyPrint")) Module["prettyPrint"] = function() { abort("'prettyPrint' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2253if (!Object.getOwnPropertyDescriptor(Module, "makeBigInt")) Module["makeBigInt"] = function() { abort("'makeBigInt' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2254if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = function() { abort("'dynCall' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2255if (!Object.getOwnPropertyDescriptor(Module, "getCompilerSetting")) Module["getCompilerSetting"] = function() { abort("'getCompilerSetting' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2256if (!Object.getOwnPropertyDescriptor(Module, "stackSave")) Module["stackSave"] = function() { abort("'stackSave' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2257if (!Object.getOwnPropertyDescriptor(Module, "stackRestore")) Module["stackRestore"] = function() { abort("'stackRestore' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2258if (!Object.getOwnPropertyDescriptor(Module, "stackAlloc")) Module["stackAlloc"] = function() { abort("'stackAlloc' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2259if (!Object.getOwnPropertyDescriptor(Module, "establishStackSpace")) Module["establishStackSpace"] = function() { abort("'establishStackSpace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2260if (!Object.getOwnPropertyDescriptor(Module, "print")) Module["print"] = function() { abort("'print' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2261if (!Object.getOwnPropertyDescriptor(Module, "printErr")) Module["printErr"] = function() { abort("'printErr' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2262if (!Object.getOwnPropertyDescriptor(Module, "getTempRet0")) Module["getTempRet0"] = function() { abort("'getTempRet0' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2263if (!Object.getOwnPropertyDescriptor(Module, "setTempRet0")) Module["setTempRet0"] = function() { abort("'setTempRet0' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2264if (!Object.getOwnPropertyDescriptor(Module, "callMain")) Module["callMain"] = function() { abort("'callMain' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
2265if (!Object.getOwnPropertyDescriptor(Module, "Pointer_stringify")) Module["Pointer_stringify"] = function() { abort("'Pointer_stringify' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_NORMAL")) Object.defineProperty(Module, "ALLOC_NORMAL", { get: function() { abort("'ALLOC_NORMAL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
2266if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_STACK")) Object.defineProperty(Module, "ALLOC_STACK", { get: function() { abort("'ALLOC_STACK' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
2267if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_DYNAMIC")) Object.defineProperty(Module, "ALLOC_DYNAMIC", { get: function() { abort("'ALLOC_DYNAMIC' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
2268if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_NONE")) Object.defineProperty(Module, "ALLOC_NONE", { get: function() { abort("'ALLOC_NONE' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
2269
2270
2271
2272
2273/**
2274 * @constructor
2275 * @this {ExitStatus}
2276 */
2277function ExitStatus(status) {
2278 this.name = "ExitStatus";
2279 this.message = "Program terminated with exit(" + status + ")";
2280 this.status = status;
2281}
2282
2283var calledMain = false;
2284
2285dependenciesFulfilled = function runCaller() {
2286 // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
2287 if (!Module['calledRun']) run();
2288 if (!Module['calledRun']) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
2289};
2290
2291function callMain(args) {
2292 assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on Module["onRuntimeInitialized"])');
2293 assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
2294
2295 args = args || [];
2296
2297 var argc = args.length+1;
2298 var argv = stackAlloc((argc + 1) * 4);
2299 HEAP32[argv >> 2] = allocateUTF8OnStack(thisProgram);
2300 for (var i = 1; i < argc; i++) {
2301 HEAP32[(argv >> 2) + i] = allocateUTF8OnStack(args[i - 1]);
2302 }
2303 HEAP32[(argv >> 2) + argc] = 0;
2304
2305
2306 try {
2307
2308
2309 var ret = Module['_main'](argc, argv);
2310
2311
2312 // if we're not running an evented main loop, it's time to exit
2313 exit(ret, /* implicit = */ true);
2314 }
2315 catch(e) {
2316 if (e instanceof ExitStatus) {
2317 // exit() throws this once it's done to make sure execution
2318 // has been stopped completely
2319 return;
2320 } else if (e == 'SimulateInfiniteLoop') {
2321 // running an evented main loop, don't immediately exit
2322 Module['noExitRuntime'] = true;
2323 return;
2324 } else {
2325 var toLog = e;
2326 if (e && typeof e === 'object' && e.stack) {
2327 toLog = [e, e.stack];
2328 }
2329 err('exception thrown: ' + toLog);
2330 quit_(1, e);
2331 }
2332 } finally {
2333 calledMain = true;
2334 }
2335}
2336
2337
2338
2339
2340/** @type {function(Array=)} */
2341function run(args) {
2342 args = args || arguments_;
2343
2344 if (runDependencies > 0) {
2345 return;
2346 }
2347
2348 writeStackCookie();
2349
2350 preRun();
2351
2352 if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
2353 if (Module['calledRun']) return; // run may have just been called through dependencies being fulfilled just in this very frame
2354
2355 function doRun() {
2356 if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
2357 Module['calledRun'] = true;
2358
2359 if (ABORT) return;
2360
2361 initRuntime();
2362
2363 preMain();
2364
2365 if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
2366
2367 if (shouldRunNow) callMain(args);
2368
2369 postRun();
2370 }
2371
2372 if (Module['setStatus']) {
2373 Module['setStatus']('Running...');
2374 setTimeout(function() {
2375 setTimeout(function() {
2376 Module['setStatus']('');
2377 }, 1);
2378 doRun();
2379 }, 1);
2380 } else
2381 {
2382 doRun();
2383 }
2384 checkStackCookie();
2385}
2386Module['run'] = run;
2387
2388function checkUnflushedContent() {
2389 // Compiler settings do not allow exiting the runtime, so flushing
2390 // the streams is not possible. but in ASSERTIONS mode we check
2391 // if there was something to flush, and if so tell the user they
2392 // should request that the runtime be exitable.
2393 // Normally we would not even include flush() at all, but in ASSERTIONS
2394 // builds we do so just for this check, and here we see if there is any
2395 // content to flush, that is, we check if there would have been
2396 // something a non-ASSERTIONS build would have not seen.
2397 // How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0
2398 // mode (which has its own special function for this; otherwise, all
2399 // the code is inside libc)
2400 var print = out;
2401 var printErr = err;
2402 var has = false;
2403 out = err = function(x) {
2404 has = true;
2405 }
2406 try { // it doesn't matter if it fails
2407 var flush = flush_NO_FILESYSTEM;
2408 if (flush) flush(0);
2409 } catch(e) {}
2410 out = print;
2411 err = printErr;
2412 if (has) {
2413 warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc.');
2414 warnOnce('(this may also be due to not including full filesystem support - try building with -s FORCE_FILESYSTEM=1)');
2415 }
2416}
2417
2418function exit(status, implicit) {
2419 checkUnflushedContent();
2420
2421 // if this is just main exit-ing implicitly, and the status is 0, then we
2422 // don't need to do anything here and can just leave. if the status is
2423 // non-zero, though, then we need to report it.
2424 // (we may have warned about this earlier, if a situation justifies doing so)
2425 if (implicit && Module['noExitRuntime'] && status === 0) {
2426 return;
2427 }
2428
2429 if (Module['noExitRuntime']) {
2430 // if exit() was called, we may warn the user if the runtime isn't actually being shut down
2431 if (!implicit) {
2432 err('exit(' + status + ') called, but EXIT_RUNTIME is not set, so halting execution but not exiting the runtime or preventing further async execution (build with EXIT_RUNTIME=1, if you want a true shutdown)');
2433 }
2434 } else {
2435
2436 ABORT = true;
2437 EXITSTATUS = status;
2438
2439 exitRuntime();
2440
2441 if (Module['onExit']) Module['onExit'](status);
2442 }
2443
2444 quit_(status, new ExitStatus(status));
2445}
2446
2447var abortDecorators = [];
2448
2449function abort(what) {
2450 if (Module['onAbort']) {
2451 Module['onAbort'](what);
2452 }
2453
2454 what += '';
2455 out(what);
2456 err(what);
2457
2458 ABORT = true;
2459 EXITSTATUS = 1;
2460
2461 var extra = '';
2462 var output = 'abort(' + what + ') at ' + stackTrace() + extra;
2463 if (abortDecorators) {
2464 abortDecorators.forEach(function(decorator) {
2465 output = decorator(output, what);
2466 });
2467 }
2468 throw output;
2469}
2470Module['abort'] = abort;
2471
2472if (Module['preInit']) {
2473 if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
2474 while (Module['preInit'].length > 0) {
2475 Module['preInit'].pop()();
2476 }
2477}
2478
2479// shouldRunNow refers to calling main(), not run().
2480var shouldRunNow = true;
2481
2482if (Module['noInitialRun']) shouldRunNow = false;
2483
2484
2485 Module["noExitRuntime"] = true;
2486
2487run();
2488
2489
2490
2491
2492
2493// {{MODULE_ADDITIONS}}