You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2964 lines
103 KiB

8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
  1. // include: shell.js
  2. // The Module object: Our interface to the outside world. We import
  3. // and export values on it. There are various ways Module can be used:
  4. // 1. Not defined. We create it here
  5. // 2. A function parameter, function(moduleArg) => Promise<Module>
  6. // 3. pre-run appended it, var Module = {}; ..generated code..
  7. // 4. External script tag defines var Module.
  8. // We need to check if Module already exists (e.g. case 3 above).
  9. // Substitution will be replaced with actual code on later stage of the build,
  10. // this way Closure Compiler will not mangle it (e.g. case 4. above).
  11. // Note that if you want to run closure, and also to use Module
  12. // after the generated code, you will need to define var Module = {};
  13. // before the code. Then that object will be used in the code, and you
  14. // can continue to use Module afterwards as well.
  15. var Module = typeof Module != 'undefined' ? Module : {};
  16. // Determine the runtime environment we are in. You can customize this by
  17. // setting the ENVIRONMENT setting at compile time (see settings.js).
  18. // Attempt to auto-detect the environment
  19. var ENVIRONMENT_IS_WEB = typeof window == 'object';
  20. var ENVIRONMENT_IS_WORKER = typeof importScripts == 'function';
  21. // N.b. Electron.js environment is simultaneously a NODE-environment, but
  22. // also a web environment.
  23. var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string';
  24. var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
  25. if (Module['ENVIRONMENT']) {
  26. throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)');
  27. }
  28. if (ENVIRONMENT_IS_NODE) {
  29. // `require()` is no-op in an ESM module, use `createRequire()` to construct
  30. // the require()` function. This is only necessary for multi-environment
  31. // builds, `-sENVIRONMENT=node` emits a static import declaration instead.
  32. // TODO: Swap all `require()`'s with `import()`'s?
  33. }
  34. // --pre-jses are emitted after the Module integration code, so that they can
  35. // refer to Module (if they choose; they can also define Module)
  36. // Sometimes an existing Module object exists with properties
  37. // meant to overwrite the default module functionality. Here
  38. // we collect those properties and reapply _after_ we configure
  39. // the current environment's defaults to avoid having to be so
  40. // defensive during initialization.
  41. var moduleOverrides = Object.assign({}, Module);
  42. var arguments_ = [];
  43. var thisProgram = './this.program';
  44. var quit_ = (status, toThrow) => {
  45. throw toThrow;
  46. };
  47. // `/` should be present at the end if `scriptDirectory` is not empty
  48. var scriptDirectory = '';
  49. function locateFile(path) {
  50. if (Module['locateFile']) {
  51. return Module['locateFile'](path, scriptDirectory);
  52. }
  53. return scriptDirectory + path;
  54. }
  55. // Hooks that are implemented differently in different runtime environments.
  56. var read_,
  57. readAsync,
  58. readBinary;
  59. if (ENVIRONMENT_IS_NODE) {
  60. if (typeof process == 'undefined' || !process.release || process.release.name !== 'node') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  61. var nodeVersion = process.versions.node;
  62. var numericVersion = nodeVersion.split('.').slice(0, 3);
  63. numericVersion = (numericVersion[0] * 10000) + (numericVersion[1] * 100) + (numericVersion[2].split('-')[0] * 1);
  64. var minVersion = 160000;
  65. if (numericVersion < 160000) {
  66. throw new Error('This emscripten-generated code requires node v16.0.0 (detected v' + nodeVersion + ')');
  67. }
  68. // These modules will usually be used on Node.js. Load them eagerly to avoid
  69. // the complexity of lazy-loading.
  70. var fs = require('fs');
  71. var nodePath = require('path');
  72. if (ENVIRONMENT_IS_WORKER) {
  73. scriptDirectory = nodePath.dirname(scriptDirectory) + '/';
  74. } else {
  75. scriptDirectory = __dirname + '/';
  76. }
  77. // include: node_shell_read.js
  78. read_ = (filename, binary) => {
  79. // We need to re-wrap `file://` strings to URLs. Normalizing isn't
  80. // necessary in that case, the path should already be absolute.
  81. filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
  82. return fs.readFileSync(filename, binary ? undefined : 'utf8');
  83. };
  84. readBinary = (filename) => {
  85. var ret = read_(filename, true);
  86. if (!ret.buffer) {
  87. ret = new Uint8Array(ret);
  88. }
  89. assert(ret.buffer);
  90. return ret;
  91. };
  92. readAsync = (filename, onload, onerror, binary = true) => {
  93. // See the comment in the `read_` function.
  94. filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
  95. fs.readFile(filename, binary ? undefined : 'utf8', (err, data) => {
  96. if (err) onerror(err);
  97. else onload(binary ? data.buffer : data);
  98. });
  99. };
  100. // end include: node_shell_read.js
  101. if (!Module['thisProgram'] && process.argv.length > 1) {
  102. thisProgram = process.argv[1].replace(/\\/g, '/');
  103. }
  104. arguments_ = process.argv.slice(2);
  105. if (typeof module != 'undefined') {
  106. module['exports'] = Module;
  107. }
  108. process.on('uncaughtException', (ex) => {
  109. // suppress ExitStatus exceptions from showing an error
  110. if (ex !== 'unwind' && !(ex instanceof ExitStatus) && !(ex.context instanceof ExitStatus)) {
  111. throw ex;
  112. }
  113. });
  114. quit_ = (status, toThrow) => {
  115. process.exitCode = status;
  116. throw toThrow;
  117. };
  118. } else
  119. if (ENVIRONMENT_IS_SHELL) {
  120. if ((typeof process == 'object' && typeof require === 'function') || typeof window == 'object' || typeof importScripts == 'function') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  121. } else
  122. // Note that this includes Node.js workers when relevant (pthreads is enabled).
  123. // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
  124. // ENVIRONMENT_IS_NODE.
  125. if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
  126. if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled
  127. scriptDirectory = self.location.href;
  128. } else if (typeof document != 'undefined' && document.currentScript) { // web
  129. scriptDirectory = document.currentScript.src;
  130. }
  131. // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
  132. // otherwise, slice off the final part of the url to find the script directory.
  133. // if scriptDirectory does not contain a slash, lastIndexOf will return -1,
  134. // and scriptDirectory will correctly be replaced with an empty string.
  135. // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #),
  136. // they are removed because they could contain a slash.
  137. if (scriptDirectory.startsWith('blob:')) {
  138. scriptDirectory = '';
  139. } else {
  140. scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/')+1);
  141. }
  142. if (!(typeof window == 'object' || typeof importScripts == 'function')) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)');
  143. {
  144. // include: web_or_worker_shell_read.js
  145. read_ = (url) => {
  146. var xhr = new XMLHttpRequest();
  147. xhr.open('GET', url, false);
  148. xhr.send(null);
  149. return xhr.responseText;
  150. }
  151. if (ENVIRONMENT_IS_WORKER) {
  152. readBinary = (url) => {
  153. var xhr = new XMLHttpRequest();
  154. xhr.open('GET', url, false);
  155. xhr.responseType = 'arraybuffer';
  156. xhr.send(null);
  157. return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
  158. };
  159. }
  160. readAsync = (url, onload, onerror) => {
  161. var xhr = new XMLHttpRequest();
  162. xhr.open('GET', url, true);
  163. xhr.responseType = 'arraybuffer';
  164. xhr.onload = () => {
  165. if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
  166. onload(xhr.response);
  167. return;
  168. }
  169. onerror();
  170. };
  171. xhr.onerror = onerror;
  172. xhr.send(null);
  173. }
  174. // end include: web_or_worker_shell_read.js
  175. }
  176. } else
  177. {
  178. throw new Error('environment detection error');
  179. }
  180. var out = Module['print'] || console.log.bind(console);
  181. var err = Module['printErr'] || console.error.bind(console);
  182. // Merge back in the overrides
  183. Object.assign(Module, moduleOverrides);
  184. // Free the object hierarchy contained in the overrides, this lets the GC
  185. // reclaim data used.
  186. moduleOverrides = null;
  187. checkIncomingModuleAPI();
  188. // Emit code to handle expected values on the Module object. This applies Module.x
  189. // to the proper local x. This has two benefits: first, we only emit it if it is
  190. // expected to arrive, and second, by using a local everywhere else that can be
  191. // minified.
  192. if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');
  193. if (Module['thisProgram']) thisProgram = Module['thisProgram'];legacyModuleProp('thisProgram', 'thisProgram');
  194. if (Module['quit']) quit_ = Module['quit'];legacyModuleProp('quit', 'quit_');
  195. // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
  196. // Assertions on removed incoming Module JS APIs.
  197. assert(typeof Module['memoryInitializerPrefixURL'] == 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
  198. assert(typeof Module['pthreadMainPrefixURL'] == 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
  199. assert(typeof Module['cdInitializerPrefixURL'] == 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
  200. assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
  201. assert(typeof Module['read'] == 'undefined', 'Module.read option was removed (modify read_ in JS)');
  202. assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
  203. assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
  204. assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)');
  205. assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY');
  206. legacyModuleProp('asm', 'wasmExports');
  207. legacyModuleProp('read', 'read_');
  208. legacyModuleProp('readAsync', 'readAsync');
  209. legacyModuleProp('readBinary', 'readBinary');
  210. legacyModuleProp('setWindowTitle', 'setWindowTitle');
  211. var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';
  212. var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';
  213. var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';
  214. var FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js';
  215. var ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js';
  216. var JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js';
  217. var OPFS = 'OPFS is no longer included by default; build with -lopfs.js';
  218. var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';
  219. assert(!ENVIRONMENT_IS_SHELL, 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.');
  220. // end include: shell.js
  221. // include: preamble.js
  222. // === Preamble library stuff ===
  223. // Documentation for the public APIs defined in this file must be updated in:
  224. // site/source/docs/api_reference/preamble.js.rst
  225. // A prebuilt local version of the documentation is available at:
  226. // site/build/text/docs/api_reference/preamble.js.txt
  227. // You can also build docs locally as HTML or other formats in site/
  228. // An online HTML version (which may be of a different version of Emscripten)
  229. // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
  230. var wasmBinary;
  231. if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];legacyModuleProp('wasmBinary', 'wasmBinary');
  232. if (typeof WebAssembly != 'object') {
  233. err('no native wasm support detected');
  234. }
  235. // Wasm globals
  236. var wasmMemory;
  237. //========================================
  238. // Runtime essentials
  239. //========================================
  240. // whether we are quitting the application. no code should run after this.
  241. // set in exit() and abort()
  242. var ABORT = false;
  243. // set by exit() and abort(). Passed to 'onExit' handler.
  244. // NOTE: This is also used as the process return code code in shell environments
  245. // but only when noExitRuntime is false.
  246. var EXITSTATUS;
  247. // In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we
  248. // don't define it at all in release modes. This matches the behaviour of
  249. // MINIMAL_RUNTIME.
  250. // TODO(sbc): Make this the default even without STRICT enabled.
  251. /** @type {function(*, string=)} */
  252. function assert(condition, text) {
  253. if (!condition) {
  254. abort('Assertion failed' + (text ? ': ' + text : ''));
  255. }
  256. }
  257. // We used to include malloc/free by default in the past. Show a helpful error in
  258. // builds with assertions.
  259. // Memory management
  260. var HEAP,
  261. /** @type {!Int8Array} */
  262. HEAP8,
  263. /** @type {!Uint8Array} */
  264. HEAPU8,
  265. /** @type {!Int16Array} */
  266. HEAP16,
  267. /** @type {!Uint16Array} */
  268. HEAPU16,
  269. /** @type {!Int32Array} */
  270. HEAP32,
  271. /** @type {!Uint32Array} */
  272. HEAPU32,
  273. /** @type {!Float32Array} */
  274. HEAPF32,
  275. /** @type {!Float64Array} */
  276. HEAPF64;
  277. // include: runtime_shared.js
  278. function updateMemoryViews() {
  279. var b = wasmMemory.buffer;
  280. Module['HEAP8'] = HEAP8 = new Int8Array(b);
  281. Module['HEAP16'] = HEAP16 = new Int16Array(b);
  282. Module['HEAPU8'] = HEAPU8 = new Uint8Array(b);
  283. Module['HEAPU16'] = HEAPU16 = new Uint16Array(b);
  284. Module['HEAP32'] = HEAP32 = new Int32Array(b);
  285. Module['HEAPU32'] = HEAPU32 = new Uint32Array(b);
  286. Module['HEAPF32'] = HEAPF32 = new Float32Array(b);
  287. Module['HEAPF64'] = HEAPF64 = new Float64Array(b);
  288. }
  289. // end include: runtime_shared.js
  290. assert(!Module['STACK_SIZE'], 'STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time')
  291. assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined,
  292. 'JS engine does not provide full typed array support');
  293. // If memory is defined in wasm, the user can't provide it, or set INITIAL_MEMORY
  294. assert(!Module['wasmMemory'], 'Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally');
  295. assert(!Module['INITIAL_MEMORY'], 'Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically');
  296. // include: runtime_stack_check.js
  297. // Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
  298. function writeStackCookie() {
  299. var max = _emscripten_stack_get_end();
  300. assert((max & 3) == 0);
  301. // If the stack ends at address zero we write our cookies 4 bytes into the
  302. // stack. This prevents interference with SAFE_HEAP and ASAN which also
  303. // monitor writes to address zero.
  304. if (max == 0) {
  305. max += 4;
  306. }
  307. // The stack grow downwards towards _emscripten_stack_get_end.
  308. // We write cookies to the final two words in the stack and detect if they are
  309. // ever overwritten.
  310. HEAPU32[((max)>>2)] = 0x02135467;
  311. HEAPU32[(((max)+(4))>>2)] = 0x89BACDFE;
  312. // Also test the global address 0 for integrity.
  313. HEAPU32[((0)>>2)] = 1668509029;
  314. }
  315. function checkStackCookie() {
  316. if (ABORT) return;
  317. var max = _emscripten_stack_get_end();
  318. // See writeStackCookie().
  319. if (max == 0) {
  320. max += 4;
  321. }
  322. var cookie1 = HEAPU32[((max)>>2)];
  323. var cookie2 = HEAPU32[(((max)+(4))>>2)];
  324. if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) {
  325. abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`);
  326. }
  327. // Also test the global address 0 for integrity.
  328. if (HEAPU32[((0)>>2)] != 0x63736d65 /* 'emsc' */) {
  329. abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
  330. }
  331. }
  332. // end include: runtime_stack_check.js
  333. // include: runtime_assertions.js
  334. // Endianness check
  335. (function() {
  336. var h16 = new Int16Array(1);
  337. var h8 = new Int8Array(h16.buffer);
  338. h16[0] = 0x6373;
  339. if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)';
  340. })();
  341. // end include: runtime_assertions.js
  342. var __ATPRERUN__ = []; // functions called before the runtime is initialized
  343. var __ATINIT__ = []; // functions called during startup
  344. var __ATMAIN__ = []; // functions called when main() is to be run
  345. var __ATEXIT__ = []; // functions called during shutdown
  346. var __ATPOSTRUN__ = []; // functions called after the main() is called
  347. var runtimeInitialized = false;
  348. function preRun() {
  349. if (Module['preRun']) {
  350. if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
  351. while (Module['preRun'].length) {
  352. addOnPreRun(Module['preRun'].shift());
  353. }
  354. }
  355. callRuntimeCallbacks(__ATPRERUN__);
  356. }
  357. function initRuntime() {
  358. assert(!runtimeInitialized);
  359. runtimeInitialized = true;
  360. checkStackCookie();
  361. callRuntimeCallbacks(__ATINIT__);
  362. }
  363. function preMain() {
  364. checkStackCookie();
  365. callRuntimeCallbacks(__ATMAIN__);
  366. }
  367. function postRun() {
  368. checkStackCookie();
  369. if (Module['postRun']) {
  370. if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
  371. while (Module['postRun'].length) {
  372. addOnPostRun(Module['postRun'].shift());
  373. }
  374. }
  375. callRuntimeCallbacks(__ATPOSTRUN__);
  376. }
  377. function addOnPreRun(cb) {
  378. __ATPRERUN__.unshift(cb);
  379. }
  380. function addOnInit(cb) {
  381. __ATINIT__.unshift(cb);
  382. }
  383. function addOnPreMain(cb) {
  384. __ATMAIN__.unshift(cb);
  385. }
  386. function addOnExit(cb) {
  387. }
  388. function addOnPostRun(cb) {
  389. __ATPOSTRUN__.unshift(cb);
  390. }
  391. // include: runtime_math.js
  392. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
  393. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
  394. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
  395. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
  396. assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  397. assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  398. assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  399. assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
  400. // end include: runtime_math.js
  401. // A counter of dependencies for calling run(). If we need to
  402. // do asynchronous work before running, increment this and
  403. // decrement it. Incrementing must happen in a place like
  404. // Module.preRun (used by emcc to add file preloading).
  405. // Note that you can add dependencies in preRun, even though
  406. // it happens right before run - run will be postponed until
  407. // the dependencies are met.
  408. var runDependencies = 0;
  409. var runDependencyWatcher = null;
  410. var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
  411. var runDependencyTracking = {};
  412. function getUniqueRunDependency(id) {
  413. var orig = id;
  414. while (1) {
  415. if (!runDependencyTracking[id]) return id;
  416. id = orig + Math.random();
  417. }
  418. }
  419. function addRunDependency(id) {
  420. runDependencies++;
  421. Module['monitorRunDependencies']?.(runDependencies);
  422. if (id) {
  423. assert(!runDependencyTracking[id]);
  424. runDependencyTracking[id] = 1;
  425. if (runDependencyWatcher === null && typeof setInterval != 'undefined') {
  426. // Check for missing dependencies every few seconds
  427. runDependencyWatcher = setInterval(() => {
  428. if (ABORT) {
  429. clearInterval(runDependencyWatcher);
  430. runDependencyWatcher = null;
  431. return;
  432. }
  433. var shown = false;
  434. for (var dep in runDependencyTracking) {
  435. if (!shown) {
  436. shown = true;
  437. err('still waiting on run dependencies:');
  438. }
  439. err(`dependency: ${dep}`);
  440. }
  441. if (shown) {
  442. err('(end of list)');
  443. }
  444. }, 10000);
  445. }
  446. } else {
  447. err('warning: run dependency added without ID');
  448. }
  449. }
  450. function removeRunDependency(id) {
  451. runDependencies--;
  452. Module['monitorRunDependencies']?.(runDependencies);
  453. if (id) {
  454. assert(runDependencyTracking[id]);
  455. delete runDependencyTracking[id];
  456. } else {
  457. err('warning: run dependency removed without ID');
  458. }
  459. if (runDependencies == 0) {
  460. if (runDependencyWatcher !== null) {
  461. clearInterval(runDependencyWatcher);
  462. runDependencyWatcher = null;
  463. }
  464. if (dependenciesFulfilled) {
  465. var callback = dependenciesFulfilled;
  466. dependenciesFulfilled = null;
  467. callback(); // can add another dependenciesFulfilled
  468. }
  469. }
  470. }
  471. /** @param {string|number=} what */
  472. function abort(what) {
  473. Module['onAbort']?.(what);
  474. what = 'Aborted(' + what + ')';
  475. // TODO(sbc): Should we remove printing and leave it up to whoever
  476. // catches the exception?
  477. err(what);
  478. ABORT = true;
  479. EXITSTATUS = 1;
  480. // Use a wasm runtime error, because a JS error might be seen as a foreign
  481. // exception, which means we'd run destructors on it. We need the error to
  482. // simply make the program stop.
  483. // FIXME This approach does not work in Wasm EH because it currently does not assume
  484. // all RuntimeErrors are from traps; it decides whether a RuntimeError is from
  485. // a trap or not based on a hidden field within the object. So at the moment
  486. // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that
  487. // allows this in the wasm spec.
  488. // Suppress closure compiler warning here. Closure compiler's builtin extern
  489. // definition for WebAssembly.RuntimeError claims it takes no arguments even
  490. // though it can.
  491. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.
  492. /** @suppress {checkTypes} */
  493. var e = new WebAssembly.RuntimeError(what);
  494. // Throw the error whether or not MODULARIZE is set because abort is used
  495. // in code paths apart from instantiation where an exception is expected
  496. // to be thrown when abort is called.
  497. throw e;
  498. }
  499. // include: memoryprofiler.js
  500. // end include: memoryprofiler.js
  501. // show errors on likely calls to FS when it was not included
  502. var FS = {
  503. error() {
  504. abort('Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM');
  505. },
  506. init() { FS.error() },
  507. createDataFile() { FS.error() },
  508. createPreloadedFile() { FS.error() },
  509. createLazyFile() { FS.error() },
  510. open() { FS.error() },
  511. mkdev() { FS.error() },
  512. registerDevice() { FS.error() },
  513. analyzePath() { FS.error() },
  514. ErrnoError() { FS.error() },
  515. };
  516. Module['FS_createDataFile'] = FS.createDataFile;
  517. Module['FS_createPreloadedFile'] = FS.createPreloadedFile;
  518. // include: URIUtils.js
  519. // Prefix of data URIs emitted by SINGLE_FILE and related options.
  520. var dataURIPrefix = 'data:application/octet-stream;base64,';
  521. /**
  522. * Indicates whether filename is a base64 data URI.
  523. * @noinline
  524. */
  525. var isDataURI = (filename) => filename.startsWith(dataURIPrefix);
  526. /**
  527. * Indicates whether filename is delivered via file protocol (as opposed to http/https)
  528. * @noinline
  529. */
  530. var isFileURI = (filename) => filename.startsWith('file://');
  531. // end include: URIUtils.js
  532. function createExportWrapper(name, nargs) {
  533. return (...args) => {
  534. assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`);
  535. var f = wasmExports[name];
  536. assert(f, `exported native function \`${name}\` not found`);
  537. // Only assert for too many arguments. Too few can be valid since the missing arguments will be zero filled.
  538. assert(args.length <= nargs, `native function \`${name}\` called with ${args.length} args but expects ${nargs}`);
  539. return f(...args);
  540. };
  541. }
  542. // include: runtime_exceptions.js
  543. // end include: runtime_exceptions.js
  544. var wasmBinaryFile;
  545. wasmBinaryFile = 'test.wasm';
  546. if (!isDataURI(wasmBinaryFile)) {
  547. wasmBinaryFile = locateFile(wasmBinaryFile);
  548. }
  549. function getBinarySync(file) {
  550. if (file == wasmBinaryFile && wasmBinary) {
  551. return new Uint8Array(wasmBinary);
  552. }
  553. if (readBinary) {
  554. return readBinary(file);
  555. }
  556. throw 'both async and sync fetching of the wasm failed';
  557. }
  558. function getBinaryPromise(binaryFile) {
  559. // If we don't have the binary yet, try to load it asynchronously.
  560. // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.
  561. // See https://github.com/github/fetch/pull/92#issuecomment-140665932
  562. // Cordova or Electron apps are typically loaded from a file:// url.
  563. // So use fetch if it is available and the url is not a file, otherwise fall back to XHR.
  564. if (!wasmBinary
  565. && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
  566. if (typeof fetch == 'function'
  567. && !isFileURI(binaryFile)
  568. ) {
  569. return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => {
  570. if (!response['ok']) {
  571. throw `failed to load wasm binary file at '${binaryFile}'`;
  572. }
  573. return response['arrayBuffer']();
  574. }).catch(() => getBinarySync(binaryFile));
  575. }
  576. else if (readAsync) {
  577. // fetch is not available or url is file => try XHR (readAsync uses XHR internally)
  578. return new Promise((resolve, reject) => {
  579. readAsync(binaryFile, (response) => resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))), reject)
  580. });
  581. }
  582. }
  583. // Otherwise, getBinarySync should be able to get it synchronously
  584. return Promise.resolve().then(() => getBinarySync(binaryFile));
  585. }
  586. function instantiateArrayBuffer(binaryFile, imports, receiver) {
  587. return getBinaryPromise(binaryFile).then((binary) => {
  588. return WebAssembly.instantiate(binary, imports);
  589. }).then(receiver, (reason) => {
  590. err(`failed to asynchronously prepare wasm: ${reason}`);
  591. // Warn on some common problems.
  592. if (isFileURI(wasmBinaryFile)) {
  593. err(`warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`);
  594. }
  595. abort(reason);
  596. });
  597. }
  598. function instantiateAsync(binary, binaryFile, imports, callback) {
  599. if (!binary &&
  600. typeof WebAssembly.instantiateStreaming == 'function' &&
  601. !isDataURI(binaryFile) &&
  602. // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.
  603. !isFileURI(binaryFile) &&
  604. // Avoid instantiateStreaming() on Node.js environment for now, as while
  605. // Node.js v18.1.0 implements it, it does not have a full fetch()
  606. // implementation yet.
  607. //
  608. // Reference:
  609. // https://github.com/emscripten-core/emscripten/pull/16917
  610. !ENVIRONMENT_IS_NODE &&
  611. typeof fetch == 'function') {
  612. return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => {
  613. // Suppress closure warning here since the upstream definition for
  614. // instantiateStreaming only allows Promise<Repsponse> rather than
  615. // an actual Response.
  616. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed.
  617. /** @suppress {checkTypes} */
  618. var result = WebAssembly.instantiateStreaming(response, imports);
  619. return result.then(
  620. callback,
  621. function(reason) {
  622. // We expect the most common failure cause to be a bad MIME type for the binary,
  623. // in which case falling back to ArrayBuffer instantiation should work.
  624. err(`wasm streaming compile failed: ${reason}`);
  625. err('falling back to ArrayBuffer instantiation');
  626. return instantiateArrayBuffer(binaryFile, imports, callback);
  627. });
  628. });
  629. }
  630. return instantiateArrayBuffer(binaryFile, imports, callback);
  631. }
  632. function getWasmImports() {
  633. // prepare imports
  634. return {
  635. 'env': wasmImports,
  636. 'wasi_snapshot_preview1': wasmImports,
  637. }
  638. }
  639. // Create the wasm instance.
  640. // Receives the wasm imports, returns the exports.
  641. function createWasm() {
  642. var info = getWasmImports();
  643. // Load the wasm module and create an instance of using native support in the JS engine.
  644. // handle a generated wasm instance, receiving its exports and
  645. // performing other necessary setup
  646. /** @param {WebAssembly.Module=} module*/
  647. function receiveInstance(instance, module) {
  648. wasmExports = instance.exports;
  649. wasmMemory = wasmExports['memory'];
  650. assert(wasmMemory, 'memory not found in wasm exports');
  651. updateMemoryViews();
  652. wasmTable = wasmExports['__indirect_function_table'];
  653. assert(wasmTable, 'table not found in wasm exports');
  654. addOnInit(wasmExports['__wasm_call_ctors']);
  655. removeRunDependency('wasm-instantiate');
  656. return wasmExports;
  657. }
  658. // wait for the pthread pool (if any)
  659. addRunDependency('wasm-instantiate');
  660. // Prefer streaming instantiation if available.
  661. // Async compilation can be confusing when an error on the page overwrites Module
  662. // (for example, if the order of elements is wrong, and the one defining Module is
  663. // later), so we save Module and check it later.
  664. var trueModule = Module;
  665. function receiveInstantiationResult(result) {
  666. // 'result' is a ResultObject object which has both the module and instance.
  667. // receiveInstance() will swap in the exports (to Module.asm) so they can be called
  668. assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
  669. trueModule = null;
  670. // 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.
  671. // When the regression is fixed, can restore the above PTHREADS-enabled path.
  672. receiveInstance(result['instance']);
  673. }
  674. // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
  675. // to manually instantiate the Wasm module themselves. This allows pages to
  676. // run the instantiation parallel to any other async startup actions they are
  677. // performing.
  678. // Also pthreads and wasm workers initialize the wasm instance through this
  679. // path.
  680. if (Module['instantiateWasm']) {
  681. try {
  682. return Module['instantiateWasm'](info, receiveInstance);
  683. } catch(e) {
  684. err(`Module.instantiateWasm callback failed with error: ${e}`);
  685. return false;
  686. }
  687. }
  688. instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult);
  689. return {}; // no exports yet; we'll fill them in later
  690. }
  691. // Globals used by JS i64 conversions (see makeSetValue)
  692. var tempDouble;
  693. var tempI64;
  694. // include: runtime_debug.js
  695. function legacyModuleProp(prop, newName, incoming=true) {
  696. if (!Object.getOwnPropertyDescriptor(Module, prop)) {
  697. Object.defineProperty(Module, prop, {
  698. configurable: true,
  699. get() {
  700. let extra = incoming ? ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)' : '';
  701. abort(`\`Module.${prop}\` has been replaced by \`${newName}\`` + extra);
  702. }
  703. });
  704. }
  705. }
  706. function ignoredModuleProp(prop) {
  707. if (Object.getOwnPropertyDescriptor(Module, prop)) {
  708. abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`);
  709. }
  710. }
  711. // forcing the filesystem exports a few things by default
  712. function isExportedByForceFilesystem(name) {
  713. return name === 'FS_createPath' ||
  714. name === 'FS_createDataFile' ||
  715. name === 'FS_createPreloadedFile' ||
  716. name === 'FS_unlink' ||
  717. name === 'addRunDependency' ||
  718. // The old FS has some functionality that WasmFS lacks.
  719. name === 'FS_createLazyFile' ||
  720. name === 'FS_createDevice' ||
  721. name === 'removeRunDependency';
  722. }
  723. function missingGlobal(sym, msg) {
  724. if (typeof globalThis != 'undefined') {
  725. Object.defineProperty(globalThis, sym, {
  726. configurable: true,
  727. get() {
  728. warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`);
  729. return undefined;
  730. }
  731. });
  732. }
  733. }
  734. missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer');
  735. missingGlobal('asm', 'Please use wasmExports instead');
  736. function missingLibrarySymbol(sym) {
  737. if (typeof globalThis != 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) {
  738. Object.defineProperty(globalThis, sym, {
  739. configurable: true,
  740. get() {
  741. // Can't `abort()` here because it would break code that does runtime
  742. // checks. e.g. `if (typeof SDL === 'undefined')`.
  743. var msg = `\`${sym}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`;
  744. // DEFAULT_LIBRARY_FUNCS_TO_INCLUDE requires the name as it appears in
  745. // library.js, which means $name for a JS name with no prefix, or name
  746. // for a JS name like _name.
  747. var librarySymbol = sym;
  748. if (!librarySymbol.startsWith('_')) {
  749. librarySymbol = '$' + sym;
  750. }
  751. msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`;
  752. if (isExportedByForceFilesystem(sym)) {
  753. msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';
  754. }
  755. warnOnce(msg);
  756. return undefined;
  757. }
  758. });
  759. }
  760. // Any symbol that is not included from the JS library is also (by definition)
  761. // not exported on the Module object.
  762. unexportedRuntimeSymbol(sym);
  763. }
  764. function unexportedRuntimeSymbol(sym) {
  765. if (!Object.getOwnPropertyDescriptor(Module, sym)) {
  766. Object.defineProperty(Module, sym, {
  767. configurable: true,
  768. get() {
  769. var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;
  770. if (isExportedByForceFilesystem(sym)) {
  771. msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';
  772. }
  773. abort(msg);
  774. }
  775. });
  776. }
  777. }
  778. // Used by XXXXX_DEBUG settings to output debug messages.
  779. function dbg(...args) {
  780. // TODO(sbc): Make this configurable somehow. Its not always convenient for
  781. // logging to show up as warnings.
  782. console.warn(...args);
  783. }
  784. // end include: runtime_debug.js
  785. // === Body ===
  786. // end include: preamble.js
  787. /** @constructor */
  788. function ExitStatus(status) {
  789. this.name = 'ExitStatus';
  790. this.message = `Program terminated with exit(${status})`;
  791. this.status = status;
  792. }
  793. var callRuntimeCallbacks = (callbacks) => {
  794. while (callbacks.length > 0) {
  795. // Pass the module as the first argument.
  796. callbacks.shift()(Module);
  797. }
  798. };
  799. /**
  800. * @param {number} ptr
  801. * @param {string} type
  802. */
  803. function getValue(ptr, type = 'i8') {
  804. if (type.endsWith('*')) type = '*';
  805. switch (type) {
  806. case 'i1': return HEAP8[ptr];
  807. case 'i8': return HEAP8[ptr];
  808. case 'i16': return HEAP16[((ptr)>>1)];
  809. case 'i32': return HEAP32[((ptr)>>2)];
  810. case 'i64': abort('to do getValue(i64) use WASM_BIGINT');
  811. case 'float': return HEAPF32[((ptr)>>2)];
  812. case 'double': return HEAPF64[((ptr)>>3)];
  813. case '*': return HEAPU32[((ptr)>>2)];
  814. default: abort(`invalid type for getValue: ${type}`);
  815. }
  816. }
  817. var noExitRuntime = Module['noExitRuntime'] || true;
  818. var ptrToString = (ptr) => {
  819. assert(typeof ptr === 'number');
  820. // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
  821. ptr >>>= 0;
  822. return '0x' + ptr.toString(16).padStart(8, '0');
  823. };
  824. /**
  825. * @param {number} ptr
  826. * @param {number} value
  827. * @param {string} type
  828. */
  829. function setValue(ptr, value, type = 'i8') {
  830. if (type.endsWith('*')) type = '*';
  831. switch (type) {
  832. case 'i1': HEAP8[ptr] = value; break;
  833. case 'i8': HEAP8[ptr] = value; break;
  834. case 'i16': HEAP16[((ptr)>>1)] = value; break;
  835. case 'i32': HEAP32[((ptr)>>2)] = value; break;
  836. case 'i64': abort('to do setValue(i64) use WASM_BIGINT');
  837. case 'float': HEAPF32[((ptr)>>2)] = value; break;
  838. case 'double': HEAPF64[((ptr)>>3)] = value; break;
  839. case '*': HEAPU32[((ptr)>>2)] = value; break;
  840. default: abort(`invalid type for setValue: ${type}`);
  841. }
  842. }
  843. var stackRestore = (val) => __emscripten_stack_restore(val);
  844. var stackSave = () => _emscripten_stack_get_current();
  845. var warnOnce = (text) => {
  846. warnOnce.shown ||= {};
  847. if (!warnOnce.shown[text]) {
  848. warnOnce.shown[text] = 1;
  849. if (ENVIRONMENT_IS_NODE) text = 'warning: ' + text;
  850. err(text);
  851. }
  852. };
  853. var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined;
  854. /**
  855. * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given
  856. * array that contains uint8 values, returns a copy of that string as a
  857. * Javascript String object.
  858. * heapOrArray is either a regular array, or a JavaScript typed array view.
  859. * @param {number} idx
  860. * @param {number=} maxBytesToRead
  861. * @return {string}
  862. */
  863. var UTF8ArrayToString = (heapOrArray, idx, maxBytesToRead) => {
  864. var endIdx = idx + maxBytesToRead;
  865. var endPtr = idx;
  866. // TextDecoder needs to know the byte length in advance, it doesn't stop on
  867. // null terminator by itself. Also, use the length info to avoid running tiny
  868. // strings through TextDecoder, since .subarray() allocates garbage.
  869. // (As a tiny code save trick, compare endPtr against endIdx using a negation,
  870. // so that undefined means Infinity)
  871. while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
  872. if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
  873. return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
  874. }
  875. var str = '';
  876. // If building with TextDecoder, we have already computed the string length
  877. // above, so test loop end condition against that
  878. while (idx < endPtr) {
  879. // For UTF8 byte structure, see:
  880. // http://en.wikipedia.org/wiki/UTF-8#Description
  881. // https://www.ietf.org/rfc/rfc2279.txt
  882. // https://tools.ietf.org/html/rfc3629
  883. var u0 = heapOrArray[idx++];
  884. if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
  885. var u1 = heapOrArray[idx++] & 63;
  886. if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
  887. var u2 = heapOrArray[idx++] & 63;
  888. if ((u0 & 0xF0) == 0xE0) {
  889. u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
  890. } else {
  891. if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte ' + ptrToString(u0) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!');
  892. u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);
  893. }
  894. if (u0 < 0x10000) {
  895. str += String.fromCharCode(u0);
  896. } else {
  897. var ch = u0 - 0x10000;
  898. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  899. }
  900. }
  901. return str;
  902. };
  903. /**
  904. * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the
  905. * emscripten HEAP, returns a copy of that string as a Javascript String object.
  906. *
  907. * @param {number} ptr
  908. * @param {number=} maxBytesToRead - An optional length that specifies the
  909. * maximum number of bytes to read. You can omit this parameter to scan the
  910. * string until the first 0 byte. If maxBytesToRead is passed, and the string
  911. * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the
  912. * string will cut short at that byte index (i.e. maxBytesToRead will not
  913. * produce a string of exact length [ptr, ptr+maxBytesToRead[) N.B. mixing
  914. * frequent uses of UTF8ToString() with and without maxBytesToRead may throw
  915. * JS JIT optimizations off, so it is worth to consider consistently using one
  916. * @return {string}
  917. */
  918. var UTF8ToString = (ptr, maxBytesToRead) => {
  919. assert(typeof ptr == 'number', `UTF8ToString expects a number (got ${typeof ptr})`);
  920. return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
  921. };
  922. var ___assert_fail = (condition, filename, line, func) => {
  923. abort(`Assertion failed: ${UTF8ToString(condition)}, at: ` + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']);
  924. };
  925. class ExceptionInfo {
  926. // excPtr - Thrown object pointer to wrap. Metadata pointer is calculated from it.
  927. constructor(excPtr) {
  928. this.excPtr = excPtr;
  929. this.ptr = excPtr - 24;
  930. }
  931. set_type(type) {
  932. HEAPU32[(((this.ptr)+(4))>>2)] = type;
  933. }
  934. get_type() {
  935. return HEAPU32[(((this.ptr)+(4))>>2)];
  936. }
  937. set_destructor(destructor) {
  938. HEAPU32[(((this.ptr)+(8))>>2)] = destructor;
  939. }
  940. get_destructor() {
  941. return HEAPU32[(((this.ptr)+(8))>>2)];
  942. }
  943. set_caught(caught) {
  944. caught = caught ? 1 : 0;
  945. HEAP8[(this.ptr)+(12)] = caught;
  946. }
  947. get_caught() {
  948. return HEAP8[(this.ptr)+(12)] != 0;
  949. }
  950. set_rethrown(rethrown) {
  951. rethrown = rethrown ? 1 : 0;
  952. HEAP8[(this.ptr)+(13)] = rethrown;
  953. }
  954. get_rethrown() {
  955. return HEAP8[(this.ptr)+(13)] != 0;
  956. }
  957. // Initialize native structure fields. Should be called once after allocated.
  958. init(type, destructor) {
  959. this.set_adjusted_ptr(0);
  960. this.set_type(type);
  961. this.set_destructor(destructor);
  962. }
  963. set_adjusted_ptr(adjustedPtr) {
  964. HEAPU32[(((this.ptr)+(16))>>2)] = adjustedPtr;
  965. }
  966. get_adjusted_ptr() {
  967. return HEAPU32[(((this.ptr)+(16))>>2)];
  968. }
  969. // Get pointer which is expected to be received by catch clause in C++ code. It may be adjusted
  970. // when the pointer is casted to some of the exception object base classes (e.g. when virtual
  971. // inheritance is used). When a pointer is thrown this method should return the thrown pointer
  972. // itself.
  973. get_exception_ptr() {
  974. // Work around a fastcomp bug, this code is still included for some reason in a build without
  975. // exceptions support.
  976. var isPointer = ___cxa_is_pointer_type(this.get_type());
  977. if (isPointer) {
  978. return HEAPU32[((this.excPtr)>>2)];
  979. }
  980. var adjusted = this.get_adjusted_ptr();
  981. if (adjusted !== 0) return adjusted;
  982. return this.excPtr;
  983. }
  984. }
  985. var exceptionLast = 0;
  986. var uncaughtExceptionCount = 0;
  987. var ___cxa_throw = (ptr, type, destructor) => {
  988. var info = new ExceptionInfo(ptr);
  989. // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception.
  990. info.init(type, destructor);
  991. exceptionLast = ptr;
  992. uncaughtExceptionCount++;
  993. assert(false, 'Exception thrown, but exception catching is not enabled. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch.');
  994. };
  995. var __embind_register_bigint = (primitiveType, name, size, minRange, maxRange) => {};
  996. var embind_init_charCodes = () => {
  997. var codes = new Array(256);
  998. for (var i = 0; i < 256; ++i) {
  999. codes[i] = String.fromCharCode(i);
  1000. }
  1001. embind_charCodes = codes;
  1002. };
  1003. var embind_charCodes;
  1004. var readLatin1String = (ptr) => {
  1005. var ret = "";
  1006. var c = ptr;
  1007. while (HEAPU8[c]) {
  1008. ret += embind_charCodes[HEAPU8[c++]];
  1009. }
  1010. return ret;
  1011. };
  1012. var awaitingDependencies = {
  1013. };
  1014. var registeredTypes = {
  1015. };
  1016. var typeDependencies = {
  1017. };
  1018. var BindingError;
  1019. var throwBindingError = (message) => { throw new BindingError(message); };
  1020. var InternalError;
  1021. var throwInternalError = (message) => { throw new InternalError(message); };
  1022. var whenDependentTypesAreResolved = (myTypes, dependentTypes, getTypeConverters) => {
  1023. myTypes.forEach(function(type) {
  1024. typeDependencies[type] = dependentTypes;
  1025. });
  1026. function onComplete(typeConverters) {
  1027. var myTypeConverters = getTypeConverters(typeConverters);
  1028. if (myTypeConverters.length !== myTypes.length) {
  1029. throwInternalError('Mismatched type converter count');
  1030. }
  1031. for (var i = 0; i < myTypes.length; ++i) {
  1032. registerType(myTypes[i], myTypeConverters[i]);
  1033. }
  1034. }
  1035. var typeConverters = new Array(dependentTypes.length);
  1036. var unregisteredTypes = [];
  1037. var registered = 0;
  1038. dependentTypes.forEach((dt, i) => {
  1039. if (registeredTypes.hasOwnProperty(dt)) {
  1040. typeConverters[i] = registeredTypes[dt];
  1041. } else {
  1042. unregisteredTypes.push(dt);
  1043. if (!awaitingDependencies.hasOwnProperty(dt)) {
  1044. awaitingDependencies[dt] = [];
  1045. }
  1046. awaitingDependencies[dt].push(() => {
  1047. typeConverters[i] = registeredTypes[dt];
  1048. ++registered;
  1049. if (registered === unregisteredTypes.length) {
  1050. onComplete(typeConverters);
  1051. }
  1052. });
  1053. }
  1054. });
  1055. if (0 === unregisteredTypes.length) {
  1056. onComplete(typeConverters);
  1057. }
  1058. };
  1059. /** @param {Object=} options */
  1060. function sharedRegisterType(rawType, registeredInstance, options = {}) {
  1061. var name = registeredInstance.name;
  1062. if (!rawType) {
  1063. throwBindingError(`type "${name}" must have a positive integer typeid pointer`);
  1064. }
  1065. if (registeredTypes.hasOwnProperty(rawType)) {
  1066. if (options.ignoreDuplicateRegistrations) {
  1067. return;
  1068. } else {
  1069. throwBindingError(`Cannot register type '${name}' twice`);
  1070. }
  1071. }
  1072. registeredTypes[rawType] = registeredInstance;
  1073. delete typeDependencies[rawType];
  1074. if (awaitingDependencies.hasOwnProperty(rawType)) {
  1075. var callbacks = awaitingDependencies[rawType];
  1076. delete awaitingDependencies[rawType];
  1077. callbacks.forEach((cb) => cb());
  1078. }
  1079. }
  1080. /** @param {Object=} options */
  1081. function registerType(rawType, registeredInstance, options = {}) {
  1082. if (!('argPackAdvance' in registeredInstance)) {
  1083. throw new TypeError('registerType registeredInstance requires argPackAdvance');
  1084. }
  1085. return sharedRegisterType(rawType, registeredInstance, options);
  1086. }
  1087. var GenericWireTypeSize = 8;
  1088. /** @suppress {globalThis} */
  1089. var __embind_register_bool = (rawType, name, trueValue, falseValue) => {
  1090. name = readLatin1String(name);
  1091. registerType(rawType, {
  1092. name,
  1093. 'fromWireType': function(wt) {
  1094. // ambiguous emscripten ABI: sometimes return values are
  1095. // true or false, and sometimes integers (0 or 1)
  1096. return !!wt;
  1097. },
  1098. 'toWireType': function(destructors, o) {
  1099. return o ? trueValue : falseValue;
  1100. },
  1101. 'argPackAdvance': GenericWireTypeSize,
  1102. 'readValueFromPointer': function(pointer) {
  1103. return this['fromWireType'](HEAPU8[pointer]);
  1104. },
  1105. destructorFunction: null, // This type does not need a destructor
  1106. });
  1107. };
  1108. var emval_freelist = [];
  1109. var emval_handles = [];
  1110. var __emval_decref = (handle) => {
  1111. if (handle > 9 && 0 === --emval_handles[handle + 1]) {
  1112. assert(emval_handles[handle] !== undefined, `Decref for unallocated handle.`);
  1113. emval_handles[handle] = undefined;
  1114. emval_freelist.push(handle);
  1115. }
  1116. };
  1117. var count_emval_handles = () => {
  1118. return emval_handles.length / 2 - 5 - emval_freelist.length;
  1119. };
  1120. var init_emval = () => {
  1121. // reserve 0 and some special values. These never get de-allocated.
  1122. emval_handles.push(
  1123. 0, 1,
  1124. undefined, 1,
  1125. null, 1,
  1126. true, 1,
  1127. false, 1,
  1128. );
  1129. assert(emval_handles.length === 5 * 2);
  1130. Module['count_emval_handles'] = count_emval_handles;
  1131. };
  1132. var Emval = {
  1133. toValue:(handle) => {
  1134. if (!handle) {
  1135. throwBindingError('Cannot use deleted val. handle = ' + handle);
  1136. }
  1137. // handle 2 is supposed to be `undefined`.
  1138. assert(handle === 2 || emval_handles[handle] !== undefined && handle % 2 === 0, `invalid handle: ${handle}`);
  1139. return emval_handles[handle];
  1140. },
  1141. toHandle:(value) => {
  1142. switch (value) {
  1143. case undefined: return 2;
  1144. case null: return 4;
  1145. case true: return 6;
  1146. case false: return 8;
  1147. default:{
  1148. const handle = emval_freelist.pop() || emval_handles.length;
  1149. emval_handles[handle] = value;
  1150. emval_handles[handle + 1] = 1;
  1151. return handle;
  1152. }
  1153. }
  1154. },
  1155. };
  1156. /** @suppress {globalThis} */
  1157. function readPointer(pointer) {
  1158. return this['fromWireType'](HEAPU32[((pointer)>>2)]);
  1159. }
  1160. var EmValType = {
  1161. name: 'emscripten::val',
  1162. 'fromWireType': (handle) => {
  1163. var rv = Emval.toValue(handle);
  1164. __emval_decref(handle);
  1165. return rv;
  1166. },
  1167. 'toWireType': (destructors, value) => Emval.toHandle(value),
  1168. 'argPackAdvance': GenericWireTypeSize,
  1169. 'readValueFromPointer': readPointer,
  1170. destructorFunction: null, // This type does not need a destructor
  1171. // TODO: do we need a deleteObject here? write a test where
  1172. // emval is passed into JS via an interface
  1173. };
  1174. var __embind_register_emval = (rawType) => registerType(rawType, EmValType);
  1175. var embindRepr = (v) => {
  1176. if (v === null) {
  1177. return 'null';
  1178. }
  1179. var t = typeof v;
  1180. if (t === 'object' || t === 'array' || t === 'function') {
  1181. return v.toString();
  1182. } else {
  1183. return '' + v;
  1184. }
  1185. };
  1186. var floatReadValueFromPointer = (name, width) => {
  1187. switch (width) {
  1188. case 4: return function(pointer) {
  1189. return this['fromWireType'](HEAPF32[((pointer)>>2)]);
  1190. };
  1191. case 8: return function(pointer) {
  1192. return this['fromWireType'](HEAPF64[((pointer)>>3)]);
  1193. };
  1194. default:
  1195. throw new TypeError(`invalid float width (${width}): ${name}`);
  1196. }
  1197. };
  1198. var __embind_register_float = (rawType, name, size) => {
  1199. name = readLatin1String(name);
  1200. registerType(rawType, {
  1201. name,
  1202. 'fromWireType': (value) => value,
  1203. 'toWireType': (destructors, value) => {
  1204. if (typeof value != "number" && typeof value != "boolean") {
  1205. throw new TypeError(`Cannot convert ${embindRepr(value)} to ${this.name}`);
  1206. }
  1207. // The VM will perform JS to Wasm value conversion, according to the spec:
  1208. // https://www.w3.org/TR/wasm-js-api-1/#towebassemblyvalue
  1209. return value;
  1210. },
  1211. 'argPackAdvance': GenericWireTypeSize,
  1212. 'readValueFromPointer': floatReadValueFromPointer(name, size),
  1213. destructorFunction: null, // This type does not need a destructor
  1214. });
  1215. };
  1216. var createNamedFunction = (name, body) => Object.defineProperty(body, 'name', {
  1217. value: name
  1218. });
  1219. var runDestructors = (destructors) => {
  1220. while (destructors.length) {
  1221. var ptr = destructors.pop();
  1222. var del = destructors.pop();
  1223. del(ptr);
  1224. }
  1225. };
  1226. function usesDestructorStack(argTypes) {
  1227. // Skip return value at index 0 - it's not deleted here.
  1228. for (var i = 1; i < argTypes.length; ++i) {
  1229. // The type does not define a destructor function - must use dynamic stack
  1230. if (argTypes[i] !== null && argTypes[i].destructorFunction === undefined) {
  1231. return true;
  1232. }
  1233. }
  1234. return false;
  1235. }
  1236. function newFunc(constructor, argumentList) {
  1237. if (!(constructor instanceof Function)) {
  1238. throw new TypeError(`new_ called with constructor type ${typeof(constructor)} which is not a function`);
  1239. }
  1240. /*
  1241. * Previously, the following line was just:
  1242. * function dummy() {};
  1243. * Unfortunately, Chrome was preserving 'dummy' as the object's name, even
  1244. * though at creation, the 'dummy' has the correct constructor name. Thus,
  1245. * objects created with IMVU.new would show up in the debugger as 'dummy',
  1246. * which isn't very helpful. Using IMVU.createNamedFunction addresses the
  1247. * issue. Doubly-unfortunately, there's no way to write a test for this
  1248. * behavior. -NRD 2013.02.22
  1249. */
  1250. var dummy = createNamedFunction(constructor.name || 'unknownFunctionName', function(){});
  1251. dummy.prototype = constructor.prototype;
  1252. var obj = new dummy;
  1253. var r = constructor.apply(obj, argumentList);
  1254. return (r instanceof Object) ? r : obj;
  1255. }
  1256. function createJsInvoker(argTypes, isClassMethodFunc, returns, isAsync) {
  1257. var needsDestructorStack = usesDestructorStack(argTypes);
  1258. var argCount = argTypes.length;
  1259. var argsList = "";
  1260. var argsListWired = "";
  1261. for (var i = 0; i < argCount - 2; ++i) {
  1262. argsList += (i!==0?", ":"")+"arg"+i;
  1263. argsListWired += (i!==0?", ":"")+"arg"+i+"Wired";
  1264. }
  1265. var invokerFnBody = `
  1266. return function (${argsList}) {
  1267. if (arguments.length !== ${argCount - 2}) {
  1268. throwBindingError('function ' + humanName + ' called with ' + arguments.length + ' arguments, expected ${argCount - 2}');
  1269. }`;
  1270. if (needsDestructorStack) {
  1271. invokerFnBody += "var destructors = [];\n";
  1272. }
  1273. var dtorStack = needsDestructorStack ? "destructors" : "null";
  1274. var args1 = ["humanName", "throwBindingError", "invoker", "fn", "runDestructors", "retType", "classParam"];
  1275. if (isClassMethodFunc) {
  1276. invokerFnBody += "var thisWired = classParam['toWireType']("+dtorStack+", this);\n";
  1277. }
  1278. for (var i = 0; i < argCount - 2; ++i) {
  1279. invokerFnBody += "var arg"+i+"Wired = argType"+i+"['toWireType']("+dtorStack+", arg"+i+");\n";
  1280. args1.push("argType"+i);
  1281. }
  1282. if (isClassMethodFunc) {
  1283. argsListWired = "thisWired" + (argsListWired.length > 0 ? ", " : "") + argsListWired;
  1284. }
  1285. invokerFnBody +=
  1286. (returns || isAsync ? "var rv = ":"") + "invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";
  1287. var returnVal = returns ? "rv" : "";
  1288. if (needsDestructorStack) {
  1289. invokerFnBody += "runDestructors(destructors);\n";
  1290. } else {
  1291. for (var i = isClassMethodFunc?1:2; i < argTypes.length; ++i) { // Skip return value at index 0 - it's not deleted here. Also skip class type if not a method.
  1292. var paramName = (i === 1 ? "thisWired" : ("arg"+(i - 2)+"Wired"));
  1293. if (argTypes[i].destructorFunction !== null) {
  1294. invokerFnBody += `${paramName}_dtor(${paramName});\n`;
  1295. args1.push(`${paramName}_dtor`);
  1296. }
  1297. }
  1298. }
  1299. if (returns) {
  1300. invokerFnBody += "var ret = retType['fromWireType'](rv);\n" +
  1301. "return ret;\n";
  1302. } else {
  1303. }
  1304. invokerFnBody += "}\n";
  1305. invokerFnBody = `if (arguments.length !== ${args1.length}){ throw new Error(humanName + "Expected ${args1.length} closure arguments " + arguments.length + " given."); }\n${invokerFnBody}`;
  1306. return [args1, invokerFnBody];
  1307. }
  1308. function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc, /** boolean= */ isAsync) {
  1309. // humanName: a human-readable string name for the function to be generated.
  1310. // argTypes: An array that contains the embind type objects for all types in the function signature.
  1311. // argTypes[0] is the type object for the function return value.
  1312. // argTypes[1] is the type object for function this object/class type, or null if not crafting an invoker for a class method.
  1313. // argTypes[2...] are the actual function parameters.
  1314. // classType: The embind type object for the class to be bound, or null if this is not a method of a class.
  1315. // cppInvokerFunc: JS Function object to the C++-side function that interops into C++ code.
  1316. // cppTargetFunc: Function pointer (an integer to FUNCTION_TABLE) to the target C++ function the cppInvokerFunc will end up calling.
  1317. // isAsync: Optional. If true, returns an async function. Async bindings are only supported with JSPI.
  1318. var argCount = argTypes.length;
  1319. if (argCount < 2) {
  1320. throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!");
  1321. }
  1322. assert(!isAsync, 'Async bindings are only supported with JSPI.');
  1323. var isClassMethodFunc = (argTypes[1] !== null && classType !== null);
  1324. // Free functions with signature "void function()" do not need an invoker that marshalls between wire types.
  1325. // TODO: This omits argument count check - enable only at -O3 or similar.
  1326. // if (ENABLE_UNSAFE_OPTS && argCount == 2 && argTypes[0].name == "void" && !isClassMethodFunc) {
  1327. // return FUNCTION_TABLE[fn];
  1328. // }
  1329. // Determine if we need to use a dynamic stack to store the destructors for the function parameters.
  1330. // TODO: Remove this completely once all function invokers are being dynamically generated.
  1331. var needsDestructorStack = usesDestructorStack(argTypes);
  1332. var returns = (argTypes[0].name !== "void");
  1333. // Builld the arguments that will be passed into the closure around the invoker
  1334. // function.
  1335. var closureArgs = [humanName, throwBindingError, cppInvokerFunc, cppTargetFunc, runDestructors, argTypes[0], argTypes[1]];
  1336. for (var i = 0; i < argCount - 2; ++i) {
  1337. closureArgs.push(argTypes[i+2]);
  1338. }
  1339. if (!needsDestructorStack) {
  1340. for (var i = isClassMethodFunc?1:2; i < argTypes.length; ++i) { // Skip return value at index 0 - it's not deleted here. Also skip class type if not a method.
  1341. if (argTypes[i].destructorFunction !== null) {
  1342. closureArgs.push(argTypes[i].destructorFunction);
  1343. }
  1344. }
  1345. }
  1346. let [args, invokerFnBody] = createJsInvoker(argTypes, isClassMethodFunc, returns, isAsync);
  1347. args.push(invokerFnBody);
  1348. var invokerFn = newFunc(Function, args)(...closureArgs);
  1349. return createNamedFunction(humanName, invokerFn);
  1350. }
  1351. var ensureOverloadTable = (proto, methodName, humanName) => {
  1352. if (undefined === proto[methodName].overloadTable) {
  1353. var prevFunc = proto[methodName];
  1354. // Inject an overload resolver function that routes to the appropriate overload based on the number of arguments.
  1355. proto[methodName] = function(...args) {
  1356. // TODO This check can be removed in -O3 level "unsafe" optimizations.
  1357. if (!proto[methodName].overloadTable.hasOwnProperty(args.length)) {
  1358. throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`);
  1359. }
  1360. return proto[methodName].overloadTable[args.length].apply(this, args);
  1361. };
  1362. // Move the previous function into the overload table.
  1363. proto[methodName].overloadTable = [];
  1364. proto[methodName].overloadTable[prevFunc.argCount] = prevFunc;
  1365. }
  1366. };
  1367. /** @param {number=} numArguments */
  1368. var exposePublicSymbol = (name, value, numArguments) => {
  1369. if (Module.hasOwnProperty(name)) {
  1370. if (undefined === numArguments || (undefined !== Module[name].overloadTable && undefined !== Module[name].overloadTable[numArguments])) {
  1371. throwBindingError(`Cannot register public name '${name}' twice`);
  1372. }
  1373. // We are exposing a function with the same name as an existing function. Create an overload table and a function selector
  1374. // that routes between the two.
  1375. ensureOverloadTable(Module, name, name);
  1376. if (Module.hasOwnProperty(numArguments)) {
  1377. throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`);
  1378. }
  1379. // Add the new function into the overload table.
  1380. Module[name].overloadTable[numArguments] = value;
  1381. }
  1382. else {
  1383. Module[name] = value;
  1384. if (undefined !== numArguments) {
  1385. Module[name].numArguments = numArguments;
  1386. }
  1387. }
  1388. };
  1389. var heap32VectorToArray = (count, firstElement) => {
  1390. var array = [];
  1391. for (var i = 0; i < count; i++) {
  1392. // TODO(https://github.com/emscripten-core/emscripten/issues/17310):
  1393. // Find a way to hoist the `>> 2` or `>> 3` out of this loop.
  1394. array.push(HEAPU32[(((firstElement)+(i * 4))>>2)]);
  1395. }
  1396. return array;
  1397. };
  1398. /** @param {number=} numArguments */
  1399. var replacePublicSymbol = (name, value, numArguments) => {
  1400. if (!Module.hasOwnProperty(name)) {
  1401. throwInternalError('Replacing nonexistent public symbol');
  1402. }
  1403. // If there's an overload table for this symbol, replace the symbol in the overload table instead.
  1404. if (undefined !== Module[name].overloadTable && undefined !== numArguments) {
  1405. Module[name].overloadTable[numArguments] = value;
  1406. }
  1407. else {
  1408. Module[name] = value;
  1409. Module[name].argCount = numArguments;
  1410. }
  1411. };
  1412. var dynCallLegacy = (sig, ptr, args) => {
  1413. sig = sig.replace(/p/g, 'i')
  1414. assert(('dynCall_' + sig) in Module, `bad function pointer type - dynCall function not found for sig '${sig}'`);
  1415. if (args?.length) {
  1416. // j (64-bit integer) must be passed in as two numbers [low 32, high 32].
  1417. assert(args.length === sig.substring(1).replace(/j/g, '--').length);
  1418. } else {
  1419. assert(sig.length == 1);
  1420. }
  1421. var f = Module['dynCall_' + sig];
  1422. return f(ptr, ...args);
  1423. };
  1424. var wasmTableMirror = [];
  1425. var wasmTable;
  1426. var getWasmTableEntry = (funcPtr) => {
  1427. var func = wasmTableMirror[funcPtr];
  1428. if (!func) {
  1429. if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;
  1430. wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);
  1431. }
  1432. assert(wasmTable.get(funcPtr) == func, 'JavaScript-side Wasm function table mirror is out of date!');
  1433. return func;
  1434. };
  1435. var dynCall = (sig, ptr, args = []) => {
  1436. // Without WASM_BIGINT support we cannot directly call function with i64 as
  1437. // part of their signature, so we rely on the dynCall functions generated by
  1438. // wasm-emscripten-finalize
  1439. if (sig.includes('j')) {
  1440. return dynCallLegacy(sig, ptr, args);
  1441. }
  1442. assert(getWasmTableEntry(ptr), `missing table entry in dynCall: ${ptr}`);
  1443. var rtn = getWasmTableEntry(ptr)(...args);
  1444. return rtn;
  1445. };
  1446. var getDynCaller = (sig, ptr) => {
  1447. assert(sig.includes('j') || sig.includes('p'), 'getDynCaller should only be called with i64 sigs')
  1448. return (...args) => dynCall(sig, ptr, args);
  1449. };
  1450. var embind__requireFunction = (signature, rawFunction) => {
  1451. signature = readLatin1String(signature);
  1452. function makeDynCaller() {
  1453. if (signature.includes('j')) {
  1454. return getDynCaller(signature, rawFunction);
  1455. }
  1456. return getWasmTableEntry(rawFunction);
  1457. }
  1458. var fp = makeDynCaller();
  1459. if (typeof fp != "function") {
  1460. throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`);
  1461. }
  1462. return fp;
  1463. };
  1464. var extendError = (baseErrorType, errorName) => {
  1465. var errorClass = createNamedFunction(errorName, function(message) {
  1466. this.name = errorName;
  1467. this.message = message;
  1468. var stack = (new Error(message)).stack;
  1469. if (stack !== undefined) {
  1470. this.stack = this.toString() + '\n' +
  1471. stack.replace(/^Error(:[^\n]*)?\n/, '');
  1472. }
  1473. });
  1474. errorClass.prototype = Object.create(baseErrorType.prototype);
  1475. errorClass.prototype.constructor = errorClass;
  1476. errorClass.prototype.toString = function() {
  1477. if (this.message === undefined) {
  1478. return this.name;
  1479. } else {
  1480. return `${this.name}: ${this.message}`;
  1481. }
  1482. };
  1483. return errorClass;
  1484. };
  1485. var UnboundTypeError;
  1486. var getTypeName = (type) => {
  1487. var ptr = ___getTypeName(type);
  1488. var rv = readLatin1String(ptr);
  1489. _free(ptr);
  1490. return rv;
  1491. };
  1492. var throwUnboundTypeError = (message, types) => {
  1493. var unboundTypes = [];
  1494. var seen = {};
  1495. function visit(type) {
  1496. if (seen[type]) {
  1497. return;
  1498. }
  1499. if (registeredTypes[type]) {
  1500. return;
  1501. }
  1502. if (typeDependencies[type]) {
  1503. typeDependencies[type].forEach(visit);
  1504. return;
  1505. }
  1506. unboundTypes.push(type);
  1507. seen[type] = true;
  1508. }
  1509. types.forEach(visit);
  1510. throw new UnboundTypeError(`${message}: ` + unboundTypes.map(getTypeName).join([', ']));
  1511. };
  1512. var getFunctionName = (signature) => {
  1513. signature = signature.trim();
  1514. const argsIndex = signature.indexOf("(");
  1515. if (argsIndex !== -1) {
  1516. assert(signature[signature.length - 1] == ")", "Parentheses for argument names should match.");
  1517. return signature.substr(0, argsIndex);
  1518. } else {
  1519. return signature;
  1520. }
  1521. };
  1522. var __embind_register_function = (name, argCount, rawArgTypesAddr, signature, rawInvoker, fn, isAsync) => {
  1523. var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
  1524. name = readLatin1String(name);
  1525. name = getFunctionName(name);
  1526. rawInvoker = embind__requireFunction(signature, rawInvoker);
  1527. exposePublicSymbol(name, function() {
  1528. throwUnboundTypeError(`Cannot call ${name} due to unbound types`, argTypes);
  1529. }, argCount - 1);
  1530. whenDependentTypesAreResolved([], argTypes, (argTypes) => {
  1531. var invokerArgsArray = [argTypes[0] /* return value */, null /* no class 'this'*/].concat(argTypes.slice(1) /* actual params */);
  1532. replacePublicSymbol(name, craftInvokerFunction(name, invokerArgsArray, null /* no class 'this'*/, rawInvoker, fn, isAsync), argCount - 1);
  1533. return [];
  1534. });
  1535. };
  1536. var integerReadValueFromPointer = (name, width, signed) => {
  1537. // integers are quite common, so generate very specialized functions
  1538. switch (width) {
  1539. case 1: return signed ?
  1540. (pointer) => HEAP8[pointer] :
  1541. (pointer) => HEAPU8[pointer];
  1542. case 2: return signed ?
  1543. (pointer) => HEAP16[((pointer)>>1)] :
  1544. (pointer) => HEAPU16[((pointer)>>1)]
  1545. case 4: return signed ?
  1546. (pointer) => HEAP32[((pointer)>>2)] :
  1547. (pointer) => HEAPU32[((pointer)>>2)]
  1548. default:
  1549. throw new TypeError(`invalid integer width (${width}): ${name}`);
  1550. }
  1551. };
  1552. /** @suppress {globalThis} */
  1553. var __embind_register_integer = (primitiveType, name, size, minRange, maxRange) => {
  1554. name = readLatin1String(name);
  1555. // LLVM doesn't have signed and unsigned 32-bit types, so u32 literals come
  1556. // out as 'i32 -1'. Always treat those as max u32.
  1557. if (maxRange === -1) {
  1558. maxRange = 4294967295;
  1559. }
  1560. var fromWireType = (value) => value;
  1561. if (minRange === 0) {
  1562. var bitshift = 32 - 8*size;
  1563. fromWireType = (value) => (value << bitshift) >>> bitshift;
  1564. }
  1565. var isUnsignedType = (name.includes('unsigned'));
  1566. var checkAssertions = (value, toTypeName) => {
  1567. if (typeof value != "number" && typeof value != "boolean") {
  1568. throw new TypeError(`Cannot convert "${embindRepr(value)}" to ${toTypeName}`);
  1569. }
  1570. if (value < minRange || value > maxRange) {
  1571. throw new TypeError(`Passing a number "${embindRepr(value)}" from JS side to C/C++ side to an argument of type "${name}", which is outside the valid range [${minRange}, ${maxRange}]!`);
  1572. }
  1573. }
  1574. var toWireType;
  1575. if (isUnsignedType) {
  1576. toWireType = function(destructors, value) {
  1577. checkAssertions(value, this.name);
  1578. return value >>> 0;
  1579. }
  1580. } else {
  1581. toWireType = function(destructors, value) {
  1582. checkAssertions(value, this.name);
  1583. // The VM will perform JS to Wasm value conversion, according to the spec:
  1584. // https://www.w3.org/TR/wasm-js-api-1/#towebassemblyvalue
  1585. return value;
  1586. }
  1587. }
  1588. registerType(primitiveType, {
  1589. name,
  1590. 'fromWireType': fromWireType,
  1591. 'toWireType': toWireType,
  1592. 'argPackAdvance': GenericWireTypeSize,
  1593. 'readValueFromPointer': integerReadValueFromPointer(name, size, minRange !== 0),
  1594. destructorFunction: null, // This type does not need a destructor
  1595. });
  1596. };
  1597. var __embind_register_memory_view = (rawType, dataTypeIndex, name) => {
  1598. var typeMapping = [
  1599. Int8Array,
  1600. Uint8Array,
  1601. Int16Array,
  1602. Uint16Array,
  1603. Int32Array,
  1604. Uint32Array,
  1605. Float32Array,
  1606. Float64Array,
  1607. ];
  1608. var TA = typeMapping[dataTypeIndex];
  1609. function decodeMemoryView(handle) {
  1610. var size = HEAPU32[((handle)>>2)];
  1611. var data = HEAPU32[(((handle)+(4))>>2)];
  1612. return new TA(HEAP8.buffer, data, size);
  1613. }
  1614. name = readLatin1String(name);
  1615. registerType(rawType, {
  1616. name,
  1617. 'fromWireType': decodeMemoryView,
  1618. 'argPackAdvance': GenericWireTypeSize,
  1619. 'readValueFromPointer': decodeMemoryView,
  1620. }, {
  1621. ignoreDuplicateRegistrations: true,
  1622. });
  1623. };
  1624. var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
  1625. assert(typeof str === 'string', `stringToUTF8Array expects a string (got ${typeof str})`);
  1626. // Parameter maxBytesToWrite is not optional. Negative values, 0, null,
  1627. // undefined and false each don't write out any bytes.
  1628. if (!(maxBytesToWrite > 0))
  1629. return 0;
  1630. var startIdx = outIdx;
  1631. var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
  1632. for (var i = 0; i < str.length; ++i) {
  1633. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code
  1634. // unit, not a Unicode code point of the character! So decode
  1635. // UTF16->UTF32->UTF8.
  1636. // See http://unicode.org/faq/utf_bom.html#utf16-3
  1637. // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description
  1638. // and https://www.ietf.org/rfc/rfc2279.txt
  1639. // and https://tools.ietf.org/html/rfc3629
  1640. var u = str.charCodeAt(i); // possibly a lead surrogate
  1641. if (u >= 0xD800 && u <= 0xDFFF) {
  1642. var u1 = str.charCodeAt(++i);
  1643. u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF);
  1644. }
  1645. if (u <= 0x7F) {
  1646. if (outIdx >= endIdx) break;
  1647. heap[outIdx++] = u;
  1648. } else if (u <= 0x7FF) {
  1649. if (outIdx + 1 >= endIdx) break;
  1650. heap[outIdx++] = 0xC0 | (u >> 6);
  1651. heap[outIdx++] = 0x80 | (u & 63);
  1652. } else if (u <= 0xFFFF) {
  1653. if (outIdx + 2 >= endIdx) break;
  1654. heap[outIdx++] = 0xE0 | (u >> 12);
  1655. heap[outIdx++] = 0x80 | ((u >> 6) & 63);
  1656. heap[outIdx++] = 0x80 | (u & 63);
  1657. } else {
  1658. if (outIdx + 3 >= endIdx) break;
  1659. if (u > 0x10FFFF) warnOnce('Invalid Unicode code point ' + ptrToString(u) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).');
  1660. heap[outIdx++] = 0xF0 | (u >> 18);
  1661. heap[outIdx++] = 0x80 | ((u >> 12) & 63);
  1662. heap[outIdx++] = 0x80 | ((u >> 6) & 63);
  1663. heap[outIdx++] = 0x80 | (u & 63);
  1664. }
  1665. }
  1666. // Null-terminate the pointer to the buffer.
  1667. heap[outIdx] = 0;
  1668. return outIdx - startIdx;
  1669. };
  1670. var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {
  1671. assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  1672. return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
  1673. };
  1674. var lengthBytesUTF8 = (str) => {
  1675. var len = 0;
  1676. for (var i = 0; i < str.length; ++i) {
  1677. // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code
  1678. // unit, not a Unicode code point of the character! So decode
  1679. // UTF16->UTF32->UTF8.
  1680. // See http://unicode.org/faq/utf_bom.html#utf16-3
  1681. var c = str.charCodeAt(i); // possibly a lead surrogate
  1682. if (c <= 0x7F) {
  1683. len++;
  1684. } else if (c <= 0x7FF) {
  1685. len += 2;
  1686. } else if (c >= 0xD800 && c <= 0xDFFF) {
  1687. len += 4; ++i;
  1688. } else {
  1689. len += 3;
  1690. }
  1691. }
  1692. return len;
  1693. };
  1694. var __embind_register_std_string = (rawType, name) => {
  1695. name = readLatin1String(name);
  1696. var stdStringIsUTF8
  1697. //process only std::string bindings with UTF8 support, in contrast to e.g. std::basic_string<unsigned char>
  1698. = (name === "std::string");
  1699. registerType(rawType, {
  1700. name,
  1701. // For some method names we use string keys here since they are part of
  1702. // the public/external API and/or used by the runtime-generated code.
  1703. 'fromWireType'(value) {
  1704. var length = HEAPU32[((value)>>2)];
  1705. var payload = value + 4;
  1706. var str;
  1707. if (stdStringIsUTF8) {
  1708. var decodeStartPtr = payload;
  1709. // Looping here to support possible embedded '0' bytes
  1710. for (var i = 0; i <= length; ++i) {
  1711. var currentBytePtr = payload + i;
  1712. if (i == length || HEAPU8[currentBytePtr] == 0) {
  1713. var maxRead = currentBytePtr - decodeStartPtr;
  1714. var stringSegment = UTF8ToString(decodeStartPtr, maxRead);
  1715. if (str === undefined) {
  1716. str = stringSegment;
  1717. } else {
  1718. str += String.fromCharCode(0);
  1719. str += stringSegment;
  1720. }
  1721. decodeStartPtr = currentBytePtr + 1;
  1722. }
  1723. }
  1724. } else {
  1725. var a = new Array(length);
  1726. for (var i = 0; i < length; ++i) {
  1727. a[i] = String.fromCharCode(HEAPU8[payload + i]);
  1728. }
  1729. str = a.join('');
  1730. }
  1731. _free(value);
  1732. return str;
  1733. },
  1734. 'toWireType'(destructors, value) {
  1735. if (value instanceof ArrayBuffer) {
  1736. value = new Uint8Array(value);
  1737. }
  1738. var length;
  1739. var valueIsOfTypeString = (typeof value == 'string');
  1740. if (!(valueIsOfTypeString || value instanceof Uint8Array || value instanceof Uint8ClampedArray || value instanceof Int8Array)) {
  1741. throwBindingError('Cannot pass non-string to std::string');
  1742. }
  1743. if (stdStringIsUTF8 && valueIsOfTypeString) {
  1744. length = lengthBytesUTF8(value);
  1745. } else {
  1746. length = value.length;
  1747. }
  1748. // assumes POINTER_SIZE alignment
  1749. var base = _malloc(4 + length + 1);
  1750. var ptr = base + 4;
  1751. HEAPU32[((base)>>2)] = length;
  1752. if (stdStringIsUTF8 && valueIsOfTypeString) {
  1753. stringToUTF8(value, ptr, length + 1);
  1754. } else {
  1755. if (valueIsOfTypeString) {
  1756. for (var i = 0; i < length; ++i) {
  1757. var charCode = value.charCodeAt(i);
  1758. if (charCode > 255) {
  1759. _free(ptr);
  1760. throwBindingError('String has UTF-16 code units that do not fit in 8 bits');
  1761. }
  1762. HEAPU8[ptr + i] = charCode;
  1763. }
  1764. } else {
  1765. for (var i = 0; i < length; ++i) {
  1766. HEAPU8[ptr + i] = value[i];
  1767. }
  1768. }
  1769. }
  1770. if (destructors !== null) {
  1771. destructors.push(_free, base);
  1772. }
  1773. return base;
  1774. },
  1775. 'argPackAdvance': GenericWireTypeSize,
  1776. 'readValueFromPointer': readPointer,
  1777. destructorFunction(ptr) {
  1778. _free(ptr);
  1779. },
  1780. });
  1781. };
  1782. var UTF16Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf-16le') : undefined;;
  1783. var UTF16ToString = (ptr, maxBytesToRead) => {
  1784. assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!');
  1785. var endPtr = ptr;
  1786. // TextDecoder needs to know the byte length in advance, it doesn't stop on
  1787. // null terminator by itself.
  1788. // Also, use the length info to avoid running tiny strings through
  1789. // TextDecoder, since .subarray() allocates garbage.
  1790. var idx = endPtr >> 1;
  1791. var maxIdx = idx + maxBytesToRead / 2;
  1792. // If maxBytesToRead is not passed explicitly, it will be undefined, and this
  1793. // will always evaluate to true. This saves on code size.
  1794. while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;
  1795. endPtr = idx << 1;
  1796. if (endPtr - ptr > 32 && UTF16Decoder)
  1797. return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
  1798. // Fallback: decode without UTF16Decoder
  1799. var str = '';
  1800. // If maxBytesToRead is not passed explicitly, it will be undefined, and the
  1801. // for-loop's condition will always evaluate to true. The loop is then
  1802. // terminated on the first null char.
  1803. for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
  1804. var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
  1805. if (codeUnit == 0) break;
  1806. // fromCharCode constructs a character from a UTF-16 code unit, so we can
  1807. // pass the UTF16 string right through.
  1808. str += String.fromCharCode(codeUnit);
  1809. }
  1810. return str;
  1811. };
  1812. var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {
  1813. assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
  1814. assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  1815. // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  1816. maxBytesToWrite ??= 0x7FFFFFFF;
  1817. if (maxBytesToWrite < 2) return 0;
  1818. maxBytesToWrite -= 2; // Null terminator.
  1819. var startPtr = outPtr;
  1820. var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
  1821. for (var i = 0; i < numCharsToWrite; ++i) {
  1822. // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
  1823. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
  1824. HEAP16[((outPtr)>>1)] = codeUnit;
  1825. outPtr += 2;
  1826. }
  1827. // Null-terminate the pointer to the HEAP.
  1828. HEAP16[((outPtr)>>1)] = 0;
  1829. return outPtr - startPtr;
  1830. };
  1831. var lengthBytesUTF16 = (str) => {
  1832. return str.length*2;
  1833. };
  1834. var UTF32ToString = (ptr, maxBytesToRead) => {
  1835. assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!');
  1836. var i = 0;
  1837. var str = '';
  1838. // If maxBytesToRead is not passed explicitly, it will be undefined, and this
  1839. // will always evaluate to true. This saves on code size.
  1840. while (!(i >= maxBytesToRead / 4)) {
  1841. var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
  1842. if (utf32 == 0) break;
  1843. ++i;
  1844. // 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.
  1845. // See http://unicode.org/faq/utf_bom.html#utf16-3
  1846. if (utf32 >= 0x10000) {
  1847. var ch = utf32 - 0x10000;
  1848. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  1849. } else {
  1850. str += String.fromCharCode(utf32);
  1851. }
  1852. }
  1853. return str;
  1854. };
  1855. var stringToUTF32 = (str, outPtr, maxBytesToWrite) => {
  1856. assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!');
  1857. assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
  1858. // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
  1859. maxBytesToWrite ??= 0x7FFFFFFF;
  1860. if (maxBytesToWrite < 4) return 0;
  1861. var startPtr = outPtr;
  1862. var endPtr = startPtr + maxBytesToWrite - 4;
  1863. for (var i = 0; i < str.length; ++i) {
  1864. // 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.
  1865. // See http://unicode.org/faq/utf_bom.html#utf16-3
  1866. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
  1867. if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
  1868. var trailSurrogate = str.charCodeAt(++i);
  1869. codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
  1870. }
  1871. HEAP32[((outPtr)>>2)] = codeUnit;
  1872. outPtr += 4;
  1873. if (outPtr + 4 > endPtr) break;
  1874. }
  1875. // Null-terminate the pointer to the HEAP.
  1876. HEAP32[((outPtr)>>2)] = 0;
  1877. return outPtr - startPtr;
  1878. };
  1879. var lengthBytesUTF32 = (str) => {
  1880. var len = 0;
  1881. for (var i = 0; i < str.length; ++i) {
  1882. // 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.
  1883. // See http://unicode.org/faq/utf_bom.html#utf16-3
  1884. var codeUnit = str.charCodeAt(i);
  1885. if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate.
  1886. len += 4;
  1887. }
  1888. return len;
  1889. };
  1890. var __embind_register_std_wstring = (rawType, charSize, name) => {
  1891. name = readLatin1String(name);
  1892. var decodeString, encodeString, readCharAt, lengthBytesUTF;
  1893. if (charSize === 2) {
  1894. decodeString = UTF16ToString;
  1895. encodeString = stringToUTF16;
  1896. lengthBytesUTF = lengthBytesUTF16;
  1897. readCharAt = (pointer) => HEAPU16[((pointer)>>1)];
  1898. } else if (charSize === 4) {
  1899. decodeString = UTF32ToString;
  1900. encodeString = stringToUTF32;
  1901. lengthBytesUTF = lengthBytesUTF32;
  1902. readCharAt = (pointer) => HEAPU32[((pointer)>>2)];
  1903. }
  1904. registerType(rawType, {
  1905. name,
  1906. 'fromWireType': (value) => {
  1907. // Code mostly taken from _embind_register_std_string fromWireType
  1908. var length = HEAPU32[((value)>>2)];
  1909. var str;
  1910. var decodeStartPtr = value + 4;
  1911. // Looping here to support possible embedded '0' bytes
  1912. for (var i = 0; i <= length; ++i) {
  1913. var currentBytePtr = value + 4 + i * charSize;
  1914. if (i == length || readCharAt(currentBytePtr) == 0) {
  1915. var maxReadBytes = currentBytePtr - decodeStartPtr;
  1916. var stringSegment = decodeString(decodeStartPtr, maxReadBytes);
  1917. if (str === undefined) {
  1918. str = stringSegment;
  1919. } else {
  1920. str += String.fromCharCode(0);
  1921. str += stringSegment;
  1922. }
  1923. decodeStartPtr = currentBytePtr + charSize;
  1924. }
  1925. }
  1926. _free(value);
  1927. return str;
  1928. },
  1929. 'toWireType': (destructors, value) => {
  1930. if (!(typeof value == 'string')) {
  1931. throwBindingError(`Cannot pass non-string to C++ string type ${name}`);
  1932. }
  1933. // assumes POINTER_SIZE alignment
  1934. var length = lengthBytesUTF(value);
  1935. var ptr = _malloc(4 + length + charSize);
  1936. HEAPU32[((ptr)>>2)] = length / charSize;
  1937. encodeString(value, ptr + 4, length + charSize);
  1938. if (destructors !== null) {
  1939. destructors.push(_free, ptr);
  1940. }
  1941. return ptr;
  1942. },
  1943. 'argPackAdvance': GenericWireTypeSize,
  1944. 'readValueFromPointer': readPointer,
  1945. destructorFunction(ptr) {
  1946. _free(ptr);
  1947. }
  1948. });
  1949. };
  1950. var __embind_register_void = (rawType, name) => {
  1951. name = readLatin1String(name);
  1952. registerType(rawType, {
  1953. isVoid: true, // void return values can be optimized out sometimes
  1954. name,
  1955. 'argPackAdvance': 0,
  1956. 'fromWireType': () => undefined,
  1957. // TODO: assert if anything else is given?
  1958. 'toWireType': (destructors, o) => undefined,
  1959. });
  1960. };
  1961. var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num);
  1962. var _abort = () => {
  1963. abort('native code called abort()');
  1964. };
  1965. var getHeapMax = () =>
  1966. HEAPU8.length;
  1967. var abortOnCannotGrowMemory = (requestedSize) => {
  1968. abort(`Cannot enlarge memory arrays to size ${requestedSize} bytes (OOM). Either (1) compile with -sINITIAL_MEMORY=X with X higher than the current value ${HEAP8.length}, (2) compile with -sALLOW_MEMORY_GROWTH which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -sABORTING_MALLOC=0`);
  1969. };
  1970. var _emscripten_resize_heap = (requestedSize) => {
  1971. var oldSize = HEAPU8.length;
  1972. // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
  1973. requestedSize >>>= 0;
  1974. abortOnCannotGrowMemory(requestedSize);
  1975. };
  1976. var SYSCALLS = {
  1977. varargs:undefined,
  1978. getStr(ptr) {
  1979. var ret = UTF8ToString(ptr);
  1980. return ret;
  1981. },
  1982. };
  1983. var _fd_close = (fd) => {
  1984. abort('fd_close called without SYSCALLS_REQUIRE_FILESYSTEM');
  1985. };
  1986. var convertI32PairToI53Checked = (lo, hi) => {
  1987. assert(lo == (lo >>> 0) || lo == (lo|0)); // lo should either be a i32 or a u32
  1988. assert(hi === (hi|0)); // hi should be a i32
  1989. return ((hi + 0x200000) >>> 0 < 0x400001 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN;
  1990. };
  1991. function _fd_seek(fd,offset_low, offset_high,whence,newOffset) {
  1992. var offset = convertI32PairToI53Checked(offset_low, offset_high);
  1993. return 70;
  1994. ;
  1995. }
  1996. var printCharBuffers = [null,[],[]];
  1997. var printChar = (stream, curr) => {
  1998. var buffer = printCharBuffers[stream];
  1999. assert(buffer);
  2000. if (curr === 0 || curr === 10) {
  2001. (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0));
  2002. buffer.length = 0;
  2003. } else {
  2004. buffer.push(curr);
  2005. }
  2006. };
  2007. var flush_NO_FILESYSTEM = () => {
  2008. // flush anything remaining in the buffers during shutdown
  2009. _fflush(0);
  2010. if (printCharBuffers[1].length) printChar(1, 10);
  2011. if (printCharBuffers[2].length) printChar(2, 10);
  2012. };
  2013. var _fd_write = (fd, iov, iovcnt, pnum) => {
  2014. // hack to support printf in SYSCALLS_REQUIRE_FILESYSTEM=0
  2015. var num = 0;
  2016. for (var i = 0; i < iovcnt; i++) {
  2017. var ptr = HEAPU32[((iov)>>2)];
  2018. var len = HEAPU32[(((iov)+(4))>>2)];
  2019. iov += 8;
  2020. for (var j = 0; j < len; j++) {
  2021. printChar(fd, HEAPU8[ptr+j]);
  2022. }
  2023. num += len;
  2024. }
  2025. HEAPU32[((pnum)>>2)] = num;
  2026. return 0;
  2027. };
  2028. var runtimeKeepaliveCounter = 0;
  2029. var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;
  2030. var _proc_exit = (code) => {
  2031. EXITSTATUS = code;
  2032. if (!keepRuntimeAlive()) {
  2033. Module['onExit']?.(code);
  2034. ABORT = true;
  2035. }
  2036. quit_(code, new ExitStatus(code));
  2037. };
  2038. /** @param {boolean|number=} implicit */
  2039. var exitJS = (status, implicit) => {
  2040. EXITSTATUS = status;
  2041. checkUnflushedContent();
  2042. // if exit() was called explicitly, warn the user if the runtime isn't actually being shut down
  2043. if (keepRuntimeAlive() && !implicit) {
  2044. var msg = `program exited (with status: ${status}), but keepRuntimeAlive() is set (counter=${runtimeKeepaliveCounter}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`;
  2045. err(msg);
  2046. }
  2047. _proc_exit(status);
  2048. };
  2049. var handleException = (e) => {
  2050. // Certain exception types we do not treat as errors since they are used for
  2051. // internal control flow.
  2052. // 1. ExitStatus, which is thrown by exit()
  2053. // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others
  2054. // that wish to return to JS event loop.
  2055. if (e instanceof ExitStatus || e == 'unwind') {
  2056. return EXITSTATUS;
  2057. }
  2058. checkStackCookie();
  2059. if (e instanceof WebAssembly.RuntimeError) {
  2060. if (_emscripten_stack_get_current() <= 0) {
  2061. err('Stack overflow detected. You can try increasing -sSTACK_SIZE (currently set to 65536)');
  2062. }
  2063. }
  2064. quit_(1, e);
  2065. };
  2066. embind_init_charCodes();
  2067. BindingError = Module['BindingError'] = class BindingError extends Error { constructor(message) { super(message); this.name = 'BindingError'; }};
  2068. InternalError = Module['InternalError'] = class InternalError extends Error { constructor(message) { super(message); this.name = 'InternalError'; }};
  2069. init_emval();;
  2070. UnboundTypeError = Module['UnboundTypeError'] = extendError(Error, 'UnboundTypeError');;
  2071. function checkIncomingModuleAPI() {
  2072. ignoredModuleProp('fetchSettings');
  2073. }
  2074. var wasmImports = {
  2075. /** @export */
  2076. __assert_fail: ___assert_fail,
  2077. /** @export */
  2078. __cxa_throw: ___cxa_throw,
  2079. /** @export */
  2080. _embind_register_bigint: __embind_register_bigint,
  2081. /** @export */
  2082. _embind_register_bool: __embind_register_bool,
  2083. /** @export */
  2084. _embind_register_emval: __embind_register_emval,
  2085. /** @export */
  2086. _embind_register_float: __embind_register_float,
  2087. /** @export */
  2088. _embind_register_function: __embind_register_function,
  2089. /** @export */
  2090. _embind_register_integer: __embind_register_integer,
  2091. /** @export */
  2092. _embind_register_memory_view: __embind_register_memory_view,
  2093. /** @export */
  2094. _embind_register_std_string: __embind_register_std_string,
  2095. /** @export */
  2096. _embind_register_std_wstring: __embind_register_std_wstring,
  2097. /** @export */
  2098. _embind_register_void: __embind_register_void,
  2099. /** @export */
  2100. _emscripten_memcpy_js: __emscripten_memcpy_js,
  2101. /** @export */
  2102. abort: _abort,
  2103. /** @export */
  2104. emscripten_resize_heap: _emscripten_resize_heap,
  2105. /** @export */
  2106. fd_close: _fd_close,
  2107. /** @export */
  2108. fd_seek: _fd_seek,
  2109. /** @export */
  2110. fd_write: _fd_write
  2111. };
  2112. var wasmExports = createWasm();
  2113. var ___wasm_call_ctors = createExportWrapper('__wasm_call_ctors', 0);
  2114. var ___getTypeName = createExportWrapper('__getTypeName', 1);
  2115. var _malloc = createExportWrapper('malloc', 1);
  2116. var _main = Module['_main'] = createExportWrapper('main', 2);
  2117. var _fflush = createExportWrapper('fflush', 1);
  2118. var _free = createExportWrapper('free', 1);
  2119. var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports['emscripten_stack_init'])();
  2120. var _emscripten_stack_get_free = () => (_emscripten_stack_get_free = wasmExports['emscripten_stack_get_free'])();
  2121. var _emscripten_stack_get_base = () => (_emscripten_stack_get_base = wasmExports['emscripten_stack_get_base'])();
  2122. var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports['emscripten_stack_get_end'])();
  2123. var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports['_emscripten_stack_restore'])(a0);
  2124. var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports['_emscripten_stack_alloc'])(a0);
  2125. var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports['emscripten_stack_get_current'])();
  2126. var ___cxa_is_pointer_type = createExportWrapper('__cxa_is_pointer_type', 1);
  2127. var dynCall_jiji = Module['dynCall_jiji'] = createExportWrapper('dynCall_jiji', 5);
  2128. // include: postamble.js
  2129. // === Auto-generated postamble setup entry stuff ===
  2130. var missingLibrarySymbols = [
  2131. 'writeI53ToI64',
  2132. 'writeI53ToI64Clamped',
  2133. 'writeI53ToI64Signaling',
  2134. 'writeI53ToU64Clamped',
  2135. 'writeI53ToU64Signaling',
  2136. 'readI53FromI64',
  2137. 'readI53FromU64',
  2138. 'convertI32PairToI53',
  2139. 'convertU32PairToI53',
  2140. 'stackAlloc',
  2141. 'getTempRet0',
  2142. 'setTempRet0',
  2143. 'zeroMemory',
  2144. 'growMemory',
  2145. 'isLeapYear',
  2146. 'ydayFromDate',
  2147. 'arraySum',
  2148. 'addDays',
  2149. 'inetPton4',
  2150. 'inetNtop4',
  2151. 'inetPton6',
  2152. 'inetNtop6',
  2153. 'readSockaddr',
  2154. 'writeSockaddr',
  2155. 'initRandomFill',
  2156. 'randomFill',
  2157. 'emscriptenLog',
  2158. 'readEmAsmArgs',
  2159. 'jstoi_q',
  2160. 'getExecutableName',
  2161. 'listenOnce',
  2162. 'autoResumeAudioContext',
  2163. 'runtimeKeepalivePush',
  2164. 'runtimeKeepalivePop',
  2165. 'callUserCallback',
  2166. 'maybeExit',
  2167. 'asmjsMangle',
  2168. 'asyncLoad',
  2169. 'alignMemory',
  2170. 'mmapAlloc',
  2171. 'HandleAllocator',
  2172. 'getNativeTypeSize',
  2173. 'STACK_SIZE',
  2174. 'STACK_ALIGN',
  2175. 'POINTER_SIZE',
  2176. 'ASSERTIONS',
  2177. 'getCFunc',
  2178. 'ccall',
  2179. 'cwrap',
  2180. 'uleb128Encode',
  2181. 'sigToWasmTypes',
  2182. 'generateFuncType',
  2183. 'convertJsFunctionToWasm',
  2184. 'getEmptyTableSlot',
  2185. 'updateTableMap',
  2186. 'getFunctionAddress',
  2187. 'addFunction',
  2188. 'removeFunction',
  2189. 'reallyNegative',
  2190. 'unSign',
  2191. 'strLen',
  2192. 'reSign',
  2193. 'formatString',
  2194. 'intArrayFromString',
  2195. 'intArrayToString',
  2196. 'AsciiToString',
  2197. 'stringToAscii',
  2198. 'stringToNewUTF8',
  2199. 'stringToUTF8OnStack',
  2200. 'writeArrayToMemory',
  2201. 'registerKeyEventCallback',
  2202. 'maybeCStringToJsString',
  2203. 'findEventTarget',
  2204. 'getBoundingClientRect',
  2205. 'fillMouseEventData',
  2206. 'registerMouseEventCallback',
  2207. 'registerWheelEventCallback',
  2208. 'registerUiEventCallback',
  2209. 'registerFocusEventCallback',
  2210. 'fillDeviceOrientationEventData',
  2211. 'registerDeviceOrientationEventCallback',
  2212. 'fillDeviceMotionEventData',
  2213. 'registerDeviceMotionEventCallback',
  2214. 'screenOrientation',
  2215. 'fillOrientationChangeEventData',
  2216. 'registerOrientationChangeEventCallback',
  2217. 'fillFullscreenChangeEventData',
  2218. 'registerFullscreenChangeEventCallback',
  2219. 'JSEvents_requestFullscreen',
  2220. 'JSEvents_resizeCanvasForFullscreen',
  2221. 'registerRestoreOldStyle',
  2222. 'hideEverythingExceptGivenElement',
  2223. 'restoreHiddenElements',
  2224. 'setLetterbox',
  2225. 'softFullscreenResizeWebGLRenderTarget',
  2226. 'doRequestFullscreen',
  2227. 'fillPointerlockChangeEventData',
  2228. 'registerPointerlockChangeEventCallback',
  2229. 'registerPointerlockErrorEventCallback',
  2230. 'requestPointerLock',
  2231. 'fillVisibilityChangeEventData',
  2232. 'registerVisibilityChangeEventCallback',
  2233. 'registerTouchEventCallback',
  2234. 'fillGamepadEventData',
  2235. 'registerGamepadEventCallback',
  2236. 'registerBeforeUnloadEventCallback',
  2237. 'fillBatteryEventData',
  2238. 'battery',
  2239. 'registerBatteryEventCallback',
  2240. 'setCanvasElementSize',
  2241. 'getCanvasElementSize',
  2242. 'jsStackTrace',
  2243. 'getCallstack',
  2244. 'convertPCtoSourceLocation',
  2245. 'getEnvStrings',
  2246. 'checkWasiClock',
  2247. 'wasiRightsToMuslOFlags',
  2248. 'wasiOFlagsToMuslOFlags',
  2249. 'createDyncallWrapper',
  2250. 'safeSetTimeout',
  2251. 'setImmediateWrapped',
  2252. 'clearImmediateWrapped',
  2253. 'polyfillSetImmediate',
  2254. 'getPromise',
  2255. 'makePromise',
  2256. 'idsToPromises',
  2257. 'makePromiseCallback',
  2258. 'findMatchingCatch',
  2259. 'Browser_asyncPrepareDataCounter',
  2260. 'setMainLoop',
  2261. 'getSocketFromFD',
  2262. 'getSocketAddress',
  2263. 'FS_createPreloadedFile',
  2264. 'FS_modeStringToFlags',
  2265. 'FS_getMode',
  2266. 'FS_stdin_getChar',
  2267. 'FS_createDataFile',
  2268. 'FS_unlink',
  2269. 'FS_mkdirTree',
  2270. '_setNetworkCallback',
  2271. 'heapObjectForWebGLType',
  2272. 'toTypedArrayIndex',
  2273. 'webgl_enable_ANGLE_instanced_arrays',
  2274. 'webgl_enable_OES_vertex_array_object',
  2275. 'webgl_enable_WEBGL_draw_buffers',
  2276. 'webgl_enable_WEBGL_multi_draw',
  2277. 'emscriptenWebGLGet',
  2278. 'computeUnpackAlignedImageSize',
  2279. 'colorChannelsInGlTextureFormat',
  2280. 'emscriptenWebGLGetTexPixelData',
  2281. 'emscriptenWebGLGetUniform',
  2282. 'webglGetUniformLocation',
  2283. 'webglPrepareUniformLocationsBeforeFirstUse',
  2284. 'webglGetLeftBracePos',
  2285. 'emscriptenWebGLGetVertexAttrib',
  2286. '__glGetActiveAttribOrUniform',
  2287. 'writeGLArray',
  2288. 'registerWebGlEventCallback',
  2289. 'runAndAbortIfError',
  2290. 'ALLOC_NORMAL',
  2291. 'ALLOC_STACK',
  2292. 'allocate',
  2293. 'writeStringToMemory',
  2294. 'writeAsciiToMemory',
  2295. 'setErrNo',
  2296. 'demangle',
  2297. 'stackTrace',
  2298. 'getFunctionArgsName',
  2299. 'requireRegisteredType',
  2300. 'createJsInvokerSignature',
  2301. 'init_embind',
  2302. 'getBasestPointer',
  2303. 'registerInheritedInstance',
  2304. 'unregisterInheritedInstance',
  2305. 'getInheritedInstance',
  2306. 'getInheritedInstanceCount',
  2307. 'getLiveInheritedInstances',
  2308. 'enumReadValueFromPointer',
  2309. 'genericPointerToWireType',
  2310. 'constNoSmartPtrRawPointerToWireType',
  2311. 'nonConstNoSmartPtrRawPointerToWireType',
  2312. 'init_RegisteredPointer',
  2313. 'RegisteredPointer',
  2314. 'RegisteredPointer_fromWireType',
  2315. 'runDestructor',
  2316. 'releaseClassHandle',
  2317. 'detachFinalizer',
  2318. 'attachFinalizer',
  2319. 'makeClassHandle',
  2320. 'init_ClassHandle',
  2321. 'ClassHandle',
  2322. 'throwInstanceAlreadyDeleted',
  2323. 'flushPendingDeletes',
  2324. 'setDelayFunction',
  2325. 'RegisteredClass',
  2326. 'shallowCopyInternalPointer',
  2327. 'downcastPointer',
  2328. 'upcastPointer',
  2329. 'validateThis',
  2330. 'char_0',
  2331. 'char_9',
  2332. 'makeLegalFunctionName',
  2333. 'getStringOrSymbol',
  2334. 'emval_get_global',
  2335. 'emval_returnValue',
  2336. 'emval_lookupTypes',
  2337. 'emval_addMethodCaller',
  2338. ];
  2339. missingLibrarySymbols.forEach(missingLibrarySymbol)
  2340. var unexportedSymbols = [
  2341. 'run',
  2342. 'addOnPreRun',
  2343. 'addOnInit',
  2344. 'addOnPreMain',
  2345. 'addOnExit',
  2346. 'addOnPostRun',
  2347. 'addRunDependency',
  2348. 'removeRunDependency',
  2349. 'FS_createFolder',
  2350. 'FS_createPath',
  2351. 'FS_createLazyFile',
  2352. 'FS_createLink',
  2353. 'FS_createDevice',
  2354. 'FS_readFile',
  2355. 'out',
  2356. 'err',
  2357. 'callMain',
  2358. 'abort',
  2359. 'wasmMemory',
  2360. 'wasmExports',
  2361. 'writeStackCookie',
  2362. 'checkStackCookie',
  2363. 'convertI32PairToI53Checked',
  2364. 'stackSave',
  2365. 'stackRestore',
  2366. 'ptrToString',
  2367. 'exitJS',
  2368. 'getHeapMax',
  2369. 'abortOnCannotGrowMemory',
  2370. 'ENV',
  2371. 'MONTH_DAYS_REGULAR',
  2372. 'MONTH_DAYS_LEAP',
  2373. 'MONTH_DAYS_REGULAR_CUMULATIVE',
  2374. 'MONTH_DAYS_LEAP_CUMULATIVE',
  2375. 'ERRNO_CODES',
  2376. 'ERRNO_MESSAGES',
  2377. 'DNS',
  2378. 'Protocols',
  2379. 'Sockets',
  2380. 'timers',
  2381. 'warnOnce',
  2382. 'readEmAsmArgsArray',
  2383. 'jstoi_s',
  2384. 'dynCallLegacy',
  2385. 'getDynCaller',
  2386. 'dynCall',
  2387. 'handleException',
  2388. 'keepRuntimeAlive',
  2389. 'wasmTable',
  2390. 'noExitRuntime',
  2391. 'freeTableIndexes',
  2392. 'functionsInTableMap',
  2393. 'setValue',
  2394. 'getValue',
  2395. 'PATH',
  2396. 'PATH_FS',
  2397. 'UTF8Decoder',
  2398. 'UTF8ArrayToString',
  2399. 'UTF8ToString',
  2400. 'stringToUTF8Array',
  2401. 'stringToUTF8',
  2402. 'lengthBytesUTF8',
  2403. 'UTF16Decoder',
  2404. 'UTF16ToString',
  2405. 'stringToUTF16',
  2406. 'lengthBytesUTF16',
  2407. 'UTF32ToString',
  2408. 'stringToUTF32',
  2409. 'lengthBytesUTF32',
  2410. 'JSEvents',
  2411. 'specialHTMLTargets',
  2412. 'findCanvasEventTarget',
  2413. 'currentFullscreenStrategy',
  2414. 'restoreOldWindowedStyle',
  2415. 'UNWIND_CACHE',
  2416. 'ExitStatus',
  2417. 'flush_NO_FILESYSTEM',
  2418. 'promiseMap',
  2419. 'uncaughtExceptionCount',
  2420. 'exceptionLast',
  2421. 'exceptionCaught',
  2422. 'ExceptionInfo',
  2423. 'Browser',
  2424. 'getPreloadedImageData__data',
  2425. 'wget',
  2426. 'SYSCALLS',
  2427. 'preloadPlugins',
  2428. 'FS_stdin_getChar_buffer',
  2429. 'FS',
  2430. 'MEMFS',
  2431. 'TTY',
  2432. 'PIPEFS',
  2433. 'SOCKFS',
  2434. 'tempFixedLengthArray',
  2435. 'miniTempWebGLFloatBuffers',
  2436. 'miniTempWebGLIntBuffers',
  2437. 'GL',
  2438. 'AL',
  2439. 'GLUT',
  2440. 'EGL',
  2441. 'GLEW',
  2442. 'IDBStore',
  2443. 'SDL',
  2444. 'SDL_gfx',
  2445. 'allocateUTF8',
  2446. 'allocateUTF8OnStack',
  2447. 'InternalError',
  2448. 'BindingError',
  2449. 'throwInternalError',
  2450. 'throwBindingError',
  2451. 'registeredTypes',
  2452. 'awaitingDependencies',
  2453. 'typeDependencies',
  2454. 'tupleRegistrations',
  2455. 'structRegistrations',
  2456. 'sharedRegisterType',
  2457. 'whenDependentTypesAreResolved',
  2458. 'embind_charCodes',
  2459. 'embind_init_charCodes',
  2460. 'readLatin1String',
  2461. 'getTypeName',
  2462. 'getFunctionName',
  2463. 'heap32VectorToArray',
  2464. 'usesDestructorStack',
  2465. 'createJsInvoker',
  2466. 'UnboundTypeError',
  2467. 'PureVirtualError',
  2468. 'GenericWireTypeSize',
  2469. 'EmValType',
  2470. 'throwUnboundTypeError',
  2471. 'ensureOverloadTable',
  2472. 'exposePublicSymbol',
  2473. 'replacePublicSymbol',
  2474. 'extendError',
  2475. 'createNamedFunction',
  2476. 'embindRepr',
  2477. 'registeredInstances',
  2478. 'registeredPointers',
  2479. 'registerType',
  2480. 'integerReadValueFromPointer',
  2481. 'floatReadValueFromPointer',
  2482. 'readPointer',
  2483. 'runDestructors',
  2484. 'newFunc',
  2485. 'craftInvokerFunction',
  2486. 'embind__requireFunction',
  2487. 'finalizationRegistry',
  2488. 'detachFinalizer_deps',
  2489. 'deletionQueue',
  2490. 'delayFunction',
  2491. 'emval_freelist',
  2492. 'emval_handles',
  2493. 'emval_symbols',
  2494. 'init_emval',
  2495. 'count_emval_handles',
  2496. 'Emval',
  2497. 'emval_methodCallers',
  2498. 'reflectConstruct',
  2499. ];
  2500. unexportedSymbols.forEach(unexportedRuntimeSymbol);
  2501. var calledRun;
  2502. dependenciesFulfilled = function runCaller() {
  2503. // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
  2504. if (!calledRun) run();
  2505. if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
  2506. };
  2507. function callMain() {
  2508. assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on Module["onRuntimeInitialized"])');
  2509. assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
  2510. var entryFunction = _main;
  2511. var argc = 0;
  2512. var argv = 0;
  2513. try {
  2514. var ret = entryFunction(argc, argv);
  2515. // if we're not running an evented main loop, it's time to exit
  2516. exitJS(ret, /* implicit = */ true);
  2517. return ret;
  2518. }
  2519. catch (e) {
  2520. return handleException(e);
  2521. }
  2522. }
  2523. function stackCheckInit() {
  2524. // This is normally called automatically during __wasm_call_ctors but need to
  2525. // get these values before even running any of the ctors so we call it redundantly
  2526. // here.
  2527. _emscripten_stack_init();
  2528. // TODO(sbc): Move writeStackCookie to native to to avoid this.
  2529. writeStackCookie();
  2530. }
  2531. function run() {
  2532. if (runDependencies > 0) {
  2533. return;
  2534. }
  2535. stackCheckInit();
  2536. preRun();
  2537. // a preRun added a dependency, run will be called later
  2538. if (runDependencies > 0) {
  2539. return;
  2540. }
  2541. function doRun() {
  2542. // run may have just been called through dependencies being fulfilled just in this very frame,
  2543. // or while the async setStatus time below was happening
  2544. if (calledRun) return;
  2545. calledRun = true;
  2546. Module['calledRun'] = true;
  2547. if (ABORT) return;
  2548. initRuntime();
  2549. preMain();
  2550. if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
  2551. if (shouldRunNow) callMain();
  2552. postRun();
  2553. }
  2554. if (Module['setStatus']) {
  2555. Module['setStatus']('Running...');
  2556. setTimeout(function() {
  2557. setTimeout(function() {
  2558. Module['setStatus']('');
  2559. }, 1);
  2560. doRun();
  2561. }, 1);
  2562. } else
  2563. {
  2564. doRun();
  2565. }
  2566. checkStackCookie();
  2567. }
  2568. function checkUnflushedContent() {
  2569. // Compiler settings do not allow exiting the runtime, so flushing
  2570. // the streams is not possible. but in ASSERTIONS mode we check
  2571. // if there was something to flush, and if so tell the user they
  2572. // should request that the runtime be exitable.
  2573. // Normally we would not even include flush() at all, but in ASSERTIONS
  2574. // builds we do so just for this check, and here we see if there is any
  2575. // content to flush, that is, we check if there would have been
  2576. // something a non-ASSERTIONS build would have not seen.
  2577. // How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0
  2578. // mode (which has its own special function for this; otherwise, all
  2579. // the code is inside libc)
  2580. var oldOut = out;
  2581. var oldErr = err;
  2582. var has = false;
  2583. out = err = (x) => {
  2584. has = true;
  2585. }
  2586. try { // it doesn't matter if it fails
  2587. flush_NO_FILESYSTEM();
  2588. } catch(e) {}
  2589. out = oldOut;
  2590. err = oldErr;
  2591. if (has) {
  2592. warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the Emscripten FAQ), or make sure to emit a newline when you printf etc.');
  2593. warnOnce('(this may also be due to not including full filesystem support - try building with -sFORCE_FILESYSTEM)');
  2594. }
  2595. }
  2596. if (Module['preInit']) {
  2597. if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
  2598. while (Module['preInit'].length > 0) {
  2599. Module['preInit'].pop()();
  2600. }
  2601. }
  2602. // shouldRunNow refers to calling main(), not run().
  2603. var shouldRunNow = true;
  2604. if (Module['noInitialRun']) shouldRunNow = false;
  2605. run();
  2606. // end include: postamble.js