dtk-z3-solver-deno-v2
Version:
This directory contains JavaScript code to automatically derive TypeScript bindings for the C API, which are published on npm as [z3-solver](https://www.npmjs.com/package/z3-solver).
1,332 lines (1,132 loc) • 311 kB
JavaScript
var initZ3 = (() => {
var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
if (typeof __filename != 'undefined') _scriptName = _scriptName || __filename;
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).
// Attempt to auto-detect the environment
var ENVIRONMENT_IS_WEB = typeof window == 'object';
var ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != 'undefined';
// N.b. Electron.js environment is simultaneously a NODE-environment, but
// also a web environment.
var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string' && process.type != 'renderer';
var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
// 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) {
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)
// include: src/low-level/async-wrapper.js
// this wrapper works with async-fns to provide promise-based off-thread versions of some functions
// It's prepended directly by emscripten to the resulting z3-built.js
let threadTimeouts = [];
let capability = null;
function resolve_async(val) {
// setTimeout is a workaround for https://github.com/emscripten-core/emscripten/issues/15900
if (capability == null) {
return;
}
let cap = capability;
capability = null;
setTimeout(() => {
cap.resolve(val);
}, 0);
}
function reject_async(val) {
if (capability == null) {
return;
}
let cap = capability;
capability = null;
setTimeout(() => {
cap.reject(val);
}, 0);
}
Module.async_call = function (f, ...args) {
if (capability !== null) {
throw new Error(`you can't execute multiple async functions at the same time; let the previous one finish first`);
}
let promise = new Promise((resolve, reject) => {
capability = { resolve, reject };
});
f(...args);
return promise;
};
// end include: src/low-level/async-wrapper.js
// Sometimes an existing Module object exists with properties
// meant to overwrite the default module functionality. Here
// we collect those properties and reapply _after_ we configure
// the current environment's defaults to avoid having to be so
// defensive during initialization.
var moduleOverrides = {...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 = 160400;
if (numericVersion < 160400) {
throw new Error('This emscripten-generated code requires node v16.04.4.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');
scriptDirectory = __dirname + '/';
// 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 (!Module['thisProgram'] && process.argv.length > 1) {
thisProgram = process.argv[1].replace(/\\/g, '/');
}
arguments_ = process.argv.slice(2);
// MODULARIZE will export the module in the proper place outside, we don't need to export here
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) => {
// Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.
// See https://github.com/github/fetch/pull/92#issuecomment-140665932
// Cordova or Electron apps are typically loaded from a file:// url.
// So use XHR on webview if URL is a file URL.
if (isFileURI(url)) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = () => {
if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
resolve(xhr.response);
return;
}
reject(xhr.status);
};
xhr.onerror = reject;
xhr.send(null);
});
}
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) {
defaultPrint = (...args) => fs.writeSync(1, args.join(' ') + '\n');
defaultPrintErr = (...args) => fs.writeSync(2, args.join(' ') + '\n');
}
var out = Module['print'] || defaultPrint;
var err = Module['printErr'] || defaultPrintErr;
// Merge back in the overrides
Object.assign(Module, moduleOverrides);
// Free the object hierarchy contained in the overrides, this lets the GC
// reclaim data used.
moduleOverrides = null;
checkIncomingModuleAPI();
// Emit code to handle expected values on the Module object. This applies Module.x
// to the proper local x. This has two benefits: first, we only emit it if it is
// expected to arrive, and second, by using a local everywhere else that can be
// minified.
if (Module['arguments']) arguments_ = Module['arguments'];legacyModuleProp('arguments', 'arguments_');
if (Module['thisProgram']) thisProgram = Module['thisProgram'];legacyModuleProp('thisProgram', 'thisProgram');
// perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
// Assertions on removed incoming Module JS APIs.
assert(typeof Module['memoryInitializerPrefixURL'] == 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
assert(typeof Module['pthreadMainPrefixURL'] == 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
assert(typeof Module['cdInitializerPrefixURL'] == 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
assert(typeof Module['filePackagePrefixURL'] == 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
assert(typeof Module['read'] == 'undefined', 'Module.read option was removed');
assert(typeof Module['readAsync'] == 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
assert(typeof Module['readBinary'] == 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
assert(typeof Module['setWindowTitle'] == 'undefined', 'Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)');
assert(typeof Module['TOTAL_MEMORY'] == 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY');
legacyModuleProp('asm', 'wasmExports');
legacyModuleProp('readAsync', 'readAsync');
legacyModuleProp('readBinary', 'readBinary');
legacyModuleProp('setWindowTitle', 'setWindowTitle');
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';
var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';
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_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 = Module['wasmBinary'];legacyModuleProp('wasmBinary', '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
// Base Emscripten EH error class
class EmscriptenEH extends Error {}
class EmscriptenSjLj extends EmscriptenEH {}
class CppException extends EmscriptenEH {
constructor(excPtr) {
super(excPtr);
this.excPtr = excPtr;
const excInfo = getExceptionMessage(excPtr);
this.name = excInfo[0];
this.message = excInfo[1];
}
}
// 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)';
})();
if (Module['ENVIRONMENT']) {
throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)');
}
function legacyModuleProp(prop, newName, incoming=true) {
if (!Object.getOwnPropertyDescriptor(Module, prop)) {
Object.defineProperty(Module, prop, {
configurable: true,
get() {
let extra = incoming ? ' (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)' : '';
abort(`\`Module.${prop}\` has been replaced by \`${newName}\`` + extra);
}
});
}
}
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) {
// In MODULARIZE mode the generated code runs inside a function scope and not
// the global scope, and JavaScript does not provide access to function scopes
// so we cannot dynamically modify the scrope using `defineProperty` in this
// case.
//
// In this mode we simply ignore requests for `hookGlobalSymbolAccess`. Since
// this is a debug-only feature, skipping it is not major issue.
}
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 && fs) {
fs.writeSync(2, args.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;
function threadPrintErr(...args) {
// See https://github.com/emscripten-core/emscripten/issues/14804
if (ENVIRONMENT_IS_NODE) {
fs.writeSync(2, args.join(' ') + '\n');
return;
}
console.error(...args);
}
if (!Module['printErr'])
err = threadPrintErr;
// Turn unhandled rejected promises into errors so that the main thread will be
// notified about them.
self.onunhandledrejection = (e) => { throw e.reason || e; };
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) {
initializedJS = true;
}
try {
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;
Module['HEAP8'] = HEAP8 = new Int8Array(b);
Module['HEAP16'] = HEAP16 = new Int16Array(b);
Module['HEAPU8'] = HEAPU8 = new Uint8Array(b);
Module['HEAPU16'] = HEAPU16 = new Uint16Array(b);
Module['HEAP32'] = HEAP32 = new Int32Array(b);
Module['HEAPU32'] = HEAPU32 = new Uint32Array(b);
Module['HEAPF32'] = HEAPF32 = new Float32Array(b);
Module['HEAPF64'] = HEAPF64 = new Float64Array(b);
Module['HEAP64'] = HEAP64 = new BigInt64Array(b);
Module['HEAPU64'] = HEAPU64 = new BigUint64Array(b);
}
// end include: runtime_shared.js
assert(!Module['STACK_SIZE'], 'STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time')
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)
if (!ENVIRONMENT_IS_PTHREAD) {
if (Module['wasmMemory']) {
wasmMemory = Module['wasmMemory'];
} else
{
var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 2147483648;legacyModuleProp('INITIAL_MEMORY', 'INITIAL_MEMORY');
assert(INITIAL_MEMORY >= 20971520, 'INITIAL_MEMORY should be larger than STACK_SIZE, was ' + INITIAL_MEMORY + '! (STACK_SIZE=' + 20971520 + ')');
/** @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');
callRuntimeCallbacks(onPreRuns);
}
function initRuntime() {
assert(!runtimeInitialized);
runtimeInitialized = true;
if (ENVIRONMENT_IS_PTHREAD) return startWorker(Module);
checkStackCookie();
if (!Module['noFSInit'] && !FS.initialized) FS.init();
TTY.init();
wasmExports['__wasm_call_ctors']();
FS.ignorePermissions = false;
}
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');
callRuntimeCallbacks(onPostRuns);
}
// 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() {
return locateFile('z3-built.wasm');
}
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'
// Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.
&& !isFileURI(binaryFile)
// 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();
// 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;
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) => {
receiveInstance(mod, inst);
resolve(mod.exports);
});
} 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.unshift(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