base32.js (96609B)
1 2 var Base32Module = (() => { 3 var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; 4 if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; 5 return ( 6 function(Base32Module) { 7 Base32Module = Base32Module || {}; 8 9 10 11 // The Module object: Our interface to the outside world. We import 12 // and export values on it. There are various ways Module can be used: 13 // 1. Not defined. We create it here 14 // 2. A function parameter, function(Module) { ..generated code.. } 15 // 3. pre-run appended it, var Module = {}; ..generated code.. 16 // 4. External script tag defines var Module. 17 // We need to check if Module already exists (e.g. case 3 above). 18 // Substitution will be replaced with actual code on later stage of the build, 19 // this way Closure Compiler will not mangle it (e.g. case 4. above). 20 // Note that if you want to run closure, and also to use Module 21 // after the generated code, you will need to define var Module = {}; 22 // before the code. Then that object will be used in the code, and you 23 // can continue to use Module afterwards as well. 24 var Module = typeof Base32Module != 'undefined' ? Base32Module : {}; 25 26 // See https://caniuse.com/mdn-javascript_builtins_object_assign 27 28 // Set up the promise that indicates the Module is initialized 29 var readyPromiseResolve, readyPromiseReject; 30 Module['ready'] = new Promise(function(resolve, reject) { 31 readyPromiseResolve = resolve; 32 readyPromiseReject = reject; 33 }); 34 35 if (!Object.getOwnPropertyDescriptor(Module['ready'], '_base32_decodeString')) { 36 Object.defineProperty(Module['ready'], '_base32_decodeString', { configurable: true, get: function() { abort('You are getting _base32_decodeString on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 37 Object.defineProperty(Module['ready'], '_base32_decodeString', { configurable: true, set: function() { abort('You are setting _base32_decodeString on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 38 } 39 40 41 if (!Object.getOwnPropertyDescriptor(Module['ready'], '_base32_encodeBytes')) { 42 Object.defineProperty(Module['ready'], '_base32_encodeBytes', { configurable: true, get: function() { abort('You are getting _base32_encodeBytes on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 43 Object.defineProperty(Module['ready'], '_base32_encodeBytes', { configurable: true, set: function() { abort('You are setting _base32_encodeBytes on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 44 } 45 46 47 if (!Object.getOwnPropertyDescriptor(Module['ready'], '_malloc')) { 48 Object.defineProperty(Module['ready'], '_malloc', { configurable: true, get: function() { abort('You are getting _malloc on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 49 Object.defineProperty(Module['ready'], '_malloc', { configurable: true, set: function() { abort('You are setting _malloc on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 50 } 51 52 53 if (!Object.getOwnPropertyDescriptor(Module['ready'], '_free')) { 54 Object.defineProperty(Module['ready'], '_free', { configurable: true, get: function() { abort('You are getting _free on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 55 Object.defineProperty(Module['ready'], '_free', { configurable: true, set: function() { abort('You are setting _free on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 56 } 57 58 59 if (!Object.getOwnPropertyDescriptor(Module['ready'], '___stdio_exit')) { 60 Object.defineProperty(Module['ready'], '___stdio_exit', { configurable: true, get: function() { abort('You are getting ___stdio_exit on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 61 Object.defineProperty(Module['ready'], '___stdio_exit', { configurable: true, set: function() { abort('You are setting ___stdio_exit on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 62 } 63 64 65 if (!Object.getOwnPropertyDescriptor(Module['ready'], 'onRuntimeInitialized')) { 66 Object.defineProperty(Module['ready'], 'onRuntimeInitialized', { configurable: true, get: function() { abort('You are getting onRuntimeInitialized on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 67 Object.defineProperty(Module['ready'], 'onRuntimeInitialized', { configurable: true, set: function() { abort('You are setting onRuntimeInitialized on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js') } }); 68 } 69 70 71 // --pre-jses are emitted after the Module integration code, so that they can 72 // refer to Module (if they choose; they can also define Module) 73 // {{PRE_JSES}} 74 75 // Sometimes an existing Module object exists with properties 76 // meant to overwrite the default module functionality. Here 77 // we collect those properties and reapply _after_ we configure 78 // the current environment's defaults to avoid having to be so 79 // defensive during initialization. 80 var moduleOverrides = Object.assign({}, Module); 81 82 var arguments_ = []; 83 var thisProgram = './this.program'; 84 var quit_ = (status, toThrow) => { 85 throw toThrow; 86 }; 87 88 // Determine the runtime environment we are in. You can customize this by 89 // setting the ENVIRONMENT setting at compile time (see settings.js). 90 91 // Attempt to auto-detect the environment 92 var ENVIRONMENT_IS_WEB = typeof window == 'object'; 93 var ENVIRONMENT_IS_WORKER = typeof importScripts == 'function'; 94 // N.b. Electron.js environment is simultaneously a NODE-environment, but 95 // also a web environment. 96 var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string'; 97 var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; 98 99 if (Module['ENVIRONMENT']) { 100 throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -s ENVIRONMENT=web or -s ENVIRONMENT=node)'); 101 } 102 103 // `/` should be present at the end if `scriptDirectory` is not empty 104 var scriptDirectory = ''; 105 function locateFile(path) { 106 if (Module['locateFile']) { 107 return Module['locateFile'](path, scriptDirectory); 108 } 109 return scriptDirectory + path; 110 } 111 112 // Hooks that are implemented differently in different runtime environments. 113 var read_, 114 readAsync, 115 readBinary, 116 setWindowTitle; 117 118 // Normally we don't log exceptions but instead let them bubble out the top 119 // level where the embedding environment (e.g. the browser) can handle 120 // them. 121 // However under v8 and node we sometimes exit the process direcly in which case 122 // its up to use us to log the exception before exiting. 123 // If we fix https://github.com/emscripten-core/emscripten/issues/15080 124 // this may no longer be needed under node. 125 function logExceptionOnExit(e) { 126 if (e instanceof ExitStatus) return; 127 let toLog = e; 128 if (e && typeof e == 'object' && e.stack) { 129 toLog = [e, e.stack]; 130 } 131 err('exiting due to exception: ' + toLog); 132 } 133 134 var fs; 135 var nodePath; 136 var requireNodeFS; 137 138 if (ENVIRONMENT_IS_NODE) { 139 if (!(typeof process == 'object' && typeof require == '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?)'); 140 if (ENVIRONMENT_IS_WORKER) { 141 scriptDirectory = require('path').dirname(scriptDirectory) + '/'; 142 } else { 143 scriptDirectory = __dirname + '/'; 144 } 145 146 // include: node_shell_read.js 147 148 149 requireNodeFS = () => { 150 // Use nodePath as the indicator for these not being initialized, 151 // since in some environments a global fs may have already been 152 // created. 153 if (!nodePath) { 154 fs = require('fs'); 155 nodePath = require('path'); 156 } 157 }; 158 159 read_ = function shell_read(filename, binary) { 160 requireNodeFS(); 161 filename = nodePath['normalize'](filename); 162 return fs.readFileSync(filename, binary ? undefined : 'utf8'); 163 }; 164 165 readBinary = (filename) => { 166 var ret = read_(filename, true); 167 if (!ret.buffer) { 168 ret = new Uint8Array(ret); 169 } 170 assert(ret.buffer); 171 return ret; 172 }; 173 174 readAsync = (filename, onload, onerror) => { 175 requireNodeFS(); 176 filename = nodePath['normalize'](filename); 177 fs.readFile(filename, function(err, data) { 178 if (err) onerror(err); 179 else onload(data.buffer); 180 }); 181 }; 182 183 // end include: node_shell_read.js 184 if (process['argv'].length > 1) { 185 thisProgram = process['argv'][1].replace(/\\/g, '/'); 186 } 187 188 arguments_ = process['argv'].slice(2); 189 190 // MODULARIZE will export the module in the proper place outside, we don't need to export here 191 192 process['on']('uncaughtException', function(ex) { 193 // suppress ExitStatus exceptions from showing an error 194 if (!(ex instanceof ExitStatus)) { 195 throw ex; 196 } 197 }); 198 199 // Without this older versions of node (< v15) will log unhandled rejections 200 // but return 0, which is not normally the desired behaviour. This is 201 // not be needed with node v15 and about because it is now the default 202 // behaviour: 203 // See https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode 204 process['on']('unhandledRejection', function(reason) { throw reason; }); 205 206 quit_ = (status, toThrow) => { 207 if (keepRuntimeAlive()) { 208 process['exitCode'] = status; 209 throw toThrow; 210 } 211 logExceptionOnExit(toThrow); 212 process['exit'](status); 213 }; 214 215 Module['inspect'] = function () { return '[Emscripten Module object]'; }; 216 217 } else 218 if (ENVIRONMENT_IS_SHELL) { 219 220 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?)'); 221 222 if (typeof read != 'undefined') { 223 read_ = function shell_read(f) { 224 return read(f); 225 }; 226 } 227 228 readBinary = function readBinary(f) { 229 let data; 230 if (typeof readbuffer == 'function') { 231 return new Uint8Array(readbuffer(f)); 232 } 233 data = read(f, 'binary'); 234 assert(typeof data == 'object'); 235 return data; 236 }; 237 238 readAsync = function readAsync(f, onload, onerror) { 239 setTimeout(() => onload(readBinary(f)), 0); 240 }; 241 242 if (typeof scriptArgs != 'undefined') { 243 arguments_ = scriptArgs; 244 } else if (typeof arguments != 'undefined') { 245 arguments_ = arguments; 246 } 247 248 if (typeof quit == 'function') { 249 quit_ = (status, toThrow) => { 250 // Unlike node which has process.exitCode, d8 has no such mechanism. So we 251 // have no way to set the exit code and then let the program exit with 252 // that code when it naturally stops running (say, when all setTimeouts 253 // have completed). For that reason we must call `quit` - the only way to 254 // set the exit code - but quit also halts immediately, so we need to be 255 // careful of whether the runtime is alive or not, which is why this code 256 // path looks different than node. It also has the downside that it will 257 // halt the entire program when no code remains to run, which means this 258 // is not friendly for bundling this code into a larger codebase, and for 259 // that reason the "shell" environment is mainly useful for testing whole 260 // programs by themselves, basically. 261 if (runtimeKeepaliveCounter) { 262 throw toThrow; 263 } 264 logExceptionOnExit(toThrow); 265 quit(status); 266 }; 267 } 268 269 if (typeof print != 'undefined') { 270 // Prefer to use print/printErr where they exist, as they usually work better. 271 if (typeof console == 'undefined') console = /** @type{!Console} */({}); 272 console.log = /** @type{!function(this:Console, ...*): undefined} */ (print); 273 console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (typeof printErr != 'undefined' ? printErr : print); 274 } 275 276 } else 277 278 // Note that this includes Node.js workers when relevant (pthreads is enabled). 279 // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and 280 // ENVIRONMENT_IS_NODE. 281 if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { 282 if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled 283 scriptDirectory = self.location.href; 284 } else if (typeof document != 'undefined' && document.currentScript) { // web 285 scriptDirectory = document.currentScript.src; 286 } 287 // When MODULARIZE, this JS may be executed later, after document.currentScript 288 // is gone, so we saved it, and we use it here instead of any other info. 289 if (_scriptDir) { 290 scriptDirectory = _scriptDir; 291 } 292 // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them. 293 // otherwise, slice off the final part of the url to find the script directory. 294 // if scriptDirectory does not contain a slash, lastIndexOf will return -1, 295 // and scriptDirectory will correctly be replaced with an empty string. 296 // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #), 297 // they are removed because they could contain a slash. 298 if (scriptDirectory.indexOf('blob:') !== 0) { 299 scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf('/')+1); 300 } else { 301 scriptDirectory = ''; 302 } 303 304 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?)'); 305 306 // Differentiate the Web Worker from the Node Worker case, as reading must 307 // be done differently. 308 { 309 // include: web_or_worker_shell_read.js 310 311 312 read_ = (url) => { 313 var xhr = new XMLHttpRequest(); 314 xhr.open('GET', url, false); 315 xhr.send(null); 316 return xhr.responseText; 317 } 318 319 if (ENVIRONMENT_IS_WORKER) { 320 readBinary = (url) => { 321 var xhr = new XMLHttpRequest(); 322 xhr.open('GET', url, false); 323 xhr.responseType = 'arraybuffer'; 324 xhr.send(null); 325 return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response)); 326 }; 327 } 328 329 readAsync = (url, onload, onerror) => { 330 var xhr = new XMLHttpRequest(); 331 xhr.open('GET', url, true); 332 xhr.responseType = 'arraybuffer'; 333 xhr.onload = () => { 334 if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0 335 onload(xhr.response); 336 return; 337 } 338 onerror(); 339 }; 340 xhr.onerror = onerror; 341 xhr.send(null); 342 } 343 344 // end include: web_or_worker_shell_read.js 345 } 346 347 setWindowTitle = (title) => document.title = title; 348 } else 349 { 350 throw new Error('environment detection error'); 351 } 352 353 var out = Module['print'] || console.log.bind(console); 354 var err = Module['printErr'] || console.warn.bind(console); 355 356 // Merge back in the overrides 357 Object.assign(Module, moduleOverrides); 358 // Free the object hierarchy contained in the overrides, this lets the GC 359 // reclaim data used e.g. in memoryInitializerRequest, which is a large typed array. 360 moduleOverrides = null; 361 checkIncomingModuleAPI(); 362 363 // Emit code to handle expected values on the Module object. This applies Module.x 364 // to the proper local x. This has two benefits: first, we only emit it if it is 365 // expected to arrive, and second, by using a local everywhere else that can be 366 // minified. 367 368 if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_'); 369 370 if (Module['thisProgram']) thisProgram = Module['thisProgram'];legacyModuleProp('thisProgram', 'thisProgram'); 371 372 if (Module['quit']) quit_ = Module['quit'];legacyModuleProp('quit', 'quit_'); 373 374 // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message 375 // Assertions on removed incoming Module JS APIs. 376 assert(typeof Module['memoryInitializerPrefixURL'] == 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead'); 377 assert(typeof Module['pthreadMainPrefixURL'] == 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead'); 378 assert(typeof Module['cdInitializerPrefixURL'] == 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead'); 379 assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead'); 380 assert(typeof Module['read'] == 'undefined', 'Module.read option was removed (modify read_ in JS)'); 381 assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)'); 382 assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)'); 383 assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify setWindowTitle in JS)'); 384 assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY'); 385 legacyModuleProp('read', 'read_'); 386 legacyModuleProp('readAsync', 'readAsync'); 387 legacyModuleProp('readBinary', 'readBinary'); 388 legacyModuleProp('setWindowTitle', 'setWindowTitle'); 389 var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js'; 390 var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js'; 391 var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js'; 392 var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js'; 393 function alignMemory() { abort('`alignMemory` is now a library function and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line'); } 394 395 assert(!ENVIRONMENT_IS_SHELL, "shell environment detected but not enabled at build time. Add 'shell' to `-s ENVIRONMENT` to enable."); 396 397 398 399 400 var STACK_ALIGN = 16; 401 var POINTER_SIZE = 4; 402 403 function getNativeTypeSize(type) { 404 switch (type) { 405 case 'i1': case 'i8': return 1; 406 case 'i16': return 2; 407 case 'i32': return 4; 408 case 'i64': return 8; 409 case 'float': return 4; 410 case 'double': return 8; 411 default: { 412 if (type[type.length - 1] === '*') { 413 return POINTER_SIZE; 414 } else if (type[0] === 'i') { 415 const bits = Number(type.substr(1)); 416 assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type); 417 return bits / 8; 418 } else { 419 return 0; 420 } 421 } 422 } 423 } 424 425 function warnOnce(text) { 426 if (!warnOnce.shown) warnOnce.shown = {}; 427 if (!warnOnce.shown[text]) { 428 warnOnce.shown[text] = 1; 429 err(text); 430 } 431 } 432 433 // include: runtime_functions.js 434 435 436 // Wraps a JS function as a wasm function with a given signature. 437 function convertJsFunctionToWasm(func, sig) { 438 439 // If the type reflection proposal is available, use the new 440 // "WebAssembly.Function" constructor. 441 // Otherwise, construct a minimal wasm module importing the JS function and 442 // re-exporting it. 443 if (typeof WebAssembly.Function == "function") { 444 var typeNames = { 445 'i': 'i32', 446 'j': 'i64', 447 'f': 'f32', 448 'd': 'f64' 449 }; 450 var type = { 451 parameters: [], 452 results: sig[0] == 'v' ? [] : [typeNames[sig[0]]] 453 }; 454 for (var i = 1; i < sig.length; ++i) { 455 type.parameters.push(typeNames[sig[i]]); 456 } 457 return new WebAssembly.Function(type, func); 458 } 459 460 // The module is static, with the exception of the type section, which is 461 // generated based on the signature passed in. 462 var typeSection = [ 463 0x01, // id: section, 464 0x00, // length: 0 (placeholder) 465 0x01, // count: 1 466 0x60, // form: func 467 ]; 468 var sigRet = sig.slice(0, 1); 469 var sigParam = sig.slice(1); 470 var typeCodes = { 471 'i': 0x7f, // i32 472 'j': 0x7e, // i64 473 'f': 0x7d, // f32 474 'd': 0x7c, // f64 475 }; 476 477 // Parameters, length + signatures 478 typeSection.push(sigParam.length); 479 for (var i = 0; i < sigParam.length; ++i) { 480 typeSection.push(typeCodes[sigParam[i]]); 481 } 482 483 // Return values, length + signatures 484 // With no multi-return in MVP, either 0 (void) or 1 (anything else) 485 if (sigRet == 'v') { 486 typeSection.push(0x00); 487 } else { 488 typeSection = typeSection.concat([0x01, typeCodes[sigRet]]); 489 } 490 491 // Write the overall length of the type section back into the section header 492 // (excepting the 2 bytes for the section id and length) 493 typeSection[1] = typeSection.length - 2; 494 495 // Rest of the module is static 496 var bytes = new Uint8Array([ 497 0x00, 0x61, 0x73, 0x6d, // magic ("\0asm") 498 0x01, 0x00, 0x00, 0x00, // version: 1 499 ].concat(typeSection, [ 500 0x02, 0x07, // import section 501 // (import "e" "f" (func 0 (type 0))) 502 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00, 503 0x07, 0x05, // export section 504 // (export "f" (func 0 (type 0))) 505 0x01, 0x01, 0x66, 0x00, 0x00, 506 ])); 507 508 // We can compile this wasm module synchronously because it is very small. 509 // This accepts an import (at "e.f"), that it reroutes to an export (at "f") 510 var module = new WebAssembly.Module(bytes); 511 var instance = new WebAssembly.Instance(module, { 512 'e': { 513 'f': func 514 } 515 }); 516 var wrappedFunc = instance.exports['f']; 517 return wrappedFunc; 518 } 519 520 var freeTableIndexes = []; 521 522 // Weak map of functions in the table to their indexes, created on first use. 523 var functionsInTableMap; 524 525 function getEmptyTableSlot() { 526 // Reuse a free index if there is one, otherwise grow. 527 if (freeTableIndexes.length) { 528 return freeTableIndexes.pop(); 529 } 530 // Grow the table 531 try { 532 wasmTable.grow(1); 533 } catch (err) { 534 if (!(err instanceof RangeError)) { 535 throw err; 536 } 537 throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.'; 538 } 539 return wasmTable.length - 1; 540 } 541 542 function updateTableMap(offset, count) { 543 for (var i = offset; i < offset + count; i++) { 544 var item = getWasmTableEntry(i); 545 // Ignore null values. 546 if (item) { 547 functionsInTableMap.set(item, i); 548 } 549 } 550 } 551 552 /** 553 * Add a function to the table. 554 * 'sig' parameter is required if the function being added is a JS function. 555 * @param {string=} sig 556 */ 557 function addFunction(func, sig) { 558 assert(typeof func != 'undefined'); 559 560 // Check if the function is already in the table, to ensure each function 561 // gets a unique index. First, create the map if this is the first use. 562 if (!functionsInTableMap) { 563 functionsInTableMap = new WeakMap(); 564 updateTableMap(0, wasmTable.length); 565 } 566 if (functionsInTableMap.has(func)) { 567 return functionsInTableMap.get(func); 568 } 569 570 // It's not in the table, add it now. 571 572 var ret = getEmptyTableSlot(); 573 574 // Set the new value. 575 try { 576 // Attempting to call this with JS function will cause of table.set() to fail 577 setWasmTableEntry(ret, func); 578 } catch (err) { 579 if (!(err instanceof TypeError)) { 580 throw err; 581 } 582 assert(typeof sig != 'undefined', 'Missing signature argument to addFunction: ' + func); 583 var wrapped = convertJsFunctionToWasm(func, sig); 584 setWasmTableEntry(ret, wrapped); 585 } 586 587 functionsInTableMap.set(func, ret); 588 589 return ret; 590 } 591 592 function removeFunction(index) { 593 functionsInTableMap.delete(getWasmTableEntry(index)); 594 freeTableIndexes.push(index); 595 } 596 597 // end include: runtime_functions.js 598 // include: runtime_debug.js 599 600 601 function legacyModuleProp(prop, newName) { 602 if (!Object.getOwnPropertyDescriptor(Module, prop)) { 603 Object.defineProperty(Module, prop, { 604 configurable: true, 605 get: function() { 606 abort('Module.' + prop + ' has been replaced with plain ' + newName + ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)'); 607 } 608 }); 609 } 610 } 611 612 function ignoredModuleProp(prop) { 613 if (Object.getOwnPropertyDescriptor(Module, prop)) { 614 abort('`Module.' + prop + '` was supplied but `' + prop + '` not included in INCOMING_MODULE_JS_API'); 615 } 616 } 617 618 function unexportedMessage(sym, isFSSybol) { 619 var msg = "'" + sym + "' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)"; 620 if (isFSSybol) { 621 msg += '. Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you'; 622 } 623 return msg; 624 } 625 626 function unexportedRuntimeSymbol(sym, isFSSybol) { 627 if (!Object.getOwnPropertyDescriptor(Module, sym)) { 628 Object.defineProperty(Module, sym, { 629 configurable: true, 630 get: function() { 631 abort(unexportedMessage(sym, isFSSybol)); 632 } 633 }); 634 } 635 } 636 637 function unexportedRuntimeFunction(sym, isFSSybol) { 638 if (!Object.getOwnPropertyDescriptor(Module, sym)) { 639 Module[sym] = () => abort(unexportedMessage(sym, isFSSybol)); 640 } 641 } 642 643 // end include: runtime_debug.js 644 var tempRet0 = 0; 645 var setTempRet0 = (value) => { tempRet0 = value; }; 646 var getTempRet0 = () => tempRet0; 647 648 649 650 // === Preamble library stuff === 651 652 // Documentation for the public APIs defined in this file must be updated in: 653 // site/source/docs/api_reference/preamble.js.rst 654 // A prebuilt local version of the documentation is available at: 655 // site/build/text/docs/api_reference/preamble.js.txt 656 // You can also build docs locally as HTML or other formats in site/ 657 // An online HTML version (which may be of a different version of Emscripten) 658 // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html 659 660 var wasmBinary; 661 if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];legacyModuleProp('wasmBinary', 'wasmBinary'); 662 var noExitRuntime = Module['noExitRuntime'] || true;legacyModuleProp('noExitRuntime', 'noExitRuntime'); 663 664 if (typeof WebAssembly != 'object') { 665 abort('no native wasm support detected'); 666 } 667 668 // include: runtime_safe_heap.js 669 670 671 // In MINIMAL_RUNTIME, setValue() and getValue() are only available when building with safe heap enabled, for heap safety checking. 672 // In traditional runtime, setValue() and getValue() are always available (although their use is highly discouraged due to perf penalties) 673 674 /** @param {number} ptr 675 @param {number} value 676 @param {string} type 677 @param {number|boolean=} noSafe */ 678 function setValue(ptr, value, type = 'i8', noSafe) { 679 if (type.charAt(type.length-1) === '*') type = 'i32'; 680 switch (type) { 681 case 'i1': HEAP8[((ptr)>>0)] = value; break; 682 case 'i8': HEAP8[((ptr)>>0)] = value; break; 683 case 'i16': HEAP16[((ptr)>>1)] = value; break; 684 case 'i32': HEAP32[((ptr)>>2)] = value; break; 685 case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math.abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math.min((+(Math.floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((ptr)>>2)] = tempI64[0],HEAP32[(((ptr)+(4))>>2)] = tempI64[1]); break; 686 case 'float': HEAPF32[((ptr)>>2)] = value; break; 687 case 'double': HEAPF64[((ptr)>>3)] = value; break; 688 default: abort('invalid type for setValue: ' + type); 689 } 690 } 691 692 /** @param {number} ptr 693 @param {string} type 694 @param {number|boolean=} noSafe */ 695 function getValue(ptr, type = 'i8', noSafe) { 696 if (type.charAt(type.length-1) === '*') type = 'i32'; 697 switch (type) { 698 case 'i1': return HEAP8[((ptr)>>0)]; 699 case 'i8': return HEAP8[((ptr)>>0)]; 700 case 'i16': return HEAP16[((ptr)>>1)]; 701 case 'i32': return HEAP32[((ptr)>>2)]; 702 case 'i64': return HEAP32[((ptr)>>2)]; 703 case 'float': return HEAPF32[((ptr)>>2)]; 704 case 'double': return Number(HEAPF64[((ptr)>>3)]); 705 default: abort('invalid type for getValue: ' + type); 706 } 707 return null; 708 } 709 710 // end include: runtime_safe_heap.js 711 // Wasm globals 712 713 var wasmMemory; 714 715 //======================================== 716 // Runtime essentials 717 //======================================== 718 719 // whether we are quitting the application. no code should run after this. 720 // set in exit() and abort() 721 var ABORT = false; 722 723 // set by exit() and abort(). Passed to 'onExit' handler. 724 // NOTE: This is also used as the process return code code in shell environments 725 // but only when noExitRuntime is false. 726 var EXITSTATUS; 727 728 /** @type {function(*, string=)} */ 729 function assert(condition, text) { 730 if (!condition) { 731 abort('Assertion failed' + (text ? ': ' + text : '')); 732 } 733 } 734 735 // Returns the C function with a specified identifier (for C++, you need to do manual name mangling) 736 function getCFunc(ident) { 737 var func = Module['_' + ident]; // closure exported function 738 assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported'); 739 return func; 740 } 741 742 // C calling interface. 743 /** @param {string|null=} returnType 744 @param {Array=} argTypes 745 @param {Arguments|Array=} args 746 @param {Object=} opts */ 747 function ccall(ident, returnType, argTypes, args, opts) { 748 // For fast lookup of conversion functions 749 var toC = { 750 'string': function(str) { 751 var ret = 0; 752 if (str !== null && str !== undefined && str !== 0) { // null string 753 // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0' 754 var len = (str.length << 2) + 1; 755 ret = stackAlloc(len); 756 stringToUTF8(str, ret, len); 757 } 758 return ret; 759 }, 760 'array': function(arr) { 761 var ret = stackAlloc(arr.length); 762 writeArrayToMemory(arr, ret); 763 return ret; 764 } 765 }; 766 767 function convertReturnValue(ret) { 768 if (returnType === 'string') return UTF8ToString(ret); 769 if (returnType === 'boolean') return Boolean(ret); 770 return ret; 771 } 772 773 var func = getCFunc(ident); 774 var cArgs = []; 775 var stack = 0; 776 assert(returnType !== 'array', 'Return type should not be "array".'); 777 if (args) { 778 for (var i = 0; i < args.length; i++) { 779 var converter = toC[argTypes[i]]; 780 if (converter) { 781 if (stack === 0) stack = stackSave(); 782 cArgs[i] = converter(args[i]); 783 } else { 784 cArgs[i] = args[i]; 785 } 786 } 787 } 788 var ret = func.apply(null, cArgs); 789 function onDone(ret) { 790 if (stack !== 0) stackRestore(stack); 791 return convertReturnValue(ret); 792 } 793 794 ret = onDone(ret); 795 return ret; 796 } 797 798 /** @param {string=} returnType 799 @param {Array=} argTypes 800 @param {Object=} opts */ 801 function cwrap(ident, returnType, argTypes, opts) { 802 return function() { 803 return ccall(ident, returnType, argTypes, arguments, opts); 804 } 805 } 806 807 // We used to include malloc/free by default in the past. Show a helpful error in 808 // builds with assertions. 809 810 // include: runtime_legacy.js 811 812 813 var ALLOC_NORMAL = 0; // Tries to use _malloc() 814 var ALLOC_STACK = 1; // Lives for the duration of the current function call 815 816 /** 817 * allocate(): This function is no longer used by emscripten but is kept around to avoid 818 * breaking external users. 819 * You should normally not use allocate(), and instead allocate 820 * memory using _malloc()/stackAlloc(), initialize it with 821 * setValue(), and so forth. 822 * @param {(Uint8Array|Array<number>)} slab: An array of data. 823 * @param {number=} allocator : How to allocate memory, see ALLOC_* 824 */ 825 function allocate(slab, allocator) { 826 var ret; 827 assert(typeof allocator == 'number', 'allocate no longer takes a type argument') 828 assert(typeof slab != 'number', 'allocate no longer takes a number as arg0') 829 830 if (allocator == ALLOC_STACK) { 831 ret = stackAlloc(slab.length); 832 } else { 833 ret = _malloc(slab.length); 834 } 835 836 if (!slab.subarray && !slab.slice) { 837 slab = new Uint8Array(slab); 838 } 839 HEAPU8.set(slab, ret); 840 return ret; 841 } 842 843 // end include: runtime_legacy.js 844 // include: runtime_strings.js 845 846 847 // runtime_strings.js: Strings related runtime functions that are part of both MINIMAL_RUNTIME and regular runtime. 848 849 // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns 850 // a copy of that string as a Javascript String object. 851 852 var UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined; 853 854 /** 855 * @param {number} idx 856 * @param {number=} maxBytesToRead 857 * @return {string} 858 */ 859 function UTF8ArrayToString(heap, idx, maxBytesToRead) { 860 var endIdx = idx + maxBytesToRead; 861 var endPtr = idx; 862 // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself. 863 // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage. 864 // (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity) 865 while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr; 866 867 if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) { 868 return UTF8Decoder.decode(heap.subarray(idx, endPtr)); 869 } else { 870 var str = ''; 871 // If building with TextDecoder, we have already computed the string length above, so test loop end condition against that 872 while (idx < endPtr) { 873 // For UTF8 byte structure, see: 874 // http://en.wikipedia.org/wiki/UTF-8#Description 875 // https://www.ietf.org/rfc/rfc2279.txt 876 // https://tools.ietf.org/html/rfc3629 877 var u0 = heap[idx++]; 878 if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; } 879 var u1 = heap[idx++] & 63; 880 if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } 881 var u2 = heap[idx++] & 63; 882 if ((u0 & 0xF0) == 0xE0) { 883 u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; 884 } else { 885 if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte 0x' + u0.toString(16) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!'); 886 u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heap[idx++] & 63); 887 } 888 889 if (u0 < 0x10000) { 890 str += String.fromCharCode(u0); 891 } else { 892 var ch = u0 - 0x10000; 893 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); 894 } 895 } 896 } 897 return str; 898 } 899 900 // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a 901 // copy of that string as a Javascript String object. 902 // maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit 903 // this parameter to scan the string until the first \0 byte. If maxBytesToRead is 904 // passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the 905 // middle, then the string will cut short at that byte index (i.e. maxBytesToRead will 906 // not produce a string of exact length [ptr, ptr+maxBytesToRead[) 907 // N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may 908 // throw JS JIT optimizations off, so it is worth to consider consistently using one 909 // style or the other. 910 /** 911 * @param {number} ptr 912 * @param {number=} maxBytesToRead 913 * @return {string} 914 */ 915 function UTF8ToString(ptr, maxBytesToRead) { 916 ; 917 return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ''; 918 } 919 920 // Copies the given Javascript String object 'str' to the given byte array at address 'outIdx', 921 // encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP. 922 // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write. 923 // Parameters: 924 // str: the Javascript string to copy. 925 // heap: the array to copy to. Each index in this array is assumed to be one 8-byte element. 926 // outIdx: The starting offset in the array to begin the copying. 927 // maxBytesToWrite: The maximum number of bytes this function can write to the array. 928 // This count should include the null terminator, 929 // i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else. 930 // maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator. 931 // Returns the number of bytes written, EXCLUDING the null terminator. 932 933 function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { 934 if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes. 935 return 0; 936 937 var startIdx = outIdx; 938 var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator. 939 for (var i = 0; i < str.length; ++i) { 940 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8. 941 // See http://unicode.org/faq/utf_bom.html#utf16-3 942 // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629 943 var u = str.charCodeAt(i); // possibly a lead surrogate 944 if (u >= 0xD800 && u <= 0xDFFF) { 945 var u1 = str.charCodeAt(++i); 946 u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); 947 } 948 if (u <= 0x7F) { 949 if (outIdx >= endIdx) break; 950 heap[outIdx++] = u; 951 } else if (u <= 0x7FF) { 952 if (outIdx + 1 >= endIdx) break; 953 heap[outIdx++] = 0xC0 | (u >> 6); 954 heap[outIdx++] = 0x80 | (u & 63); 955 } else if (u <= 0xFFFF) { 956 if (outIdx + 2 >= endIdx) break; 957 heap[outIdx++] = 0xE0 | (u >> 12); 958 heap[outIdx++] = 0x80 | ((u >> 6) & 63); 959 heap[outIdx++] = 0x80 | (u & 63); 960 } else { 961 if (outIdx + 3 >= endIdx) break; 962 if (u > 0x10FFFF) warnOnce('Invalid Unicode code point 0x' + u.toString(16) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).'); 963 heap[outIdx++] = 0xF0 | (u >> 18); 964 heap[outIdx++] = 0x80 | ((u >> 12) & 63); 965 heap[outIdx++] = 0x80 | ((u >> 6) & 63); 966 heap[outIdx++] = 0x80 | (u & 63); 967 } 968 } 969 // Null-terminate the pointer to the buffer. 970 heap[outIdx] = 0; 971 return outIdx - startIdx; 972 } 973 974 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', 975 // null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP. 976 // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write. 977 // Returns the number of bytes written, EXCLUDING the null terminator. 978 979 function stringToUTF8(str, outPtr, maxBytesToWrite) { 980 assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); 981 return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite); 982 } 983 984 // Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte. 985 function lengthBytesUTF8(str) { 986 var len = 0; 987 for (var i = 0; i < str.length; ++i) { 988 // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8. 989 // See http://unicode.org/faq/utf_bom.html#utf16-3 990 var u = str.charCodeAt(i); // possibly a lead surrogate 991 if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF); 992 if (u <= 0x7F) ++len; 993 else if (u <= 0x7FF) len += 2; 994 else if (u <= 0xFFFF) len += 3; 995 else len += 4; 996 } 997 return len; 998 } 999 1000 // end include: runtime_strings.js 1001 // include: runtime_strings_extra.js 1002 1003 1004 // runtime_strings_extra.js: Strings related runtime functions that are available only in regular runtime. 1005 1006 // Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns 1007 // a copy of that string as a Javascript String object. 1008 1009 function AsciiToString(ptr) { 1010 var str = ''; 1011 while (1) { 1012 var ch = HEAPU8[((ptr++)>>0)]; 1013 if (!ch) return str; 1014 str += String.fromCharCode(ch); 1015 } 1016 } 1017 1018 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', 1019 // null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP. 1020 1021 function stringToAscii(str, outPtr) { 1022 return writeAsciiToMemory(str, outPtr, false); 1023 } 1024 1025 // Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns 1026 // a copy of that string as a Javascript String object. 1027 1028 var UTF16Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf-16le') : undefined; 1029 1030 function UTF16ToString(ptr, maxBytesToRead) { 1031 assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!'); 1032 var endPtr = ptr; 1033 // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself. 1034 // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage. 1035 var idx = endPtr >> 1; 1036 var maxIdx = idx + maxBytesToRead / 2; 1037 // If maxBytesToRead is not passed explicitly, it will be undefined, and this 1038 // will always evaluate to true. This saves on code size. 1039 while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx; 1040 endPtr = idx << 1; 1041 1042 if (endPtr - ptr > 32 && UTF16Decoder) { 1043 return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)); 1044 } else { 1045 var str = ''; 1046 1047 // If maxBytesToRead is not passed explicitly, it will be undefined, and the for-loop's condition 1048 // will always evaluate to true. The loop is then terminated on the first null char. 1049 for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { 1050 var codeUnit = HEAP16[(((ptr)+(i*2))>>1)]; 1051 if (codeUnit == 0) break; 1052 // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through. 1053 str += String.fromCharCode(codeUnit); 1054 } 1055 1056 return str; 1057 } 1058 } 1059 1060 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', 1061 // null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP. 1062 // Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write. 1063 // Parameters: 1064 // str: the Javascript string to copy. 1065 // outPtr: Byte address in Emscripten HEAP where to write the string to. 1066 // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null 1067 // terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else. 1068 // maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator. 1069 // Returns the number of bytes written, EXCLUDING the null terminator. 1070 1071 function stringToUTF16(str, outPtr, maxBytesToWrite) { 1072 assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!'); 1073 assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); 1074 // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. 1075 if (maxBytesToWrite === undefined) { 1076 maxBytesToWrite = 0x7FFFFFFF; 1077 } 1078 if (maxBytesToWrite < 2) return 0; 1079 maxBytesToWrite -= 2; // Null terminator. 1080 var startPtr = outPtr; 1081 var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length; 1082 for (var i = 0; i < numCharsToWrite; ++i) { 1083 // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP. 1084 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate 1085 HEAP16[((outPtr)>>1)] = codeUnit; 1086 outPtr += 2; 1087 } 1088 // Null-terminate the pointer to the HEAP. 1089 HEAP16[((outPtr)>>1)] = 0; 1090 return outPtr - startPtr; 1091 } 1092 1093 // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte. 1094 1095 function lengthBytesUTF16(str) { 1096 return str.length*2; 1097 } 1098 1099 function UTF32ToString(ptr, maxBytesToRead) { 1100 assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!'); 1101 var i = 0; 1102 1103 var str = ''; 1104 // If maxBytesToRead is not passed explicitly, it will be undefined, and this 1105 // will always evaluate to true. This saves on code size. 1106 while (!(i >= maxBytesToRead / 4)) { 1107 var utf32 = HEAP32[(((ptr)+(i*4))>>2)]; 1108 if (utf32 == 0) break; 1109 ++i; 1110 // 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. 1111 // See http://unicode.org/faq/utf_bom.html#utf16-3 1112 if (utf32 >= 0x10000) { 1113 var ch = utf32 - 0x10000; 1114 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); 1115 } else { 1116 str += String.fromCharCode(utf32); 1117 } 1118 } 1119 return str; 1120 } 1121 1122 // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', 1123 // null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP. 1124 // Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write. 1125 // Parameters: 1126 // str: the Javascript string to copy. 1127 // outPtr: Byte address in Emscripten HEAP where to write the string to. 1128 // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null 1129 // terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else. 1130 // maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator. 1131 // Returns the number of bytes written, EXCLUDING the null terminator. 1132 1133 function stringToUTF32(str, outPtr, maxBytesToWrite) { 1134 assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!'); 1135 assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); 1136 // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. 1137 if (maxBytesToWrite === undefined) { 1138 maxBytesToWrite = 0x7FFFFFFF; 1139 } 1140 if (maxBytesToWrite < 4) return 0; 1141 var startPtr = outPtr; 1142 var endPtr = startPtr + maxBytesToWrite - 4; 1143 for (var i = 0; i < str.length; ++i) { 1144 // 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. 1145 // See http://unicode.org/faq/utf_bom.html#utf16-3 1146 var codeUnit = str.charCodeAt(i); // possibly a lead surrogate 1147 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) { 1148 var trailSurrogate = str.charCodeAt(++i); 1149 codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF); 1150 } 1151 HEAP32[((outPtr)>>2)] = codeUnit; 1152 outPtr += 4; 1153 if (outPtr + 4 > endPtr) break; 1154 } 1155 // Null-terminate the pointer to the HEAP. 1156 HEAP32[((outPtr)>>2)] = 0; 1157 return outPtr - startPtr; 1158 } 1159 1160 // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte. 1161 1162 function lengthBytesUTF32(str) { 1163 var len = 0; 1164 for (var i = 0; i < str.length; ++i) { 1165 // 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. 1166 // See http://unicode.org/faq/utf_bom.html#utf16-3 1167 var codeUnit = str.charCodeAt(i); 1168 if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate. 1169 len += 4; 1170 } 1171 1172 return len; 1173 } 1174 1175 // Allocate heap space for a JS string, and write it there. 1176 // It is the responsibility of the caller to free() that memory. 1177 function allocateUTF8(str) { 1178 var size = lengthBytesUTF8(str) + 1; 1179 var ret = _malloc(size); 1180 if (ret) stringToUTF8Array(str, HEAP8, ret, size); 1181 return ret; 1182 } 1183 1184 // Allocate stack space for a JS string, and write it there. 1185 function allocateUTF8OnStack(str) { 1186 var size = lengthBytesUTF8(str) + 1; 1187 var ret = stackAlloc(size); 1188 stringToUTF8Array(str, HEAP8, ret, size); 1189 return ret; 1190 } 1191 1192 // Deprecated: This function should not be called because it is unsafe and does not provide 1193 // a maximum length limit of how many bytes it is allowed to write. Prefer calling the 1194 // function stringToUTF8Array() instead, which takes in a maximum length that can be used 1195 // to be secure from out of bounds writes. 1196 /** @deprecated 1197 @param {boolean=} dontAddNull */ 1198 function writeStringToMemory(string, buffer, dontAddNull) { 1199 warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!'); 1200 1201 var /** @type {number} */ lastChar, /** @type {number} */ end; 1202 if (dontAddNull) { 1203 // stringToUTF8Array always appends null. If we don't want to do that, remember the 1204 // character that existed at the location where the null will be placed, and restore 1205 // that after the write (below). 1206 end = buffer + lengthBytesUTF8(string); 1207 lastChar = HEAP8[end]; 1208 } 1209 stringToUTF8(string, buffer, Infinity); 1210 if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character. 1211 } 1212 1213 function writeArrayToMemory(array, buffer) { 1214 assert(array.length >= 0, 'writeArrayToMemory array must have a length (should be an array or typed array)') 1215 HEAP8.set(array, buffer); 1216 } 1217 1218 /** @param {boolean=} dontAddNull */ 1219 function writeAsciiToMemory(str, buffer, dontAddNull) { 1220 for (var i = 0; i < str.length; ++i) { 1221 assert(str.charCodeAt(i) === (str.charCodeAt(i) & 0xff)); 1222 HEAP8[((buffer++)>>0)] = str.charCodeAt(i); 1223 } 1224 // Null-terminate the pointer to the HEAP. 1225 if (!dontAddNull) HEAP8[((buffer)>>0)] = 0; 1226 } 1227 1228 // end include: runtime_strings_extra.js 1229 // Memory management 1230 1231 var HEAP, 1232 /** @type {!ArrayBuffer} */ 1233 buffer, 1234 /** @type {!Int8Array} */ 1235 HEAP8, 1236 /** @type {!Uint8Array} */ 1237 HEAPU8, 1238 /** @type {!Int16Array} */ 1239 HEAP16, 1240 /** @type {!Uint16Array} */ 1241 HEAPU16, 1242 /** @type {!Int32Array} */ 1243 HEAP32, 1244 /** @type {!Uint32Array} */ 1245 HEAPU32, 1246 /** @type {!Float32Array} */ 1247 HEAPF32, 1248 /** @type {!Float64Array} */ 1249 HEAPF64; 1250 1251 function updateGlobalBufferAndViews(buf) { 1252 buffer = buf; 1253 Module['HEAP8'] = HEAP8 = new Int8Array(buf); 1254 Module['HEAP16'] = HEAP16 = new Int16Array(buf); 1255 Module['HEAP32'] = HEAP32 = new Int32Array(buf); 1256 Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf); 1257 Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf); 1258 Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf); 1259 Module['HEAPF32'] = HEAPF32 = new Float32Array(buf); 1260 Module['HEAPF64'] = HEAPF64 = new Float64Array(buf); 1261 } 1262 1263 var TOTAL_STACK = 5242880; 1264 if (Module['TOTAL_STACK']) assert(TOTAL_STACK === Module['TOTAL_STACK'], 'the stack size can no longer be determined at runtime') 1265 1266 var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216;legacyModuleProp('INITIAL_MEMORY', 'INITIAL_MEMORY'); 1267 1268 assert(INITIAL_MEMORY >= TOTAL_STACK, 'INITIAL_MEMORY should be larger than TOTAL_STACK, was ' + INITIAL_MEMORY + '! (TOTAL_STACK=' + TOTAL_STACK + ')'); 1269 1270 // check for full engine support (use string 'subarray' to avoid closure compiler confusion) 1271 assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined, 1272 'JS engine does not provide full typed array support'); 1273 1274 // If memory is defined in wasm, the user can't provide it. 1275 assert(!Module['wasmMemory'], 'Use of `wasmMemory` detected. Use -s IMPORTED_MEMORY to define wasmMemory externally'); 1276 assert(INITIAL_MEMORY == 16777216, 'Detected runtime INITIAL_MEMORY setting. Use -s IMPORTED_MEMORY to define wasmMemory dynamically'); 1277 1278 // include: runtime_init_table.js 1279 // In regular non-RELOCATABLE mode the table is exported 1280 // from the wasm module and this will be assigned once 1281 // the exports are available. 1282 var wasmTable; 1283 1284 // end include: runtime_init_table.js 1285 // include: runtime_stack_check.js 1286 1287 1288 // Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode. 1289 function writeStackCookie() { 1290 var max = _emscripten_stack_get_end(); 1291 assert((max & 3) == 0); 1292 // The stack grows downwards 1293 HEAP32[((max + 4)>>2)] = 0x2135467; 1294 HEAP32[((max + 8)>>2)] = 0x89BACDFE; 1295 // Also test the global address 0 for integrity. 1296 HEAP32[0] = 0x63736d65; /* 'emsc' */ 1297 } 1298 1299 function checkStackCookie() { 1300 if (ABORT) return; 1301 var max = _emscripten_stack_get_end(); 1302 var cookie1 = HEAPU32[((max + 4)>>2)]; 1303 var cookie2 = HEAPU32[((max + 8)>>2)]; 1304 if (cookie1 != 0x2135467 || cookie2 != 0x89BACDFE) { 1305 abort('Stack overflow! Stack cookie has been overwritten, expected hex dwords 0x89BACDFE and 0x2135467, but received 0x' + cookie2.toString(16) + ' 0x' + cookie1.toString(16)); 1306 } 1307 // Also test the global address 0 for integrity. 1308 if (HEAP32[0] !== 0x63736d65 /* 'emsc' */) abort('Runtime error: The application has corrupted its heap memory area (address zero)!'); 1309 } 1310 1311 // end include: runtime_stack_check.js 1312 // include: runtime_assertions.js 1313 1314 1315 // Endianness check 1316 (function() { 1317 var h16 = new Int16Array(1); 1318 var h8 = new Int8Array(h16.buffer); 1319 h16[0] = 0x6373; 1320 if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -s SUPPORT_BIG_ENDIAN=1 to bypass)'; 1321 })(); 1322 1323 // end include: runtime_assertions.js 1324 var __ATPRERUN__ = []; // functions called before the runtime is initialized 1325 var __ATINIT__ = []; // functions called during startup 1326 var __ATEXIT__ = []; // functions called during shutdown 1327 var __ATPOSTRUN__ = []; // functions called after the main() is called 1328 1329 var runtimeInitialized = false; 1330 var runtimeExited = false; 1331 var runtimeKeepaliveCounter = 0; 1332 1333 function keepRuntimeAlive() { 1334 return noExitRuntime || runtimeKeepaliveCounter > 0; 1335 } 1336 1337 function preRun() { 1338 1339 if (Module['preRun']) { 1340 if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']]; 1341 while (Module['preRun'].length) { 1342 addOnPreRun(Module['preRun'].shift()); 1343 } 1344 } 1345 1346 callRuntimeCallbacks(__ATPRERUN__); 1347 } 1348 1349 function initRuntime() { 1350 checkStackCookie(); 1351 assert(!runtimeInitialized); 1352 runtimeInitialized = true; 1353 1354 1355 callRuntimeCallbacks(__ATINIT__); 1356 } 1357 1358 function exitRuntime() { 1359 checkStackCookie(); 1360 runtimeExited = true; 1361 } 1362 1363 function postRun() { 1364 checkStackCookie(); 1365 1366 if (Module['postRun']) { 1367 if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']]; 1368 while (Module['postRun'].length) { 1369 addOnPostRun(Module['postRun'].shift()); 1370 } 1371 } 1372 1373 callRuntimeCallbacks(__ATPOSTRUN__); 1374 } 1375 1376 function addOnPreRun(cb) { 1377 __ATPRERUN__.unshift(cb); 1378 } 1379 1380 function addOnInit(cb) { 1381 __ATINIT__.unshift(cb); 1382 } 1383 1384 function addOnExit(cb) { 1385 } 1386 1387 function addOnPostRun(cb) { 1388 __ATPOSTRUN__.unshift(cb); 1389 } 1390 1391 // include: runtime_math.js 1392 1393 1394 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul 1395 1396 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround 1397 1398 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 1399 1400 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc 1401 1402 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'); 1403 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'); 1404 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'); 1405 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'); 1406 1407 // end include: runtime_math.js 1408 // A counter of dependencies for calling run(). If we need to 1409 // do asynchronous work before running, increment this and 1410 // decrement it. Incrementing must happen in a place like 1411 // Module.preRun (used by emcc to add file preloading). 1412 // Note that you can add dependencies in preRun, even though 1413 // it happens right before run - run will be postponed until 1414 // the dependencies are met. 1415 var runDependencies = 0; 1416 var runDependencyWatcher = null; 1417 var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled 1418 var runDependencyTracking = {}; 1419 1420 function getUniqueRunDependency(id) { 1421 var orig = id; 1422 while (1) { 1423 if (!runDependencyTracking[id]) return id; 1424 id = orig + Math.random(); 1425 } 1426 } 1427 1428 function addRunDependency(id) { 1429 runDependencies++; 1430 1431 if (Module['monitorRunDependencies']) { 1432 Module['monitorRunDependencies'](runDependencies); 1433 } 1434 1435 if (id) { 1436 assert(!runDependencyTracking[id]); 1437 runDependencyTracking[id] = 1; 1438 if (runDependencyWatcher === null && typeof setInterval != 'undefined') { 1439 // Check for missing dependencies every few seconds 1440 runDependencyWatcher = setInterval(function() { 1441 if (ABORT) { 1442 clearInterval(runDependencyWatcher); 1443 runDependencyWatcher = null; 1444 return; 1445 } 1446 var shown = false; 1447 for (var dep in runDependencyTracking) { 1448 if (!shown) { 1449 shown = true; 1450 err('still waiting on run dependencies:'); 1451 } 1452 err('dependency: ' + dep); 1453 } 1454 if (shown) { 1455 err('(end of list)'); 1456 } 1457 }, 10000); 1458 } 1459 } else { 1460 err('warning: run dependency added without ID'); 1461 } 1462 } 1463 1464 function removeRunDependency(id) { 1465 runDependencies--; 1466 1467 if (Module['monitorRunDependencies']) { 1468 Module['monitorRunDependencies'](runDependencies); 1469 } 1470 1471 if (id) { 1472 assert(runDependencyTracking[id]); 1473 delete runDependencyTracking[id]; 1474 } else { 1475 err('warning: run dependency removed without ID'); 1476 } 1477 if (runDependencies == 0) { 1478 if (runDependencyWatcher !== null) { 1479 clearInterval(runDependencyWatcher); 1480 runDependencyWatcher = null; 1481 } 1482 if (dependenciesFulfilled) { 1483 var callback = dependenciesFulfilled; 1484 dependenciesFulfilled = null; 1485 callback(); // can add another dependenciesFulfilled 1486 } 1487 } 1488 } 1489 1490 Module["preloadedImages"] = {}; // maps url to image data 1491 Module["preloadedAudios"] = {}; // maps url to audio data 1492 1493 /** @param {string|number=} what */ 1494 function abort(what) { 1495 { 1496 if (Module['onAbort']) { 1497 Module['onAbort'](what); 1498 } 1499 } 1500 1501 what = 'Aborted(' + what + ')'; 1502 // TODO(sbc): Should we remove printing and leave it up to whoever 1503 // catches the exception? 1504 err(what); 1505 1506 ABORT = true; 1507 EXITSTATUS = 1; 1508 1509 // Use a wasm runtime error, because a JS error might be seen as a foreign 1510 // exception, which means we'd run destructors on it. We need the error to 1511 // simply make the program stop. 1512 1513 // Suppress closure compiler warning here. Closure compiler's builtin extern 1514 // defintion for WebAssembly.RuntimeError claims it takes no arguments even 1515 // though it can. 1516 // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed. 1517 1518 /** @suppress {checkTypes} */ 1519 var e = new WebAssembly.RuntimeError(what); 1520 1521 readyPromiseReject(e); 1522 // Throw the error whether or not MODULARIZE is set because abort is used 1523 // in code paths apart from instantiation where an exception is expected 1524 // to be thrown when abort is called. 1525 throw e; 1526 } 1527 1528 // {{MEM_INITIALIZER}} 1529 1530 // include: memoryprofiler.js 1531 1532 1533 // end include: memoryprofiler.js 1534 // show errors on likely calls to FS when it was not included 1535 var FS = { 1536 error: function() { 1537 abort('Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -s FORCE_FILESYSTEM=1'); 1538 }, 1539 init: function() { FS.error() }, 1540 createDataFile: function() { FS.error() }, 1541 createPreloadedFile: function() { FS.error() }, 1542 createLazyFile: function() { FS.error() }, 1543 open: function() { FS.error() }, 1544 mkdev: function() { FS.error() }, 1545 registerDevice: function() { FS.error() }, 1546 analyzePath: function() { FS.error() }, 1547 loadFilesFromDB: function() { FS.error() }, 1548 1549 ErrnoError: function ErrnoError() { FS.error() }, 1550 }; 1551 Module['FS_createDataFile'] = FS.createDataFile; 1552 Module['FS_createPreloadedFile'] = FS.createPreloadedFile; 1553 1554 // include: URIUtils.js 1555 1556 1557 // Prefix of data URIs emitted by SINGLE_FILE and related options. 1558 var dataURIPrefix = 'data:application/octet-stream;base64,'; 1559 1560 // Indicates whether filename is a base64 data URI. 1561 function isDataURI(filename) { 1562 // Prefix of data URIs emitted by SINGLE_FILE and related options. 1563 return filename.startsWith(dataURIPrefix); 1564 } 1565 1566 // Indicates whether filename is delivered via file protocol (as opposed to http/https) 1567 function isFileURI(filename) { 1568 return filename.startsWith('file://'); 1569 } 1570 1571 // end include: URIUtils.js 1572 /** @param {boolean=} fixedasm */ 1573 function createExportWrapper(name, fixedasm) { 1574 return function() { 1575 var displayName = name; 1576 var asm = fixedasm; 1577 if (!fixedasm) { 1578 asm = Module['asm']; 1579 } 1580 assert(runtimeInitialized, 'native function `' + displayName + '` called before runtime initialization'); 1581 assert(!runtimeExited, 'native function `' + displayName + '` called after runtime exit (use NO_EXIT_RUNTIME to keep it alive after main() exits)'); 1582 if (!asm[name]) { 1583 assert(asm[name], 'exported native function `' + displayName + '` not found'); 1584 } 1585 return asm[name].apply(null, arguments); 1586 }; 1587 } 1588 1589 var wasmBinaryFile; 1590 wasmBinaryFile = 'base32.wasm'; 1591 if (!isDataURI(wasmBinaryFile)) { 1592 wasmBinaryFile = locateFile(wasmBinaryFile); 1593 } 1594 1595 function getBinary(file) { 1596 try { 1597 if (file == wasmBinaryFile && wasmBinary) { 1598 return new Uint8Array(wasmBinary); 1599 } 1600 if (readBinary) { 1601 return readBinary(file); 1602 } else { 1603 throw "both async and sync fetching of the wasm failed"; 1604 } 1605 } 1606 catch (err) { 1607 abort(err); 1608 } 1609 } 1610 1611 function getBinaryPromise() { 1612 // If we don't have the binary yet, try to to load it asynchronously. 1613 // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url. 1614 // See https://github.com/github/fetch/pull/92#issuecomment-140665932 1615 // Cordova or Electron apps are typically loaded from a file:// url. 1616 // So use fetch if it is available and the url is not a file, otherwise fall back to XHR. 1617 if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { 1618 if (typeof fetch == 'function' 1619 && !isFileURI(wasmBinaryFile) 1620 ) { 1621 return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) { 1622 if (!response['ok']) { 1623 throw "failed to load wasm binary file at '" + wasmBinaryFile + "'"; 1624 } 1625 return response['arrayBuffer'](); 1626 }).catch(function () { 1627 return getBinary(wasmBinaryFile); 1628 }); 1629 } 1630 else { 1631 if (readAsync) { 1632 // fetch is not available or url is file => try XHR (readAsync uses XHR internally) 1633 return new Promise(function(resolve, reject) { 1634 readAsync(wasmBinaryFile, function(response) { resolve(new Uint8Array(/** @type{!ArrayBuffer} */(response))) }, reject) 1635 }); 1636 } 1637 } 1638 } 1639 1640 // Otherwise, getBinary should be able to get it synchronously 1641 return Promise.resolve().then(function() { return getBinary(wasmBinaryFile); }); 1642 } 1643 1644 // Create the wasm instance. 1645 // Receives the wasm imports, returns the exports. 1646 function createWasm() { 1647 // prepare imports 1648 var info = { 1649 'env': asmLibraryArg, 1650 'wasi_snapshot_preview1': asmLibraryArg, 1651 }; 1652 // Load the wasm module and create an instance of using native support in the JS engine. 1653 // handle a generated wasm instance, receiving its exports and 1654 // performing other necessary setup 1655 /** @param {WebAssembly.Module=} module*/ 1656 function receiveInstance(instance, module) { 1657 var exports = instance.exports; 1658 1659 Module['asm'] = exports; 1660 1661 wasmMemory = Module['asm']['memory']; 1662 assert(wasmMemory, "memory not found in wasm exports"); 1663 // This assertion doesn't hold when emscripten is run in --post-link 1664 // mode. 1665 // TODO(sbc): Read INITIAL_MEMORY out of the wasm file in post-link mode. 1666 //assert(wasmMemory.buffer.byteLength === 16777216); 1667 updateGlobalBufferAndViews(wasmMemory.buffer); 1668 1669 wasmTable = Module['asm']['__indirect_function_table']; 1670 assert(wasmTable, "table not found in wasm exports"); 1671 1672 addOnInit(Module['asm']['__wasm_call_ctors']); 1673 1674 removeRunDependency('wasm-instantiate'); 1675 } 1676 // we can't run yet (except in a pthread, where we have a custom sync instantiator) 1677 addRunDependency('wasm-instantiate'); 1678 1679 // Prefer streaming instantiation if available. 1680 // Async compilation can be confusing when an error on the page overwrites Module 1681 // (for example, if the order of elements is wrong, and the one defining Module is 1682 // later), so we save Module and check it later. 1683 var trueModule = Module; 1684 function receiveInstantiationResult(result) { 1685 // 'result' is a ResultObject object which has both the module and instance. 1686 // receiveInstance() will swap in the exports (to Module.asm) so they can be called 1687 assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?'); 1688 trueModule = null; 1689 // 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. 1690 // When the regression is fixed, can restore the above USE_PTHREADS-enabled path. 1691 receiveInstance(result['instance']); 1692 } 1693 1694 function instantiateArrayBuffer(receiver) { 1695 return getBinaryPromise().then(function(binary) { 1696 return WebAssembly.instantiate(binary, info); 1697 }).then(function (instance) { 1698 return instance; 1699 }).then(receiver, function(reason) { 1700 err('failed to asynchronously prepare wasm: ' + reason); 1701 1702 // Warn on some common problems. 1703 if (isFileURI(wasmBinaryFile)) { 1704 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'); 1705 } 1706 abort(reason); 1707 }); 1708 } 1709 1710 function instantiateAsync() { 1711 if (!wasmBinary && 1712 typeof WebAssembly.instantiateStreaming == 'function' && 1713 !isDataURI(wasmBinaryFile) && 1714 // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously. 1715 !isFileURI(wasmBinaryFile) && 1716 typeof fetch == 'function') { 1717 return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) { 1718 // Suppress closure warning here since the upstream definition for 1719 // instantiateStreaming only allows Promise<Repsponse> rather than 1720 // an actual Response. 1721 // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed. 1722 /** @suppress {checkTypes} */ 1723 var result = WebAssembly.instantiateStreaming(response, info); 1724 1725 return result.then( 1726 receiveInstantiationResult, 1727 function(reason) { 1728 // We expect the most common failure cause to be a bad MIME type for the binary, 1729 // in which case falling back to ArrayBuffer instantiation should work. 1730 err('wasm streaming compile failed: ' + reason); 1731 err('falling back to ArrayBuffer instantiation'); 1732 return instantiateArrayBuffer(receiveInstantiationResult); 1733 }); 1734 }); 1735 } else { 1736 return instantiateArrayBuffer(receiveInstantiationResult); 1737 } 1738 } 1739 1740 // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback 1741 // to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel 1742 // to any other async startup actions they are performing. 1743 if (Module['instantiateWasm']) { 1744 try { 1745 var exports = Module['instantiateWasm'](info, receiveInstance); 1746 return exports; 1747 } catch(e) { 1748 err('Module.instantiateWasm callback failed with error: ' + e); 1749 return false; 1750 } 1751 } 1752 1753 // If instantiation fails, reject the module ready promise. 1754 instantiateAsync().catch(readyPromiseReject); 1755 return {}; // no exports yet; we'll fill them in later 1756 } 1757 1758 // Globals used by JS i64 conversions (see makeSetValue) 1759 var tempDouble; 1760 var tempI64; 1761 1762 // === Body === 1763 1764 var ASM_CONSTS = { 1765 1766 }; 1767 1768 1769 1770 1771 1772 1773 function callRuntimeCallbacks(callbacks) { 1774 while (callbacks.length > 0) { 1775 var callback = callbacks.shift(); 1776 if (typeof callback == 'function') { 1777 callback(Module); // Pass the module as the first argument. 1778 continue; 1779 } 1780 var func = callback.func; 1781 if (typeof func == 'number') { 1782 if (callback.arg === undefined) { 1783 getWasmTableEntry(func)(); 1784 } else { 1785 getWasmTableEntry(func)(callback.arg); 1786 } 1787 } else { 1788 func(callback.arg === undefined ? null : callback.arg); 1789 } 1790 } 1791 } 1792 1793 function withStackSave(f) { 1794 var stack = stackSave(); 1795 var ret = f(); 1796 stackRestore(stack); 1797 return ret; 1798 } 1799 function demangle(func) { 1800 warnOnce('warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling'); 1801 return func; 1802 } 1803 1804 function demangleAll(text) { 1805 var regex = 1806 /\b_Z[\w\d_]+/g; 1807 return text.replace(regex, 1808 function(x) { 1809 var y = demangle(x); 1810 return x === y ? x : (y + ' [' + x + ']'); 1811 }); 1812 } 1813 1814 var wasmTableMirror = []; 1815 function getWasmTableEntry(funcPtr) { 1816 var func = wasmTableMirror[funcPtr]; 1817 if (!func) { 1818 if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1; 1819 wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr); 1820 } 1821 assert(wasmTable.get(funcPtr) == func, "JavaScript-side Wasm function table mirror is out of date!"); 1822 return func; 1823 } 1824 1825 function handleException(e) { 1826 // Certain exception types we do not treat as errors since they are used for 1827 // internal control flow. 1828 // 1. ExitStatus, which is thrown by exit() 1829 // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others 1830 // that wish to return to JS event loop. 1831 if (e instanceof ExitStatus || e == 'unwind') { 1832 return EXITSTATUS; 1833 } 1834 quit_(1, e); 1835 } 1836 1837 function jsStackTrace() { 1838 var error = new Error(); 1839 if (!error.stack) { 1840 // IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown, 1841 // so try that as a special-case. 1842 try { 1843 throw new Error(); 1844 } catch(e) { 1845 error = e; 1846 } 1847 if (!error.stack) { 1848 return '(no stack trace available)'; 1849 } 1850 } 1851 return error.stack.toString(); 1852 } 1853 1854 function setWasmTableEntry(idx, func) { 1855 wasmTable.set(idx, func); 1856 wasmTableMirror[idx] = func; 1857 } 1858 1859 function stackTrace() { 1860 var js = jsStackTrace(); 1861 if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace'](); 1862 return demangleAll(js); 1863 } 1864 1865 function _emscripten_get_heap_max() { 1866 // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate 1867 // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side 1868 // for any code that deals with heap sizes, which would require special 1869 // casing all heap size related code to treat 0 specially. 1870 return 2147483648; 1871 } 1872 1873 function emscripten_realloc_buffer(size) { 1874 try { 1875 // round size grow request up to wasm page size (fixed 64KB per spec) 1876 wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16); // .grow() takes a delta compared to the previous size 1877 updateGlobalBufferAndViews(wasmMemory.buffer); 1878 return 1 /*success*/; 1879 } catch(e) { 1880 err('emscripten_realloc_buffer: Attempted to grow heap from ' + buffer.byteLength + ' bytes to ' + size + ' bytes, but got error: ' + e); 1881 } 1882 // implicit 0 return to save code size (caller will cast "undefined" into 0 1883 // anyhow) 1884 } 1885 function _emscripten_resize_heap(requestedSize) { 1886 var oldSize = HEAPU8.length; 1887 requestedSize = requestedSize >>> 0; 1888 // With pthreads, races can happen (another thread might increase the size 1889 // in between), so return a failure, and let the caller retry. 1890 assert(requestedSize > oldSize); 1891 1892 // Memory resize rules: 1893 // 1. Always increase heap size to at least the requested size, rounded up 1894 // to next page multiple. 1895 // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap 1896 // geometrically: increase the heap size according to 1897 // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most 1898 // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB). 1899 // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap 1900 // linearly: increase the heap size by at least 1901 // MEMORY_GROWTH_LINEAR_STEP bytes. 1902 // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by 1903 // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest 1904 // 4. If we were unable to allocate as much memory, it may be due to 1905 // over-eager decision to excessively reserve due to (3) above. 1906 // Hence if an allocation fails, cut down on the amount of excess 1907 // growth, in an attempt to succeed to perform a smaller allocation. 1908 1909 // A limit is set for how much we can grow. We should not exceed that 1910 // (the wasm binary specifies it, so if we tried, we'd fail anyhow). 1911 var maxHeapSize = _emscripten_get_heap_max(); 1912 if (requestedSize > maxHeapSize) { 1913 err('Cannot enlarge memory, asked to go up to ' + requestedSize + ' bytes, but the limit is ' + maxHeapSize + ' bytes!'); 1914 return false; 1915 } 1916 1917 let alignUp = (x, multiple) => x + (multiple - x % multiple) % multiple; 1918 1919 // Loop through potential heap size increases. If we attempt a too eager 1920 // reservation that fails, cut down on the attempted size and reserve a 1921 // smaller bump instead. (max 3 times, chosen somewhat arbitrarily) 1922 for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { 1923 var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); // ensure geometric growth 1924 // but limit overreserving (default to capping at +96MB overgrowth at most) 1925 overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296 ); 1926 1927 var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)); 1928 1929 var replacement = emscripten_realloc_buffer(newSize); 1930 if (replacement) { 1931 1932 return true; 1933 } 1934 } 1935 err('Failed to grow the heap from ' + oldSize + ' bytes to ' + newSize + ' bytes, not enough memory!'); 1936 return false; 1937 } 1938 var ASSERTIONS = true; 1939 1940 1941 1942 /** @type {function(string, boolean=, number=)} */ 1943 function intArrayFromString(stringy, dontAddNull, length) { 1944 var len = length > 0 ? length : lengthBytesUTF8(stringy)+1; 1945 var u8array = new Array(len); 1946 var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length); 1947 if (dontAddNull) u8array.length = numBytesWritten; 1948 return u8array; 1949 } 1950 1951 function intArrayToString(array) { 1952 var ret = []; 1953 for (var i = 0; i < array.length; i++) { 1954 var chr = array[i]; 1955 if (chr > 0xFF) { 1956 if (ASSERTIONS) { 1957 assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.'); 1958 } 1959 chr &= 0xFF; 1960 } 1961 ret.push(String.fromCharCode(chr)); 1962 } 1963 return ret.join(''); 1964 } 1965 1966 1967 function checkIncomingModuleAPI() { 1968 ignoredModuleProp('fetchSettings'); 1969 } 1970 var asmLibraryArg = { 1971 "emscripten_resize_heap": _emscripten_resize_heap 1972 }; 1973 var asm = createWasm(); 1974 /** @type {function(...*):?} */ 1975 var ___wasm_call_ctors = Module["___wasm_call_ctors"] = createExportWrapper("__wasm_call_ctors"); 1976 1977 /** @type {function(...*):?} */ 1978 var _base32_decodeString = Module["_base32_decodeString"] = createExportWrapper("base32_decodeString"); 1979 1980 /** @type {function(...*):?} */ 1981 var _base32_encodeBytes = Module["_base32_encodeBytes"] = createExportWrapper("base32_encodeBytes"); 1982 1983 /** @type {function(...*):?} */ 1984 var ___errno_location = Module["___errno_location"] = createExportWrapper("__errno_location"); 1985 1986 /** @type {function(...*):?} */ 1987 var ___stdio_exit = Module["___stdio_exit"] = createExportWrapper("__stdio_exit"); 1988 1989 /** @type {function(...*):?} */ 1990 var _malloc = Module["_malloc"] = createExportWrapper("malloc"); 1991 1992 /** @type {function(...*):?} */ 1993 var _free = Module["_free"] = createExportWrapper("free"); 1994 1995 /** @type {function(...*):?} */ 1996 var _emscripten_stack_init = Module["_emscripten_stack_init"] = function() { 1997 return (_emscripten_stack_init = Module["_emscripten_stack_init"] = Module["asm"]["emscripten_stack_init"]).apply(null, arguments); 1998 }; 1999 2000 /** @type {function(...*):?} */ 2001 var _emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = function() { 2002 return (_emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = Module["asm"]["emscripten_stack_get_free"]).apply(null, arguments); 2003 }; 2004 2005 /** @type {function(...*):?} */ 2006 var _emscripten_stack_get_base = Module["_emscripten_stack_get_base"] = function() { 2007 return (_emscripten_stack_get_base = Module["_emscripten_stack_get_base"] = Module["asm"]["emscripten_stack_get_base"]).apply(null, arguments); 2008 }; 2009 2010 /** @type {function(...*):?} */ 2011 var _emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = function() { 2012 return (_emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = Module["asm"]["emscripten_stack_get_end"]).apply(null, arguments); 2013 }; 2014 2015 /** @type {function(...*):?} */ 2016 var stackSave = Module["stackSave"] = createExportWrapper("stackSave"); 2017 2018 /** @type {function(...*):?} */ 2019 var stackRestore = Module["stackRestore"] = createExportWrapper("stackRestore"); 2020 2021 /** @type {function(...*):?} */ 2022 var stackAlloc = Module["stackAlloc"] = createExportWrapper("stackAlloc"); 2023 2024 2025 2026 2027 2028 // === Auto-generated postamble setup entry stuff === 2029 2030 Module["intArrayFromString"] = intArrayFromString; 2031 unexportedRuntimeFunction('intArrayToString', false); 2032 unexportedRuntimeFunction('ccall', false); 2033 Module["cwrap"] = cwrap; 2034 unexportedRuntimeFunction('setValue', false); 2035 unexportedRuntimeFunction('getValue', false); 2036 Module["allocate"] = allocate; 2037 unexportedRuntimeFunction('UTF8ArrayToString', false); 2038 Module["UTF8ToString"] = UTF8ToString; 2039 unexportedRuntimeFunction('stringToUTF8Array', false); 2040 unexportedRuntimeFunction('stringToUTF8', false); 2041 unexportedRuntimeFunction('lengthBytesUTF8', false); 2042 unexportedRuntimeFunction('stackTrace', false); 2043 unexportedRuntimeFunction('addOnPreRun', false); 2044 unexportedRuntimeFunction('addOnInit', false); 2045 unexportedRuntimeFunction('addOnPreMain', false); 2046 unexportedRuntimeFunction('addOnExit', false); 2047 unexportedRuntimeFunction('addOnPostRun', false); 2048 unexportedRuntimeFunction('writeStringToMemory', false); 2049 unexportedRuntimeFunction('writeArrayToMemory', false); 2050 unexportedRuntimeFunction('writeAsciiToMemory', false); 2051 unexportedRuntimeFunction('addRunDependency', true); 2052 unexportedRuntimeFunction('removeRunDependency', true); 2053 unexportedRuntimeFunction('FS_createFolder', false); 2054 unexportedRuntimeFunction('FS_createPath', true); 2055 unexportedRuntimeFunction('FS_createDataFile', true); 2056 unexportedRuntimeFunction('FS_createPreloadedFile', true); 2057 unexportedRuntimeFunction('FS_createLazyFile', true); 2058 unexportedRuntimeFunction('FS_createLink', false); 2059 unexportedRuntimeFunction('FS_createDevice', true); 2060 unexportedRuntimeFunction('FS_unlink', true); 2061 unexportedRuntimeFunction('getLEB', false); 2062 unexportedRuntimeFunction('getFunctionTables', false); 2063 unexportedRuntimeFunction('alignFunctionTables', false); 2064 unexportedRuntimeFunction('registerFunctions', false); 2065 unexportedRuntimeFunction('addFunction', false); 2066 unexportedRuntimeFunction('removeFunction', false); 2067 unexportedRuntimeFunction('getFuncWrapper', false); 2068 unexportedRuntimeFunction('prettyPrint', false); 2069 unexportedRuntimeFunction('dynCall', false); 2070 unexportedRuntimeFunction('getCompilerSetting', false); 2071 unexportedRuntimeFunction('print', false); 2072 unexportedRuntimeFunction('printErr', false); 2073 unexportedRuntimeFunction('getTempRet0', false); 2074 unexportedRuntimeFunction('setTempRet0', false); 2075 unexportedRuntimeFunction('callMain', false); 2076 unexportedRuntimeFunction('abort', false); 2077 unexportedRuntimeFunction('keepRuntimeAlive', false); 2078 unexportedRuntimeFunction('zeroMemory', false); 2079 unexportedRuntimeFunction('stringToNewUTF8', false); 2080 unexportedRuntimeFunction('emscripten_realloc_buffer', false); 2081 unexportedRuntimeFunction('ENV', false); 2082 unexportedRuntimeFunction('withStackSave', false); 2083 unexportedRuntimeFunction('ERRNO_CODES', false); 2084 unexportedRuntimeFunction('ERRNO_MESSAGES', false); 2085 unexportedRuntimeFunction('setErrNo', false); 2086 unexportedRuntimeFunction('inetPton4', false); 2087 unexportedRuntimeFunction('inetNtop4', false); 2088 unexportedRuntimeFunction('inetPton6', false); 2089 unexportedRuntimeFunction('inetNtop6', false); 2090 unexportedRuntimeFunction('readSockaddr', false); 2091 unexportedRuntimeFunction('writeSockaddr', false); 2092 unexportedRuntimeFunction('DNS', false); 2093 unexportedRuntimeFunction('getHostByName', false); 2094 unexportedRuntimeFunction('Protocols', false); 2095 unexportedRuntimeFunction('Sockets', false); 2096 unexportedRuntimeFunction('getRandomDevice', false); 2097 unexportedRuntimeFunction('traverseStack', false); 2098 unexportedRuntimeFunction('convertFrameToPC', false); 2099 unexportedRuntimeFunction('UNWIND_CACHE', false); 2100 unexportedRuntimeFunction('saveInUnwindCache', false); 2101 unexportedRuntimeFunction('convertPCtoSourceLocation', false); 2102 unexportedRuntimeFunction('readAsmConstArgsArray', false); 2103 unexportedRuntimeFunction('readAsmConstArgs', false); 2104 unexportedRuntimeFunction('mainThreadEM_ASM', false); 2105 unexportedRuntimeFunction('jstoi_q', false); 2106 unexportedRuntimeFunction('jstoi_s', false); 2107 unexportedRuntimeFunction('getExecutableName', false); 2108 unexportedRuntimeFunction('listenOnce', false); 2109 unexportedRuntimeFunction('autoResumeAudioContext', false); 2110 unexportedRuntimeFunction('dynCallLegacy', false); 2111 unexportedRuntimeFunction('getDynCaller', false); 2112 unexportedRuntimeFunction('dynCall', false); 2113 unexportedRuntimeFunction('callRuntimeCallbacks', false); 2114 unexportedRuntimeFunction('wasmTableMirror', false); 2115 unexportedRuntimeFunction('setWasmTableEntry', false); 2116 unexportedRuntimeFunction('getWasmTableEntry', false); 2117 unexportedRuntimeFunction('handleException', false); 2118 unexportedRuntimeFunction('runtimeKeepalivePush', false); 2119 unexportedRuntimeFunction('runtimeKeepalivePop', false); 2120 unexportedRuntimeFunction('callUserCallback', false); 2121 unexportedRuntimeFunction('maybeExit', false); 2122 unexportedRuntimeFunction('safeSetTimeout', false); 2123 unexportedRuntimeFunction('asmjsMangle', false); 2124 unexportedRuntimeFunction('asyncLoad', false); 2125 unexportedRuntimeFunction('alignMemory', false); 2126 unexportedRuntimeFunction('mmapAlloc', false); 2127 unexportedRuntimeFunction('reallyNegative', false); 2128 unexportedRuntimeFunction('unSign', false); 2129 unexportedRuntimeFunction('reSign', false); 2130 unexportedRuntimeFunction('formatString', false); 2131 unexportedRuntimeFunction('PATH', false); 2132 unexportedRuntimeFunction('PATH_FS', false); 2133 unexportedRuntimeFunction('SYSCALLS', false); 2134 unexportedRuntimeFunction('getSocketFromFD', false); 2135 unexportedRuntimeFunction('getSocketAddress', false); 2136 unexportedRuntimeFunction('JSEvents', false); 2137 unexportedRuntimeFunction('registerKeyEventCallback', false); 2138 unexportedRuntimeFunction('specialHTMLTargets', false); 2139 unexportedRuntimeFunction('maybeCStringToJsString', false); 2140 unexportedRuntimeFunction('findEventTarget', false); 2141 unexportedRuntimeFunction('findCanvasEventTarget', false); 2142 unexportedRuntimeFunction('getBoundingClientRect', false); 2143 unexportedRuntimeFunction('fillMouseEventData', false); 2144 unexportedRuntimeFunction('registerMouseEventCallback', false); 2145 unexportedRuntimeFunction('registerWheelEventCallback', false); 2146 unexportedRuntimeFunction('registerUiEventCallback', false); 2147 unexportedRuntimeFunction('registerFocusEventCallback', false); 2148 unexportedRuntimeFunction('fillDeviceOrientationEventData', false); 2149 unexportedRuntimeFunction('registerDeviceOrientationEventCallback', false); 2150 unexportedRuntimeFunction('fillDeviceMotionEventData', false); 2151 unexportedRuntimeFunction('registerDeviceMotionEventCallback', false); 2152 unexportedRuntimeFunction('screenOrientation', false); 2153 unexportedRuntimeFunction('fillOrientationChangeEventData', false); 2154 unexportedRuntimeFunction('registerOrientationChangeEventCallback', false); 2155 unexportedRuntimeFunction('fillFullscreenChangeEventData', false); 2156 unexportedRuntimeFunction('registerFullscreenChangeEventCallback', false); 2157 unexportedRuntimeFunction('registerRestoreOldStyle', false); 2158 unexportedRuntimeFunction('hideEverythingExceptGivenElement', false); 2159 unexportedRuntimeFunction('restoreHiddenElements', false); 2160 unexportedRuntimeFunction('setLetterbox', false); 2161 unexportedRuntimeFunction('currentFullscreenStrategy', false); 2162 unexportedRuntimeFunction('restoreOldWindowedStyle', false); 2163 unexportedRuntimeFunction('softFullscreenResizeWebGLRenderTarget', false); 2164 unexportedRuntimeFunction('doRequestFullscreen', false); 2165 unexportedRuntimeFunction('fillPointerlockChangeEventData', false); 2166 unexportedRuntimeFunction('registerPointerlockChangeEventCallback', false); 2167 unexportedRuntimeFunction('registerPointerlockErrorEventCallback', false); 2168 unexportedRuntimeFunction('requestPointerLock', false); 2169 unexportedRuntimeFunction('fillVisibilityChangeEventData', false); 2170 unexportedRuntimeFunction('registerVisibilityChangeEventCallback', false); 2171 unexportedRuntimeFunction('registerTouchEventCallback', false); 2172 unexportedRuntimeFunction('fillGamepadEventData', false); 2173 unexportedRuntimeFunction('registerGamepadEventCallback', false); 2174 unexportedRuntimeFunction('registerBeforeUnloadEventCallback', false); 2175 unexportedRuntimeFunction('fillBatteryEventData', false); 2176 unexportedRuntimeFunction('battery', false); 2177 unexportedRuntimeFunction('registerBatteryEventCallback', false); 2178 unexportedRuntimeFunction('setCanvasElementSize', false); 2179 unexportedRuntimeFunction('getCanvasElementSize', false); 2180 unexportedRuntimeFunction('demangle', false); 2181 unexportedRuntimeFunction('demangleAll', false); 2182 unexportedRuntimeFunction('jsStackTrace', false); 2183 unexportedRuntimeFunction('stackTrace', false); 2184 unexportedRuntimeFunction('getEnvStrings', false); 2185 unexportedRuntimeFunction('checkWasiClock', false); 2186 unexportedRuntimeFunction('flush_NO_FILESYSTEM', false); 2187 unexportedRuntimeFunction('writeI53ToI64', false); 2188 unexportedRuntimeFunction('writeI53ToI64Clamped', false); 2189 unexportedRuntimeFunction('writeI53ToI64Signaling', false); 2190 unexportedRuntimeFunction('writeI53ToU64Clamped', false); 2191 unexportedRuntimeFunction('writeI53ToU64Signaling', false); 2192 unexportedRuntimeFunction('readI53FromI64', false); 2193 unexportedRuntimeFunction('readI53FromU64', false); 2194 unexportedRuntimeFunction('convertI32PairToI53', false); 2195 unexportedRuntimeFunction('convertU32PairToI53', false); 2196 unexportedRuntimeFunction('setImmediateWrapped', false); 2197 unexportedRuntimeFunction('clearImmediateWrapped', false); 2198 unexportedRuntimeFunction('polyfillSetImmediate', false); 2199 unexportedRuntimeFunction('uncaughtExceptionCount', false); 2200 unexportedRuntimeFunction('exceptionLast', false); 2201 unexportedRuntimeFunction('exceptionCaught', false); 2202 unexportedRuntimeFunction('ExceptionInfo', false); 2203 unexportedRuntimeFunction('CatchInfo', false); 2204 unexportedRuntimeFunction('exception_addRef', false); 2205 unexportedRuntimeFunction('exception_decRef', false); 2206 unexportedRuntimeFunction('Browser', false); 2207 unexportedRuntimeFunction('funcWrappers', false); 2208 unexportedRuntimeFunction('getFuncWrapper', false); 2209 unexportedRuntimeFunction('setMainLoop', false); 2210 unexportedRuntimeFunction('wget', false); 2211 unexportedRuntimeFunction('FS', false); 2212 unexportedRuntimeFunction('MEMFS', false); 2213 unexportedRuntimeFunction('TTY', false); 2214 unexportedRuntimeFunction('PIPEFS', false); 2215 unexportedRuntimeFunction('SOCKFS', false); 2216 unexportedRuntimeFunction('_setNetworkCallback', false); 2217 unexportedRuntimeFunction('tempFixedLengthArray', false); 2218 unexportedRuntimeFunction('miniTempWebGLFloatBuffers', false); 2219 unexportedRuntimeFunction('heapObjectForWebGLType', false); 2220 unexportedRuntimeFunction('heapAccessShiftForWebGLHeap', false); 2221 unexportedRuntimeFunction('GL', false); 2222 unexportedRuntimeFunction('emscriptenWebGLGet', false); 2223 unexportedRuntimeFunction('computeUnpackAlignedImageSize', false); 2224 unexportedRuntimeFunction('emscriptenWebGLGetTexPixelData', false); 2225 unexportedRuntimeFunction('emscriptenWebGLGetUniform', false); 2226 unexportedRuntimeFunction('webglGetUniformLocation', false); 2227 unexportedRuntimeFunction('webglPrepareUniformLocationsBeforeFirstUse', false); 2228 unexportedRuntimeFunction('webglGetLeftBracePos', false); 2229 unexportedRuntimeFunction('emscriptenWebGLGetVertexAttrib', false); 2230 unexportedRuntimeFunction('writeGLArray', false); 2231 unexportedRuntimeFunction('AL', false); 2232 unexportedRuntimeFunction('SDL_unicode', false); 2233 unexportedRuntimeFunction('SDL_ttfContext', false); 2234 unexportedRuntimeFunction('SDL_audio', false); 2235 unexportedRuntimeFunction('SDL', false); 2236 unexportedRuntimeFunction('SDL_gfx', false); 2237 unexportedRuntimeFunction('GLUT', false); 2238 unexportedRuntimeFunction('EGL', false); 2239 unexportedRuntimeFunction('GLFW_Window', false); 2240 unexportedRuntimeFunction('GLFW', false); 2241 unexportedRuntimeFunction('GLEW', false); 2242 unexportedRuntimeFunction('IDBStore', false); 2243 unexportedRuntimeFunction('runAndAbortIfError', false); 2244 unexportedRuntimeFunction('warnOnce', false); 2245 unexportedRuntimeFunction('stackSave', false); 2246 unexportedRuntimeFunction('stackRestore', false); 2247 unexportedRuntimeFunction('stackAlloc', false); 2248 unexportedRuntimeFunction('AsciiToString', false); 2249 unexportedRuntimeFunction('stringToAscii', false); 2250 unexportedRuntimeFunction('UTF16ToString', false); 2251 unexportedRuntimeFunction('stringToUTF16', false); 2252 unexportedRuntimeFunction('lengthBytesUTF16', false); 2253 unexportedRuntimeFunction('UTF32ToString', false); 2254 unexportedRuntimeFunction('stringToUTF32', false); 2255 unexportedRuntimeFunction('lengthBytesUTF32', false); 2256 Module["allocateUTF8"] = allocateUTF8; 2257 unexportedRuntimeFunction('allocateUTF8OnStack', false); 2258 Module["writeStackCookie"] = writeStackCookie; 2259 Module["checkStackCookie"] = checkStackCookie; 2260 unexportedRuntimeSymbol('ALLOC_NORMAL', false); 2261 unexportedRuntimeSymbol('ALLOC_STACK', false); 2262 2263 var calledRun; 2264 2265 /** 2266 * @constructor 2267 * @this {ExitStatus} 2268 */ 2269 function ExitStatus(status) { 2270 this.name = "ExitStatus"; 2271 this.message = "Program terminated with exit(" + status + ")"; 2272 this.status = status; 2273 } 2274 2275 var calledMain = false; 2276 2277 dependenciesFulfilled = function runCaller() { 2278 // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false) 2279 if (!calledRun) run(); 2280 if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled 2281 }; 2282 2283 function stackCheckInit() { 2284 // This is normally called automatically during __wasm_call_ctors but need to 2285 // get these values before even running any of the ctors so we call it redundantly 2286 // here. 2287 // TODO(sbc): Move writeStackCookie to native to to avoid this. 2288 _emscripten_stack_init(); 2289 writeStackCookie(); 2290 } 2291 2292 /** @type {function(Array=)} */ 2293 function run(args) { 2294 args = args || arguments_; 2295 2296 if (runDependencies > 0) { 2297 return; 2298 } 2299 2300 stackCheckInit(); 2301 2302 preRun(); 2303 2304 // a preRun added a dependency, run will be called later 2305 if (runDependencies > 0) { 2306 return; 2307 } 2308 2309 function doRun() { 2310 // run may have just been called through dependencies being fulfilled just in this very frame, 2311 // or while the async setStatus time below was happening 2312 if (calledRun) return; 2313 calledRun = true; 2314 Module['calledRun'] = true; 2315 2316 if (ABORT) return; 2317 2318 initRuntime(); 2319 2320 readyPromiseResolve(Module); 2321 if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized'](); 2322 2323 assert(!Module['_main'], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'); 2324 2325 postRun(); 2326 } 2327 2328 if (Module['setStatus']) { 2329 Module['setStatus']('Running...'); 2330 setTimeout(function() { 2331 setTimeout(function() { 2332 Module['setStatus'](''); 2333 }, 1); 2334 doRun(); 2335 }, 1); 2336 } else 2337 { 2338 doRun(); 2339 } 2340 checkStackCookie(); 2341 } 2342 Module['run'] = run; 2343 2344 function checkUnflushedContent() { 2345 // Compiler settings do not allow exiting the runtime, so flushing 2346 // the streams is not possible. but in ASSERTIONS mode we check 2347 // if there was something to flush, and if so tell the user they 2348 // should request that the runtime be exitable. 2349 // Normally we would not even include flush() at all, but in ASSERTIONS 2350 // builds we do so just for this check, and here we see if there is any 2351 // content to flush, that is, we check if there would have been 2352 // something a non-ASSERTIONS build would have not seen. 2353 // How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0 2354 // mode (which has its own special function for this; otherwise, all 2355 // the code is inside libc) 2356 var oldOut = out; 2357 var oldErr = err; 2358 var has = false; 2359 out = err = (x) => { 2360 has = true; 2361 } 2362 try { // it doesn't matter if it fails 2363 var flush = null; 2364 if (flush) flush(); 2365 } catch(e) {} 2366 out = oldOut; 2367 err = oldErr; 2368 if (has) { 2369 warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc.'); 2370 warnOnce('(this may also be due to not including full filesystem support - try building with -s FORCE_FILESYSTEM=1)'); 2371 } 2372 } 2373 2374 /** @param {boolean|number=} implicit */ 2375 function exit(status, implicit) { 2376 EXITSTATUS = status; 2377 2378 // Skip this check if the runtime is being kept alive deliberately. 2379 // For example if `exit_with_live_runtime` is called. 2380 if (!runtimeKeepaliveCounter) { 2381 checkUnflushedContent(); 2382 } 2383 2384 if (keepRuntimeAlive()) { 2385 // if exit() was called, we may warn the user if the runtime isn't actually being shut down 2386 if (!implicit) { 2387 var msg = 'program exited (with status: ' + status + '), but EXIT_RUNTIME is not set, so halting execution but not exiting the runtime or preventing further async execution (build with EXIT_RUNTIME=1, if you want a true shutdown)'; 2388 readyPromiseReject(msg); 2389 err(msg); 2390 } 2391 } else { 2392 exitRuntime(); 2393 } 2394 2395 procExit(status); 2396 } 2397 2398 function procExit(code) { 2399 EXITSTATUS = code; 2400 if (!keepRuntimeAlive()) { 2401 if (Module['onExit']) Module['onExit'](code); 2402 ABORT = true; 2403 } 2404 quit_(code, new ExitStatus(code)); 2405 } 2406 2407 if (Module['preInit']) { 2408 if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']]; 2409 while (Module['preInit'].length > 0) { 2410 Module['preInit'].pop()(); 2411 } 2412 } 2413 2414 run(); 2415 2416 2417 2418 2419 2420 2421 2422 return Base32Module.ready 2423 } 2424 ); 2425 })(); 2426 if (typeof exports === 'object' && typeof module === 'object') 2427 module.exports = Base32Module; 2428 else if (typeof define === 'function' && define['amd']) 2429 define([], function() { return Base32Module; }); 2430 else if (typeof exports === 'object') 2431 exports["Base32Module"] = Base32Module;