Skip to content

[dylink] Don't walk the main module's table in pthread workers - #28105

Open
clementperon wants to merge 10 commits into
emscripten-core:mainfrom
clementperon:dylink-worker-export-slots
Open

clementperon wants to merge 10 commits into
emscripten-core:mainfrom
clementperon:dylink-worker-export-slots

Conversation

@clementperon

@clementperon clementperon commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

The first call to getFunctionAddress walks the whole table and keeps a JS function object for every entry. With MAIN_MODULE and pthreads, every worker makes that call when it instantiates the main module (updateGOT), so each worker holds a wrapper for every address-taken function of the main module for its whole lifetime.

The dynamic linker only looks up the main module's exported functions. So the main thread now records their table slots, and passes them to workers in the load message next to sharedModules. Right before updateGOT, a worker creates functionsInTableMap with just those slots. At that point the table only holds the main module. Side modules add their own slots when they are loaded, as before.

Both halves are in one function, initFunctionsInTableMap in libdylink.js. addFunction and getFunctionAddress are unchanged.

Impact

Kodi's WebAssembly port links Kodi as MAIN_MODULE=2 so binary add-ons can be dlopened. Its table has 50,476 slots, and 76 of its exported functions are in the table.

Measured in headless Chrome 157 with Emscripten 7.0.0 and with this change applied to 7.0.0. The wasm is byte-identical in both builds; only the JS differs. Kodi sits on its home screen with 11 to 13 workers, three runs each:

7.0.0 7.0.0 + this change
JS heap per idle worker, after GC 12.0–12.6 MiB 4.4–5.0 MiB
JS heap of the main thread, after GC 13.8 MiB 13.8 MiB
Resident memory of the renderer process 880–904 MiB 769–798 MiB

For reference, the same app linked without MAIN_MODULE has 3.0–3.7 MiB of JS heap per worker.

An earlier revision of this change, applied to the Emscripten 6.0.9 glue, took the 17 workers Kodi has during playback from 257 MiB to 117 MiB of JS heap.

Behavior

Lookups by the dynamic linker in workers return the same slots as before. A function that appears in several slots still resolves to its last slot, as the walk did.

The difference is a non-exported main-module function passed to addFunction in a worker. JS can only reach such a function through the table itself (for example with getWasmTableEntry), so it already has its address. Before, the walk found its existing slot. Now, the worker gives it a new slot at the end of its own table.

That makes the worker's table differ from the other threads' tables. If another thread later loads a library, the library's functions get the same indices, and in that worker a pointer to one of them calls the function that was added instead. I checked this with a small program: after the dlopen, the worker's call through the side module's pointer ran the main-module function.

This is not a new failure mode. Emscripten 7.0.0 without this change does the same for any function that a worker adds with addFunction before another thread calls dlopen, for example a JS callback: in the same program, the side module's pointer then called the JS callback. This PR moves one more case into it: re-adding a function that is already in the table but not exported.

Keeping the old result for that case would need the full walk this PR removes. With ASSERTIONS=2, addFunction reports it ("function in Table but not functionsInTableMap"). The limitation is noted in a comment on initFunctionsInTableMap and in the ChangeLog entry.

The main thread still walks the table once. #27993 creates the main module's GOT entries lazily and doesn't change the walk, so the two changes are independent.

Testing

test_pthread_dylink now asserts that a side module sees the same &bar_main as the main module, on the main thread and in a worker. That assertion fails if workers don't add the recorded slots.

Run locally on this revision, with the LLVM of the 7.0.0 release: all test_pthread_dl*, test_pthread_dylink* and test_pthread_tls_dylink tests in core0, core2 and wasm64, and other.test_dylink_pthread*. 56 pass and 2 are skipped by the test suite itself (wasm64.test_pthread_dlopen_many, other.test_dylink_pthread_comdat). I did not run the codesize tests locally; the Codesize check on this PR passes.

No test checks that workers skip the walk.

🤖 Generated with Claude Code

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes worker initialization in pthreads builds with MAIN_MODULE by passing only the table slots of the main module's exported functions to workers, rather than having them walk the entire function table. Feedback suggests adding a defensive check in src/lib/libaddfunction.js to ensure getWasmTableEntry(slot) returns a valid object before adding it to the WeakMap, preventing potential runtime crashes in workers.

Comment thread src/lib/libaddfunction.js Resolved
@clementperon

Copy link
Copy Markdown
Contributor Author

@sbc100 is this something you want to merge upstream ?

@sbc100

sbc100 commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Mostly likely yes, I'm just a little review constrained right now.

I'll try to get to it.

@clementperon

Copy link
Copy Markdown
Contributor Author

Thank you, take your time and don't hesitate if you want me to perform more test.

Comment thread src/lib/libaddfunction.js Resolved
@clementperon
clementperon force-pushed the dylink-worker-export-slots branch 3 times, most recently from 509af0f to 12b8416 Compare November 3, 2026 10:19
clementperon and others added 5 commits November 8, 2026 11:24
The first call to getFunctionAddress walks the whole table, which creates a
JS function object for every entry.  With MAIN_MODULE and pthreads, every
worker does this when it instantiates the main module, and keeps those
objects for its lifetime: about 8 MiB per worker for a 50k-entry table.

The dynamic linker only looks up the main module's exported functions, so
the main thread now records their table slots and passes them to workers,
which add just those to the map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Note in getFunctionAddress and the ChangeLog that a non-exported
main-module function passed to addFunction in a worker now gets a new
slot. Add an ASSERTIONS=2 variant of test_pthread_dylink, whose
addFunction check catches export slots missing from a worker's map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Instead of special-casing workers in getFunctionAddress, fill their
functionsInTableMap with the main module's export slots right before
updateGOT.  At that point the table only holds the main module, and side
modules add their own slots when they are loaded, so workers no longer
need the main module's table size.  The main thread's recording and the
worker's seeding are now one function, initFunctionsInTableMap.

Drop the ASSERTIONS=2 variant of test_pthread_dylink: the &bar_main
assertion already fails if workers don't get the export slots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@clementperon
clementperon force-pushed the dylink-worker-export-slots branch from 12b8416 to 0b49138 Compare November 8, 2026 10:27
@clementperon

Copy link
Copy Markdown
Contributor Author

@sbc100 just to add more information I retest this PR on top of 7.0.0

addFunction(getWasmTableEntry(ptr)) in a worker on a non-exported main-module function allocates a new slot, and if another thread later dlopens a library, a side-module function pointer with that index calls the old function in that worker => not nice :(

But, the same happens today on 7.0.0 without this PR for any function a worker adds with addFunction before a dlopen on another thread, for example a JS callback: the table layouts diverge and the side module's pointer calls the callback. So the PR does not introduce a new failure mode; it moves one case (re-adding a function that is already in the table but not exported) into the existing one. ASSERTIONS=2 reports it.

Keeping the old result exactly needs the full walk in every worker, which is what costs 7–8 MiB of JS heap per worker in our app (12.3 → 4.7 MiB with 7.0.0). I can reword the ChangeLog entry to state the consequence precisely.

Would that be acceptable, or do you want workers to fall back to the walk on a miss from user code?

@sbc100

sbc100 commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

[@sbc100](https://github.com/sbc100) just to add more information I retest this PR on top of 7.0.0

addFunction(getWasmTableEntry(ptr)) in a worker on a non-exported main-module function allocates a new slot, and if another thread later dlopens a library, a side-module function pointer with that index calls the old function in that worker => not nice :(

But, the same happens today on 7.0.0 without this PR for any function a worker adds with addFunction before a dlopen on another thread, for example a JS callback: the table layouts diverge and the side module's pointer calls the callback. So the PR does not introduce a new failure mode; it moves one case (re-adding a function that is already in the table but not exported) into the existing one. ASSERTIONS=2 reports it.

Yes, directly calling addFunction in a multi-threaded program is not supported and never really has been, because we have no way to synchronize those table slots between workers.

We should probably have made this more clear.. I had thought there was an error message for such cases but maybe not?

Keeping the old result exactly needs the full walk in every worker, which is what costs 7–8 MiB of JS heap per worker in our app (12.3 → 4.7 MiB with 7.0.0). I can reword the ChangeLog entry to state the consequence precisely.

I'm not quite sure exactly that would look like. Perhaps you could draft that changelog entry here so we could see exactly what the semantic differences is that you are proposing .

Would that be acceptable, or do you want workers to fall back to the walk on a miss from user code?

@clementperon

Copy link
Copy Markdown
Contributor Author

On the error message: I did not find one.

AI: addFunction has no pthread check in libaddfunction.js, and the addFunction section of Interacting-with-code.rst does not mention threads. The dynamic linker itself calls addFunction in workers (updateGOT, reportUndefinedSymbols, dlsym), so a check would have to sit on the user-facing path only.

I can look at that in a separate PR if you want.

Here is the ChangeLog entry I propose:

 - In pthreads builds with `MAIN_MODULE`, workers no longer create a JS function
    object for every entry of the main module's function table at startup, which
    reduces the memory used by each worker.  As a result, `addFunction` in a
    worker no longer recognises main-module functions that are not exported.
    (#28105)

@sbc100

sbc100 commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

That sounds reasonable to me. I don't think direct calls to addFunction have every worked in multi-threaded programs. I think we should try to first land a error or warning when they are combined.

sbc100 pushed a commit that referenced this pull request Nov 20, 2026
Follow-up to the discussion in #28105: each thread has its own table, so
a function pointer returned by `addFunction` is only valid in the thread
that called it which break C/C++ semantics.

In builds with assertions and shared memory (pthreads or Wasm Workers),
`addFunction` now warns once when it has to add a function to the table.
clementperon and others added 2 commits November 20, 2026 21:48
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@clementperon

Copy link
Copy Markdown
Contributor Author

@sbc100 shorten the Changelog

@clementperon

Copy link
Copy Markdown
Contributor Author

@sbc100 if you have a bit of time to review 🙏

@sbc100 sbc100 changed the title Don't walk the main module's table in pthread workers [dylink] Don't walk the main module's table in pthread workers Dec 1, 2026
Comment thread src/lib/libdylink.js Resolved
Comment thread ChangeLog.md Resolved
Comment thread src/lib/libdylink.js Resolved

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

lgtm % nits

I like how clean this change is now.

- Assert that workers received mainModuleExportSlots instead of silently
  falling back to the full table walk.
- Reword the initFunctionsInTableMap comment.
- Drop the ChangeLog entry.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@clementperon

Copy link
Copy Markdown
Contributor Author

@sbc100 done, thanks for the review 👍

Comment thread src/lib/libdylink.js Resolved
Move the worker half of initFunctionsInTableMap into the lazy init in
getFunctionAddress, so the map is only created in one place, and rename
the remaining main-thread half to initMainModuleExportSlots.

Workers still seed the map during the main module's updateGOT, before any
side module is loaded.  Assert that when a side module is loaded.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Comment thread src/lib/libaddfunction.js Resolved
Comment thread src/lib/libaddfunction.js Outdated
for (var slot of mainModuleExportSlots) {
functionsInTableMap.set(getWasmTableEntry(slot), slot);
}
} else

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.

Hmm.. now I'm little worried we might not fully initialize the functionsInTableMap if this is called late (i.e. after one or more side modules are loaded).

Could that happen? Then the differed updateTableMap entries for the side module wouldn't make it into the final functionsInTableMap.

I guess there is some tension here between wanting to defer the creation of functionsInTableMap.. and this new optimization?

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.

AI review It can't happen today: in a worker, updateGOT calls getFunctionAddress right after the main module is instantiated, before any side module is loaded, and this commit asserts that in loadWebAssemblyModule. But it does depend on updateGOT staying eager (#27993 would change that).
That tension is why the previous revision created the map up front in workers. I'd rather go back to that and live with the duplicated new WeakMap().

  $initFunctionsInTableMap: (exports) => {
    if (!ENVIRONMENT_IS_PTHREAD) {
      mainModuleExportSlots = [];
      for (var value of Object.values(exports)) {
        var addr = typeof value == 'function' && getFunctionAddress(value);
        if (addr) {
          mainModuleExportSlots.push(addr);
        }
      }
    } else {
#if ASSERTIONS
      assert(mainModuleExportSlots);
#endif
      functionsInTableMap = new WeakMap();   // <- the duplicated line
      for (var slot of mainModuleExportSlots) {
        functionsInTableMap.set(getWasmTableEntry(slot), slot);
      }
    }
  }

Should i rollback to this version ?

This reverts commit 4ee63af.

The lazy version only works if the first getFunctionAddress call in a
worker happens before any side module is loaded, which depends on
updateGOT calling it right after the main module is instantiated.  Go
back to creating the map up front in workers, so that it does not depend
on that ordering.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@sbc100

sbc100 commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Can you come up with a final commit message here?

The full PR description I think is a little too much information for this. You can either post it here as a comment or update the commit message.

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