2025-12-14 11:59:50 +01:00
|
|
|
#!/bin/bash
|
|
|
|
|
# Apply asyncify transformation to KiCad WASM
|
|
|
|
|
#
|
|
|
|
|
# Usage: ./scripts/common/apply-asyncify.sh <input.wasm> <output.wasm>
|
|
|
|
|
#
|
|
|
|
|
# This script is called by docker/build.sh but can also be run standalone
|
|
|
|
|
# for debugging asyncify issues.
|
|
|
|
|
|
|
|
|
|
set -e
|
|
|
|
|
|
|
|
|
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
|
|
|
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
|
|
|
|
|
|
|
|
|
|
# Get wasm-opt path
|
|
|
|
|
WASM_OPT=$("${SCRIPT_DIR}/get-wasm-opt.sh")
|
|
|
|
|
|
2026-06-11 07:46:48 +02:00
|
|
|
# Bound Binaryen's host thread pool. wasm-opt runs function-parallel passes, and
|
|
|
|
|
# each worker holds the optimization working-set of one function at a time — so
|
|
|
|
|
# peak RAM scales with thread count. Binaryen reads BINARYEN_CORES to size the
|
|
|
|
|
# pool; default to 8 for memory-constrained dev machines, overridable via the
|
|
|
|
|
# environment (CI sets it to $(nproc) on the 128 GB Hetzner runner).
|
|
|
|
|
export BINARYEN_CORES="${BINARYEN_CORES:-8}"
|
|
|
|
|
|
|
|
|
|
# Preload a scalable allocator on Linux. wasm-opt churns a ~40 GB high-water mark
|
|
|
|
|
# of short-lived allocations across all worker threads; glibc malloc serializes
|
|
|
|
|
# concurrent alloc/free on per-arena locks, so under many threads ~half of every
|
|
|
|
|
# core's cycles collapse into futex lock-spin (strace: ~99% kernel time in futex)
|
|
|
|
|
# instead of optimization work — the more cores, the worse it gets. jemalloc and
|
|
|
|
|
# mimalloc are built for exactly this many-thread churn and eliminate the storm,
|
|
|
|
|
# roughly halving wall-clock. macOS already ships a scalable allocator
|
|
|
|
|
# (libmalloc/nano-zone), so only Linux needs this. Honor an externally-set
|
|
|
|
|
# WASM_OPT_PRELOAD; otherwise auto-detect a system jemalloc/mimalloc.
|
|
|
|
|
#
|
|
|
|
|
# WASM_OPT_PRELOAD=none (or 0) forces NO preload — a clean glibc baseline for
|
|
|
|
|
# benchmarking the allocator A/B (see scripts/bench/).
|
|
|
|
|
if [[ "${WASM_OPT_PRELOAD:-}" == "none" || "${WASM_OPT_PRELOAD:-}" == "0" ]]; then
|
|
|
|
|
WASM_OPT_PRELOAD=""
|
|
|
|
|
_PRELOAD_FORCED_OFF=1
|
|
|
|
|
fi
|
|
|
|
|
|
|
|
|
|
if [[ -z "${WASM_OPT_PRELOAD:-}" && -z "${_PRELOAD_FORCED_OFF:-}" && "$(uname -s)" == "Linux" ]]; then
|
|
|
|
|
for _alloc in \
|
|
|
|
|
"/usr/lib/$(uname -m)-linux-gnu/libjemalloc.so.2" \
|
|
|
|
|
"/usr/lib/$(uname -m)-linux-gnu/libmimalloc.so.2" \
|
|
|
|
|
/usr/lib/libjemalloc.so.2 \
|
|
|
|
|
/usr/lib/libmimalloc.so.2; do
|
|
|
|
|
if [[ -e "${_alloc}" ]]; then
|
|
|
|
|
WASM_OPT_PRELOAD="${_alloc}"
|
|
|
|
|
break
|
|
|
|
|
fi
|
|
|
|
|
done
|
|
|
|
|
fi
|
|
|
|
|
|
|
|
|
|
# Build the command prefix that injects the allocator (preserving any existing
|
|
|
|
|
# LD_PRELOAD). Empty when no scalable allocator was found — wasm-opt then runs
|
|
|
|
|
# under the default allocator, just slower.
|
|
|
|
|
if [[ -n "${WASM_OPT_PRELOAD:-}" ]]; then
|
|
|
|
|
PRELOAD_CMD=(env "LD_PRELOAD=${WASM_OPT_PRELOAD}${LD_PRELOAD:+:${LD_PRELOAD}}")
|
|
|
|
|
else
|
|
|
|
|
PRELOAD_CMD=()
|
|
|
|
|
fi
|
|
|
|
|
|
|
|
|
|
# Wrap wasm-opt in GNU `time -v` when available (Linux CI) so the log records
|
|
|
|
|
# peak RSS + wall-clock for each pass. macOS `time` lacks -v, so fall back to
|
|
|
|
|
# running wasm-opt directly there.
|
|
|
|
|
if /usr/bin/time -v true >/dev/null 2>&1; then
|
|
|
|
|
TIME_CMD=(/usr/bin/time -v)
|
|
|
|
|
else
|
|
|
|
|
TIME_CMD=()
|
|
|
|
|
fi
|
|
|
|
|
|
2025-12-14 11:59:50 +01:00
|
|
|
INPUT_WASM="${1:-output/pcbnew.wasm}"
|
|
|
|
|
OUTPUT_WASM="${2:-${INPUT_WASM}}"
|
|
|
|
|
|
|
|
|
|
if [ ! -f "${INPUT_WASM}" ]; then
|
|
|
|
|
echo "ERROR: Input file not found: ${INPUT_WASM}"
|
|
|
|
|
exit 1
|
|
|
|
|
fi
|
|
|
|
|
|
|
|
|
|
echo "Applying asyncify transformation..."
|
|
|
|
|
echo " Input: ${INPUT_WASM}"
|
|
|
|
|
echo " Output: ${OUTPUT_WASM}"
|
|
|
|
|
echo " Tool: ${WASM_OPT}"
|
|
|
|
|
|
|
|
|
|
# Asyncify import patterns (functions that trigger async suspension)
|
|
|
|
|
# - env.invoke_* : Exception handling trampolines
|
|
|
|
|
# - env.__asyncjs__* : EM_ASYNC_JS functions (like startModal())
|
wip: nested-asyncify fix, wxAuiToolBar registration, tests, research docs
Main-repo side of a multi-part WIP covering the KiCad WASM tool-selection
and nested-Asyncify work. Submodule commits are in kicad@f6e9239aaa
(libcontext hygiene) and wxwidgets@bb80f91e8b (auibar registration +
dialog diagnostics).
## scripts/common/inject-dyncall-shims.sh
Wrap Asyncify.handleSleep / allocateData to save-and-restore Asyncify.currData
around each EM_ASYNC_JS sleep. This fixes the nested Asyncify collision where
a fiber swap that fired during a modal's event loop clobbered currData, and
the modal's later doRewind used the fiber's buffer and hit "RuntimeError:
index out of bounds". Root cause documented as Emscripten Issue #9153
(wontfix upstream).
Diagnostic-rewind logging (forcedBottomOfCallStack, callStack traces) is
retained to help future debugging of Asyncify state corruption.
## tests/
- tests/playwright-kicad.config.ts: add `channel: 'chrome'` for the
chromium project so --project=chromium --headed uses system Chrome
(real GPU) instead of SwiftShader on ARM Mac. Also switch trace to
retain-on-failure + screenshot on-failure for easier E2E debugging.
- tests/kicad/pcbnew.spec.ts: replace `tool.checked` assertions with a
label-suffix check (`[checked]`) since our auibar registration encodes
checked state in the label (no schema change to the registry).
- tests/apps/Makefile.wasm: add `coroutine-nested` build target + include
it in the all: list.
- tests/apps/standalone/coroutine/: kicad_coroutine_harness.h + test app
reproducing KiCad COROUTINE semantics against real libcontext.
- tests/apps/standalone/coroutine-nested/: nested_test.cpp reproduces the
EM_ASYNC_JS-modal + fiber-swap nesting bug in isolation. 8 scenarios
from baseline_modal_alone through nested_fibers_inside_modal.
- tests/e2e/coroutine.spec.ts + coroutine-nested.spec.ts: Playwright specs
that load the standalone apps and assert all case cases pass via
[COROUTINE_TEST] SUMMARY log parsing.
## research/ and features/browser-tools/
Three background docs capturing the investigation trajectory:
- features/browser-tools/0001-kicad-wasm-tool-activation-investigation.md
Early investigation: why tools don't activate; initial dynCall-empty-
callback hypothesis.
- features/browser-tools/0002-wasm-coroutine-deep-dive.md
Deep dive on Asyncify internals, fiber API, QEMU's coroutine-wasm
reference implementation.
- features/browser-tools/0003-wxauitoolbar-registration-fix.md
The narrow fix: why wxAuiToolBar needs a registration block, where to
add it, what the fallback plan is.
- research/threading_1.md: corrected root-cause analysis after reading
runtime logs — nested-Asyncify currData collision, Emscripten #9153.
- research/threading_2.md: extended research on alternative approaches
(JSPI/WasmFX/state-machines) and why they don't help here.
## Submodule pointer updates
kicad: f6e9239aaa (wip: libcontext WASM hygiene cleanup)
wxwidgets: bb80f91e8b (wip: wxAuiToolBar element-registry registration +
dialog diagnostics)
## Open threads not yet in scope
- Firefox/Chrome divergent behavior: "indirect call signature mismatch"
traps in Firefox vs renderer crash in system Chrome (tracked in
plans/peaceful-hugging-pnueli.md and the research docs).
- E2E pixel-diff for Draw Lines fails because the test's diff region does
not cover where the line is actually drawn; tool activation works, the
line is visible in test-results/pcbnew-draw-lines-02-after-drawing.png.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 13:58:16 +02:00
|
|
|
ASYNCIFY_IMPORTS="env.invoke_*,env.__asyncjs__*,env.emscripten_fiber_swap"
|
2025-12-14 11:59:50 +01:00
|
|
|
|
|
|
|
|
# Functions to exclude from asyncify instrumentation
|
wip: nested-asyncify fix, wxAuiToolBar registration, tests, research docs
Main-repo side of a multi-part WIP covering the KiCad WASM tool-selection
and nested-Asyncify work. Submodule commits are in kicad@f6e9239aaa
(libcontext hygiene) and wxwidgets@bb80f91e8b (auibar registration +
dialog diagnostics).
## scripts/common/inject-dyncall-shims.sh
Wrap Asyncify.handleSleep / allocateData to save-and-restore Asyncify.currData
around each EM_ASYNC_JS sleep. This fixes the nested Asyncify collision where
a fiber swap that fired during a modal's event loop clobbered currData, and
the modal's later doRewind used the fiber's buffer and hit "RuntimeError:
index out of bounds". Root cause documented as Emscripten Issue #9153
(wontfix upstream).
Diagnostic-rewind logging (forcedBottomOfCallStack, callStack traces) is
retained to help future debugging of Asyncify state corruption.
## tests/
- tests/playwright-kicad.config.ts: add `channel: 'chrome'` for the
chromium project so --project=chromium --headed uses system Chrome
(real GPU) instead of SwiftShader on ARM Mac. Also switch trace to
retain-on-failure + screenshot on-failure for easier E2E debugging.
- tests/kicad/pcbnew.spec.ts: replace `tool.checked` assertions with a
label-suffix check (`[checked]`) since our auibar registration encodes
checked state in the label (no schema change to the registry).
- tests/apps/Makefile.wasm: add `coroutine-nested` build target + include
it in the all: list.
- tests/apps/standalone/coroutine/: kicad_coroutine_harness.h + test app
reproducing KiCad COROUTINE semantics against real libcontext.
- tests/apps/standalone/coroutine-nested/: nested_test.cpp reproduces the
EM_ASYNC_JS-modal + fiber-swap nesting bug in isolation. 8 scenarios
from baseline_modal_alone through nested_fibers_inside_modal.
- tests/e2e/coroutine.spec.ts + coroutine-nested.spec.ts: Playwright specs
that load the standalone apps and assert all case cases pass via
[COROUTINE_TEST] SUMMARY log parsing.
## research/ and features/browser-tools/
Three background docs capturing the investigation trajectory:
- features/browser-tools/0001-kicad-wasm-tool-activation-investigation.md
Early investigation: why tools don't activate; initial dynCall-empty-
callback hypothesis.
- features/browser-tools/0002-wasm-coroutine-deep-dive.md
Deep dive on Asyncify internals, fiber API, QEMU's coroutine-wasm
reference implementation.
- features/browser-tools/0003-wxauitoolbar-registration-fix.md
The narrow fix: why wxAuiToolBar needs a registration block, where to
add it, what the fallback plan is.
- research/threading_1.md: corrected root-cause analysis after reading
runtime logs — nested-Asyncify currData collision, Emscripten #9153.
- research/threading_2.md: extended research on alternative approaches
(JSPI/WasmFX/state-machines) and why they don't help here.
## Submodule pointer updates
kicad: f6e9239aaa (wip: libcontext WASM hygiene cleanup)
wxwidgets: bb80f91e8b (wip: wxAuiToolBar element-registry registration +
dialog diagnostics)
## Open threads not yet in scope
- Firefox/Chrome divergent behavior: "indirect call signature mismatch"
traps in Firefox vs renderer crash in system Chrome (tracked in
plans/peaceful-hugging-pnueli.md and the research docs).
- E2E pixel-diff for Draw Lines fails because the test's diff region does
not cover where the line is actually drawn; tool activation works, the
line is visible in test-results/pcbnew-draw-lines-02-after-drawing.png.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 13:58:16 +02:00
|
|
|
# These are large functions that inflate beyond V8's local-count limits.
|
2025-12-14 11:59:50 +01:00
|
|
|
ASYNCIFY_REMOVE=$(cat << 'REMOVELIST'
|
|
|
|
|
COLOR_SETTINGS::COLOR_SETTINGS(wxString const&, bool)
|
|
|
|
|
BuildBitmapInfo(std::__2::unordered_map<BITMAPS, std::__2::vector<BITMAP_INFO, std::__2::allocator<BITMAP_INFO>>, std::__2::hash<BITMAPS>, std::__2::equal_to<BITMAPS>, std::__2::allocator<std::__2::pair<BITMAPS const, std::__2::vector<BITMAP_INFO, std::__2::allocator<BITMAP_INFO>>>>>&)
|
|
|
|
|
match
|
2025-12-22 16:30:53 +01:00
|
|
|
DIALOG_PAD_PROPERTIES_BASE::DIALOG_PAD_PROPERTIES_BASE(wxWindow*, int, wxString const&, wxPoint const&, wxSize const&, long)
|
|
|
|
|
buildKicadAboutBanner(EDA_BASE_FRAME*, ABOUT_APP_INFO&)
|
|
|
|
|
IGESToBRep_CurveAndSurface::TransferGeometry(opencascade::handle<IGESData_IGESEntity> const&, Message_ProgressRange const&)
|
|
|
|
|
StepAP214_Protocol::StepAP214_Protocol()
|
|
|
|
|
BRepCheck_ParallelAnalyzer::operator()(int) const
|
|
|
|
|
ShapeFix_Wire::FixGap3d(int, bool)
|
|
|
|
|
ShapeFix_Wire::FixGap2d(int, bool)
|
2026-05-27 16:14:03 +02:00
|
|
|
PCB_EDIT_FRAME::setupUIConditions()
|
2025-12-14 11:59:50 +01:00
|
|
|
REMOVELIST
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
ASYNCIFY_REMOVE_ARG=$(echo "${ASYNCIFY_REMOVE}" | tr '\n' ',' | sed 's/,$//')
|
|
|
|
|
|
|
|
|
|
echo ""
|
|
|
|
|
echo "Running wasm-opt --asyncify..."
|
|
|
|
|
echo "This may take several minutes and use significant RAM..."
|
2026-06-11 07:46:48 +02:00
|
|
|
echo " BINARYEN_CORES=${BINARYEN_CORES}"
|
|
|
|
|
echo " LD_PRELOAD=${WASM_OPT_PRELOAD:-<none>}"
|
2025-12-14 11:59:50 +01:00
|
|
|
|
2026-06-11 07:46:48 +02:00
|
|
|
"${PRELOAD_CMD[@]}" "${TIME_CMD[@]}" "${WASM_OPT}" --asyncify \
|
2025-12-14 11:59:50 +01:00
|
|
|
"--pass-arg=asyncify-imports@${ASYNCIFY_IMPORTS}" \
|
|
|
|
|
"--pass-arg=asyncify-removelist@${ASYNCIFY_REMOVE_ARG}" \
|
|
|
|
|
--pass-arg=asyncify-propagate-addlist \
|
|
|
|
|
"${INPUT_WASM}" -o "${OUTPUT_WASM}"
|
|
|
|
|
|
2026-06-11 07:46:48 +02:00
|
|
|
# ASYNCIFY_ONLY=1 stops after the asyncify pass (skips -O2). Used by the
|
|
|
|
|
# benchmark harness (scripts/bench/) to time/compare just the asyncify pass,
|
|
|
|
|
# whose RAM fits where the -O2 pass on the bloated module would not.
|
|
|
|
|
if [[ "${ASYNCIFY_ONLY:-0}" == "1" ]]; then
|
|
|
|
|
echo ""
|
|
|
|
|
echo "ASYNCIFY_ONLY=1 → skipping -O2 pass (benchmark mode)."
|
|
|
|
|
ls -lh "${OUTPUT_WASM}"
|
|
|
|
|
exit 0
|
|
|
|
|
fi
|
|
|
|
|
|
2026-06-16 12:55:01 +02:00
|
|
|
# Post-asyncify shrink pass. Asyncify emits deliberately verbose instrumentation
|
|
|
|
|
# (spills every live local) and relies on the optimizer to coalesce it back down
|
|
|
|
|
# under V8's per-function locals limit — without it, large coroutine-entry
|
|
|
|
|
# functions silently stall (and on newer Chromium hard-crash the renderer while
|
|
|
|
|
# loading a heavy board) in Chrome's V8. See docs/debugging/DEBUG.md §6-7.
|
|
|
|
|
#
|
|
|
|
|
# Level is configurable via BINARYEN_OPT_LEVEL: -O1 already runs CoalesceLocals
|
|
|
|
|
# and is sufficient (measured: same ~187 MB / 64 MB-gzip output as -O2 on pcbnew,
|
|
|
|
|
# validated green on the load-pcb chromium-ci spec — but a lighter, faster pass,
|
|
|
|
|
# which is why CI sets -O1). -O2 stays the default for the more thorough rewrite.
|
|
|
|
|
# Do NOT use -Os/-Oz here: they break the asyncify runtime (Binaryen #4484).
|
|
|
|
|
BINARYEN_OPT_LEVEL="${BINARYEN_OPT_LEVEL:--O2}"
|
|
|
|
|
|
2025-12-14 11:59:50 +01:00
|
|
|
echo ""
|
2026-06-16 12:55:01 +02:00
|
|
|
echo "Running wasm-opt ${BINARYEN_OPT_LEVEL} on the asyncified wasm..."
|
2026-05-28 13:52:49 +02:00
|
|
|
echo " Purpose: shrink asyncify-instrumented functions back under V8's"
|
|
|
|
|
echo " per-function locals limit (otherwise large coroutine-entry and"
|
2026-06-16 12:55:01 +02:00
|
|
|
echo " similar functions stall/crash in Chrome's V8). See docs/debugging/DEBUG.md §6-7."
|
|
|
|
|
echo " This pass takes several minutes and ~10-15 GB RAM."
|
2026-06-11 07:46:48 +02:00
|
|
|
echo " BINARYEN_CORES=${BINARYEN_CORES}"
|
|
|
|
|
echo " LD_PRELOAD=${WASM_OPT_PRELOAD:-<none>}"
|
2026-05-28 13:52:49 +02:00
|
|
|
|
2026-06-16 12:55:01 +02:00
|
|
|
"${PRELOAD_CMD[@]}" "${TIME_CMD[@]}" "${WASM_OPT}" "${BINARYEN_OPT_LEVEL}" "${OUTPUT_WASM}" -o "${OUTPUT_WASM}"
|
2026-05-28 13:52:49 +02:00
|
|
|
|
|
|
|
|
echo ""
|
2026-06-16 12:55:01 +02:00
|
|
|
echo "Asyncify + ${BINARYEN_OPT_LEVEL} complete: ${OUTPUT_WASM}"
|
2025-12-14 11:59:50 +01:00
|
|
|
ls -lh "${OUTPUT_WASM}"
|