Repository navigation
Read exported global mutability from the side module binary - #28006
rustyconover wants to merge 7 commits into
Conversation
66bc16e to
005a883
Compare
sbc100
left a comment
There was a problem hiding this comment.
The fact that we need to do this type of thing is probably a good argument for a some kind of new/improve type-reflection proposal. https://github.com/WebAssembly/js-types is currently not making much progress. @stevenfontanella might be interesting in this.
I'm a little wary of adding this extra JS code. Maybe we could put it behind the SHRINK_LEVEL setting since its trading codesize for perf? Maybe its doesn't matter since dynamic linking is already fairly heavy weight?
| $relocateExports__deps: ['$isImmutableGlobal'], | ||
| $relocateExports: (exports, memoryBase = 0) => { | ||
| $relocateExports__docs: '/** @param {Set<string>=} mutableGlobals */', | ||
| $relocateExports: (exports, memoryBase = 0, mutableGlobals) => { |
There was a problem hiding this comment.
Having non-default argument after the default ones looks odd to me. Can we make mutableGlobals the second argument?
There was a problem hiding this comment.
Done in 9d2a5fb. Both callers pass memoryBase (this one and the TLS relocation in libpthread.js), so I dropped the = 0 default instead of moving mutableGlobals to second place, which would have made the libpthread.js call pass undefined.
| // which are relative to `memoryBase`. `mutableGlobals`, when known, | ||
| // saves probing each global. | ||
| var immutable = mutableGlobals | ||
| ? value instanceof WebAssembly.Global && !mutableGlobals.has(name) |
There was a problem hiding this comment.
Do we need value instanceof WebAssembly.Global here?
There was a problem hiding this comment.
Yes. exports also contains functions, memories and tables, while mutableGlobals only lists globals. Without the check, !mutableGlobals.has(name) would be true for a function export, and it would be relocated as if it were a data address. isImmutableGlobal makes the same instanceof check first.
There was a problem hiding this comment.
Maybe we should flip mutableGlobals to immutableGlobals then? That way this change can just be var immutable = immutableGlobals.has(name)
There was a problem hiding this comment.
Done in 8f3bc6d. relocateExports now just checks immutableGlobals.has(name) when the set is available, and still falls back to isImmutableGlobal at -Oz or if the parser bails. A global only counts as immutable if the parser actually saw it, so an unexpected index falls on the safe side. This is also 30 bytes smaller than before.
While you're in the dylink code, would you have time to look at #27993 (lazy GOT entries) and #28007 (freeing side module file data once all threads have loaded it)? Both are green and have been waiting about a week.
| // This saves relocateExports from probing each exported global with | ||
| // isImmutableGlobal, which throws for every immutable one. Returns | ||
| // undefined if it finds something it doesn't handle. | ||
| function getMutableGlobals() { |
There was a problem hiding this comment.
This function seems long enough that we should perhaps split it out into its own library function?
Also since it itself include more sub-functions.
But I guess since the subfunctions also close over other helper like getU8 we might need a bigger refactor here?
There was a problem hiding this comment.
It closes over getDylinkMetadata's reader (binary, offset, getU8, getLEB), so splitting it out means moving that reader out too. I'd rather do that as a follow-up that factors the section reader out of getDylinkMetadata, so this PR stays focused, but I'm happy to do it here if you prefer.
|
Real-world data point: the DuckDB spatial extension exports 1,286 symbols, and before this change each one threw and caught an exception during load to probe mutability. Measurements from the wider startup work: https://query.farm/blog/duckdb-wasm-startup-time/ |
005a883 to
9d2a5fb
Compare
|
Agreed on js-types: On size: after rebasing on main, this adds 808 bytes of JS (336 gzipped) to |
5a2a209 to
1757e77
Compare
|
@sbc100 I've put the parser behind
The section-reader refactor is still planned as a follow-up, unless you'd like it done in this PR. |
| if (!isModule) { | ||
| customSection.immutableGlobals = getImmutableGlobals(); | ||
| } | ||
| #endif |
There was a problem hiding this comment.
Can this move up to line 553 and be an else { block?
There was a problem hiding this comment.
Done in 93d7551. It now runs in the else branch: save offset, jump to end (the end of the dylink section, where the import/global/export sections follow), parse, then restore. That also let me drop the isModule variable, so the if (binary instanceof WebAssembly.Module) line is back to how it was on main. It costs 11 bytes (13 gzipped) in test_codesize_hello_dylink versus calling it after the subsection loop.
| EM_ASM({ | ||
| // Unless optimizing for size, the loader read the immutable globals | ||
| // from the binary, rather than falling back to probing each one. | ||
| var metadata = getDylinkMetadata(new Uint8Array(require('fs').readFileSync('libside.wasm'))); |
There was a problem hiding this comment.
I don't love these kind of tests there we peek inside the internals like this .. but I suppose its hard to test this in any other way, since its basically a perf improvment.
There was a problem hiding this comment.
Agreed, it's not ideal. Since the observable behavior is the same either way, checking the parsed set was the only way I found to catch the parser silently bailing out and falling back to probing.
| else if (kind === 3) { skipValType(); mutable.push(getU8() & 1); } // global | ||
| else if (kind === 4) { getU8(); getLEB(); } // tag | ||
| else return; | ||
| } |
There was a problem hiding this comment.
Do we need this block? i.e. aren't we only interested in defined + exported globals here?
There was a problem hiding this comment.
We do need to walk it, but only to count. wasm-ld only exports defined globals (calculateExports), but the export index is in the combined index space with imported globals first. In this test's side module, side_data is exported as global 4, after __memory_base, __table_base and two GOT.mem imports. Import entries vary in length, so we have to step through each one to count the globals. Their mutability doesn't matter. Pushing them onto the same mutable array is just the shortest way to keep the indices lined up.
There was a problem hiding this comment.
Ah yes, can you add a comment here. Something like: "We need to parse the import section, even though we really care about exported globals because ..."
There was a problem hiding this comment.
Added the comment explaining that export indices include imported globals before defined globals, so the import section must be parsed to keep the indices aligned.
| // `immutableGlobals`, when known, saves probing each global. | ||
| var immutable = immutableGlobals | ||
| ? immutableGlobals.has(name) | ||
| : isImmutableGlobal(value); |
There was a problem hiding this comment.
Can you write this as var immutable = immutableGlobals?.has(name) ?? isImmutableGlobal(value);
There was a problem hiding this comment.
Done: this now uses immutableGlobals?.has(name) ?? isImmutableGlobal(value). Both test_dlopen_exported_globals and its -Oz fallback variant pass.
| // the import, global and export sections that follow the dylink section. | ||
| // This saves relocateExports from probing each exported global with | ||
| // isImmutableGlobal, which throws for every immutable one. Returns | ||
| // undefined if it finds something it doesn't handle. |
There was a problem hiding this comment.
Can you add something like "Note: This can be removed if we ever get https://github.com/WebAssembly/js-types"
There was a problem hiding this comment.
Added the note and the js-types link above the parser.
|
Can you propose a final commit message to use for this PR? |
relocateExports used isImmutableGlobal on every exported global, which detects an immutable global by trying to write it and catching the exception. Side modules export each data symbol as an immutable global, so loading one throws and catches an exception per data export (over a thousand for some real libraries). getDylinkMetadata now also reads the import, global and export sections when it has the module bytes, and records which exported globals are mutable. relocateExports uses that instead of probing. When only a compiled WebAssembly.Module is available, or the sections contain something the parser doesn't handle, it falls back to isImmutableGlobal. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
At SHRINK_LEVEL 2 the loader now leaves out the parser and probes each exported global with isImmutableGlobal, as before, trading load time for code size. -Os keeps the parser. test_dlopen_exported_globals gains an -Oz variant covering the fallback. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
As suggested in review, this lets relocateExports check membership directly instead of also testing for WebAssembly.Global. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
As suggested in review, this drops the isModule variable. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
93d7551 to
f89548c
Compare
|
@sbc100 Suggested final commit message: The three remaining inline requests are addressed, and the branch is rebased on Validated on aarch64 Linux with Node 24.19.0 and SDK |
dlopengets slower with every data symbol a side module exports.relocateExportspasses each exported global toisImmutableGlobal, which tests for an immutable global by writing to it and catching the exception. Side modules export every data symbol as an immutable global, so loading one throws and catches an exception for each data export. This PR reads mutability from the module bytes instead, so nothing is thrown.Original benchmark
A side module with 2,000 exported data symbols (
int d0 = 0; ... int d1999 = 1999;), built at-O2and loaded withdlopenfrom aMAIN_MODULE=2program. Each build was timed in 15 fresh Node processes, interleaved, on aarch64 (Graviton) EC2. Medians, IQR in brackets:maindlopenThat's about 3.5 µs per exported global in Node. A throw costs more inside a browser worker that is running deep wasm stacks: 25–45 µs per global in Chrome. In DuckDB-wasm in Chrome, removing the probe cut 30–60 ms from loading an extension that has about 1,300 data exports.
Change
getDylinkMetadataalready parses the start of the binary. When it has the bytes, it now continues through the import, global and export sections and records which exported globals are immutable.relocateExportsuses that set instead of probing. The parse takes 0.1–3 ms even for modules with several thousand imports and exports.It falls back to
isImmutableGlobalin three cases:At
-Oz(SHRINK_LEVEL == 2), the parser is omitted to avoid its code-size cost.-Osretains it.Only a
WebAssembly.Moduleis available, with no bytes. This happens for preloaded modules, and for workers started after thedlopen, which get the module fromsharedModules. Threads that are already running when thedlopenhappens load from the bytes thatdynlink.ckeeps infile_data, so they take the fast path too.The parser finds something it doesn't handle, such as a constant expression outside i32/i64/f32/f64.const, global.get, ref.null, ref.func and the extended-const add/sub/mul.
Assuming that every side-module export is immutable would be smaller, but #25530 made exported mutable globals a supported case.
Size
After rebasing on
45c7d098d, measured with the SDK pinned bytest/emsdk_version.txt:codesize.test_codesize_hello_dylinkcodesize.test_codesize_hello_dylink_allBuilds without dynamic linking do not change.
Testing
other.test_dlopen_exported_globalschecks that immutable data addresses are relocated, mutable globals remain writable, and the parsed set containsside_databut notside_global. Its-Ozvariant checks that the parser is omitted and probing still produces the correct behavior.Validated on aarch64 Linux with Node 24.19.0 and SDK
811a854f017d74e02a40aaf3a25532a50d32482c, as pinned bytest/emsdk_version.txt. The dylink/dlfcn/dlopen/dlsym/main_module/side_module selectors acrosscore0,core2,corez,wasm64,core_2gbandothercompleted successfully: 932 tests, 39 skipped. All 65 codesize tests passed with regenerated expectations, and Ruff and ESLint passed.