Browse documentation

WebAssembly modules link with wasm-ld

Date: 2026-12-03 Area: build, apps Refines: ADR 0235, whose modules FreePascal's internal linker linked Related: ADR 0236, ADR 0238

Context

FreePascal's internal WebAssembly linker linked the wasm32-wasip1 modules of ADR 0235. It always writes a name section, 2.95 MB of GocciaRunner's 24.5 MB, and it links no C library: it stops at C constructors, so it cannot link ICU4C, which the playground needs before it runs scripts in the browser by default.

fpc-toolchain 3.3.1+12 ships LLVM's wasm-ld, from wasi-sdk 34, in every host archive's cross/bin, which the build's fpc.cfg names with -FD. Its patches make a program linked by wasm-ld start its heap at __heap_base, pass $linklib and -Fl on to wasm-ld, and add the RTL unit wasilibc, which puts wasi-libc's malloc on FreePascal's heap and runs C constructors.

Decision

  • build.pas links wasm32-wasip1 with wasm-ld. For FPC_TARGET_OS=wasip1 it passes -Xe, so FreePascal's external linker for WASI runs wasm-ld with the program's 8 MB stack (-z stack-size), and with --strip-all under --prod's -Xs. wasm-ld removes functions, data and imports nothing references.
  • A development build keeps names, not DWARF. wasm-ld refuses the symbols FreePascal writes for its DWARF sections (symbol type 6, SYMTAB_FPC_CUSTOM), which only its internal linker reads, so a wasm32-wasip1 build passes no -g option. A development build passes -Xs- instead, over fpc.cfg's -Xs, so it keeps wasm-ld's name section and a trap names its functions.
  • The stack comes first. wasm-ld puts the stack at the bottom of linear memory, below the static data, and the heap starts at __heap_base, after both.
  • wasilibc waits for the first C library. The modules link no C code yet, so no program uses the unit; the build that links ICU4C adds it.

Consequences

  • The --prod modules shrink (bytes; gzip -9, brotli -q 11):

    ModuleInternal linker (3.3.1+11)wasm-ld (3.3.1+12)
    GocciaRunner raw24,482,69614,822,543
    GocciaRunner gzip4,902,0293,258,492
    GocciaRunner brotli2,931,9792,086,155
    GocciaTestRunner raw23,743,77914,685,115
    GocciaTestRunner gzip4,767,2683,214,559
    GocciaTestRunner brotli2,866,3522,057,666
  • The modules import the 24 WASI functions they call. fd_filestat_set_times, path_filestat_set_times, path_remove_directory and random_get, which nothing calls, are no longer imported; the browser's WASI host still provides them.

  • A stack that overflows runs below address 0 and traps, where it ran into the static data before.

  • A development module has no line information, where the internal linker's carried DWARF, until FreePascal writes debug symbols wasm-ld reads; a --prod module has neither, as before it had only the name section.

  • Building a module needs the toolchain's wasm-ld, which install.sh and the fpc-toolchain action install with the host archive.