UNPKG

libxslt-wasm

Version:

JavaScript bindings for libxslt compiled to WebAssembly

1,348 lines (1,160 loc) 293 kB
var LibxsltModule = (() => { var _scriptName = import.meta.url; return ( async function(moduleArg = {}) { var moduleRtn; // include: shell.js // The Module object: Our interface to the outside world. We import // and export values on it. There are various ways Module can be used: // 1. Not defined. We create it here // 2. A function parameter, function(moduleArg) => Promise<Module> // 3. pre-run appended it, var Module = {}; ..generated code.. // 4. External script tag defines var Module. // We need to check if Module already exists (e.g. case 3 above). // Substitution will be replaced with actual code on later stage of the build, // this way Closure Compiler will not mangle it (e.g. case 4. above). // Note that if you want to run closure, and also to use Module // after the generated code, you will need to define var Module = {}; // before the code. Then that object will be used in the code, and you // can continue to use Module afterwards as well. var Module = moduleArg; // Set up the promise that indicates the Module is initialized var readyPromiseResolve, readyPromiseReject; var readyPromise = new Promise((resolve, reject) => { readyPromiseResolve = resolve; readyPromiseReject = reject; }); // Determine the runtime environment we are in. You can customize this by // setting the ENVIRONMENT setting at compile time (see settings.js). var ENVIRONMENT_IS_WEB = false; // node+pthreads always supports workers; detect which we are at runtime var ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != 'undefined'; var ENVIRONMENT_IS_NODE = true; var ENVIRONMENT_IS_SHELL = false; // Three configurations we can be running in: // 1) We could be the application main() thread running in the main JS UI thread. (ENVIRONMENT_IS_WORKER == false and ENVIRONMENT_IS_PTHREAD == false) // 2) We could be the application main() thread proxied to worker. (with Emscripten -sPROXY_TO_WORKER) (ENVIRONMENT_IS_WORKER == true, ENVIRONMENT_IS_PTHREAD == false) // 3) We could be an application pthread running in a worker. (ENVIRONMENT_IS_WORKER == true and ENVIRONMENT_IS_PTHREAD == true) // The way we signal to a worker that it is hosting a pthread is to construct // it with a specific name. var ENVIRONMENT_IS_PTHREAD = ENVIRONMENT_IS_WORKER && self.name?.startsWith('em-pthread'); if (ENVIRONMENT_IS_PTHREAD) { assert(!globalThis.moduleLoaded, 'module should only be loaded once on each pthread worker'); globalThis.moduleLoaded = true; } if (ENVIRONMENT_IS_NODE) { // When building an ES module `require` is not normally available. // We need to use `createRequire()` to construct the require()` function. const { createRequire } = await import('module'); /** @suppress{duplicate} */ var require = createRequire(import.meta.url); var worker_threads = require('worker_threads'); global.Worker = worker_threads.Worker; ENVIRONMENT_IS_WORKER = !worker_threads.isMainThread; // Under node we set `workerData` to `em-pthread` to signal that the worker // is hosting a pthread. ENVIRONMENT_IS_PTHREAD = ENVIRONMENT_IS_WORKER && worker_threads['workerData'] == 'em-pthread' } // --pre-jses are emitted after the Module integration code, so that they can // refer to Module (if they choose; they can also define Module) var arguments_ = []; var thisProgram = './this.program'; var quit_ = (status, toThrow) => { throw toThrow; }; // `/` should be present at the end if `scriptDirectory` is not empty var scriptDirectory = ''; function locateFile(path) { if (Module['locateFile']) { return Module['locateFile'](path, scriptDirectory); } return scriptDirectory + path; } // Hooks that are implemented differently in different runtime environments. var readAsync, readBinary; if (ENVIRONMENT_IS_NODE) { if (typeof process == 'undefined' || !process.release || process.release.name !== 'node') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); var nodeVersion = process.versions.node; var numericVersion = nodeVersion.split('.').slice(0, 3); numericVersion = (numericVersion[0] * 10000) + (numericVersion[1] * 100) + (numericVersion[2].split('-')[0] * 1); var minVersion = 190200; if (numericVersion < 190200) { throw new Error('This emscripten-generated code requires node v19.02.2.0 (detected v' + nodeVersion + ')'); } // These modules will usually be used on Node.js. Load them eagerly to avoid // the complexity of lazy-loading. var fs = require('fs'); var nodePath = require('path'); // EXPORT_ES6 + ENVIRONMENT_IS_NODE always requires use of import.meta.url, // since there's no way getting the current absolute path of the module when // support for that is not available. if (!import.meta.url.startsWith('data:')) { scriptDirectory = nodePath.dirname(require('url').fileURLToPath(import.meta.url)) + '/'; } // include: node_shell_read.js readBinary = (filename) => { // We need to re-wrap `file://` strings to URLs. filename = isFileURI(filename) ? new URL(filename) : filename; var ret = fs.readFileSync(filename); assert(Buffer.isBuffer(ret)); return ret; }; readAsync = async (filename, binary = true) => { // See the comment in the `readBinary` function. filename = isFileURI(filename) ? new URL(filename) : filename; var ret = fs.readFileSync(filename, binary ? undefined : 'utf8'); assert(binary ? Buffer.isBuffer(ret) : typeof ret == 'string'); return ret; }; // end include: node_shell_read.js if (process.argv.length > 1) { thisProgram = process.argv[1].replace(/\\/g, '/'); } arguments_ = process.argv.slice(2); quit_ = (status, toThrow) => { process.exitCode = status; throw toThrow; }; } else if (ENVIRONMENT_IS_SHELL) { if ((typeof process == 'object' && typeof require === 'function') || typeof window == 'object' || typeof WorkerGlobalScope != 'undefined') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); } else // Note that this includes Node.js workers when relevant (pthreads is enabled). // Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and // ENVIRONMENT_IS_NODE. if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled scriptDirectory = self.location.href; } else if (typeof document != 'undefined' && document.currentScript) { // web scriptDirectory = document.currentScript.src; } // When MODULARIZE, this JS may be executed later, after document.currentScript // is gone, so we saved it, and we use it here instead of any other info. if (_scriptName) { scriptDirectory = _scriptName; } // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them. // otherwise, slice off the final part of the url to find the script directory. // if scriptDirectory does not contain a slash, lastIndexOf will return -1, // and scriptDirectory will correctly be replaced with an empty string. // If scriptDirectory contains a query (starting with ?) or a fragment (starting with #), // they are removed because they could contain a slash. if (scriptDirectory.startsWith('blob:')) { scriptDirectory = ''; } else { scriptDirectory = scriptDirectory.slice(0, scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/')+1); } if (!(typeof window == 'object' || typeof WorkerGlobalScope != 'undefined')) throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); // Differentiate the Web Worker from the Node Worker case, as reading must // be done differently. if (!ENVIRONMENT_IS_NODE) { // include: web_or_worker_shell_read.js if (ENVIRONMENT_IS_WORKER) { readBinary = (url) => { var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.responseType = 'arraybuffer'; xhr.send(null); return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response)); }; } readAsync = async (url) => { assert(!isFileURI(url), "readAsync does not work with file:// URLs"); var response = await fetch(url, { credentials: 'same-origin' }); if (response.ok) { return response.arrayBuffer(); } throw new Error(response.status + ' : ' + response.url); }; // end include: web_or_worker_shell_read.js } } else { throw new Error('environment detection error'); } // Set up the out() and err() hooks, which are how we can print to stdout or // stderr, respectively. // Normally just binding console.log/console.error here works fine, but // under node (with workers) we see missing/out-of-order messages so route // directly to stdout and stderr. // See https://github.com/emscripten-core/emscripten/issues/14804 var defaultPrint = console.log.bind(console); var defaultPrintErr = console.error.bind(console); if (ENVIRONMENT_IS_NODE) { var utils = require('util'); var stringify = (a) => typeof a == 'object' ? utils.inspect(a) : a; defaultPrint = (...args) => fs.writeSync(1, args.map(stringify).join(' ') + '\n'); defaultPrintErr = (...args) => fs.writeSync(2, args.map(stringify).join(' ') + '\n'); } var out = defaultPrint; var err = defaultPrintErr; var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js'; var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js'; var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js'; var FETCHFS = 'FETCHFS is no longer included by default; build with -lfetchfs.js'; var ICASEFS = 'ICASEFS is no longer included by default; build with -licasefs.js'; var JSFILEFS = 'JSFILEFS is no longer included by default; build with -ljsfilefs.js'; var OPFS = 'OPFS is no longer included by default; build with -lopfs.js'; // perform assertions in shell.js after we set up out() and err(), as otherwise // if an assertion fails it cannot print the message assert( ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER || ENVIRONMENT_IS_NODE, 'Pthreads do not work in this environment yet (need Web Workers, or an alternative to them)'); assert(!ENVIRONMENT_IS_WEB, 'web environment detected but not enabled at build time. Add `web` to `-sENVIRONMENT` to enable.'); assert(!ENVIRONMENT_IS_SHELL, 'shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.'); // end include: shell.js // include: preamble.js // === Preamble library stuff === // Documentation for the public APIs defined in this file must be updated in: // site/source/docs/api_reference/preamble.js.rst // A prebuilt local version of the documentation is available at: // site/build/text/docs/api_reference/preamble.js.txt // You can also build docs locally as HTML or other formats in site/ // An online HTML version (which may be of a different version of Emscripten) // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html var wasmBinary; if (typeof WebAssembly != 'object') { err('no native wasm support detected'); } // Wasm globals var wasmMemory; // For sending to workers. var wasmModule; //======================================== // Runtime essentials //======================================== // whether we are quitting the application. no code should run after this. // set in exit() and abort() var ABORT = false; // set by exit() and abort(). Passed to 'onExit' handler. // NOTE: This is also used as the process return code code in shell environments // but only when noExitRuntime is false. var EXITSTATUS; // In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we // don't define it at all in release modes. This matches the behaviour of // MINIMAL_RUNTIME. // TODO(sbc): Make this the default even without STRICT enabled. /** @type {function(*, string=)} */ function assert(condition, text) { if (!condition) { abort('Assertion failed' + (text ? ': ' + text : '')); } } // We used to include malloc/free by default in the past. Show a helpful error in // builds with assertions. // Memory management var HEAP, /** @type {!Int8Array} */ HEAP8, /** @type {!Uint8Array} */ HEAPU8, /** @type {!Int16Array} */ HEAP16, /** @type {!Uint16Array} */ HEAPU16, /** @type {!Int32Array} */ HEAP32, /** @type {!Uint32Array} */ HEAPU32, /** @type {!Float32Array} */ HEAPF32, /* BigInt64Array type is not correctly defined in closure /** not-@type {!BigInt64Array} */ HEAP64, /* BigUint64Array type is not correctly defined in closure /** not-t@type {!BigUint64Array} */ HEAPU64, /** @type {!Float64Array} */ HEAPF64; var runtimeInitialized = false; /** * Indicates whether filename is delivered via file protocol (as opposed to http/https) * @noinline */ var isFileURI = (filename) => filename.startsWith('file://'); // include: runtime_shared.js // include: runtime_stack_check.js // Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode. function writeStackCookie() { var max = _emscripten_stack_get_end(); assert((max & 3) == 0); // If the stack ends at address zero we write our cookies 4 bytes into the // stack. This prevents interference with SAFE_HEAP and ASAN which also // monitor writes to address zero. if (max == 0) { max += 4; } // The stack grow downwards towards _emscripten_stack_get_end. // We write cookies to the final two words in the stack and detect if they are // ever overwritten. HEAPU32[((max)>>2)] = 0x02135467; HEAPU32[(((max)+(4))>>2)] = 0x89BACDFE; // Also test the global address 0 for integrity. HEAPU32[((0)>>2)] = 1668509029; } function checkStackCookie() { if (ABORT) return; var max = _emscripten_stack_get_end(); // See writeStackCookie(). if (max == 0) { max += 4; } var cookie1 = HEAPU32[((max)>>2)]; var cookie2 = HEAPU32[(((max)+(4))>>2)]; if (cookie1 != 0x02135467 || cookie2 != 0x89BACDFE) { abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`); } // Also test the global address 0 for integrity. if (HEAPU32[((0)>>2)] != 0x63736d65 /* 'emsc' */) { abort('Runtime error: The application has corrupted its heap memory area (address zero)!'); } } // end include: runtime_stack_check.js // include: runtime_exceptions.js // end include: runtime_exceptions.js // include: runtime_debug.js // Endianness check (() => { var h16 = new Int16Array(1); var h8 = new Int8Array(h16.buffer); h16[0] = 0x6373; if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)'; })(); function consumedModuleProp(prop) { if (!Object.getOwnPropertyDescriptor(Module, prop)) { Object.defineProperty(Module, prop, { configurable: true, set() { abort(`Attempt to set \`Module.${prop}\` after it has already been processed. This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`); } }); } } function ignoredModuleProp(prop) { if (Object.getOwnPropertyDescriptor(Module, prop)) { abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`); } } // forcing the filesystem exports a few things by default function isExportedByForceFilesystem(name) { return name === 'FS_createPath' || name === 'FS_createDataFile' || name === 'FS_createPreloadedFile' || name === 'FS_unlink' || name === 'addRunDependency' || // The old FS has some functionality that WasmFS lacks. name === 'FS_createLazyFile' || name === 'FS_createDevice' || name === 'removeRunDependency'; } /** * Intercept access to a global symbol. This enables us to give informative * warnings/errors when folks attempt to use symbols they did not include in * their build, or no symbols that no longer exist. */ function hookGlobalSymbolAccess(sym, func) { if (typeof globalThis != 'undefined' && !Object.getOwnPropertyDescriptor(globalThis, sym)) { Object.defineProperty(globalThis, sym, { configurable: true, get() { func(); return undefined; } }); } } function missingGlobal(sym, msg) { hookGlobalSymbolAccess(sym, () => { warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`); }); } missingGlobal('buffer', 'Please use HEAP8.buffer or wasmMemory.buffer'); missingGlobal('asm', 'Please use wasmExports instead'); function missingLibrarySymbol(sym) { hookGlobalSymbolAccess(sym, () => { // Can't `abort()` here because it would break code that does runtime // checks. e.g. `if (typeof SDL === 'undefined')`. var msg = `\`${sym}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`; // DEFAULT_LIBRARY_FUNCS_TO_INCLUDE requires the name as it appears in // library.js, which means $name for a JS name with no prefix, or name // for a JS name like _name. var librarySymbol = sym; if (!librarySymbol.startsWith('_')) { librarySymbol = '$' + sym; } msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`; if (isExportedByForceFilesystem(sym)) { msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; } warnOnce(msg); }); // Any symbol that is not included from the JS library is also (by definition) // not exported on the Module object. unexportedRuntimeSymbol(sym); } function unexportedRuntimeSymbol(sym) { if (ENVIRONMENT_IS_PTHREAD) { return; } if (!Object.getOwnPropertyDescriptor(Module, sym)) { Object.defineProperty(Module, sym, { configurable: true, get() { var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`; if (isExportedByForceFilesystem(sym)) { msg += '. Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you'; } abort(msg); } }); } } var runtimeDebug = true; // Switch to false at runtime to disable logging at the right times // Used by XXXXX_DEBUG settings to output debug messages. function dbg(...args) { if (!runtimeDebug && typeof runtimeDebug != 'undefined') return; // Avoid using the console for debugging in multi-threaded node applications // See https://github.com/emscripten-core/emscripten/issues/14804 if (ENVIRONMENT_IS_NODE) { // TODO(sbc): Unify with err/out implementation in shell.sh. var fs = require('fs'); var utils = require('util'); var stringify = (a) => typeof a == 'object' ? utils.inspect(a) : a; fs.writeSync(1, args.map(stringify).join(' ') + '\n'); } else // TODO(sbc): Make this configurable somehow. Its not always convenient for // logging to show up as warnings. console.warn(...args); } // end include: runtime_debug.js // include: memoryprofiler.js // end include: memoryprofiler.js // include: runtime_pthread.js // Pthread Web Worker handling code. // This code runs only on pthread web workers and handles pthread setup // and communication with the main thread via postMessage. // Unique ID of the current pthread worker (zero on non-pthread-workers // including the main thread). var workerID = 0; if (ENVIRONMENT_IS_PTHREAD) { var wasmModuleReceived; // Node.js support if (ENVIRONMENT_IS_NODE) { // Create as web-worker-like an environment as we can. var parentPort = worker_threads['parentPort']; parentPort.on('message', (msg) => onmessage({ data: msg })); Object.assign(globalThis, { self: global, postMessage: (msg) => parentPort.postMessage(msg), }); } // Thread-local guard variable for one-time init of the JS state var initializedJS = false; // Turn unhandled rejected promises into errors so that the main thread will be // notified about them. self.onunhandledrejection = (e) => { throw e.reason || e; }; async function handleMessage(e) { try { var msgData = e['data']; //dbg('msgData: ' + Object.keys(msgData)); var cmd = msgData.cmd; if (cmd === 'load') { // Preload command that is called once per worker to parse and load the Emscripten code. workerID = msgData.workerID; // Until we initialize the runtime, queue up any further incoming messages. let messageQueue = []; self.onmessage = (e) => messageQueue.push(e); // And add a callback for when the runtime is initialized. self.startWorker = (instance) => { // Notify the main thread that this thread has loaded. postMessage({ cmd: 'loaded' }); // Process any messages that were queued before the thread was ready. for (let msg of messageQueue) { handleMessage(msg); } // Restore the real message handler. self.onmessage = handleMessage; }; // Use `const` here to ensure that the variable is scoped only to // that iteration, allowing safe reference from a closure. for (const handler of msgData.handlers) { // The the main module has a handler for a certain even, but no // handler exists on the pthread worker, then proxy that handler // back to the main thread. if (!Module[handler] || Module[handler].proxy) { Module[handler] = (...args) => { postMessage({ cmd: 'callHandler', handler, args: args }); } // Rebind the out / err handlers if needed if (handler == 'print') out = Module[handler]; if (handler == 'printErr') err = Module[handler]; } } wasmMemory = msgData.wasmMemory; updateMemoryViews(); wasmModuleReceived(msgData.wasmModule); } else if (cmd === 'run') { assert(msgData.pthread_ptr); // Call inside JS module to set up the stack frame for this pthread in JS module scope. // This needs to be the first thing that we do, as we cannot call to any C/C++ functions // until the thread stack is initialized. establishStackSpace(msgData.pthread_ptr); // Pass the thread address to wasm to store it for fast access. __emscripten_thread_init(msgData.pthread_ptr, /*is_main=*/0, /*is_runtime=*/0, /*can_block=*/1, 0, 0); PThread.threadInitTLS(); // Await mailbox notifications with `Atomics.waitAsync` so we can start // using the fast `Atomics.notify` notification path. __emscripten_thread_mailbox_await(msgData.pthread_ptr); if (!initializedJS) { // Embind must initialize itself on all threads, as it generates support JS. // We only do this once per worker since they get reused __embind_initialize_bindings(); initializedJS = true; } try { await invokeEntryPoint(msgData.start_routine, msgData.arg); } catch(ex) { if (ex != 'unwind') { // The pthread "crashed". Do not call `_emscripten_thread_exit` (which // would make this thread joinable). Instead, re-throw the exception // and let the top level handler propagate it back to the main thread. throw ex; } } } else if (msgData.target === 'setimmediate') { // no-op } else if (cmd === 'checkMailbox') { if (initializedJS) { checkMailbox(); } } else if (cmd) { // The received message looks like something that should be handled by this message // handler, (since there is a cmd field present), but is not one of the // recognized commands: err(`worker: received unknown command ${cmd}`); err(msgData); } } catch(ex) { err(`worker: onmessage() captured an uncaught exception: ${ex}`); if (ex?.stack) err(ex.stack); __emscripten_thread_crashed(); throw ex; } }; self.onmessage = handleMessage; } // ENVIRONMENT_IS_PTHREAD // end include: runtime_pthread.js function updateMemoryViews() { var b = wasmMemory.buffer; HEAP8 = new Int8Array(b); HEAP16 = new Int16Array(b); HEAPU8 = new Uint8Array(b); HEAPU16 = new Uint16Array(b); HEAP32 = new Int32Array(b); HEAPU32 = new Uint32Array(b); HEAPF32 = new Float32Array(b); HEAPF64 = new Float64Array(b); HEAP64 = new BigInt64Array(b); HEAPU64 = new BigUint64Array(b); } // end include: runtime_shared.js assert(typeof Int32Array != 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray != undefined && Int32Array.prototype.set != undefined, 'JS engine does not provide full typed array support'); // In non-standalone/normal mode, we create the memory here. // include: runtime_init_memory.js // Create the wasm memory. (Note: this only applies if IMPORTED_MEMORY is defined) // check for full engine support (use string 'subarray' to avoid closure compiler confusion) function initMemory() { if (ENVIRONMENT_IS_PTHREAD) return; if (Module['wasmMemory']) { wasmMemory = Module['wasmMemory']; } else { var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216 assert(INITIAL_MEMORY >= 65536, 'INITIAL_MEMORY should be larger than STACK_SIZE, was ' + INITIAL_MEMORY + '! (STACK_SIZE=' + 65536 + ')'); /** @suppress {checkTypes} */ wasmMemory = new WebAssembly.Memory({ 'initial': INITIAL_MEMORY / 65536, 'maximum': INITIAL_MEMORY / 65536, 'shared': true, }); } updateMemoryViews(); } // end include: runtime_init_memory.js function preRun() { assert(!ENVIRONMENT_IS_PTHREAD); // PThreads reuse the runtime from the main thread. if (Module['preRun']) { if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']]; while (Module['preRun'].length) { addOnPreRun(Module['preRun'].shift()); } } consumedModuleProp('preRun'); // Begin ATPRERUNS hooks callRuntimeCallbacks(onPreRuns); // End ATPRERUNS hooks } function initRuntime() { assert(!runtimeInitialized); runtimeInitialized = true; if (ENVIRONMENT_IS_PTHREAD) return startWorker(Module); checkStackCookie(); // Begin ATINITS hooks if (!Module['noFSInit'] && !FS.initialized) FS.init(); TTY.init(); // End ATINITS hooks wasmExports['__wasm_call_ctors'](); // Begin ATPOSTCTORS hooks FS.ignorePermissions = false; // End ATPOSTCTORS hooks } function preMain() { checkStackCookie(); // No ATMAINS hooks } function postRun() { checkStackCookie(); if (ENVIRONMENT_IS_PTHREAD) return; // PThreads reuse the runtime from the main thread. if (Module['postRun']) { if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']]; while (Module['postRun'].length) { addOnPostRun(Module['postRun'].shift()); } } consumedModuleProp('postRun'); // Begin ATPOSTRUNS hooks callRuntimeCallbacks(onPostRuns); // End ATPOSTRUNS hooks } // A counter of dependencies for calling run(). If we need to // do asynchronous work before running, increment this and // decrement it. Incrementing must happen in a place like // Module.preRun (used by emcc to add file preloading). // Note that you can add dependencies in preRun, even though // it happens right before run - run will be postponed until // the dependencies are met. var runDependencies = 0; var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled var runDependencyTracking = {}; var runDependencyWatcher = null; function getUniqueRunDependency(id) { var orig = id; while (1) { if (!runDependencyTracking[id]) return id; id = orig + Math.random(); } } function addRunDependency(id) { runDependencies++; Module['monitorRunDependencies']?.(runDependencies); if (id) { assert(!runDependencyTracking[id]); runDependencyTracking[id] = 1; if (runDependencyWatcher === null && typeof setInterval != 'undefined') { // Check for missing dependencies every few seconds runDependencyWatcher = setInterval(() => { if (ABORT) { clearInterval(runDependencyWatcher); runDependencyWatcher = null; return; } var shown = false; for (var dep in runDependencyTracking) { if (!shown) { shown = true; err('still waiting on run dependencies:'); } err(`dependency: ${dep}`); } if (shown) { err('(end of list)'); } }, 10000); } } else { err('warning: run dependency added without ID'); } } function removeRunDependency(id) { runDependencies--; Module['monitorRunDependencies']?.(runDependencies); if (id) { assert(runDependencyTracking[id]); delete runDependencyTracking[id]; } else { err('warning: run dependency removed without ID'); } if (runDependencies == 0) { if (runDependencyWatcher !== null) { clearInterval(runDependencyWatcher); runDependencyWatcher = null; } if (dependenciesFulfilled) { var callback = dependenciesFulfilled; dependenciesFulfilled = null; callback(); // can add another dependenciesFulfilled } } } /** @param {string|number=} what */ function abort(what) { Module['onAbort']?.(what); what = 'Aborted(' + what + ')'; // TODO(sbc): Should we remove printing and leave it up to whoever // catches the exception? err(what); ABORT = true; // Use a wasm runtime error, because a JS error might be seen as a foreign // exception, which means we'd run destructors on it. We need the error to // simply make the program stop. // FIXME This approach does not work in Wasm EH because it currently does not assume // all RuntimeErrors are from traps; it decides whether a RuntimeError is from // a trap or not based on a hidden field within the object. So at the moment // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that // allows this in the wasm spec. // Suppress closure compiler warning here. Closure compiler's builtin extern // definition for WebAssembly.RuntimeError claims it takes no arguments even // though it can. // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed. /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what); readyPromiseReject(e); // Throw the error whether or not MODULARIZE is set because abort is used // in code paths apart from instantiation where an exception is expected // to be thrown when abort is called. throw e; } function createExportWrapper(name, nargs) { return (...args) => { assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`); var f = wasmExports[name]; assert(f, `exported native function \`${name}\` not found`); // Only assert for too many arguments. Too few can be valid since the missing arguments will be zero filled. assert(args.length <= nargs, `native function \`${name}\` called with ${args.length} args but expects ${nargs}`); return f(...args); }; } var wasmBinaryFile; function findWasmBinary() { if (Module['locateFile']) { return locateFile('libxslt.wasm'); } // Use bundler-friendly `new URL(..., import.meta.url)` pattern; works in browsers too. return new URL('libxslt.wasm', import.meta.url).href; } function getBinarySync(file) { if (file == wasmBinaryFile && wasmBinary) { return new Uint8Array(wasmBinary); } if (readBinary) { return readBinary(file); } throw 'both async and sync fetching of the wasm failed'; } async function getWasmBinary(binaryFile) { // If we don't have the binary yet, load it asynchronously using readAsync. if (!wasmBinary) { // Fetch the binary using readAsync try { var response = await readAsync(binaryFile); return new Uint8Array(response); } catch { // Fall back to getBinarySync below; } } // Otherwise, getBinarySync should be able to get it synchronously return getBinarySync(binaryFile); } async function instantiateArrayBuffer(binaryFile, imports) { try { var binary = await getWasmBinary(binaryFile); var instance = await WebAssembly.instantiate(binary, imports); return instance; } catch (reason) { err(`failed to asynchronously prepare wasm: ${reason}`); // Warn on some common problems. if (isFileURI(wasmBinaryFile)) { 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`); } abort(reason); } } async function instantiateAsync(binary, binaryFile, imports) { if (!binary && typeof WebAssembly.instantiateStreaming == 'function' // Avoid instantiateStreaming() on Node.js environment for now, as while // Node.js v18.1.0 implements it, it does not have a full fetch() // implementation yet. // // Reference: // https://github.com/emscripten-core/emscripten/pull/16917 && !ENVIRONMENT_IS_NODE ) { try { var response = fetch(binaryFile, { credentials: 'same-origin' }); var instantiationResult = await WebAssembly.instantiateStreaming(response, imports); return instantiationResult; } catch (reason) { // We expect the most common failure cause to be a bad MIME type for the binary, // in which case falling back to ArrayBuffer instantiation should work. err(`wasm streaming compile failed: ${reason}`); err('falling back to ArrayBuffer instantiation'); // fall back of instantiateArrayBuffer below }; } return instantiateArrayBuffer(binaryFile, imports); } function getWasmImports() { assignWasmImports(); // instrumenting imports is used in asyncify in two ways: to add assertions // that check for proper import use, and for ASYNCIFY=2 we use them to set up // the Promise API on the import side. // In pthreads builds getWasmImports is called more than once but we only // and the instrument the imports once. if (!wasmImports.__instrumented) { wasmImports.__instrumented = true; Asyncify.instrumentWasmImports(wasmImports); } // prepare imports return { 'env': wasmImports, 'wasi_snapshot_preview1': wasmImports, } } // Create the wasm instance. // Receives the wasm imports, returns the exports. async function createWasm() { // Load the wasm module and create an instance of using native support in the JS engine. // handle a generated wasm instance, receiving its exports and // performing other necessary setup /** @param {WebAssembly.Module=} module*/ function receiveInstance(instance, module) { wasmExports = instance.exports; wasmExports = Asyncify.instrumentWasmExports(wasmExports); registerTLSInit(wasmExports['_emscripten_tls_init']); wasmTable = wasmExports['__indirect_function_table']; assert(wasmTable, 'table not found in wasm exports'); // We now have the Wasm module loaded up, keep a reference to the compiled module so we can post it to the workers. wasmModule = module; removeRunDependency('wasm-instantiate'); return wasmExports; } // wait for the pthread pool (if any) addRunDependency('wasm-instantiate'); // Prefer streaming instantiation if available. // Async compilation can be confusing when an error on the page overwrites Module // (for example, if the order of elements is wrong, and the one defining Module is // later), so we save Module and check it later. var trueModule = Module; function receiveInstantiationResult(result) { // 'result' is a ResultObject object which has both the module and instance. // receiveInstance() will swap in the exports (to Module.asm) so they can be called assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?'); trueModule = null; return receiveInstance(result['instance'], result['module']); } var info = getWasmImports(); // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback // to manually instantiate the Wasm module themselves. This allows pages to // run the instantiation parallel to any other async startup actions they are // performing. // Also pthreads and wasm workers initialize the wasm instance through this // path. if (Module['instantiateWasm']) { return new Promise((resolve, reject) => { try { Module['instantiateWasm'](info, (mod, inst) => { resolve(receiveInstance(mod, inst)); }); } catch(e) { err(`Module.instantiateWasm callback failed with error: ${e}`); reject(e); } }); } if (ENVIRONMENT_IS_PTHREAD) { return new Promise((resolve) => { wasmModuleReceived = (module) => { // Instantiate from the module posted from the main thread. // We can just use sync instantiation in the worker. var instance = new WebAssembly.Instance(module, getWasmImports()); resolve(receiveInstance(instance, module)); }; }); } wasmBinaryFile ??= findWasmBinary(); try { var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info); var exports = receiveInstantiationResult(result); return exports; } catch (e) { // If instantiation fails, reject the module ready promise. readyPromiseReject(e); return Promise.reject(e); } } // end include: preamble.js // Begin JS library code class ExitStatus { name = 'ExitStatus'; constructor(status) { this.message = `Program terminated with exit(${status})`; this.status = status; } } var terminateWorker = (worker) => { worker.terminate(); // terminate() can be asynchronous, so in theory the worker can continue // to run for some amount of time after termination. However from our POV // the worker now dead and we don't want to hear from it again, so we stub // out its message handler here. This avoids having to check in each of // the onmessage handlers if the message was coming from valid worker. worker.onmessage = (e) => { var cmd = e['data'].cmd; err(`received "${cmd}" command from terminated worker: ${worker.workerID}`); }; }; var cleanupThread = (pthread_ptr) => { assert(!ENVIRONMENT_IS_PTHREAD, 'Internal Error! cleanupThread() can only ever be called from main application thread!'); assert(pthread_ptr, 'Internal Error! Null pthread_ptr in cleanupThread!'); var worker = PThread.pthreads[pthread_ptr]; assert(worker); PThread.returnWorkerToPool(worker); }; var callRuntimeCallbacks = (callbacks) => { while (callbacks.length > 0) { // Pass the module as the first argument. callbacks.shift()(Module); } }; var onPreRuns = []; var addOnPreRun = (cb) => onPreRuns.push(cb); var spawnThread = (threadParams) => { assert(!ENVIRONMENT_IS_PTHREAD, 'Internal Error! spawnThread() can only ever be called from main application thread!'); assert(threadParams.pthread_ptr, 'Internal error, no pthread ptr!'); var worker = PThread.getNewWorker(); if (!worker) { // No available workers in the PThread pool. return 6; } assert(!worker.pthread_ptr, 'Internal error!'); PThread.runningWorkers.push(worker); // Add to pthreads map PThread.pthreads[threadParams.pthread_ptr] = worker; worker.pthread_ptr = threadParams.pthread_ptr; var msg = { cmd: 'run', start_routine: threadParams.startRoutine, arg: threadParams.arg, pthread_ptr: threadParams.pthread_ptr, }; if (ENVIRONMENT_IS_NODE) { // Mark worker as weakly referenced once we start executing a pthread, // so that its existence does not prevent Node.js from exiting. This // has no effect if the worker is already weakly referenced (e.g. if // this worker was previously idle/unused). worker.unref(); } // Ask the worker to start executing its pthread entry point function. worker.postMessage(msg, threadParams.transferList); return 0; }; var runtimeKeepaliveCounter = 0; var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0; var stackSave = () => _emscripten_stack_get_current(); var stackRestore = (val) => __emscripten_stack_restore(val); var stackAlloc = (sz) => __emscripten_stack_alloc(sz); /** @type{function(number, (number|boolean), ...number)} */ var proxyToMainThread = (funcIndex, emAsmAddr, sync, ...callArgs) => { // EM_ASM proxying is done by passing a pointer to the address of the EM_ASM // content as `emAsmAddr`. JS library proxying is done by passing an index // into `proxiedJSCallArgs` as `funcIndex`. If `emAsmAddr` is non-zero then // `funcIndex` will be ignored. // Additional arguments are passed after the first three are the actual // function arguments. // The serialization buffer contains the number of call params, and then // all the args here. // We also pass 'sync' to C separately, since C needs to look at it. // Allocate a buffer, which will be copied by the C code. // // First passed parameter specifies the number of arguments to the function. // When BigInt support is enabled, we must handle types in a more complex // way, detecting at runtime if a value is a BigInt or not (as we have no // type info here). To do that, add a "prefix" before each value that // indicates if it is a BigInt, which effectively doubles the number of // values we serialize for proxying. TODO: pack this? var serializedNumCallArgs = callArgs.length * 2; var sp = stackSave(); var args = stackAlloc(serializedNumCallArgs * 8); var b = ((args)>>3); for (var i = 0; i < callArgs.length; i++) { var arg = callArgs[i]; if (typeof arg == 'bigint') { // The prefix is non-zero to indicate a bigint. HEAP64[b + 2*i] = 1n; HEAP64[b + 2*i + 1] = arg; } else { // The prefix is zero to indicate a JS Number. HEAP64[b + 2*i] = 0n; HEAPF64[b + 2*i + 1] = arg; } } var rtn = __emscripten_run_on_main_thread_js(funcIndex, emAsmAddr, serializedNumCallArgs, args, sync); stackRestore(sp); return rtn; }; function _proc_exit(code) { if (ENVIRONMENT_IS_PTHREAD) return proxyToMainThread(0, 0, 1, code); EXITSTATUS = code; if (!keepRuntimeAlive()) { PThread.terminateAllThreads(); Module['onExit']?.(code); ABORT = true; } quit_(code, new ExitStatus(code)); } function exitOnMainThread(returnCode) { if (ENVIRONMENT_IS_PTHREAD) return proxyToMainThread(1, 0, 0, returnCode); _exit(returnCode); } /** @suppress {duplicate } */ /** @param {boolean|number=} implicit */ var exitJS = (status, implicit) => { EXITSTATUS = status; checkUnflushedContent(); if (ENVIRONMENT_IS_PTHREAD) { // implicit exit can never happen on a pthread assert(!implicit); // When running in a pthread we propagate the exit back to the main thread // where it can decide if the whole process should be shut down or not. // The pthread may have decided not to exit its own runtime, for example // because it runs a main loop, but that doesn't affect the main thread. exitOnMainThread(status); throw 'unwind'; } // if exit() was called explicitly, warn the user if the runtime isn't actually being shut down if (keepRuntimeAlive() && !implicit) { var msg = `program exited (with status: ${status}), but keepRuntimeAlive() is set (counter=${runtimeKeepaliveCounter}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`; readyPromiseReject(msg); err(msg); } _proc_exit(status); }; var _exit = exitJS; var ptrToString = (ptr) => { assert(typeof ptr === 'number'); // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned. ptr >>>= 0; return '0x' + ptr.toString(16).padStart(8, '0'); }; var PThread = { unusedWorkers:[], runningWorkers:[], tlsInitFunctions:[], pthreads:{ }, nextWorkerID:1, debugInit() { function pthreadLogPrefix() { var t = 0; if (runtimeInitialized && typeof _pthread_self != 'undefined' ) { t = _pthread_self(); } return `w:${workerID},t:${ptrToString(t)}: `; } // Prefix all err()/dbg() messages with the calling thread ID. var origDbg = dbg; dbg = (...args) => origDbg(pthreadLogPrefix() + args.join(' ')); }, init() { PThread.debugInit(); if ((!(ENVIRONMENT_IS_PTHREAD))) { PThread.initMainThread(); } }, initMainThread() { // MINIMAL_RUNTIME takes care of calling loadWasmModuleToAllWorkers // in postamble_minimal.js addOnPreRun(() => { addRunDependency('loading-workers') PThread.loadWasmModuleToAllWorkers(() => removeRunDependency('loading-workers')); }); }, terminateAllThreads:() => { assert(!ENVIRONMENT_IS_PTHREAD, 'Internal Error! terminateAllThreads() can only ever be called from main application thread!'); // Attempt to kill all workers. Sadly (at least on the web) there is no // way to terminate a worker synchronously, or to be notified when a // worker in actually terminated. This means there is some risk that // pthreads will continue to be executing after `worker.terminate` has // returned. For this reason, we don't call `returnWorkerToPool` here or // free the underlying pthread data structures. for (var worker of PThread.runningWorkers) { terminateWorker(worker); } for (var worker of PThread.unusedWorkers) { terminateWorker(worker); } PThread.unusedWorkers = []; PThread.runningWorkers = []; PThread.pthreads = {}; }, returnWorkerToPool:(worker) => { // We don't want to run main thread queued calls here, since we are doing // some operations that leave the worker queue in an invalid state until // we are completely done (it would be bad if free() ends up calling a // queued pthread_create which looks at the global data structures we are // modifying). To achieve that, defer the free() til the very end, when // we are all done. var pthread_ptr = worker.pthread_ptr; delete PThread.pthreads[pthread_ptr]; // Note: worker is intentionally not terminated so the pool can // dynamically grow. PThread.unusedWorkers.push(worker); PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker), 1); // Not a running Worker anymore // Detach the worker from the pthread object, and return it to the // worker pool as an unused worker. worker.pthread_ptr = 0; // Finally, free the underlying (and now-unused) pthread structure in // linear memory. __emscripten_thread_free_data(pthread_ptr); }, threadInitTLS() { // Call thread init functions (these are the _emscripten_tls_init for each // module loaded. PThread.tlsInitFunctions.forEach((f) => f()); }, loadWasmModuleToWorker:(worker) => new Promise((onFinishedLoading) => { worker.onmessage = (e) => { var d = e['data']; var cmd = d.cmd; // If this message is intended to a recipient that is not the main // thread, forward it to the target thread. if (d.targetThread && d.targetThread != _pthread_self()) { var targetWorker = PThread.pthreads[d.targetThread]; if (targetWorker) { targetWorker.postMessage(d, d.transferList); } else { err(`Internal error! Worker sent a message "${cmd}" to target pthread ${d.targetThread}, but that thread no longer exists!`); } return; } if (cmd === 'checkMailbox') { checkMailbox(); } else if (cmd === 'spawnThread') { spawnThread(d); } else if (cmd === 'cleanupThread') { cleanupThread(d.thread); } else if (cmd === 'loaded') { worker.loaded = true; onFinishedLoading(worker); } else if (d.target === 'setimmediate') { // Worker wants to postMessage() to itself to implement setImmediate() // emulation. worker.postMessage(d); } else if (cmd === 'callHandler') { Module[d.handler](...d.args); } else if (cmd) { // The received message looks like something th