space-data-module-sdk 0.9.9 → 0.9.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/_shell/consumer-assets.html +3 -3
- package/docs/assets/vendor/hd-wallet-ui/2.2.1/sdn-wallet-callback.0f2dee485c8f0d7afe5f70b4b42093a382c92d32af551bd71b41733336091c7a.js +1 -0
- package/docs/assets/vendor/hd-wallet-ui/2.2.1/sdn-wallet-public-client.9ab041131df957fcb6ef7e3d87bf9d19fe313bc5d7f1e53337752faf0ba354da.js +1 -0
- package/docs/assets/vendor/hd-wallet-ui/2.2.1/sdn-wallet-public-client.c3f68d1cfd88478f10d836a5e829d1dfc6a10157972cf0f7d4d319d0636f2cc4.css +32 -0
- package/docs/assets/vendor/sdn-stack-nav/1.0.1/sdn-stack-nav.24eb3001afc5448a90cef87e53bb4e599c0ae4dc9e14bafb6d1236e0233c6008.js +283 -0
- package/docs/assets/vendor/sdn-stack-nav/1.0.1/sdn-stack-nav.36a36359ce18322185e9ff179f88175bab67d5ad84a14d9c08a54f2ff27267e7.css +118 -0
- package/docs/browser-wasmedge-isomorphic.html +3 -3
- package/docs/byo-wasm-quickstart.html +3 -3
- package/docs/conformance.html +3 -3
- package/docs/events-abi.html +3 -3
- package/docs/families/analytics.html +3 -3
- package/docs/families/attitude.html +3 -3
- package/docs/families/behavior.html +3 -3
- package/docs/families/breakup.html +3 -3
- package/docs/families/conjunction.html +3 -3
- package/docs/families/data-source.html +3 -3
- package/docs/families/effects.html +3 -3
- package/docs/families/environment.html +3 -3
- package/docs/families/estimation.html +3 -3
- package/docs/families/gnc.html +3 -3
- package/docs/families/maneuver.html +3 -3
- package/docs/families/obstruction.html +3 -3
- package/docs/families/propagator.html +3 -3
- package/docs/families/propulsion.html +3 -3
- package/docs/families/reentry.html +3 -3
- package/docs/families/rf.html +3 -3
- package/docs/families/scheduler.html +3 -3
- package/docs/families/sensor.html +3 -3
- package/docs/families/signature.html +3 -3
- package/docs/flatsql-host-contract.html +3 -3
- package/docs/flatsql-streaming-standard.html +3 -3
- package/docs/gpu-module-abi.html +3 -3
- package/docs/index.html +3 -3
- package/docs/isomorphic-pthreads.html +3 -3
- package/docs/isomorphic-sdn-runtime-plan.html +3 -3
- package/docs/language-runtime-matrix.html +3 -3
- package/docs/module-bundle-runtime-plan.html +3 -3
- package/docs/module-publication-standard.html +3 -3
- package/docs/node-red-default-node-parity.html +3 -3
- package/docs/protect-and-sign.html +3 -3
- package/docs/protocol-installation.html +3 -3
- package/docs/publication-submission.html +3 -3
- package/docs/secrets-capability.html +3 -3
- package/docs/testing-harness.html +3 -3
- package/docs/tri-runtime-parity-gate.html +3 -3
- package/docs/tri-runtime-parity.html +3 -3
- package/docs/wallet-callback.html +1 -1
- package/package.json +1 -1
- package/src/compiler/compileCache.js +495 -0
- package/src/compiler/compileModule.js +537 -509
- package/src/compiler/emceptionNode.js +127 -1
- package/src/compiler/guestLinkFiles.js +60 -0
- package/src/compiler/index.d.ts +7 -0
- package/src/compiler/index.js +7 -0
- package/src/compiler/wasmObjectSymbols.js +369 -0
- package/src/flow/flowCompiler.js +124 -4
- package/src/flow/flowRuntimeHost.js +2 -2
- package/src/host/abi.js +2 -3
- package/src/host/hostWorkerBundleSources.js +3 -3
- package/src/host/hostcallWire.js +3 -2
- package/src/host/providerAccess.js +2 -3
- package/src/host/typedDispatch.js +2 -2
- package/src/host/wasiShim.js +5 -1
- package/src/index.d.ts +93 -0
- package/src/runtime-host/flatsqlRuntimeStore.js +2 -2
- package/src/testing/isomorphicHarness.js +15 -1
- package/src/testing/parityGate.js +14 -9
- package/src/utils/guestText.js +12 -0
|
@@ -4,6 +4,7 @@ import { createHash, randomBytes } from "node:crypto";
|
|
|
4
4
|
import {
|
|
5
5
|
cp,
|
|
6
6
|
lstat,
|
|
7
|
+
mkdir,
|
|
7
8
|
mkdtemp,
|
|
8
9
|
readFile,
|
|
9
10
|
readdir,
|
|
@@ -16,6 +17,8 @@ import { constants as fsConstants, createReadStream, readFileSync } from "node:f
|
|
|
16
17
|
import { createRequire } from "node:module";
|
|
17
18
|
import { pathToFileURL } from "node:url";
|
|
18
19
|
|
|
20
|
+
import { getEmceptionPackageIdentity, resolveCompileCacheRoot } from "./compileCache.js";
|
|
21
|
+
|
|
19
22
|
const require = createRequire(import.meta.url);
|
|
20
23
|
// Bump when the patched tree's layout or meaning changes. The patch transform's
|
|
21
24
|
// own source text is part of the cache key as well (see
|
|
@@ -442,9 +445,112 @@ function getPatchedEmceptionRoot() {
|
|
|
442
445
|
return patchedEmceptionRootPromise;
|
|
443
446
|
}
|
|
444
447
|
|
|
448
|
+
// Emscripten builds system libraries (libstandalonewasm-memgrow.a, the libc
|
|
449
|
+
// variants a flag set needs, ...) on first use and caches them under
|
|
450
|
+
// /emscripten/cache, and it runs its sanity checks until /emscripten/cache/
|
|
451
|
+
// sanity.txt exists. Inside emception that directory is in-memory, so every
|
|
452
|
+
// process paid both again (~2.4-3 s on the first link). The files it adds are
|
|
453
|
+
// persisted on disk per emception identity, at
|
|
454
|
+
// <compile cache root>/emception-cache/<identity>/, and restored into the
|
|
455
|
+
// in-memory cache when an instance loads. Writes are temp-file + rename, so
|
|
456
|
+
// concurrent processes only ever see whole files.
|
|
457
|
+
// SPACE_DATA_MODULE_SDK_EMCEPTION_CACHE=0 (or the compile cache switched off)
|
|
458
|
+
// turns it off.
|
|
459
|
+
const EMSCRIPTEN_CACHE_DIR = "/emscripten/cache";
|
|
460
|
+
const EMSCRIPTEN_CACHE_SKIP = new Set(["cache.lock"]);
|
|
461
|
+
const DISABLED_SETTINGS = new Set(["0", "off", "false", "no", "disabled"]);
|
|
462
|
+
|
|
463
|
+
function emceptionCacheDisabled() {
|
|
464
|
+
const own = String(process.env.SPACE_DATA_MODULE_SDK_EMCEPTION_CACHE ?? "").trim().toLowerCase();
|
|
465
|
+
const compile = String(process.env.SPACE_DATA_MODULE_SDK_COMPILE_CACHE ?? "").trim().toLowerCase();
|
|
466
|
+
return DISABLED_SETTINGS.has(own) || DISABLED_SETTINGS.has(compile);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function listEmscriptenCache(FS, dir = EMSCRIPTEN_CACHE_DIR, out = new Map()) {
|
|
470
|
+
let entries;
|
|
471
|
+
try {
|
|
472
|
+
entries = FS.readdir(dir);
|
|
473
|
+
} catch {
|
|
474
|
+
return out;
|
|
475
|
+
}
|
|
476
|
+
for (const entry of entries) {
|
|
477
|
+
if (entry === "." || entry === "..") continue;
|
|
478
|
+
const full = `${dir}/${entry}`;
|
|
479
|
+
const info = FS.stat(full);
|
|
480
|
+
if (FS.isDir(info.mode)) {
|
|
481
|
+
listEmscriptenCache(FS, full, out);
|
|
482
|
+
} else if (!EMSCRIPTEN_CACHE_SKIP.has(entry)) {
|
|
483
|
+
out.set(full, `${info.size}:${info.mtime?.getTime?.() ?? info.mtime}`);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return out;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async function listDiskTree(root, relative = "", out = []) {
|
|
490
|
+
let entries;
|
|
491
|
+
try {
|
|
492
|
+
entries = await readdir(path.join(root, relative), { withFileTypes: true });
|
|
493
|
+
} catch {
|
|
494
|
+
return out;
|
|
495
|
+
}
|
|
496
|
+
for (const entry of entries) {
|
|
497
|
+
const rel = relative ? path.posix.join(relative, entry.name) : entry.name;
|
|
498
|
+
if (entry.isDirectory()) {
|
|
499
|
+
await listDiskTree(root, rel, out);
|
|
500
|
+
} else if (entry.isFile() && !entry.name.includes(".tmp-")) {
|
|
501
|
+
out.push(rel);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return out;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
class PersistedEmscriptenCache {
|
|
508
|
+
#dir = null;
|
|
509
|
+
#known = new Map();
|
|
510
|
+
|
|
511
|
+
async restore(emception) {
|
|
512
|
+
if (emceptionCacheDisabled()) return;
|
|
513
|
+
try {
|
|
514
|
+
const identity = await getEmceptionCompileIdentity();
|
|
515
|
+
this.#dir = path.join(resolveCompileCacheRoot(), "emception-cache", identity.slice(0, 32));
|
|
516
|
+
const FS = emception.FS;
|
|
517
|
+
for (const relative of await listDiskTree(this.#dir)) {
|
|
518
|
+
const target = `${EMSCRIPTEN_CACHE_DIR}/${relative}`;
|
|
519
|
+
FS.mkdirTree(path.posix.dirname(target));
|
|
520
|
+
emception.writeFile(target, new Uint8Array(await readFile(path.join(this.#dir, relative))));
|
|
521
|
+
}
|
|
522
|
+
FS.mkdirTree(EMSCRIPTEN_CACHE_DIR);
|
|
523
|
+
this.#known = listEmscriptenCache(FS);
|
|
524
|
+
} catch {
|
|
525
|
+
// A cache that cannot be read only costs the rebuild it would have saved.
|
|
526
|
+
this.#dir = null;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
async persist(emception) {
|
|
531
|
+
if (!this.#dir) return;
|
|
532
|
+
try {
|
|
533
|
+
const current = listEmscriptenCache(emception.FS);
|
|
534
|
+
for (const [file, signature] of current) {
|
|
535
|
+
if (this.#known.get(file) === signature) continue;
|
|
536
|
+
const relative = file.slice(EMSCRIPTEN_CACHE_DIR.length + 1);
|
|
537
|
+
const target = path.join(this.#dir, ...relative.split("/"));
|
|
538
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
539
|
+
const temp = `${target}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
540
|
+
await writeFile(temp, new Uint8Array(emception.readFile(file)));
|
|
541
|
+
await rename(temp, target);
|
|
542
|
+
}
|
|
543
|
+
this.#known = current;
|
|
544
|
+
} catch {
|
|
545
|
+
// Best effort: the next process regenerates what is missing.
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
445
550
|
class EmceptionController {
|
|
446
551
|
#instancePromise = null;
|
|
447
552
|
#executionQueue = Promise.resolve();
|
|
553
|
+
#persistedCache = new PersistedEmscriptenCache();
|
|
448
554
|
|
|
449
555
|
async load() {
|
|
450
556
|
if (!this.#instancePromise) {
|
|
@@ -457,6 +563,7 @@ class EmceptionController {
|
|
|
457
563
|
baseUrl: pathToFileURL(`${patchedRoot}${path.sep}`).href,
|
|
458
564
|
});
|
|
459
565
|
await emception.init();
|
|
566
|
+
await this.#persistedCache.restore(emception);
|
|
460
567
|
return emception;
|
|
461
568
|
})().catch((error) => {
|
|
462
569
|
this.#instancePromise = null;
|
|
@@ -481,7 +588,17 @@ class EmceptionController {
|
|
|
481
588
|
}
|
|
482
589
|
throw error;
|
|
483
590
|
});
|
|
484
|
-
|
|
591
|
+
// Emception's tools are Emscripten programs, and an Emscripten program
|
|
592
|
+
// that exits non-zero sets process.exitCode. A failed compile inside a
|
|
593
|
+
// build that handles the error would otherwise make the whole process
|
|
594
|
+
// exit 1; the caller sees the failure as the thrown error instead.
|
|
595
|
+
const exitCode = process.exitCode;
|
|
596
|
+
try {
|
|
597
|
+
return await task(emception);
|
|
598
|
+
} finally {
|
|
599
|
+
process.exitCode = exitCode;
|
|
600
|
+
await this.#persistedCache.persist(emception);
|
|
601
|
+
}
|
|
485
602
|
} finally {
|
|
486
603
|
release();
|
|
487
604
|
}
|
|
@@ -490,6 +607,15 @@ class EmceptionController {
|
|
|
490
607
|
|
|
491
608
|
const sharedEmceptionController = new EmceptionController();
|
|
492
609
|
|
|
610
|
+
/**
|
|
611
|
+
* The compile-cache identity of the vendored emception: the sdn-emception
|
|
612
|
+
* package (version and a stat of every file it ships) and the patch this
|
|
613
|
+
* module applies to it.
|
|
614
|
+
*/
|
|
615
|
+
export function getEmceptionCompileIdentity() {
|
|
616
|
+
return getEmceptionPackageIdentity(`${PATCH_VERSION}\0${patchEmceptionModuleSource.toString()}`);
|
|
617
|
+
}
|
|
618
|
+
|
|
493
619
|
export function getSharedEmceptionController() {
|
|
494
620
|
return sharedEmceptionController;
|
|
495
621
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// The on-disk guest-link layout a flow links (src/flow/flowCompiler.js reads it):
|
|
2
|
+
//
|
|
3
|
+
// <dir>/module-link.o the prefixed guest-link object
|
|
4
|
+
// <dir>/metadata.json format, language, threadModel, symbolPrefix, methodSymbols
|
|
5
|
+
// (+ libraries, below)
|
|
6
|
+
// <dir>/libraries/<name>-<version>-<sha12>.o
|
|
7
|
+
// each shared library object the module links
|
|
8
|
+
// (compile option `libraries`), listed in
|
|
9
|
+
// metadata.libraries as { name, version, language,
|
|
10
|
+
// namespace, sha256, file }
|
|
11
|
+
//
|
|
12
|
+
// metadata.version is 1 without libraries (the layout module build scripts have
|
|
13
|
+
// always written) and 2 with them: a flow compiler that does not link library
|
|
14
|
+
// objects must not take such a module.
|
|
15
|
+
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Write a compilation's guest-link object, its library objects and
|
|
21
|
+
* metadata.json into `dir` (usually `<package>/dist/guest-link`). `metadata`
|
|
22
|
+
* adds fields to metadata.json. Returns the metadata written.
|
|
23
|
+
*/
|
|
24
|
+
export async function writeGuestLinkFiles(compilation, dir, metadata = {}) {
|
|
25
|
+
const guestLink = compilation?.guestLink;
|
|
26
|
+
if (!guestLink?.objectBytes?.length) {
|
|
27
|
+
throw new Error("writeGuestLinkFiles needs a compilation with a guest-link object.");
|
|
28
|
+
}
|
|
29
|
+
await mkdir(dir, { recursive: true });
|
|
30
|
+
await writeFile(path.join(dir, "module-link.o"), guestLink.objectBytes);
|
|
31
|
+
const libraries = Array.isArray(guestLink.libraries) ? guestLink.libraries : [];
|
|
32
|
+
const librariesDir = path.join(dir, "libraries");
|
|
33
|
+
await rm(librariesDir, { recursive: true, force: true });
|
|
34
|
+
const libraryEntries = [];
|
|
35
|
+
for (const library of libraries) {
|
|
36
|
+
const file = `libraries/${library.name}-${library.version}-${library.sha256.slice(0, 12)}.o`;
|
|
37
|
+
await mkdir(librariesDir, { recursive: true });
|
|
38
|
+
await writeFile(path.join(dir, file), library.objectBytes);
|
|
39
|
+
libraryEntries.push({
|
|
40
|
+
name: library.name,
|
|
41
|
+
version: library.version,
|
|
42
|
+
language: library.language,
|
|
43
|
+
namespace: library.namespace,
|
|
44
|
+
sha256: library.sha256,
|
|
45
|
+
file,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const written = {
|
|
49
|
+
version: libraryEntries.length > 0 ? 2 : 1,
|
|
50
|
+
format: guestLink.format,
|
|
51
|
+
language: guestLink.language,
|
|
52
|
+
threadModel: guestLink.threadModel,
|
|
53
|
+
symbolPrefix: guestLink.symbolPrefix,
|
|
54
|
+
methodSymbols: guestLink.methodSymbols,
|
|
55
|
+
...(libraryEntries.length > 0 ? { libraries: libraryEntries } : {}),
|
|
56
|
+
...metadata,
|
|
57
|
+
};
|
|
58
|
+
await writeFile(path.join(dir, "metadata.json"), `${JSON.stringify(written, null, 2)}\n`);
|
|
59
|
+
return written;
|
|
60
|
+
}
|
package/src/compiler/index.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export type {
|
|
2
2
|
CompilationResult,
|
|
3
|
+
CompileCacheReport,
|
|
3
4
|
GuestLinkArtifact,
|
|
5
|
+
GuestLinkLibrary,
|
|
6
|
+
ModuleLibrarySource,
|
|
4
7
|
ModuleThreadModelName,
|
|
5
8
|
ProtectedArtifact,
|
|
6
9
|
} from "../index.js";
|
|
@@ -9,7 +12,11 @@ export {
|
|
|
9
12
|
cleanupCompilation,
|
|
10
13
|
compileModuleFromSource,
|
|
11
14
|
createRecipientKeypairHex,
|
|
15
|
+
deriveGuestLinkObject,
|
|
12
16
|
ModuleThreadModel,
|
|
17
|
+
pruneCompileCache,
|
|
18
|
+
resolveCompileCacheRoot,
|
|
19
|
+
writeGuestLinkFiles,
|
|
13
20
|
protectModuleArtifact,
|
|
14
21
|
getFlatbuffersCppRuntimeHeaders,
|
|
15
22
|
getInvokeCppSchemaHeaders,
|
package/src/compiler/index.js
CHANGED
|
@@ -2,6 +2,7 @@ export {
|
|
|
2
2
|
cleanupCompilation,
|
|
3
3
|
compileModuleFromSource,
|
|
4
4
|
createRecipientKeypairHex,
|
|
5
|
+
deriveGuestLinkObject,
|
|
5
6
|
ModuleThreadModel,
|
|
6
7
|
protectModuleArtifact,
|
|
7
8
|
} from "./compileModule.js";
|
|
@@ -17,6 +18,12 @@ export {
|
|
|
17
18
|
} from "./pthreadArtifactGuard.js";
|
|
18
19
|
|
|
19
20
|
export { resolveWasiThreadsToolchain } from "./wasiThreadsToolchain.js";
|
|
21
|
+
export { writeGuestLinkFiles } from "./guestLinkFiles.js";
|
|
22
|
+
|
|
23
|
+
export {
|
|
24
|
+
pruneCompileCache,
|
|
25
|
+
resolveCompileCacheRoot,
|
|
26
|
+
} from "./compileCache.js";
|
|
20
27
|
|
|
21
28
|
export {
|
|
22
29
|
getFlatbuffersCppRuntimeHeaders,
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
// Symbol-table reading and renaming for relocatable wasm objects (the `.o` files
|
|
2
|
+
// clang/wasm-ld exchange: a "linking" custom section with a symbol table and
|
|
3
|
+
// "reloc.*" sections that refer to symbols by INDEX).
|
|
4
|
+
//
|
|
5
|
+
// Renaming a symbol is therefore a rewrite of its name in the symbol table and
|
|
6
|
+
// nothing else: every relocation, init function, comdat and segment record
|
|
7
|
+
// refers to the symbol by its index, and none of those indices change. This is
|
|
8
|
+
// what lets the guest-link object (module-link.o) be derived from the one
|
|
9
|
+
// module.o compile instead of compiling the source a second time with a
|
|
10
|
+
// `-Dname=prefix_name` per symbol.
|
|
11
|
+
//
|
|
12
|
+
// The one place a name lives outside the symbol table is an undefined function,
|
|
13
|
+
// global, tag or table symbol without WASM_SYM_EXPLICIT_NAME: its name is the
|
|
14
|
+
// import's field name, so renaming it rewrites that import entry.
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
decodeUnsignedLeb128,
|
|
18
|
+
encodeUnsignedLeb128,
|
|
19
|
+
parseWasmModuleSections,
|
|
20
|
+
} from "../bundle/wasm.js";
|
|
21
|
+
|
|
22
|
+
export const WASM_SYM_BINDING_WEAK = 0x01;
|
|
23
|
+
export const WASM_SYM_BINDING_LOCAL = 0x02;
|
|
24
|
+
export const WASM_SYM_UNDEFINED = 0x10;
|
|
25
|
+
export const WASM_SYM_EXPLICIT_NAME = 0x40;
|
|
26
|
+
|
|
27
|
+
export const WasmSymbolKind = Object.freeze({
|
|
28
|
+
FUNCTION: 0,
|
|
29
|
+
DATA: 1,
|
|
30
|
+
GLOBAL: 2,
|
|
31
|
+
SECTION: 3,
|
|
32
|
+
EVENT: 4,
|
|
33
|
+
TABLE: 5,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const LINKING_SYMBOL_TABLE_SUBSECTION_ID = 8;
|
|
37
|
+
const IMPORT_SECTION_ID = 2;
|
|
38
|
+
const IMPORT_KIND_FUNCTION = 0;
|
|
39
|
+
const IMPORT_KIND_TABLE = 1;
|
|
40
|
+
const IMPORT_KIND_MEMORY = 2;
|
|
41
|
+
const IMPORT_KIND_GLOBAL = 3;
|
|
42
|
+
const IMPORT_KIND_TAG = 4;
|
|
43
|
+
|
|
44
|
+
const textDecoder = new TextDecoder();
|
|
45
|
+
const textEncoder = new TextEncoder();
|
|
46
|
+
|
|
47
|
+
function readName(bytes, offset) {
|
|
48
|
+
const lengthInfo = decodeUnsignedLeb128(bytes, offset);
|
|
49
|
+
const start = lengthInfo.nextOffset;
|
|
50
|
+
const end = start + lengthInfo.value;
|
|
51
|
+
if (end > bytes.length) {
|
|
52
|
+
throw new Error("WASM name extends past the end of its section.");
|
|
53
|
+
}
|
|
54
|
+
return { value: textDecoder.decode(bytes.subarray(start, end)), start: offset, end };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function encodeName(name) {
|
|
58
|
+
const nameBytes = textEncoder.encode(name);
|
|
59
|
+
return concatBytes([encodeUnsignedLeb128(nameBytes.length), nameBytes]);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function concatBytes(parts) {
|
|
63
|
+
let total = 0;
|
|
64
|
+
for (const part of parts) total += part.length;
|
|
65
|
+
const out = new Uint8Array(total);
|
|
66
|
+
let offset = 0;
|
|
67
|
+
for (const part of parts) {
|
|
68
|
+
out.set(part, offset);
|
|
69
|
+
offset += part.length;
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// LLVM writes section and subsection sizes as 5-byte padded LEB128s so it can
|
|
75
|
+
// patch them after the fact. A rewritten size keeps the width it had (when the
|
|
76
|
+
// new value fits), so a rename changes nothing but the names.
|
|
77
|
+
function encodeLebAtWidth(value, width) {
|
|
78
|
+
const minimal = encodeUnsignedLeb128(value);
|
|
79
|
+
if (!width || minimal.length >= width) return minimal;
|
|
80
|
+
const out = new Uint8Array(width);
|
|
81
|
+
let remaining = value;
|
|
82
|
+
for (let index = 0; index < width; index += 1) {
|
|
83
|
+
const byte = remaining & 0x7f;
|
|
84
|
+
remaining = Math.floor(remaining / 128);
|
|
85
|
+
out[index] = index < width - 1 ? byte | 0x80 : byte;
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function encodeSection(id, payload, sizeWidth = 0) {
|
|
91
|
+
return concatBytes([Uint8Array.of(id), encodeLebAtWidth(payload.length, sizeWidth), payload]);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function sizeWidthOf(section) {
|
|
95
|
+
return section.payloadStart - section.start - 1;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function findLinkingSection(parsed) {
|
|
99
|
+
const linking = parsed.sections.find((section) => section.id === 0 && section.name === "linking");
|
|
100
|
+
if (!linking) {
|
|
101
|
+
throw new Error("Wasm object is missing its linking custom section.");
|
|
102
|
+
}
|
|
103
|
+
return linking;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// The symbol table of one object, with each entry's byte span inside the
|
|
107
|
+
// linking section's data and the span of its name (null when the name is the
|
|
108
|
+
// import's field name).
|
|
109
|
+
function readSymbolTable(objectBytes) {
|
|
110
|
+
const parsed = parseWasmModuleSections(objectBytes);
|
|
111
|
+
const linking = findLinkingSection(parsed);
|
|
112
|
+
const payload = linking.dataBytes;
|
|
113
|
+
let offset = decodeUnsignedLeb128(payload, 0).nextOffset; // linking metadata version
|
|
114
|
+
while (offset < payload.length) {
|
|
115
|
+
const subsectionId = payload[offset];
|
|
116
|
+
const sizeInfo = decodeUnsignedLeb128(payload, offset + 1);
|
|
117
|
+
const contentStart = sizeInfo.nextOffset;
|
|
118
|
+
const contentEnd = contentStart + sizeInfo.value;
|
|
119
|
+
if (contentEnd > payload.length) {
|
|
120
|
+
throw new Error("Linking subsection extends past the end of its section.");
|
|
121
|
+
}
|
|
122
|
+
if (subsectionId !== LINKING_SYMBOL_TABLE_SUBSECTION_ID) {
|
|
123
|
+
offset = contentEnd;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const countInfo = decodeUnsignedLeb128(payload, contentStart);
|
|
127
|
+
let cursor = countInfo.nextOffset;
|
|
128
|
+
const symbols = [];
|
|
129
|
+
for (let index = 0; index < countInfo.value; index += 1) {
|
|
130
|
+
const start = cursor;
|
|
131
|
+
const kind = payload[cursor++];
|
|
132
|
+
const flagsInfo = decodeUnsignedLeb128(payload, cursor);
|
|
133
|
+
const flags = flagsInfo.value;
|
|
134
|
+
cursor = flagsInfo.nextOffset;
|
|
135
|
+
const symbol = { index, kind, flags, start, end: 0, name: "", nameSpan: null, elementIndex: null };
|
|
136
|
+
if (
|
|
137
|
+
kind === WasmSymbolKind.FUNCTION ||
|
|
138
|
+
kind === WasmSymbolKind.GLOBAL ||
|
|
139
|
+
kind === WasmSymbolKind.EVENT ||
|
|
140
|
+
kind === WasmSymbolKind.TABLE
|
|
141
|
+
) {
|
|
142
|
+
const elementInfo = decodeUnsignedLeb128(payload, cursor);
|
|
143
|
+
symbol.elementIndex = elementInfo.value;
|
|
144
|
+
cursor = elementInfo.nextOffset;
|
|
145
|
+
if ((flags & WASM_SYM_UNDEFINED) === 0 || (flags & WASM_SYM_EXPLICIT_NAME) !== 0) {
|
|
146
|
+
const name = readName(payload, cursor);
|
|
147
|
+
symbol.name = name.value;
|
|
148
|
+
symbol.nameSpan = [name.start, name.end];
|
|
149
|
+
cursor = name.end;
|
|
150
|
+
}
|
|
151
|
+
} else if (kind === WasmSymbolKind.DATA) {
|
|
152
|
+
const name = readName(payload, cursor);
|
|
153
|
+
symbol.name = name.value;
|
|
154
|
+
symbol.nameSpan = [name.start, name.end];
|
|
155
|
+
cursor = name.end;
|
|
156
|
+
if ((flags & WASM_SYM_UNDEFINED) === 0) {
|
|
157
|
+
cursor = decodeUnsignedLeb128(payload, cursor).nextOffset; // segment index
|
|
158
|
+
cursor = decodeUnsignedLeb128(payload, cursor).nextOffset; // offset
|
|
159
|
+
cursor = decodeUnsignedLeb128(payload, cursor).nextOffset; // size
|
|
160
|
+
}
|
|
161
|
+
} else if (kind === WasmSymbolKind.SECTION) {
|
|
162
|
+
symbol.elementIndex = decodeUnsignedLeb128(payload, cursor).value;
|
|
163
|
+
cursor = decodeUnsignedLeb128(payload, cursor).nextOffset;
|
|
164
|
+
} else {
|
|
165
|
+
throw new Error(`Unsupported wasm linking symbol kind ${kind}.`);
|
|
166
|
+
}
|
|
167
|
+
symbol.end = cursor;
|
|
168
|
+
symbols.push(symbol);
|
|
169
|
+
}
|
|
170
|
+
if (cursor !== contentEnd) {
|
|
171
|
+
throw new Error("Wasm symbol table did not end at its subsection boundary.");
|
|
172
|
+
}
|
|
173
|
+
return {
|
|
174
|
+
parsed,
|
|
175
|
+
linking,
|
|
176
|
+
payload,
|
|
177
|
+
symbols,
|
|
178
|
+
subsectionStart: offset,
|
|
179
|
+
contentStart,
|
|
180
|
+
contentEnd,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
throw new Error("Wasm object is missing its symbol table subsection.");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// The import entries of a module, each with the span of its field name and the
|
|
187
|
+
// index it has within its kind (the "element index" a symbol refers to).
|
|
188
|
+
function readImports(sectionPayload) {
|
|
189
|
+
const countInfo = decodeUnsignedLeb128(sectionPayload, 0);
|
|
190
|
+
let cursor = countInfo.nextOffset;
|
|
191
|
+
const imports = [];
|
|
192
|
+
const perKind = new Map();
|
|
193
|
+
const readLimits = () => {
|
|
194
|
+
const flags = sectionPayload[cursor++];
|
|
195
|
+
cursor = decodeUnsignedLeb128(sectionPayload, cursor).nextOffset;
|
|
196
|
+
if (flags & 0x01) cursor = decodeUnsignedLeb128(sectionPayload, cursor).nextOffset;
|
|
197
|
+
if (flags & 0x08) cursor = decodeUnsignedLeb128(sectionPayload, cursor).nextOffset;
|
|
198
|
+
};
|
|
199
|
+
for (let index = 0; index < countInfo.value; index += 1) {
|
|
200
|
+
const moduleName = readName(sectionPayload, cursor);
|
|
201
|
+
cursor = moduleName.end;
|
|
202
|
+
const field = readName(sectionPayload, cursor);
|
|
203
|
+
cursor = field.end;
|
|
204
|
+
const kind = sectionPayload[cursor++];
|
|
205
|
+
if (kind === IMPORT_KIND_FUNCTION) {
|
|
206
|
+
cursor = decodeUnsignedLeb128(sectionPayload, cursor).nextOffset;
|
|
207
|
+
} else if (kind === IMPORT_KIND_TABLE) {
|
|
208
|
+
const refType = sectionPayload[cursor++];
|
|
209
|
+
if (refType === 0x63 || refType === 0x64) {
|
|
210
|
+
throw new Error("Typed-reference table imports are not supported by the wasm object renamer.");
|
|
211
|
+
}
|
|
212
|
+
readLimits();
|
|
213
|
+
} else if (kind === IMPORT_KIND_MEMORY) {
|
|
214
|
+
readLimits();
|
|
215
|
+
} else if (kind === IMPORT_KIND_GLOBAL) {
|
|
216
|
+
const valueType = sectionPayload[cursor++];
|
|
217
|
+
if (valueType === 0x63 || valueType === 0x64) {
|
|
218
|
+
throw new Error("Typed-reference global imports are not supported by the wasm object renamer.");
|
|
219
|
+
}
|
|
220
|
+
cursor += 1; // mutability
|
|
221
|
+
} else if (kind === IMPORT_KIND_TAG) {
|
|
222
|
+
cursor += 1; // attribute
|
|
223
|
+
cursor = decodeUnsignedLeb128(sectionPayload, cursor).nextOffset;
|
|
224
|
+
} else {
|
|
225
|
+
throw new Error(`Unsupported wasm import kind ${kind}.`);
|
|
226
|
+
}
|
|
227
|
+
const kindIndex = perKind.get(kind) ?? 0;
|
|
228
|
+
perKind.set(kind, kindIndex + 1);
|
|
229
|
+
imports.push({ kind, kindIndex, field: field.value, fieldSpan: [field.start, field.end] });
|
|
230
|
+
}
|
|
231
|
+
return imports;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const SYMBOL_KIND_TO_IMPORT_KIND = new Map([
|
|
235
|
+
[WasmSymbolKind.FUNCTION, IMPORT_KIND_FUNCTION],
|
|
236
|
+
[WasmSymbolKind.GLOBAL, IMPORT_KIND_GLOBAL],
|
|
237
|
+
[WasmSymbolKind.EVENT, IMPORT_KIND_TAG],
|
|
238
|
+
[WasmSymbolKind.TABLE, IMPORT_KIND_TABLE],
|
|
239
|
+
]);
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Every symbol of a relocatable wasm object: { index, kind, flags, name,
|
|
243
|
+
* defined, local, weak }. An undefined symbol named by its import carries the
|
|
244
|
+
* import's field name.
|
|
245
|
+
*/
|
|
246
|
+
export function listWasmObjectSymbols(objectBytes) {
|
|
247
|
+
const table = readSymbolTable(objectBytes);
|
|
248
|
+
let imports = null;
|
|
249
|
+
return table.symbols.map((symbol) => {
|
|
250
|
+
let name = symbol.name;
|
|
251
|
+
if (symbol.nameSpan === null && symbol.kind !== WasmSymbolKind.SECTION) {
|
|
252
|
+
imports ??= readImportsOf(table.parsed);
|
|
253
|
+
name = importFor(imports, symbol)?.field ?? "";
|
|
254
|
+
}
|
|
255
|
+
return {
|
|
256
|
+
index: symbol.index,
|
|
257
|
+
kind: symbol.kind,
|
|
258
|
+
flags: symbol.flags,
|
|
259
|
+
name,
|
|
260
|
+
defined: (symbol.flags & WASM_SYM_UNDEFINED) === 0,
|
|
261
|
+
local: (symbol.flags & WASM_SYM_BINDING_LOCAL) !== 0,
|
|
262
|
+
weak: (symbol.flags & WASM_SYM_BINDING_WEAK) !== 0,
|
|
263
|
+
};
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function readImportsOf(parsed) {
|
|
268
|
+
const section = parsed.sections.find((entry) => entry.id === IMPORT_SECTION_ID);
|
|
269
|
+
if (!section) return [];
|
|
270
|
+
return readImports(parsed.bytes.subarray(section.payloadStart, section.payloadEnd));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function importFor(imports, symbol) {
|
|
274
|
+
const importKind = SYMBOL_KIND_TO_IMPORT_KIND.get(symbol.kind);
|
|
275
|
+
return imports.find((entry) => entry.kind === importKind && entry.kindIndex === symbol.elementIndex) ?? null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function spliceNames(bytes, edits) {
|
|
279
|
+
// edits: [{ span: [start, end], name }], non-overlapping.
|
|
280
|
+
const sorted = [...edits].sort((a, b) => a.span[0] - b.span[0]);
|
|
281
|
+
const parts = [];
|
|
282
|
+
let cursor = 0;
|
|
283
|
+
for (const edit of sorted) {
|
|
284
|
+
parts.push(bytes.subarray(cursor, edit.span[0]), encodeName(edit.name));
|
|
285
|
+
cursor = edit.span[1];
|
|
286
|
+
}
|
|
287
|
+
parts.push(bytes.subarray(cursor));
|
|
288
|
+
return concatBytes(parts);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Rename symbols of a relocatable wasm object. `renames` maps an old symbol
|
|
293
|
+
* name to its new name; every symbol carrying an old name is renamed (its
|
|
294
|
+
* definition and, through the shared symbol index, every reference to it in
|
|
295
|
+
* the object), or with `{ undefinedOnly: true }` only the undefined ones.
|
|
296
|
+
* Returns new object bytes; the input is not modified. Everything other than
|
|
297
|
+
* the names is preserved byte for byte.
|
|
298
|
+
*/
|
|
299
|
+
export function renameWasmObjectSymbols(objectBytes, renames, options = {}) {
|
|
300
|
+
const map = renames instanceof Map ? renames : new Map(Object.entries(renames ?? {}));
|
|
301
|
+
// `undefinedOnly: true` renames references (undefined symbols) and leaves
|
|
302
|
+
// definitions alone: how a module object is pointed at a library object's
|
|
303
|
+
// namespaced definitions.
|
|
304
|
+
const undefinedOnly = options.undefinedOnly === true;
|
|
305
|
+
if (map.size === 0) {
|
|
306
|
+
return new Uint8Array(objectBytes);
|
|
307
|
+
}
|
|
308
|
+
const table = readSymbolTable(objectBytes);
|
|
309
|
+
const symbolEdits = [];
|
|
310
|
+
const importEdits = [];
|
|
311
|
+
let imports = null;
|
|
312
|
+
for (const symbol of table.symbols) {
|
|
313
|
+
if (symbol.kind === WasmSymbolKind.SECTION) continue;
|
|
314
|
+
if (undefinedOnly && (symbol.flags & WASM_SYM_UNDEFINED) === 0) continue;
|
|
315
|
+
if (symbol.nameSpan !== null) {
|
|
316
|
+
const next = map.get(symbol.name);
|
|
317
|
+
if (next !== undefined && next !== symbol.name) {
|
|
318
|
+
symbolEdits.push({ span: symbol.nameSpan, name: next });
|
|
319
|
+
}
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
imports ??= readImportsOf(table.parsed);
|
|
323
|
+
const entry = importFor(imports, symbol);
|
|
324
|
+
const next = entry ? map.get(entry.field) : undefined;
|
|
325
|
+
if (entry && next !== undefined && next !== entry.field) {
|
|
326
|
+
importEdits.push({ span: entry.fieldSpan, name: next });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (symbolEdits.length === 0 && importEdits.length === 0) {
|
|
330
|
+
return new Uint8Array(objectBytes);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const { parsed, linking, payload } = table;
|
|
334
|
+
const sectionParts = [parsed.headerBytes];
|
|
335
|
+
for (const section of parsed.sections) {
|
|
336
|
+
if (section === linking && symbolEdits.length > 0) {
|
|
337
|
+
const tableContent = payload.subarray(table.contentStart, table.contentEnd);
|
|
338
|
+
const newContent = spliceNames(
|
|
339
|
+
tableContent,
|
|
340
|
+
symbolEdits.map((edit) => ({
|
|
341
|
+
span: [edit.span[0] - table.contentStart, edit.span[1] - table.contentStart],
|
|
342
|
+
name: edit.name,
|
|
343
|
+
})),
|
|
344
|
+
);
|
|
345
|
+
const newData = concatBytes([
|
|
346
|
+
payload.subarray(0, table.subsectionStart),
|
|
347
|
+
Uint8Array.of(LINKING_SYMBOL_TABLE_SUBSECTION_ID),
|
|
348
|
+
encodeLebAtWidth(newContent.length, table.contentStart - table.subsectionStart - 1),
|
|
349
|
+
newContent,
|
|
350
|
+
payload.subarray(table.contentEnd),
|
|
351
|
+
]);
|
|
352
|
+
sectionParts.push(
|
|
353
|
+
encodeSection(
|
|
354
|
+
0,
|
|
355
|
+
concatBytes([parsed.bytes.subarray(section.payloadStart, section.nameEnd), newData]),
|
|
356
|
+
sizeWidthOf(section),
|
|
357
|
+
),
|
|
358
|
+
);
|
|
359
|
+
} else if (section.id === IMPORT_SECTION_ID && importEdits.length > 0) {
|
|
360
|
+
const sectionPayload = parsed.bytes.subarray(section.payloadStart, section.payloadEnd);
|
|
361
|
+
sectionParts.push(
|
|
362
|
+
encodeSection(IMPORT_SECTION_ID, spliceNames(sectionPayload, importEdits), sizeWidthOf(section)),
|
|
363
|
+
);
|
|
364
|
+
} else {
|
|
365
|
+
sectionParts.push(section.rawBytes);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return concatBytes(sectionParts);
|
|
369
|
+
}
|