Skip to content

Read exported global mutability from the side module binary - #28006

Open
rustyconover wants to merge 7 commits into
emscripten-core:mainfrom
rustyconover:dylink-global-mutability
Open

rustyconover wants to merge 7 commits into
emscripten-core:mainfrom
rustyconover:dylink-global-mutability

Conversation

@rustyconover

@rustyconover rustyconover commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

dlopen gets slower with every data symbol a side module exports. relocateExports passes each exported global to isImmutableGlobal, 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 -O2 and loaded with dlopen from a MAIN_MODULE=2 program. Each build was timed in 15 fresh Node processes, interleaved, on aarch64 (Graviton) EC2. Medians, IQR in brackets:

main this PR
dlopen 50.2 ms [49.1–52.1] 43.3 ms [41.1–44.7]

That'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

getDylinkMetadata already 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. relocateExports uses 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 isImmutableGlobal in three cases:

  • At -Oz (SHRINK_LEVEL == 2), the parser is omitted to avoid its code-size cost. -Os retains it.

  • Only a WebAssembly.Module is available, with no bytes. This happens for preloaded modules, and for workers started after the dlopen, which get the module from sharedModules. Threads that are already running when the dlopen happens load from the bytes that dynlink.c keeps in file_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 by test/emsdk_version.txt:

Codesize test JS change gzipped JS change
codesize.test_codesize_hello_dylink +815 bytes +366 bytes
codesize.test_codesize_hello_dylink_all +822 bytes not measured

Builds without dynamic linking do not change.

Testing

other.test_dlopen_exported_globals checks that immutable data addresses are relocated, mutable globals remain writable, and the parsed set contains side_data but not side_global. Its -Oz variant 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 by test/emsdk_version.txt. The dylink/dlfcn/dlopen/dlsym/main_module/side_module selectors across core0, core2, corez, wasm64, core_2gb and other completed successfully: 932 tests, 39 skipped. All 65 codesize tests passed with regenerated expectations, and Ruff and ESLint passed.

@sbc100 sbc100 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread src/lib/libdylink.js Outdated
$relocateExports__deps: ['$isImmutableGlobal'],
$relocateExports: (exports, memoryBase = 0) => {
$relocateExports__docs: '/** @param {Set<string>=} mutableGlobals */',
$relocateExports: (exports, memoryBase = 0, mutableGlobals) => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having non-default argument after the default ones looks odd to me. Can we make mutableGlobals the second argument?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/lib/libdylink.js Outdated
// which are relative to `memoryBase`. `mutableGlobals`, when known,
// saves probing each global.
var immutable = mutableGlobals
? value instanceof WebAssembly.Global && !mutableGlobals.has(name)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need value instanceof WebAssembly.Global here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should flip mutableGlobals to immutableGlobals then? That way this change can just be var immutable = immutableGlobals.has(name)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/lib/libdylink.js Outdated
// 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() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@rustyconover

Copy link
Copy Markdown
Contributor Author

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/

@rustyconover
rustyconover force-pushed the dylink-global-mutability branch from 005a883 to 9d2a5fb Compare October 19, 2026 19:03
@rustyconover

Copy link
Copy Markdown
Contributor Author

Agreed on js-types: Global.prototype.type() would give us mutable directly, and once it ships we could feature-detect it and skip the parser.

On size: after rebasing on main, this adds 808 bytes of JS (336 gzipped) to test_codesize_hello_dylink, against 30–60 ms saved per extension load in Chrome for DuckDB-WASM. I'm happy to put the parser behind SHRINK_LEVEL. I'd suggest leaving it out only at -Oz (SHRINK_LEVEL == 2) and keeping it at -Os, since -Os users of dynamic linking probably still care about dlopen time. Let me know which you'd prefer and I'll add it.

@rustyconover
rustyconover force-pushed the dylink-global-mutability branch 2 times, most recently from 5a2a209 to 1757e77 Compare October 24, 2026 17:41
@rustyconover

Copy link
Copy Markdown
Contributor Author

@sbc100 I've put the parser behind SHRINK_LEVEL in 5bcf0e6. At -Oz (SHRINK_LEVEL == 2) the parser is left out and relocateExports falls back to probing each global with isImmutableGlobal, as before. -Os keeps the parser, since dynamic-linking users there likely still care about dlopen time. If you'd rather drop it at -Os too, that's a one-line change.

test_dlopen_exported_globals now has an -Oz variant that checks the fallback path. The corez, core0, core2 and wasm64 dylink suites and the other dlopen tests all pass.

The section-reader refactor is still planned as a follow-up, unless you'd like it done in this PR.

Comment thread src/lib/libdylink.js
if (!isModule) {
customSection.immutableGlobals = getImmutableGlobals();
}
#endif

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this move up to line 553 and be an else { block?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread test/test_other.py
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')));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/lib/libdylink.js
else if (kind === 3) { skipValType(); mutable.push(getU8() & 1); } // global
else if (kind === 4) { getU8(); getLEB(); } // tag
else return;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this block? i.e. aren't we only interested in defined + exported globals here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ..."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/lib/libdylink.js Outdated
// `immutableGlobals`, when known, saves probing each global.
var immutable = immutableGlobals
? immutableGlobals.has(name)
: isImmutableGlobal(value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you write this as var immutable = immutableGlobals?.has(name) ?? isImmutableGlobal(value);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: this now uses immutableGlobals?.has(name) ?? isImmutableGlobal(value). Both test_dlopen_exported_globals and its -Oz fallback variant pass.

Comment thread src/lib/libdylink.js
// 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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add something like "Note: This can be removed if we ever get https://github.com/WebAssembly/js-types"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the note and the js-types link above the parser.

@sbc100

sbc100 commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Can you propose a final commit message to use for this PR?

rustyconover and others added 7 commits November 4, 2026 10:18
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>
@rustyconover
rustyconover force-pushed the dylink-global-mutability branch from 93d7551 to f89548c Compare November 4, 2026 15:44
@rustyconover

Copy link
Copy Markdown
Contributor Author

@sbc100 Suggested final commit message:

[dylink] Read immutable exported globals from side-module bytes

Record immutable exported globals while parsing dylink metadata and use
them during relocation, avoiding exception-based mutability probes.
Keep probing for precompiled modules, unsupported constant expressions
and -Oz builds, where the parser is omitted to avoid its code-size cost.

Test relocation of immutable data addresses, mutation of exported
mutable globals, and the size-optimized fallback.

The three remaining inline requests are addressed, and the branch is rebased on 45c7d098d. The broader section-reader refactor remains proposed as a follow-up, as discussed above.

Validated on aarch64 Linux with Node 24.19.0 and SDK 811a854f017d74e02a40aaf3a25532a50d32482c, as pinned by test/emsdk_version.txt. The dylink/dlfcn/dlopen/dlsym/main_module/side_module selectors across core0, core2, corez, wasm64, core_2gb and other completed successfully: 932 tests, 39 skipped. All 65 codesize tests passed with regenerated expectations, and Ruff and ESLint passed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants