Skip to content

Commit 7d4cde4

Browse files
authored
Merge pull request #515 from thisisthepy/feat/175-wasm-shared-memory
wasm: post-link rewrite of Kotlin/Wasm's memory import to shared (SPEC T-7, #175 step 1)
2 parents 5aec7c5 + cdb903b commit 7d4cde4

9 files changed

Lines changed: 658 additions & 8 deletions

File tree

‎docs/SPEC.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1396,6 +1396,28 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
13961396
(root `build.gradle.kts`, the plugin build, `python-multiplatform/build.gradle.kts`, and the sed
13971397
form `libraryVersionSuffix=(.+)` in `maven-central.yml`, `desktop-release.yml`, `central-bundle.sh`,
13981398
`assemble-desktop-release.sh`), `GP/PublishedVersionTest.kt`; no release has used an empty suffix yet.
1399+
- **T-7** (#175 step 1) The Kotlin/Wasm module imports CPython's shared memory. Owner decision 2026-11-21, via
1400+
the leader (team report `pmp-binder.md`, "## Owner decision (2026-11-21, via the leader): #175 is back in
1401+
1.0"): "빌드 뒤에 .wasm을 고치기 >> 이걸로 가자", with the requirements relayed in that note: "the patch
1402+
is a small, tested binary rewrite of the import section only (a unit test on a fixture .wasm, and a check
1403+
that fails the build if the Kotlin output's memory section is not the shape the patch expects, so a Kotlin
1404+
upgrade that changes it is caught instead of silently mis-patched); keep it removable once Kotlin gains an
1405+
option". Kotlin/Wasm emits its memory import `intrinsics.memory` as non-shared with no maximum
1406+
(`WasmCompiledModuleFragment.createAndExportMemory`, checked 2026-11-14), which a shared memory cannot
1407+
satisfy (`LinkError`, #411's probe). So when the CPython runtime it is staged beside has a shared memory,
1408+
the build rewrites that one import of the linked `.wasm` to shared, minimum 0, maximum 65536 pages (the
1409+
wasm32 ceiling, so any runtime maximum fits); every other byte of the import section is copied, every
1410+
other section is copied unchanged, and the section's size is re-encoded (in its original width when it
1411+
fits). The limits grow by 3 bytes, so the module's later byte offsets move by 3 (4 when the size needs
1412+
one more byte), and the generated source map's offsets are moved with them. The check runs on every link whatever the runtime: the build fails unless
1413+
the module has exactly one memory, imported as `intrinsics.memory`, either in Kotlin's shape
1414+
(non-shared, minimum 0, no maximum) or in the rewritten shape; anything else (a defined memory, a second
1415+
memory, other limits, an import section that does not parse) fails with a message saying the rewrite may
1416+
no longer be needed. Applied in two places: the library's own `wasmJsNodeTest` / `wasmJsBrowserTest`
1417+
staging, and a consumer's `wasmJs*Webpack` through the Gradle plugin. Removing it, once Kotlin has an
1418+
option, is deleting `WasmSharedMemoryImport` and its two calls. `Status: draft` (unit tests on
1419+
hand-assembled modules, `GP/WasmSharedMemoryImportTest.kt`; no runtime with a shared memory is staged yet,
1420+
so the rewrite has not run on a real Kotlin link: that is #175 step 2).
13991421

14001422
## 8. Measurement
14011423

‎docs/platforms/free-threaded-wasm.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,9 +177,9 @@ Kotlin-side memory import).
177177
## Open: the Kotlin side (later steps of #175, not implemented)
178178

179179
- Kotlin/Wasm imports `intrinsics.memory` as non-shared (`min=0, max=none`); a shared
180-
memory cannot satisfy that import, so the library cannot instantiate this `python.wasm`
181-
until the import is marked shared with a maximum. That would revive the binary patch
182-
[`wasm-design.md`](wasm-design.md) calls obsolete.
180+
memory cannot satisfy that import. The owner chose a post-link rewrite of that import
181+
(2026-11-21, SPEC T-7, [`wasm-design.md`](wasm-design.md)); it is implemented and applies
182+
once this build is the staged runtime (#175 step 2).
183183
- Kotlin calls CPython on the JS thread that loaded the module (`noInitialRun`, no `main`),
184184
so `-sPROXY_TO_PTHREAD` does not apply there; a first `Thread.start()` from Kotlin relies on
185185
the pre-created worker pool.

‎docs/platforms/wasm-design.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ has a browser wasm target. `wasmWasi` is not a target (when last assessed it was
1717
| Decision | Choice | Why |
1818
|---|---|---|
1919
| How Kotlin reaches CPython | Raw Stable ABI symbols as `@WasmImport`s against the Emscripten module's own wasm exports, **no JS in the call path** | Preserves the exact object model (`NativePointer`, `PyObject`) of every other target; a high-level Pyodide-style JS API (`pyodide.runPython`, `PyProxy`) would replace the whole object model with `JsAny` wrappers and covers almost none of the ~330 C functions |
20-
| Memory | **One shared linear memory.** Kotlin imports Emscripten's `Module.wasmMemory` as its `intrinsics.memory` | Needs Kotlin ≥ 2.4.20-Beta2, whose `wasmJs` modules **import** `intrinsics.memory` (`min=0, max=none`). Releases up to 2.4.10 exported an unbounded memory, which Emscripten cannot import, the earlier plan to patch the `.wasm` memory section (and a YouTrack issue) is obsolete ([`../archive/wasm-youtrack-issue.md`](../archive/wasm-youtrack-issue.md)) |
20+
| Memory | **One linear memory, CPython's.** Kotlin imports Emscripten's `Module.wasmMemory` as its `intrinsics.memory` | Needs Kotlin ≥ 2.4.20-Beta2, whose `wasmJs` modules **import** `intrinsics.memory` (`min=0, max=none`); releases up to 2.4.10 exported an unbounded memory, which Emscripten cannot import ([`../archive/wasm-youtrack-issue.md`](../archive/wasm-youtrack-issue.md)). The free-threaded pthreads build's memory is **shared**, which that non-shared import cannot take, so the build rewrites the import after the link (SPEC T-7, below) |
2121
| Where CPython comes from | **Our own Emscripten build**, `python-multiplatform/scripts/wasm/build-cpython.sh`: CPython **3.14.2**, Emscripten **5.0.3**, matched to the `pyemscripten_2026_0` platform of PEP 783 | No distributor ships a `python.wasm` exporting `wasmExports,wasmMemory`. The version is deliberately not the 3.14.x pinned for native targets (`pythonVersion` in `gradle.properties`); see `docs/design/ecosystem.md` |
2222
| C shim / composition | **None** | The hops that composition amortised are gone; measured gain ≤ 2.9 ns per operation (below). It also removes a second build pipeline |
2323
| `EXPORTED_FUNCTIONS` list | **Not needed** | `-sMAIN_MODULE` is `LINKABLE`, so the whole Stable ABI is exported (all 310 C symbols `EmbedAPI.kt` declared at the time were found in the build's 8287 exports). The build adds `wasmExports,wasmMemory` to `-sEXPORTED_RUNTIME_METHODS`, which is not ABI-sensitive |
@@ -47,6 +47,17 @@ has a browser wasm target. `wasmWasi` is not a target (when last assessed it was
4747
`exports._start()`). An application must also declare the three `@WasmExport` trampolines itself,
4848
`@WasmExport` is honoured only in the compilation that produces the `.wasm` (`ProxyTypeExportNames`;
4949
generating that file from the Gradle plugin is not done).
50+
- **The memory import is rewritten to shared after the link (SPEC T-7, #175).** Owner decision
51+
2026-11-21, via the leader (team report `pmp-binder.md`, "## Owner decision (2026-11-21, via the
52+
leader): #175 is back in 1.0"): "빌드 뒤에 .wasm을 고치기 >> 이걸로 가자". Kotlin/Wasm hardcodes the
53+
import as non-shared with no maximum (`WasmCompiledModuleFragment.createAndExportMemory`, no compiler
54+
option, checked 2026-11-14), and #411's probe showed that import fails with `LinkError` against a
55+
shared memory while a shared import with a maximum links. `WasmSharedMemoryImport` (Gradle plugin)
56+
rewrites only that import's limits to shared, minimum 0, maximum 65536 pages, when the staged
57+
`python.wasm` has a shared memory; it runs from the same three places as the `.mjs` substitutions.
58+
The shape check runs on every link: a module whose memory is not exactly Kotlin's import (or the
59+
rewritten one) fails the build, so a Kotlin upgrade that changes it is caught. Removing it once Kotlin
60+
has an option is deleting that object and its calls.
5061
- **JSPI must not reach the embedding.** `cpython.mjs` deletes `WebAssembly.promising` /
5162
`WebAssembly.Suspending`; with JSPI live the first blocking syscall (`select.poll().poll(0)`, which
5263
`selectors.py` does at import) fails with `SuspendError` and surfaces as `RuntimeError: unreachable`.

‎python-multiplatform-gradle-plugin/src/main/kotlin/python/multiplatform/gradle/PythonBindingsPlugin.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -886,7 +886,7 @@ class PythonBindingsPlugin : Plugin<Project> {
886886
val syncedDir = project.rootProject.layout.buildDirectory.dir("wasm/packages/$modulePrefix/kotlin")
887887
val log = project.logger
888888
doFirst {
889-
patchWasmOutputForCPython(syncedDir.get().asFile, modulePrefix, log)
889+
patchWasmOutputForCPython(syncedDir.get().asFile, modulePrefix, log, runtimeDir = destination.get().asFile)
890890
}
891891
}
892892
}

‎python-multiplatform-gradle-plugin/src/main/kotlin/python/multiplatform/gradle/WasmBrowserRuntimeStaging.kt‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ abstract class StageWasmBrowserRuntimeTask : DefaultTask() {
9898
* @param dir the compile-sync output webpack reads, `build/wasm/packages/<name>/kotlin`.
9999
* @param modulePrefix the generated module basename, which is `<root project>-<project>`.
100100
*/
101-
internal fun patchWasmOutputForCPython(dir: File, modulePrefix: String, logger: Logger) {
101+
internal fun patchWasmOutputForCPython(dir: File, modulePrefix: String, logger: Logger, runtimeDir: File) {
102102
val importObject = dir.listFiles()?.firstOrNull { it.name.endsWith(".import-object.mjs") }
103103
?: throw GradleException("No *.import-object.mjs in $dir -- the Kotlin/Wasm output layout changed.")
104104
val text = importObject.readText()
@@ -129,6 +129,8 @@ internal fun patchWasmOutputForCPython(dir: File, modulePrefix: String, logger:
129129
)
130130
}
131131

132+
patchKotlinWasmMemoryImport(dir, modulePrefix, runtimeDir, logger)
133+
132134
val entry = dir.listFiles()
133135
?.firstOrNull {
134136
it.name.endsWith(".mjs") && !it.name.contains("import-object") &&
@@ -157,3 +159,27 @@ internal fun patchWasmOutputForCPython(dir: File, modulePrefix: String, logger:
157159
logger.lifecycle("Handed ${entry.name}'s wasm exports to cpython.mjs for upcall registration")
158160
}
159161
}
162+
163+
/**
164+
* SPEC T-7: checks the linked Kotlin/Wasm module `<modulePrefix>.wasm` in [dir] and, when the CPython
165+
* runtime in [runtimeDir] has a shared memory (the free-threaded pthreads build), rewrites its
166+
* `intrinsics.memory` import to shared (see [WasmSharedMemoryImport]). The check runs whatever the
167+
* runtime, so a Kotlin upgrade that changes the import fails the build before the runtime changes too.
168+
*/
169+
fun patchKotlinWasmMemoryImport(dir: File, modulePrefix: String, runtimeDir: File, logger: Logger) {
170+
// CPython's own python.wasm may sit in the same directory (the library's node test staging copies
171+
// it there), so the Kotlin module is the one .wasm named after the module.
172+
val candidates = dir.listFiles { f -> f.name.endsWith(".wasm") && f.name.startsWith(modulePrefix) && f.name != "python.wasm" }
173+
.orEmpty()
174+
val wasm = candidates.singleOrNull() ?: throw GradleException(
175+
"Expected one Kotlin/Wasm module $modulePrefix*.wasm in $dir, found ${candidates.map { it.name }} " +
176+
"-- the Kotlin/Wasm output layout changed (SPEC T-7).",
177+
)
178+
val python = File(runtimeDir, "python.wasm")
179+
val shared = python.isFile && WasmSharedMemoryImport.hasSharedMemory(python.readBytes()) == true
180+
try {
181+
logger.lifecycle(WasmSharedMemoryImport.applyTo(wasm, runtimeHasSharedMemory = shared))
182+
} catch (e: WasmSharedMemoryImport.ShapeException) {
183+
throw GradleException(e.message ?: "SPEC T-7", e)
184+
}
185+
}

0 commit comments

Comments
 (0)