3 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  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(Module) { ..generated code.. }
  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. // --pre-jses are emitted after the Module integration code, so that they can
  17. // refer to Module (if they choose; they can also define Module)
  18. // Sometimes an existing Module object exists with properties
  19. // meant to overwrite the default module functionality. Here
  20. // we collect those properties and reapply _after_ we configure
  21. // the current environment's defaults to avoid having to be so
  22. // defensive during initialization.
  23. var moduleOverrides = Object.assign({}, Module);
  24. var arguments_ = [];
  25. var thisProgram = './this.program';
  26. var quit_ = (status, toThrow) => {
  27. throw toThrow;
  28. };
  29. // Determine the runtime environment we are in. You can customize this by
  30. // setting the ENVIRONMENT setting at compile time (see settings.js).
  31. // Attempt to auto-detect the environment
  32. var ENVIRONMENT_IS_WEB = typeof window == 'object';
  33. var ENVIRONMENT_IS_WORKER = typeof importScripts == 'function';
  34. // N.b. Electron.js environment is simultaneously a NODE-environment, but
  35. // also a web environment.
  36. var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string';
  37. var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
  38. if (Module['ENVIRONMENT']) {
  39. 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)');
  40. }
  41. // `/` should be present at the end if `scriptDirectory` is not empty
  42. var scriptDirectory = '';
  43. function locateFile(path) {
  44. if (Module['locateFile']) {
  45. return Module['locateFile'](path, scriptDirectory);
  46. }
  47. return scriptDirectory + path;
  48. }
  49. // Hooks that are implemented differently in different runtime environments.
  50. var read_,
  51. readAsync,
  52. readBinary;
  53. if (ENVIRONMENT_IS_NODE) {
  54. 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?)');
  55. var nodeVersion = process.versions.node;
  56. var numericVersion = nodeVersion.split('.').slice(0, 3);
  57. numericVersion = (numericVersion[0] * 10000) + (numericVersion[1] * 100) + (numericVersion[2].split('-')[0] * 1);
  58. var minVersion = 160000;
  59. if (numericVersion < 160000) {
  60. throw new Error('This emscripten-generated code requires node v16.0.0 (detected v' + nodeVersion + ')');
  61. }
  62. // `require()` is no-op in an ESM module, use `createRequire()` to construct
  63. // the require()` function. This is only necessary for multi-environment
  64. // builds, `-sENVIRONMENT=node` emits a static import declaration instead.
  65. // TODO: Swap all `require()`'s with `import()`'s?
  66. // These modules will usually be used on Node.js. Load them eagerly to avoid
  67. // the complexity of lazy-loading.
  68. var fs = require('fs');
  69. var nodePath = require('path');
  70. if (ENVIRONMENT_IS_WORKER) {
  71. scriptDirectory = nodePath.dirname(scriptDirectory) + '/';
  72. } else {
  73. scriptDirectory = __dirname + '/';
  74. }
  75. // include: node_shell_read.js
  76. read_ = (filename, binary) => {
  77. // We need to re-wrap `file://` strings to URLs. Normalizing isn't
  78. // necessary in that case, the path should already be absolute.
  79. filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
  80. return fs.readFileSync(filename, binary ? undefined : 'utf8');
  81. };
  82. readBinary = (filename) => {
  83. var ret = read_(filename, true);
  84. if (!ret.buffer) {
  85. ret = new Uint8Array(ret);
  86. }
  87. assert(ret.buffer);
  88. return ret;
  89. };
  90. readAsync = (filename, onload, onerror, binary = true) => {
  91. // See the comment in the `read_` function.
  92. filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
  93. fs.readFile(filename, binary ? undefined : 'utf8', (err, data) => {
  94. if (err) onerror(err);
  95. else onload(binary ? data.buffer : data);
  96. });
  97. };
  98. // end include: node_shell_read.js
  99. if (!Module['thisProgram'] && process.argv.length > 1) {
  100. thisProgram = process.argv[1].replace(/\\/g, '/');
  101. }
  102. arguments_ = process.argv.slice(2);
  103. if (typeof module != 'undefined') {
  104. module['exports'] = Module;
  105. }
  106. process.on('uncaughtException', (ex) => {
  107. // suppress ExitStatus exceptions from showing an error
  108. if (ex !== 'unwind' && !(ex instanceof ExitStatus) && !(ex.context instanceof ExitStatus)) {
  109. throw ex;
  110. }
  111. });
  112. quit_ = (status, toThrow) => {
  113. process.exitCode = status;
  114. throw toThrow;
  115. };
  116. } else
  117. if (ENVIRONMENT_IS_SHELL) {
  118. 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?)');
  119. if (typeof read != 'undefined') {
  120. read_ = read;
  121. }
  122. readBinary = (f) => {
  123. if (typeof readbuffer == 'function') {
  124. return new Uint8Array(readbuffer(f));
  125. }
  126. let data = read(f, 'binary');
  127. assert(typeof data == 'object');
  128. return data;
  129. };
  130. readAsync = (f, onload, onerror) => {
  131. setTimeout(() => onload(readBinary(f)));
  132. };
  133. if (typeof clearTimeout == 'undefined') {
  134. globalThis.clearTimeout = (id) => { };
  135. }
  136. if (typeof setTimeout == 'undefined') {
  137. // spidermonkey lacks setTimeout but we use it above in readAsync.
  138. globalThis.setTimeout = (f) => (typeof f == 'function') ? f() : abort();
  139. }
  140. if (typeof scriptArgs != 'undefined') {
  141. arguments_ = scriptArgs;
  142. } else if (typeof arguments != 'undefined') {
  143. arguments_ = arguments;
  144. }
  145. if (typeof quit == 'function') {
  146. quit_ = (status, toThrow) => {
  147. // Unlike node which has process.exitCode, d8 has no such mechanism. So we
  148. // have no way to set the exit code and then let the program exit with
  149. // that code when it naturally stops running (say, when all setTimeouts
  150. // have completed). For that reason, we must call `quit` - the only way to
  151. // set the exit code - but quit also halts immediately. To increase
  152. // consistency with node (and the web) we schedule the actual quit call
  153. // using a setTimeout to give the current stack and any exception handlers
  154. // a chance to run. This enables features such as addOnPostRun (which
  155. // expected to be able to run code after main returns).
  156. setTimeout(() => {
  157. if (!(toThrow instanceof ExitStatus)) {
  158. let toLog = toThrow;
  159. if (toThrow && typeof toThrow == 'object' && toThrow.stack) {
  160. toLog = [toThrow, toThrow.stack];
  161. }
  162. err(`exiting due to exception: ${toLog}`);
  163. }
  164. quit(status);
  165. });
  166. throw toThrow;
  167. };
  168. }
  169. if (typeof print != 'undefined') {
  170. // Prefer to use print/printErr where they exist, as they usually work better.
  171. if (typeof console == 'undefined') console = /** @type{!Console} */({});
  172. console.log = /** @type{!function(this:Console, ...*): undefined} */ (print);
  173. console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (typeof printErr != 'undefined' ? printErr : print);
  174. }
  175. } else
  176. // Note that this includes Node.js workers when relevant (pthreads is enabled).
  177. // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
  178. // ENVIRONMENT_IS_NODE.
  179. if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
  180. if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled
  181. scriptDirectory = self.location.href;
  182. } else if (typeof document != 'undefined' && document.currentScript) { // web
  183. scriptDirectory = document.currentScript.src;
  184. }
  185. // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
  186. // otherwise, slice off the final part of the url to find the script directory.
  187. // if scriptDirectory does not contain a slash, lastIndexOf will return -1,
  188. // and scriptDirectory will correctly be replaced with an empty string.
  189. // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #),
  190. // they are removed because they could contain a slash.
  191. if (scriptDirectory.startsWith('blob:')) {
  192. scriptDirectory = '';
  193. } else {
  194. scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/') + 1);
  195. }
  196. 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?)');
  197. // Differentiate the Web Worker from the Node Worker case, as reading must
  198. // be done differently.
  199. {
  200. // include: web_or_worker_shell_read.js
  201. read_ = (url) => {
  202. var xhr = new XMLHttpRequest();
  203. xhr.open('GET', url, false);
  204. xhr.send(null);
  205. return xhr.responseText;
  206. }
  207. if (ENVIRONMENT_IS_WORKER) {
  208. readBinary = (url) => {
  209. var xhr = new XMLHttpRequest();
  210. xhr.open('GET', url, false);
  211. xhr.responseType = 'arraybuffer';
  212. xhr.send(null);
  213. return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
  214. };
  215. }
  216. readAsync = (url, onload, onerror) => {
  217. var xhr = new XMLHttpRequest();
  218. xhr.open('GET', url, true);
  219. xhr.responseType = 'arraybuffer';
  220. xhr.onload = () => {
  221. if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
  222. onload(xhr.response);
  223. return;
  224. }
  225. onerror();
  226. };
  227. xhr.onerror = onerror;
  228. xhr.send(null);
  229. }
  230. // end include: web_or_worker_shell_read.js
  231. }
  232. } else {
  233. throw new Error('environment detection error');
  234. }
  235. var out = Module['print'] || console.log.bind(console);
  236. var err = Module['printErr'] || console.error.bind(console);
  237. // Merge back in the overrides
  238. Object.assign(Module, moduleOverrides);
  239. // Free the object hierarchy contained in the overrides, this lets the GC
  240. // reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
  241. moduleOverrides = null;
  242. checkIncomingModuleAPI();
  243. // Emit code to handle expected values on the Module object. This applies Module.x
  244. // to the proper local x. This has two benefits: first, we only emit it if it is
  245. // expected to arrive, and second, by using a local everywhere else that can be
  246. // minified.
  247. if (Module['arguments']) arguments_ = Module['arguments']; legacyModuleProp('arguments', 'arguments_');
  248. if (Module['thisProgram']) thisProgram = Module['thisProgram']; legacyModuleProp('thisProgram', 'thisProgram');
  249. if (Module['quit']) quit_ = Module['quit']; legacyModuleProp('quit', 'quit_');
  250. // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
  251. // Assertions on removed incoming Module JS APIs.
  252. assert(typeof Module['memoryInitializerPrefixURL'] == 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
  253. assert(typeof Module['pthreadMainPrefixURL'] == 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
  254. assert(typeof Module['cdInitializerPrefixURL'] == 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
  255. assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
  256. assert(typeof Module['read'] == 'undefined', 'Module.read option was removed (modify read_ in JS)');
  257. assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
  258. assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
  259. assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)');
  260. assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY');
  261. legacyModuleProp('asm', 'wasmExports');
  262. legacyModuleProp('read', 'read_');
  263. legacyModuleProp('readAsync', 'readAsync');
  264. legacyModuleProp('readBinary', 'readBinary');
  265. legacyModuleProp('setWindowTitle', 'setWindowTitle');
  266. var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';
  267. var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';
  268. var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';
  269. var FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js';
  270. var ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js';
  271. var JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js';
  272. var OPFS = 'OPFS is no longer included by default; build with -lopfs.js';
  273. var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';
  274. assert(!ENVIRONMENT_IS_SHELL, 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.');
  275. // end include: shell.js
  276. // include: preamble.js
  277. // === Preamble library stuff ===
  278. // Documentation for the public APIs defined in this file must be updated in:
  279. // site/source/docs/api_reference/preamble.js.rst
  280. // A prebuilt local version of the documentation is available at:
  281. // site/build/text/docs/api_reference/preamble.js.txt
  282. // You can also build docs locally as HTML or other formats in site/
  283. // An online HTML version (which may be of a different version of Emscripten)
  284. // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
  285. var wasmBinary;
  286. if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']; legacyModuleProp('wasmBinary', 'wasmBinary');
  287. if (typeof WebAssembly != 'object') {
  288. abort('no native wasm support detected');
  289. }
  290. // Wasm globals
  291. var wasmMemory;
  292. //========================================
  293. // Runtime essentials
  294. //========================================
  295. // whether we are quitting the application. no code should run after this.
  296. // set in exit() and abort()
  297. var ABORT = false;
  298. // set by exit() and abort(). Passed to 'onExit' handler.
  299. // NOTE: This is also used as the process return code code in shell environments
  300. // but only when noExitRuntime is false.
  301. var EXITSTATUS;
  302. // In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we
  303. // don't define it at all in release modes. This matches the behaviour of
  304. // MINIMAL_RUNTIME.
  305. // TODO(sbc): Make this the default even without STRICT enabled.
  306. /** @type {function(*, string=)} */
  307. function assert(condition, text) {
  308. if (!condition) {
  309. abort('Assertion failed' + (text ? ': ' + text : ''));
  310. }
  311. }
  312. // We used to include malloc/free by default in the past. Show a helpful error in
  313. // builds with assertions.
  314. function _malloc() {
  315. abort('malloc() called but not included in the build - add `_malloc` to EXPORTED_FUNCTIONS');
  316. }
  317. function _free() {
  318. // Show a helpful error since we used to include free by default in the past.
  319. abort('free() called but not included in the build - add `_free` to EXPORTED_FUNCTIONS');
  320. }
  321. // Memory management
  322. var HEAP,
  323. /** @type {!Int8Array} */
  324. HEAP8,
  325. /** @type {!Uint8Array} */
  326. HEAPU8,
  327. /** @type {!Int16Array} */
  328. HEAP16,
  329. /** @type {!Uint16Array} */
  330. HEAPU16,
  331. /** @type {!Int32Array} */
  332. HEAP32,
  333. /** @type {!Uint32Array} */
  334. HEAPU32,
  335. /** @type {!Float32Array} */
  336. HEAPF32,
  337. /** @type {!Float64Array} */
  338. HEAPF64;
  339. function updateMemoryViews() {
  340. var b = wasmMemory.buffer;
  341. Module['HEAP8'] = HEAP8 = new Int8Array(b);
  342. Module['HEAP16'] = HEAP16 = new Int16Array(b);
  343. Module['HEAPU8'] = HEAPU8 = new Uint8Array(b);
  344. Module['HEAPU16'] = HEAPU16 = new Uint16Array(b);
  345. Module['HEAP32'] = HEAP32 = new Int32Array(b);
  346. Module['HEAPU32'] = HEAPU32 = new Uint32Array(b);
  347. Module['HEAPF32'] = HEAPF32 = new Float32Array(b);
  348. Module['HEAPF64'] = HEAPF64 = new Float64Array(b);
  349. }
  350. assert(!Module['STACK_SIZE'], 'STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time')
  351. assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined,
  352. 'JS engine does not provide full typed array support');
  353. // If memory is defined in wasm, the user can't provide it, or set INITIAL_MEMORY
  354. assert(!Module['wasmMemory'], 'Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally');
  355. assert(!Module['INITIAL_MEMORY'], 'Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically');
  356. // include: runtime_stack_check.js
  357. // Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
  358. function writeStackCookie() {
  359. var max = _emscripten_stack_get_end();
  360. assert((max & 3) == 0);
  361. // If the stack ends at address zero we write our cookies 4 bytes into the
  362. // stack. This prevents interference with SAFE_HEAP and ASAN which also
  363. // monitor writes to address zero.
  364. if (max == 0) {
  365. max += 4;
  366. }
  367. // The stack grow downwards towards _emscripten_stack_get_end.
  368. // We write cookies to the final two words in the stack and detect if they are
  369. // ever overwritten.
  370. HEAPU32[((max) >> 2)] = 0x02135467;
  371. HEAPU32[(((max) + (4)) >> 2)] = 0x89BACDFE;
  372. // Also test the global address 0 for integrity.
  373. HEAPU32[((0) >> 2)] = 1668509029;
  374. }
  375. function checkStackCookie() {
  376. if (ABORT) return;
  377. var max = _emscripten_stack_get_end();
  378. // See writeStackCookie().
  379. if (max == 0) {
  380. max += 4;
  381. }
  382. var cookie1 = HEAPU32[((max) >> 2)];
  383. var cookie2 = HEAPU32[(((max) + (4)) >> 2)];
  384. if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) {
  385. abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`);
  386. }
  387. // Also test the global address 0 for integrity.
  388. if (HEAPU32[((0) >> 2)] != 0x63736d65 /* 'emsc' */) {
  389. abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
  390. }
  391. }
  392. // end include: runtime_stack_check.js
  393. // include: runtime_assertions.js
  394. // Endianness check
  395. (function () {
  396. var h16 = new Int16Array(1);
  397. var h8 = new Int8Array(h16.buffer);
  398. h16[0] = 0x6373;
  399. if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)';
  400. })();
  401. // end include: runtime_assertions.js
  402. var __ATPRERUN__ = []; // functions called before the runtime is initialized
  403. var __ATINIT__ = []; // functions called during startup
  404. var __ATMAIN__ = []; // functions called when main() is to be run
  405. var __ATEXIT__ = []; // functions called during shutdown
  406. var __ATPOSTRUN__ = []; // functions called after the main() is called
  407. var runtimeInitialized = false;
  408. function preRun() {
  409. if (Module['preRun']) {
  410. if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
  411. while (Module['preRun'].length) {
  412. addOnPreRun(Module['preRun'].shift());
  413. }
  414. }
  415. callRuntimeCallbacks(__ATPRERUN__);
  416. }
  417. function initRuntime() {
  418. assert(!runtimeInitialized);
  419. runtimeInitialized = true;
  420. checkStackCookie();
  421. callRuntimeCallbacks(__ATINIT__);
  422. }
  423. function preMain() {
  424. checkStackCookie();
  425. callRuntimeCallbacks(__ATMAIN__);
  426. }
  427. function postRun() {
  428. checkStackCookie();
  429. if (Module['postRun']) {
  430. if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
  431. while (Module['postRun'].length) {
  432. addOnPostRun(Module['postRun'].shift());
  433. }
  434. }
  435. callRuntimeCallbacks(__ATPOSTRUN__);
  436. }
  437. function addOnPreRun(cb) {
  438. __ATPRERUN__.unshift(cb);
  439. }
  440. function addOnInit(cb) {
  441. __ATINIT__.unshift(cb);
  442. }
  443. function addOnPreMain(cb) {
  444. __ATMAIN__.unshift(cb);
  445. }
  446. function addOnExit(cb) {
  447. }
  448. function addOnPostRun(cb) {
  449. __ATPOSTRUN__.unshift(cb);
  450. }
  451. // include: runtime_math.js
  452. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
  453. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
  454. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
  455. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
  456. 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');
  457. 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');
  458. 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');
  459. 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');
  460. // end include: runtime_math.js
  461. // A counter of dependencies for calling run(). If we need to
  462. // do asynchronous work before running, increment this and
  463. // decrement it. Incrementing must happen in a place like
  464. // Module.preRun (used by emcc to add file preloading).
  465. // Note that you can add dependencies in preRun, even though
  466. // it happens right before run - run will be postponed until
  467. // the dependencies are met.
  468. var runDependencies = 0;
  469. var runDependencyWatcher = null;
  470. var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
  471. var runDependencyTracking = {};
  472. function getUniqueRunDependency(id) {
  473. var orig = id;
  474. while (1) {
  475. if (!runDependencyTracking[id]) return id;
  476. id = orig + Math.random();
  477. }
  478. }
  479. function addRunDependency(id) {
  480. runDependencies++;
  481. Module['monitorRunDependencies']?.(runDependencies);
  482. if (id) {
  483. assert(!runDependencyTracking[id]);
  484. runDependencyTracking[id] = 1;
  485. if (runDependencyWatcher === null && typeof setInterval != 'undefined') {
  486. // Check for missing dependencies every few seconds
  487. runDependencyWatcher = setInterval(() => {
  488. if (ABORT) {
  489. clearInterval(runDependencyWatcher);
  490. runDependencyWatcher = null;
  491. return;
  492. }
  493. var shown = false;
  494. for (var dep in runDependencyTracking) {
  495. if (!shown) {
  496. shown = true;
  497. err('still waiting on run dependencies:');
  498. }
  499. err(`dependency: ${dep}`);
  500. }
  501. if (shown) {
  502. err('(end of list)');
  503. }
  504. }, 10000);
  505. }
  506. } else {
  507. err('warning: run dependency added without ID');
  508. }
  509. }
  510. function removeRunDependency(id) {
  511. runDependencies--;
  512. Module['monitorRunDependencies']?.(runDependencies);
  513. if (id) {
  514. assert(runDependencyTracking[id]);
  515. delete runDependencyTracking[id];
  516. } else {
  517. err('warning: run dependency removed without ID');
  518. }
  519. if (runDependencies == 0) {
  520. if (runDependencyWatcher !== null) {
  521. clearInterval(runDependencyWatcher);
  522. runDependencyWatcher = null;
  523. }
  524. if (dependenciesFulfilled) {
  525. var callback = dependenciesFulfilled;
  526. dependenciesFulfilled = null;
  527. callback(); // can add another dependenciesFulfilled
  528. }
  529. }
  530. }
  531. /** @param {string|number=} what */
  532. function abort(what) {
  533. Module['onAbort']?.(what);
  534. what = 'Aborted(' + what + ')';
  535. // TODO(sbc): Should we remove printing and leave it up to whoever
  536. // catches the exception?
  537. err(what);
  538. ABORT = true;
  539. EXITSTATUS = 1;
  540. // Use a wasm runtime error, because a JS error might be seen as a foreign
  541. // exception, which means we'd run destructors on it. We need the error to
  542. // simply make the program stop.
  543. // FIXME This approach does not work in Wasm EH because it currently does not assume
  544. // all RuntimeErrors are from traps; it decides whether a RuntimeError is from
  545. // a trap or not based on a hidden field within the object. So at the moment
  546. // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that
  547. // allows this in the wasm spec.
  548. // Suppress closure compiler warning here. Closure compiler's builtin extern
  549. // defintion for WebAssembly.RuntimeError claims it takes no arguments even
  550. // though it can.
  551. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.
  552. /** @suppress {checkTypes} */
  553. var e = new WebAssembly.RuntimeError(what);
  554. // Throw the error whether or not MODULARIZE is set because abort is used
  555. // in code paths apart from instantiation where an exception is expected
  556. // to be thrown when abort is called.
  557. throw e;
  558. }
  559. // include: memoryprofiler.js
  560. // end include: memoryprofiler.js
  561. // show errors on likely calls to FS when it was not included
  562. var FS = {
  563. error() {
  564. 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');
  565. },
  566. init() { FS.error() },
  567. createDataFile() { FS.error() },
  568. createPreloadedFile() { FS.error() },
  569. createLazyFile() { FS.error() },
  570. open() { FS.error() },
  571. mkdev() { FS.error() },
  572. registerDevice() { FS.error() },
  573. analyzePath() { FS.error() },
  574. ErrnoError() { FS.error() },
  575. };
  576. Module['FS_createDataFile'] = FS.createDataFile;
  577. Module['FS_createPreloadedFile'] = FS.createPreloadedFile;
  578. // include: URIUtils.js
  579. // Prefix of data URIs emitted by SINGLE_FILE and related options.
  580. var dataURIPrefix = 'data:application/octet-stream;base64,';
  581. /**
  582. * Indicates whether filename is a base64 data URI.
  583. * @noinline
  584. */
  585. var isDataURI = (filename) => filename.startsWith(dataURIPrefix);
  586. /**
  587. * Indicates whether filename is delivered via file protocol (as opposed to http/https)
  588. * @noinline
  589. */
  590. var isFileURI = (filename) => filename.startsWith('file://');
  591. // end include: URIUtils.js
  592. function createExportWrapper(name) {
  593. return (...args) => {
  594. assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`);
  595. var f = wasmExports[name];
  596. assert(f, `exported native function \`${name}\` not found`);
  597. return f(...args);
  598. };
  599. }
  600. // include: runtime_exceptions.js
  601. // end include: runtime_exceptions.js
  602. var wasmBinaryFile;
  603. wasmBinaryFile = '3.wasm';
  604. if (!isDataURI(wasmBinaryFile)) {
  605. wasmBinaryFile = locateFile(wasmBinaryFile);
  606. }
  607. function getBinarySync(file) {
  608. if (file == wasmBinaryFile && wasmBinary) {
  609. return new Uint8Array(wasmBinary);
  610. }
  611. if (readBinary) {
  612. return readBinary(file);
  613. }
  614. throw 'both async and sync fetching of the wasm failed';
  615. }
  616. function getBinaryPromise(binaryFile) {
  617. // If we don't have the binary yet, try to load it asynchronously.
  618. // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.
  619. // See https://github.com/github/fetch/pull/92#issuecomment-140665932
  620. // Cordova or Electron apps are typically loaded from a file:// url.
  621. // So use fetch if it is available and the url is not a file, otherwise fall back to XHR.
  622. if (!wasmBinary
  623. && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
  624. if (typeof fetch == 'function'
  625. && !isFileURI(binaryFile)
  626. ) {
  627. return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => {
  628. if (!response['ok']) {
  629. throw `failed to load wasm binary file at '${binaryFile}'`;
  630. }
  631. return response['arrayBuffer']();
  632. }).catch(() => getBinarySync(binaryFile));
  633. }
  634. else if (readAsync) {
  635. // fetch is not available or url is file => try XHR (readAsync uses XHR internally)
  636. return new Promise((resolve, reject) => {
  637. readAsync(binaryFile, (response) => resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))), reject)
  638. });
  639. }
  640. }
  641. // Otherwise, getBinarySync should be able to get it synchronously
  642. return Promise.resolve().then(() => getBinarySync(binaryFile));
  643. }
  644. function instantiateArrayBuffer(binaryFile, imports, receiver) {
  645. return getBinaryPromise(binaryFile).then((binary) => {
  646. return WebAssembly.instantiate(binary, imports);
  647. }).then(receiver, (reason) => {
  648. err(`failed to asynchronously prepare wasm: ${reason}`);
  649. // Warn on some common problems.
  650. if (isFileURI(wasmBinaryFile)) {
  651. 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`);
  652. }
  653. abort(reason);
  654. });
  655. }
  656. function instantiateAsync(binary, binaryFile, imports, callback) {
  657. if (!binary &&
  658. typeof WebAssembly.instantiateStreaming == 'function' &&
  659. !isDataURI(binaryFile) &&
  660. // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.
  661. !isFileURI(binaryFile) &&
  662. // Avoid instantiateStreaming() on Node.js environment for now, as while
  663. // Node.js v18.1.0 implements it, it does not have a full fetch()
  664. // implementation yet.
  665. //
  666. // Reference:
  667. // https://github.com/emscripten-core/emscripten/pull/16917
  668. !ENVIRONMENT_IS_NODE &&
  669. typeof fetch == 'function') {
  670. return fetch(binaryFile, { credentials: 'same-origin' }).then((response) => {
  671. // Suppress closure warning here since the upstream definition for
  672. // instantiateStreaming only allows Promise<Repsponse> rather than
  673. // an actual Response.
  674. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed.
  675. /** @suppress {checkTypes} */
  676. var result = WebAssembly.instantiateStreaming(response, imports);
  677. return result.then(
  678. callback,
  679. function (reason) {
  680. // We expect the most common failure cause to be a bad MIME type for the binary,
  681. // in which case falling back to ArrayBuffer instantiation should work.
  682. err(`wasm streaming compile failed: ${reason}`);
  683. err('falling back to ArrayBuffer instantiation');
  684. return instantiateArrayBuffer(binaryFile, imports, callback);
  685. });
  686. });
  687. }
  688. return instantiateArrayBuffer(binaryFile, imports, callback);
  689. }
  690. // Create the wasm instance.
  691. // Receives the wasm imports, returns the exports.
  692. function createWasm() {
  693. // prepare imports
  694. var info = {
  695. 'env': wasmImports,
  696. 'wasi_snapshot_preview1': wasmImports,
  697. };
  698. // Load the wasm module and create an instance of using native support in the JS engine.
  699. // handle a generated wasm instance, receiving its exports and
  700. // performing other necessary setup
  701. /** @param {WebAssembly.Module=} module*/
  702. function receiveInstance(instance, module) {
  703. wasmExports = instance.exports;
  704. wasmMemory = wasmExports['memory'];
  705. assert(wasmMemory, 'memory not found in wasm exports');
  706. // This assertion doesn't hold when emscripten is run in --post-link
  707. // mode.
  708. // TODO(sbc): Read INITIAL_MEMORY out of the wasm file in post-link mode.
  709. //assert(wasmMemory.buffer.byteLength === 1073741824);
  710. updateMemoryViews();
  711. addOnInit(wasmExports['__wasm_call_ctors']);
  712. removeRunDependency('wasm-instantiate');
  713. return wasmExports;
  714. }
  715. // wait for the pthread pool (if any)
  716. addRunDependency('wasm-instantiate');
  717. // Prefer streaming instantiation if available.
  718. // Async compilation can be confusing when an error on the page overwrites Module
  719. // (for example, if the order of elements is wrong, and the one defining Module is
  720. // later), so we save Module and check it later.
  721. var trueModule = Module;
  722. function receiveInstantiationResult(result) {
  723. // 'result' is a ResultObject object which has both the module and instance.
  724. // receiveInstance() will swap in the exports (to Module.asm) so they can be called
  725. assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
  726. trueModule = null;
  727. // 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.
  728. // When the regression is fixed, can restore the above PTHREADS-enabled path.
  729. receiveInstance(result['instance']);
  730. }
  731. // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
  732. // to manually instantiate the Wasm module themselves. This allows pages to
  733. // run the instantiation parallel to any other async startup actions they are
  734. // performing.
  735. // Also pthreads and wasm workers initialize the wasm instance through this
  736. // path.
  737. if (Module['instantiateWasm']) {
  738. try {
  739. return Module['instantiateWasm'](info, receiveInstance);
  740. } catch (e) {
  741. err(`Module.instantiateWasm callback failed with error: ${e}`);
  742. return false;
  743. }
  744. }
  745. instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult);
  746. return {}; // no exports yet; we'll fill them in later
  747. }
  748. // Globals used by JS i64 conversions (see makeSetValue)
  749. var tempDouble;
  750. var tempI64;
  751. // include: runtime_debug.js
  752. function legacyModuleProp(prop, newName, incomming = true) {
  753. if (!Object.getOwnPropertyDescriptor(Module, prop)) {
  754. Object.defineProperty(Module, prop, {
  755. configurable: true,
  756. get() {
  757. let extra = incomming ? ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)' : '';
  758. abort(`\`Module.${prop}\` has been replaced by \`${newName}\`` + extra);
  759. }
  760. });
  761. }
  762. }
  763. function ignoredModuleProp(prop) {
  764. if (Object.getOwnPropertyDescriptor(Module, prop)) {
  765. abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`);
  766. }
  767. }
  768. // forcing the filesystem exports a few things by default
  769. function isExportedByForceFilesystem(name) {
  770. return name === 'FS_createPath' ||
  771. name === 'FS_createDataFile' ||
  772. name === 'FS_createPreloadedFile' ||
  773. name === 'FS_unlink' ||
  774. name === 'addRunDependency' ||
  775. // The old FS has some functionality that WasmFS lacks.
  776. name === 'FS_createLazyFile' ||
  777. name === 'FS_createDevice' ||
  778. name === 'removeRunDependency';
  779. }
  780. function missingGlobal(sym, msg) {
  781. if (typeof globalThis !== 'undefined') {
  782. Object.defineProperty(globalThis, sym, {
  783. configurable: true,
  784. get() {
  785. warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`);
  786. return undefined;
  787. }
  788. });
  789. }
  790. }
  791. missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer');
  792. missingGlobal('asm', 'Please use wasmExports instead');
  793. function missingLibrarySymbol(sym) {
  794. if (typeof globalThis !== 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) {
  795. Object.defineProperty(globalThis, sym, {
  796. configurable: true,
  797. get() {
  798. // Can't `abort()` here because it would break code that does runtime
  799. // checks. e.g. `if (typeof SDL === 'undefined')`.
  800. 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`;
  801. // DEFAULT_LIBRARY_FUNCS_TO_INCLUDE requires the name as it appears in
  802. // library.js, which means $name for a JS name with no prefix, or name
  803. // for a JS name like _name.
  804. var librarySymbol = sym;
  805. if (!librarySymbol.startsWith('_')) {
  806. librarySymbol = '$' + sym;
  807. }
  808. msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`;
  809. if (isExportedByForceFilesystem(sym)) {
  810. msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';
  811. }
  812. warnOnce(msg);
  813. return undefined;
  814. }
  815. });
  816. }
  817. // Any symbol that is not included from the JS libary is also (by definition)
  818. // not exported on the Module object.
  819. unexportedRuntimeSymbol(sym);
  820. }
  821. function unexportedRuntimeSymbol(sym) {
  822. if (!Object.getOwnPropertyDescriptor(Module, sym)) {
  823. Object.defineProperty(Module, sym, {
  824. configurable: true,
  825. get() {
  826. var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;
  827. if (isExportedByForceFilesystem(sym)) {
  828. msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you';
  829. }
  830. abort(msg);
  831. }
  832. });
  833. }
  834. }
  835. // Used by XXXXX_DEBUG settings to output debug messages.
  836. function dbg(...args) {
  837. // TODO(sbc): Make this configurable somehow. Its not always convenient for
  838. // logging to show up as warnings.
  839. console.warn(...args);
  840. }
  841. // end include: runtime_debug.js
  842. // === Body ===
  843. // end include: preamble.js
  844. /** @constructor */
  845. function ExitStatus(status) {
  846. this.name = 'ExitStatus';
  847. this.message = `Program terminated with exit(${status})`;
  848. this.status = status;
  849. }
  850. var callRuntimeCallbacks = (callbacks) => {
  851. while (callbacks.length > 0) {
  852. // Pass the module as the first argument.
  853. callbacks.shift()(Module);
  854. }
  855. };
  856. /**
  857. * @param {number} ptr
  858. * @param {string} type
  859. */
  860. function getValue(ptr, type = 'i8') {
  861. if (type.endsWith('*')) type = '*';
  862. switch (type) {
  863. case 'i1': return HEAP8[ptr];
  864. case 'i8': return HEAP8[ptr];
  865. case 'i16': return HEAP16[((ptr) >> 1)];
  866. case 'i32': return HEAP32[((ptr) >> 2)];
  867. case 'i64': abort('to do getValue(i64) use WASM_BIGINT');
  868. case 'float': return HEAPF32[((ptr) >> 2)];
  869. case 'double': return HEAPF64[((ptr) >> 3)];
  870. case '*': return HEAPU32[((ptr) >> 2)];
  871. default: abort(`invalid type for getValue: ${type}`);
  872. }
  873. }
  874. var noExitRuntime = Module['noExitRuntime'] || true;
  875. var ptrToString = (ptr) => {
  876. assert(typeof ptr === 'number');
  877. // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
  878. ptr >>>= 0;
  879. return '0x' + ptr.toString(16).padStart(8, '0');
  880. };
  881. /**
  882. * @param {number} ptr
  883. * @param {number} value
  884. * @param {string} type
  885. */
  886. function setValue(ptr, value, type = 'i8') {
  887. if (type.endsWith('*')) type = '*';
  888. switch (type) {
  889. case 'i1': HEAP8[ptr] = value; break;
  890. case 'i8': HEAP8[ptr] = value; break;
  891. case 'i16': HEAP16[((ptr) >> 1)] = value; break;
  892. case 'i32': HEAP32[((ptr) >> 2)] = value; break;
  893. case 'i64': abort('to do setValue(i64) use WASM_BIGINT');
  894. case 'float': HEAPF32[((ptr) >> 2)] = value; break;
  895. case 'double': HEAPF64[((ptr) >> 3)] = value; break;
  896. case '*': HEAPU32[((ptr) >> 2)] = value; break;
  897. default: abort(`invalid type for setValue: ${type}`);
  898. }
  899. }
  900. var warnOnce = (text) => {
  901. warnOnce.shown ||= {};
  902. if (!warnOnce.shown[text]) {
  903. warnOnce.shown[text] = 1;
  904. if (ENVIRONMENT_IS_NODE) text = 'warning: ' + text;
  905. err(text);
  906. }
  907. };
  908. var _emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num);
  909. var getHeapMax = () =>
  910. HEAPU8.length;
  911. var abortOnCannotGrowMemory = (requestedSize) => {
  912. 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`);
  913. };
  914. var _emscripten_resize_heap = (requestedSize) => {
  915. var oldSize = HEAPU8.length;
  916. // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.
  917. requestedSize >>>= 0;
  918. abortOnCannotGrowMemory(requestedSize);
  919. };
  920. var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined;
  921. /**
  922. * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given
  923. * array that contains uint8 values, returns a copy of that string as a
  924. * Javascript String object.
  925. * heapOrArray is either a regular array, or a JavaScript typed array view.
  926. * @param {number} idx
  927. * @param {number=} maxBytesToRead
  928. * @return {string}
  929. */
  930. var UTF8ArrayToString = (heapOrArray, idx, maxBytesToRead) => {
  931. var endIdx = idx + maxBytesToRead;
  932. var endPtr = idx;
  933. // TextDecoder needs to know the byte length in advance, it doesn't stop on
  934. // null terminator by itself. Also, use the length info to avoid running tiny
  935. // strings through TextDecoder, since .subarray() allocates garbage.
  936. // (As a tiny code save trick, compare endPtr against endIdx using a negation,
  937. // so that undefined means Infinity)
  938. while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
  939. if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
  940. return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
  941. }
  942. var str = '';
  943. // If building with TextDecoder, we have already computed the string length
  944. // above, so test loop end condition against that
  945. while (idx < endPtr) {
  946. // For UTF8 byte structure, see:
  947. // http://en.wikipedia.org/wiki/UTF-8#Description
  948. // https://www.ietf.org/rfc/rfc2279.txt
  949. // https://tools.ietf.org/html/rfc3629
  950. var u0 = heapOrArray[idx++];
  951. if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
  952. var u1 = heapOrArray[idx++] & 63;
  953. if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
  954. var u2 = heapOrArray[idx++] & 63;
  955. if ((u0 & 0xF0) == 0xE0) {
  956. u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
  957. } else {
  958. 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!');
  959. u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);
  960. }
  961. if (u0 < 0x10000) {
  962. str += String.fromCharCode(u0);
  963. } else {
  964. var ch = u0 - 0x10000;
  965. str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
  966. }
  967. }
  968. return str;
  969. };
  970. /**
  971. * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the
  972. * emscripten HEAP, returns a copy of that string as a Javascript String object.
  973. *
  974. * @param {number} ptr
  975. * @param {number=} maxBytesToRead - An optional length that specifies the
  976. * maximum number of bytes to read. You can omit this parameter to scan the
  977. * string until the first 0 byte. If maxBytesToRead is passed, and the string
  978. * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the
  979. * string will cut short at that byte index (i.e. maxBytesToRead will not
  980. * produce a string of exact length [ptr, ptr+maxBytesToRead[) N.B. mixing
  981. * frequent uses of UTF8ToString() with and without maxBytesToRead may throw
  982. * JS JIT optimizations off, so it is worth to consider consistently using one
  983. * @return {string}
  984. */
  985. var UTF8ToString = (ptr, maxBytesToRead) => {
  986. assert(typeof ptr == 'number', `UTF8ToString expects a number (got ${typeof ptr})`);
  987. return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
  988. };
  989. var SYSCALLS = {
  990. varargs: undefined,
  991. get() {
  992. assert(SYSCALLS.varargs != undefined);
  993. // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number.
  994. var ret = HEAP32[((+SYSCALLS.varargs) >> 2)];
  995. SYSCALLS.varargs += 4;
  996. return ret;
  997. },
  998. getp() { return SYSCALLS.get() },
  999. getStr(ptr) {
  1000. var ret = UTF8ToString(ptr);
  1001. return ret;
  1002. },
  1003. };
  1004. var _fd_close = (fd) => {
  1005. abort('fd_close called without SYSCALLS_REQUIRE_FILESYSTEM');
  1006. };
  1007. var convertI32PairToI53Checked = (lo, hi) => {
  1008. assert(lo == (lo >>> 0) || lo == (lo | 0)); // lo should either be a i32 or a u32
  1009. assert(hi === (hi | 0)); // hi should be a i32
  1010. return ((hi + 0x200000) >>> 0 < 0x400001 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN;
  1011. };
  1012. function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
  1013. var offset = convertI32PairToI53Checked(offset_low, offset_high);;
  1014. return 70;
  1015. ;
  1016. }
  1017. var printCharBuffers = [null, [], []];
  1018. var printChar = (stream, curr) => {
  1019. var buffer = printCharBuffers[stream];
  1020. assert(buffer);
  1021. if (curr === 0 || curr === 10) {
  1022. (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0));
  1023. buffer.length = 0;
  1024. } else {
  1025. buffer.push(curr);
  1026. }
  1027. };
  1028. var flush_NO_FILESYSTEM = () => {
  1029. // flush anything remaining in the buffers during shutdown
  1030. _fflush(0);
  1031. if (printCharBuffers[1].length) printChar(1, 10);
  1032. if (printCharBuffers[2].length) printChar(2, 10);
  1033. };
  1034. var _fd_write = (fd, iov, iovcnt, pnum) => {
  1035. // hack to support printf in SYSCALLS_REQUIRE_FILESYSTEM=0
  1036. var num = 0;
  1037. for (var i = 0; i < iovcnt; i++) {
  1038. var ptr = HEAPU32[((iov) >> 2)];
  1039. var len = HEAPU32[(((iov) + (4)) >> 2)];
  1040. iov += 8;
  1041. for (var j = 0; j < len; j++) {
  1042. printChar(fd, HEAPU8[ptr + j]);
  1043. }
  1044. num += len;
  1045. }
  1046. HEAPU32[((pnum) >> 2)] = num;
  1047. return 0;
  1048. };
  1049. var runtimeKeepaliveCounter = 0;
  1050. var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;
  1051. var _proc_exit = (code) => {
  1052. EXITSTATUS = code;
  1053. if (!keepRuntimeAlive()) {
  1054. Module['onExit']?.(code);
  1055. ABORT = true;
  1056. }
  1057. quit_(code, new ExitStatus(code));
  1058. };
  1059. /** @param {boolean|number=} implicit */
  1060. var exitJS = (status, implicit) => {
  1061. EXITSTATUS = status;
  1062. checkUnflushedContent();
  1063. // if exit() was called explicitly, warn the user if the runtime isn't actually being shut down
  1064. if (keepRuntimeAlive() && !implicit) {
  1065. 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)`;
  1066. err(msg);
  1067. }
  1068. _proc_exit(status);
  1069. };
  1070. var handleException = (e) => {
  1071. // Certain exception types we do not treat as errors since they are used for
  1072. // internal control flow.
  1073. // 1. ExitStatus, which is thrown by exit()
  1074. // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others
  1075. // that wish to return to JS event loop.
  1076. if (e instanceof ExitStatus || e == 'unwind') {
  1077. return EXITSTATUS;
  1078. }
  1079. checkStackCookie();
  1080. if (e instanceof WebAssembly.RuntimeError) {
  1081. if (_emscripten_stack_get_current() <= 0) {
  1082. err('Stack overflow detected. You can try increasing -sSTACK_SIZE (currently set to 10485760)');
  1083. }
  1084. }
  1085. quit_(1, e);
  1086. };
  1087. function checkIncomingModuleAPI() {
  1088. ignoredModuleProp('fetchSettings');
  1089. }
  1090. var wasmImports = {
  1091. /** @export */
  1092. emscripten_memcpy_js: _emscripten_memcpy_js,
  1093. /** @export */
  1094. emscripten_resize_heap: _emscripten_resize_heap,
  1095. /** @export */
  1096. fd_close: _fd_close,
  1097. /** @export */
  1098. fd_seek: _fd_seek,
  1099. /** @export */
  1100. fd_write: _fd_write
  1101. };
  1102. var wasmExports = createWasm();
  1103. var ___wasm_call_ctors = createExportWrapper('__wasm_call_ctors');
  1104. var _main = Module['_main'] = createExportWrapper('main');
  1105. var _exchange_js_get_install_bts_save_address = Module['_exchange_js_get_install_bts_save_address'] = createExportWrapper('exchange_js_get_install_bts_save_address');
  1106. var _exchange_js_get_route_bts_save_address = Module['_exchange_js_get_route_bts_save_address'] = createExportWrapper('exchange_js_get_route_bts_save_address');
  1107. var _exchange_js_get_audio_data_save_address = Module['_exchange_js_get_audio_data_save_address'] = createExportWrapper('exchange_js_get_audio_data_save_address');
  1108. var _exchange_js_notice_wasm_start_work = Module['_exchange_js_notice_wasm_start_work'] = createExportWrapper('exchange_js_notice_wasm_start_work');
  1109. var _exchange_js_get_current_location_coord_save_address = Module['_exchange_js_get_current_location_coord_save_address'] = createExportWrapper('exchange_js_get_current_location_coord_save_address');
  1110. var _exchange_js_notice_wasm_free_memory = Module['_exchange_js_notice_wasm_free_memory'] = createExportWrapper('exchange_js_notice_wasm_free_memory');
  1111. var _exchange_js_notice_wasm_show_route_bts = Module['_exchange_js_notice_wasm_show_route_bts'] = createExportWrapper('exchange_js_notice_wasm_show_route_bts');
  1112. var _exchange_js_notice_wasm_show_install_bts = Module['_exchange_js_notice_wasm_show_install_bts'] = createExportWrapper('exchange_js_notice_wasm_show_install_bts');
  1113. var _fflush = createExportWrapper('fflush');
  1114. var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports['emscripten_stack_init'])();
  1115. var _emscripten_stack_get_free = () => (_emscripten_stack_get_free = wasmExports['emscripten_stack_get_free'])();
  1116. var _emscripten_stack_get_base = () => (_emscripten_stack_get_base = wasmExports['emscripten_stack_get_base'])();
  1117. var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports['emscripten_stack_get_end'])();
  1118. var stackSave = createExportWrapper('stackSave');
  1119. var stackRestore = createExportWrapper('stackRestore');
  1120. var stackAlloc = createExportWrapper('stackAlloc');
  1121. var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports['emscripten_stack_get_current'])();
  1122. var dynCall_jiji = Module['dynCall_jiji'] = createExportWrapper('dynCall_jiji');
  1123. // include: postamble.js
  1124. // === Auto-generated postamble setup entry stuff ===
  1125. var missingLibrarySymbols = [
  1126. 'writeI53ToI64',
  1127. 'writeI53ToI64Clamped',
  1128. 'writeI53ToI64Signaling',
  1129. 'writeI53ToU64Clamped',
  1130. 'writeI53ToU64Signaling',
  1131. 'readI53FromI64',
  1132. 'readI53FromU64',
  1133. 'convertI32PairToI53',
  1134. 'convertU32PairToI53',
  1135. 'zeroMemory',
  1136. 'growMemory',
  1137. 'isLeapYear',
  1138. 'ydayFromDate',
  1139. 'arraySum',
  1140. 'addDays',
  1141. 'inetPton4',
  1142. 'inetNtop4',
  1143. 'inetPton6',
  1144. 'inetNtop6',
  1145. 'readSockaddr',
  1146. 'writeSockaddr',
  1147. 'initRandomFill',
  1148. 'randomFill',
  1149. 'getCallstack',
  1150. 'emscriptenLog',
  1151. 'convertPCtoSourceLocation',
  1152. 'readEmAsmArgs',
  1153. 'jstoi_q',
  1154. 'getExecutableName',
  1155. 'listenOnce',
  1156. 'autoResumeAudioContext',
  1157. 'dynCallLegacy',
  1158. 'getDynCaller',
  1159. 'dynCall',
  1160. 'runtimeKeepalivePush',
  1161. 'runtimeKeepalivePop',
  1162. 'callUserCallback',
  1163. 'maybeExit',
  1164. 'asmjsMangle',
  1165. 'asyncLoad',
  1166. 'alignMemory',
  1167. 'mmapAlloc',
  1168. 'HandleAllocator',
  1169. 'getNativeTypeSize',
  1170. 'STACK_SIZE',
  1171. 'STACK_ALIGN',
  1172. 'POINTER_SIZE',
  1173. 'ASSERTIONS',
  1174. 'getCFunc',
  1175. 'ccall',
  1176. 'cwrap',
  1177. 'uleb128Encode',
  1178. 'sigToWasmTypes',
  1179. 'generateFuncType',
  1180. 'convertJsFunctionToWasm',
  1181. 'getEmptyTableSlot',
  1182. 'updateTableMap',
  1183. 'getFunctionAddress',
  1184. 'addFunction',
  1185. 'removeFunction',
  1186. 'reallyNegative',
  1187. 'unSign',
  1188. 'strLen',
  1189. 'reSign',
  1190. 'formatString',
  1191. 'stringToUTF8Array',
  1192. 'stringToUTF8',
  1193. 'lengthBytesUTF8',
  1194. 'intArrayFromString',
  1195. 'intArrayToString',
  1196. 'AsciiToString',
  1197. 'stringToAscii',
  1198. 'UTF16ToString',
  1199. 'stringToUTF16',
  1200. 'lengthBytesUTF16',
  1201. 'UTF32ToString',
  1202. 'stringToUTF32',
  1203. 'lengthBytesUTF32',
  1204. 'stringToNewUTF8',
  1205. 'stringToUTF8OnStack',
  1206. 'writeArrayToMemory',
  1207. 'registerKeyEventCallback',
  1208. 'maybeCStringToJsString',
  1209. 'findEventTarget',
  1210. 'getBoundingClientRect',
  1211. 'fillMouseEventData',
  1212. 'registerMouseEventCallback',
  1213. 'registerWheelEventCallback',
  1214. 'registerUiEventCallback',
  1215. 'registerFocusEventCallback',
  1216. 'fillDeviceOrientationEventData',
  1217. 'registerDeviceOrientationEventCallback',
  1218. 'fillDeviceMotionEventData',
  1219. 'registerDeviceMotionEventCallback',
  1220. 'screenOrientation',
  1221. 'fillOrientationChangeEventData',
  1222. 'registerOrientationChangeEventCallback',
  1223. 'fillFullscreenChangeEventData',
  1224. 'registerFullscreenChangeEventCallback',
  1225. 'JSEvents_requestFullscreen',
  1226. 'JSEvents_resizeCanvasForFullscreen',
  1227. 'registerRestoreOldStyle',
  1228. 'hideEverythingExceptGivenElement',
  1229. 'restoreHiddenElements',
  1230. 'setLetterbox',
  1231. 'softFullscreenResizeWebGLRenderTarget',
  1232. 'doRequestFullscreen',
  1233. 'fillPointerlockChangeEventData',
  1234. 'registerPointerlockChangeEventCallback',
  1235. 'registerPointerlockErrorEventCallback',
  1236. 'requestPointerLock',
  1237. 'fillVisibilityChangeEventData',
  1238. 'registerVisibilityChangeEventCallback',
  1239. 'registerTouchEventCallback',
  1240. 'fillGamepadEventData',
  1241. 'registerGamepadEventCallback',
  1242. 'registerBeforeUnloadEventCallback',
  1243. 'fillBatteryEventData',
  1244. 'battery',
  1245. 'registerBatteryEventCallback',
  1246. 'setCanvasElementSize',
  1247. 'getCanvasElementSize',
  1248. 'jsStackTrace',
  1249. 'stackTrace',
  1250. 'getEnvStrings',
  1251. 'checkWasiClock',
  1252. 'wasiRightsToMuslOFlags',
  1253. 'wasiOFlagsToMuslOFlags',
  1254. 'createDyncallWrapper',
  1255. 'safeSetTimeout',
  1256. 'setImmediateWrapped',
  1257. 'clearImmediateWrapped',
  1258. 'polyfillSetImmediate',
  1259. 'getPromise',
  1260. 'makePromise',
  1261. 'idsToPromises',
  1262. 'makePromiseCallback',
  1263. 'ExceptionInfo',
  1264. 'findMatchingCatch',
  1265. 'Browser_asyncPrepareDataCounter',
  1266. 'setMainLoop',
  1267. 'getSocketFromFD',
  1268. 'getSocketAddress',
  1269. 'FS_createPreloadedFile',
  1270. 'FS_modeStringToFlags',
  1271. 'FS_getMode',
  1272. 'FS_stdin_getChar',
  1273. 'FS_createDataFile',
  1274. 'FS_unlink',
  1275. 'FS_mkdirTree',
  1276. '_setNetworkCallback',
  1277. 'heapObjectForWebGLType',
  1278. 'toTypedArrayIndex',
  1279. 'webgl_enable_ANGLE_instanced_arrays',
  1280. 'webgl_enable_OES_vertex_array_object',
  1281. 'webgl_enable_WEBGL_draw_buffers',
  1282. 'webgl_enable_WEBGL_multi_draw',
  1283. 'emscriptenWebGLGet',
  1284. 'computeUnpackAlignedImageSize',
  1285. 'colorChannelsInGlTextureFormat',
  1286. 'emscriptenWebGLGetTexPixelData',
  1287. 'emscriptenWebGLGetUniform',
  1288. 'webglGetUniformLocation',
  1289. 'webglPrepareUniformLocationsBeforeFirstUse',
  1290. 'webglGetLeftBracePos',
  1291. 'emscriptenWebGLGetVertexAttrib',
  1292. '__glGetActiveAttribOrUniform',
  1293. 'writeGLArray',
  1294. 'registerWebGlEventCallback',
  1295. 'runAndAbortIfError',
  1296. 'SDL_unicode',
  1297. 'SDL_ttfContext',
  1298. 'SDL_audio',
  1299. 'ALLOC_NORMAL',
  1300. 'ALLOC_STACK',
  1301. 'allocate',
  1302. 'writeStringToMemory',
  1303. 'writeAsciiToMemory',
  1304. 'setErrNo',
  1305. 'demangle',
  1306. ];
  1307. missingLibrarySymbols.forEach(missingLibrarySymbol)
  1308. var unexportedSymbols = [
  1309. 'run',
  1310. 'addOnPreRun',
  1311. 'addOnInit',
  1312. 'addOnPreMain',
  1313. 'addOnExit',
  1314. 'addOnPostRun',
  1315. 'addRunDependency',
  1316. 'removeRunDependency',
  1317. 'FS_createFolder',
  1318. 'FS_createPath',
  1319. 'FS_createLazyFile',
  1320. 'FS_createLink',
  1321. 'FS_createDevice',
  1322. 'FS_readFile',
  1323. 'out',
  1324. 'err',
  1325. 'callMain',
  1326. 'abort',
  1327. 'wasmMemory',
  1328. 'wasmExports',
  1329. 'stackAlloc',
  1330. 'stackSave',
  1331. 'stackRestore',
  1332. 'getTempRet0',
  1333. 'setTempRet0',
  1334. 'writeStackCookie',
  1335. 'checkStackCookie',
  1336. 'convertI32PairToI53Checked',
  1337. 'ptrToString',
  1338. 'exitJS',
  1339. 'getHeapMax',
  1340. 'abortOnCannotGrowMemory',
  1341. 'ENV',
  1342. 'MONTH_DAYS_REGULAR',
  1343. 'MONTH_DAYS_LEAP',
  1344. 'MONTH_DAYS_REGULAR_CUMULATIVE',
  1345. 'MONTH_DAYS_LEAP_CUMULATIVE',
  1346. 'ERRNO_CODES',
  1347. 'ERRNO_MESSAGES',
  1348. 'DNS',
  1349. 'Protocols',
  1350. 'Sockets',
  1351. 'timers',
  1352. 'warnOnce',
  1353. 'UNWIND_CACHE',
  1354. 'readEmAsmArgsArray',
  1355. 'jstoi_s',
  1356. 'handleException',
  1357. 'keepRuntimeAlive',
  1358. 'wasmTable',
  1359. 'noExitRuntime',
  1360. 'freeTableIndexes',
  1361. 'functionsInTableMap',
  1362. 'setValue',
  1363. 'getValue',
  1364. 'PATH',
  1365. 'PATH_FS',
  1366. 'UTF8Decoder',
  1367. 'UTF8ArrayToString',
  1368. 'UTF8ToString',
  1369. 'UTF16Decoder',
  1370. 'JSEvents',
  1371. 'specialHTMLTargets',
  1372. 'findCanvasEventTarget',
  1373. 'currentFullscreenStrategy',
  1374. 'restoreOldWindowedStyle',
  1375. 'ExitStatus',
  1376. 'flush_NO_FILESYSTEM',
  1377. 'promiseMap',
  1378. 'uncaughtExceptionCount',
  1379. 'exceptionLast',
  1380. 'exceptionCaught',
  1381. 'Browser',
  1382. 'getPreloadedImageData__data',
  1383. 'wget',
  1384. 'SYSCALLS',
  1385. 'preloadPlugins',
  1386. 'FS_stdin_getChar_buffer',
  1387. 'FS',
  1388. 'MEMFS',
  1389. 'TTY',
  1390. 'PIPEFS',
  1391. 'SOCKFS',
  1392. 'tempFixedLengthArray',
  1393. 'miniTempWebGLFloatBuffers',
  1394. 'miniTempWebGLIntBuffers',
  1395. 'GL',
  1396. 'AL',
  1397. 'GLUT',
  1398. 'EGL',
  1399. 'GLEW',
  1400. 'IDBStore',
  1401. 'SDL',
  1402. 'SDL_gfx',
  1403. 'allocateUTF8',
  1404. 'allocateUTF8OnStack',
  1405. ];
  1406. unexportedSymbols.forEach(unexportedRuntimeSymbol);
  1407. var calledRun;
  1408. dependenciesFulfilled = function runCaller() {
  1409. // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
  1410. if (!calledRun) run();
  1411. if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
  1412. };
  1413. function callMain() {
  1414. assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on Module["onRuntimeInitialized"])');
  1415. assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
  1416. var entryFunction = _main;
  1417. var argc = 0;
  1418. var argv = 0;
  1419. try {
  1420. var ret = entryFunction(argc, argv);
  1421. // if we're not running an evented main loop, it's time to exit
  1422. exitJS(ret, /* implicit = */ true);
  1423. return ret;
  1424. }
  1425. catch (e) {
  1426. return handleException(e);
  1427. }
  1428. }
  1429. function stackCheckInit() {
  1430. // This is normally called automatically during __wasm_call_ctors but need to
  1431. // get these values before even running any of the ctors so we call it redundantly
  1432. // here.
  1433. _emscripten_stack_init();
  1434. // TODO(sbc): Move writeStackCookie to native to to avoid this.
  1435. writeStackCookie();
  1436. }
  1437. function run() {
  1438. if (runDependencies > 0) {
  1439. return;
  1440. }
  1441. stackCheckInit();
  1442. preRun();
  1443. // a preRun added a dependency, run will be called later
  1444. if (runDependencies > 0) {
  1445. return;
  1446. }
  1447. function doRun() {
  1448. // run may have just been called through dependencies being fulfilled just in this very frame,
  1449. // or while the async setStatus time below was happening
  1450. if (calledRun) return;
  1451. calledRun = true;
  1452. Module['calledRun'] = true;
  1453. if (ABORT) return;
  1454. initRuntime();
  1455. preMain();
  1456. if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
  1457. if (shouldRunNow) callMain();
  1458. postRun();
  1459. }
  1460. if (Module['setStatus']) {
  1461. Module['setStatus']('Running...');
  1462. setTimeout(function () {
  1463. setTimeout(function () {
  1464. Module['setStatus']('');
  1465. }, 1);
  1466. doRun();
  1467. }, 1);
  1468. } else {
  1469. doRun();
  1470. }
  1471. checkStackCookie();
  1472. }
  1473. function checkUnflushedContent() {
  1474. // Compiler settings do not allow exiting the runtime, so flushing
  1475. // the streams is not possible. but in ASSERTIONS mode we check
  1476. // if there was something to flush, and if so tell the user they
  1477. // should request that the runtime be exitable.
  1478. // Normally we would not even include flush() at all, but in ASSERTIONS
  1479. // builds we do so just for this check, and here we see if there is any
  1480. // content to flush, that is, we check if there would have been
  1481. // something a non-ASSERTIONS build would have not seen.
  1482. // How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0
  1483. // mode (which has its own special function for this; otherwise, all
  1484. // the code is inside libc)
  1485. var oldOut = out;
  1486. var oldErr = err;
  1487. var has = false;
  1488. out = err = (x) => {
  1489. has = true;
  1490. }
  1491. try { // it doesn't matter if it fails
  1492. flush_NO_FILESYSTEM();
  1493. } catch (e) { }
  1494. out = oldOut;
  1495. err = oldErr;
  1496. if (has) {
  1497. 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.');
  1498. warnOnce('(this may also be due to not including full filesystem support - try building with -sFORCE_FILESYSTEM)');
  1499. }
  1500. }
  1501. if (Module['preInit']) {
  1502. if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
  1503. while (Module['preInit'].length > 0) {
  1504. Module['preInit'].pop()();
  1505. }
  1506. }
  1507. // shouldRunNow refers to calling main(), not run().
  1508. var shouldRunNow = true;
  1509. if (Module['noInitialRun']) shouldRunNow = false;
  1510. run();
  1511. // end include: postamble.js