From 2f980f71a85935ba4e5813eb48a90e7c9005681a Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 04:10:51 +0000 Subject: [PATCH 1/3] Grow the WASI compiler heap with bounded spare capacity --- Makefile | 1 + dev/frontend_source_sets.mk | 2 + dev/src/support/wasi_heap.cpp | 50 +++++++++++++++++++++++ scripts/export_student_repo.sh | 1 + scripts/tests/test_wasi_heap.py | 42 +++++++++++++++++++ scripts/tests/wasi_heap_host.cpp | 69 ++++++++++++++++++++++++++++++++ scripts/tests/wasi_heap_mock.h | 5 +++ 7 files changed, 170 insertions(+) create mode 100644 dev/src/support/wasi_heap.cpp create mode 100644 scripts/tests/test_wasi_heap.py create mode 100644 scripts/tests/wasi_heap_host.cpp create mode 100644 scripts/tests/wasi_heap_mock.h diff --git a/Makefile b/Makefile index e1102890e..7f1c1d96f 100644 --- a/Makefile +++ b/Makefile @@ -306,6 +306,7 @@ test-cells: # The harness unit tests: the comparison, the workers, the audits and the # export, each a self-contained python unittest file under scripts/tests. HARNESS_TESTS = \ + scripts/tests/test_wasi_heap.py \ scripts/tests/test_wasi_export.py \ scripts/tests/test_release_source.py \ scripts/tests/test_package_release.py \ diff --git a/dev/frontend_source_sets.mk b/dev/frontend_source_sets.mk index 932836ff9..d7f04eb81 100644 --- a/dev/frontend_source_sets.mk +++ b/dev/frontend_source_sets.mk @@ -82,6 +82,8 @@ FRONTEND_OBJ_BASENAMES_lowir2native += lowir/text_writer lowir/assembly_writer l # Object names use the shared UTF-8 decoder without the source lexer. FRONTEND_OBJ_BASENAMES_lowir2native += support/unicode/utf8 FRONTEND_OBJ_BASENAMES_cppgm += $(FRONTEND_PHASE_BASENAMES_wasm) +# Single-threaded WASI host heap; an empty translation unit on native hosts. +FRONTEND_OBJ_BASENAMES_cppgm += support/wasi_heap # Optional foreign producer library: typed LowIR -> optimizer -> native object. # No source frontend, text reader, command-line driver, or test batch runner. diff --git a/dev/src/support/wasi_heap.cpp b/dev/src/support/wasi_heap.cpp new file mode 100644 index 000000000..49466f827 --- /dev/null +++ b/dev/src/support/wasi_heap.cpp @@ -0,0 +1,50 @@ +#if defined(__wasi__) +#include +#include +#include + +// The compiler's WASI host is single-threaded. Keep its logical break separate +// from reserved memory: WebKit can copy the entire heap on each memory.grow. +extern "C" void* sbrk(intptr_t increment) +{ + static uintptr_t position; + const uintptr_t page = 65536; + if (!position) + position = __builtin_wasm_memory_size(0) * page; + if (!increment) + return reinterpret_cast(position); + if (increment < 0 || static_cast(increment) % page) + abort(); + const uintptr_t amount = static_cast(increment); + if (amount > UINTPTR_MAX - position) + { + errno = ENOMEM; + return reinterpret_cast(-1); + } + const uintptr_t needed = position + amount; + const uintptr_t pages = __builtin_wasm_memory_size(0); + const uint64_t available = static_cast(pages) * page; + if (needed > available) + { + const uintptr_t required = static_cast((needed - available + page - 1) / page); + uintptr_t extra = pages / 4; + if (extra < 1) + extra = 1; + if (extra > 256) + extra = 256; // Reserve at most 16 MiB beyond the requested break. + if (extra < required) + extra = required; + uintptr_t result = __builtin_wasm_memory_grow(0, extra); + if (result == UINTPTR_MAX && extra != required) + result = __builtin_wasm_memory_grow(0, required); + if (result == UINTPTR_MAX) + { + errno = ENOMEM; + return reinterpret_cast(-1); + } + } + const uintptr_t before = position; + position = needed; + return reinterpret_cast(before); +} +#endif diff --git a/scripts/export_student_repo.sh b/scripts/export_student_repo.sh index bbce37d28..2a2a2abe2 100755 --- a/scripts/export_student_repo.sh +++ b/scripts/export_student_repo.sh @@ -483,6 +483,7 @@ dev_support_files=( dev/src/support/not_implemented.h dev/src/support/testing/test_runner.cpp dev/src/support/tool_help_text.h + dev/src/support/wasi_heap.cpp ) copy_tracked_paths \ diff --git a/scripts/tests/test_wasi_heap.py b/scripts/tests/test_wasi_heap.py new file mode 100644 index 000000000..df0381861 --- /dev/null +++ b/scripts/tests/test_wasi_heap.py @@ -0,0 +1,42 @@ +"""Exercise the actual WASI heap policy with bounded, deterministic memory calls.""" +import os +from pathlib import Path +import shlex +import signal +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class WasiHeap(unittest.TestCase): + def test_contiguous_break_growth_budget_fallback_and_failures(self): + with tempfile.TemporaryDirectory() as directory: + executable = Path(directory) / 'wasi-heap' + object_file = Path(directory) / 'wasi-heap.o' + compiler = shlex.split(os.environ.get('CPPGM_HOST_CXX', 'c++')) + flags = ['-std=c++11', *shlex.split(os.environ.get('CPPGM_STDLIB_FLAGS', ''))] + subprocess.run([*compiler, *flags, '-D__wasi__', + '-Dsbrk=cppgm_test_sbrk', + '-D__builtin_wasm_memory_size=cppgm_test_memory_size', + '-D__builtin_wasm_memory_grow=cppgm_test_memory_grow', + '-include', str(ROOT / 'scripts/tests/wasi_heap_mock.h'), + '-c', str(ROOT / 'dev/src/support/wasi_heap.cpp'), '-o', str(object_file)], check=True) + subprocess.run([*compiler, *flags, str(ROOT / 'scripts/tests/wasi_heap_host.cpp'), + str(object_file), '-o', str(executable)], check=True) + for mode in ['growth', 'overflow']: + with self.subTest(mode=mode): + subprocess.run([str(executable), mode], check=True) + if os.name == 'posix': + import resource + def no_core(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + for mode in ['negative', 'unaligned']: + with self.subTest(mode=mode): + result = subprocess.run([str(executable), mode], preexec_fn=no_core, capture_output=True) + self.assertEqual(result.returncode, -signal.SIGABRT) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/tests/wasi_heap_host.cpp b/scripts/tests/wasi_heap_host.cpp new file mode 100644 index 000000000..5958fa8cb --- /dev/null +++ b/scripts/tests/wasi_heap_host.cpp @@ -0,0 +1,69 @@ +#include "wasi_heap_mock.h" + +#include +#include +#include +#include +#include + +extern "C" void* cppgm_test_sbrk(intptr_t); +namespace { +const uintptr_t page = 65536; +size_t capacity = 128, maximum = 65535; +std::vector requests; +} + +extern "C" size_t cppgm_test_memory_size(unsigned memory) +{ + assert(memory == 0); + return capacity; +} + +extern "C" size_t cppgm_test_memory_grow(unsigned memory, size_t delta) +{ + assert(memory == 0); + requests.push_back(delta); + if (delta > maximum - capacity) + return SIZE_MAX; + const size_t before = capacity; + capacity += delta; + return before; +} + +int main(int argc, char** argv) +{ + assert(argc == 2); + if (!strcmp(argv[1], "overflow")) + { + capacity = UINTPTR_MAX / page; + const void* before = cppgm_test_sbrk(0); + errno = 0; + assert(cppgm_test_sbrk(page) == reinterpret_cast(-1)); + assert(errno == ENOMEM && cppgm_test_sbrk(0) == before && requests.empty()); + return 0; + } + if (!strcmp(argv[1], "negative")) + cppgm_test_sbrk(-static_cast(page)); + if (!strcmp(argv[1], "unaligned")) + cppgm_test_sbrk(1); + assert(!strcmp(argv[1], "growth")); + uintptr_t next = capacity * page; + assert(reinterpret_cast(cppgm_test_sbrk(0)) == next && requests.empty()); + for (unsigned i = 0; i < 2048; ++i) + { + assert(reinterpret_cast(cppgm_test_sbrk(page)) == next); + next += page; + assert(reinterpret_cast(cppgm_test_sbrk(0)) == next); + assert(capacity * page >= next && capacity * page - next < 16 * 1024 * 1024); + } + assert(requests.size() < 32); // Each request must not copy the preceding heap. + maximum = capacity + 1; + const size_t count = requests.size(); + const uintptr_t amount = capacity * page - next + page; + assert(reinterpret_cast(cppgm_test_sbrk(amount)) == next); + assert(requests.size() == count + 2 && requests[count] > 1 && requests.back() == 1); + const void* before = cppgm_test_sbrk(0); + errno = 0; + assert(cppgm_test_sbrk(page) == reinterpret_cast(-1)); + assert(errno == ENOMEM && cppgm_test_sbrk(0) == before); +} diff --git a/scripts/tests/wasi_heap_mock.h b/scripts/tests/wasi_heap_mock.h new file mode 100644 index 000000000..1d3fc1077 --- /dev/null +++ b/scripts/tests/wasi_heap_mock.h @@ -0,0 +1,5 @@ +#pragma once +#include + +extern "C" size_t cppgm_test_memory_size(unsigned); +extern "C" size_t cppgm_test_memory_grow(unsigned, size_t); From f021c5fe4eb7917c91e67336a67ad694182ae764 Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 05:23:41 +0000 Subject: [PATCH 2/3] Expose WASI host state for reusable compiler processes --- dev/src/support/wasi_heap.cpp | 7 +++++++ scripts/experimental/wasi_inception.py | 18 ++++++++++++++++-- scripts/experimental/wasi_stack.S | 16 ++++++++++++++++ scripts/tests/wasi_heap_host.cpp | 3 +++ 4 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 scripts/experimental/wasi_stack.S diff --git a/dev/src/support/wasi_heap.cpp b/dev/src/support/wasi_heap.cpp index 49466f827..bfe6c9a5c 100644 --- a/dev/src/support/wasi_heap.cpp +++ b/dev/src/support/wasi_heap.cpp @@ -47,4 +47,11 @@ extern "C" void* sbrk(intptr_t increment) position = needed; return reinterpret_cast(before); } + +// Initialize the logical break before a host saves its pre-start memory image. +// Restoring that image then reuses reserved pages instead of leaking capacity. +extern "C" uintptr_t __cppgm_wasi_heap_break() +{ + return reinterpret_cast(sbrk(0)); +} #endif diff --git a/scripts/experimental/wasi_inception.py b/scripts/experimental/wasi_inception.py index 768948139..1e0802f3c 100644 --- a/scripts/experimental/wasi_inception.py +++ b/scripts/experimental/wasi_inception.py @@ -99,7 +99,15 @@ def prepare(args): for name in ['LICENSE', 'NOTICE']: shutil.copyfile(REPO / name, inputs / name) shutil.copyfile(HERE / "wasi_host.h", inputs / "wasi_host.h") + shutil.copyfile(HERE / "wasi_stack.S", inputs / "wasi_stack.S") tool_sources = source_sets(tools) + x86_sources = list(tool_sources["cppgm"]) + # These are supplied WASI command-host sources, shared by every exported + # tool. Native builds keep their owning frontend source sets unchanged. + for sources in tool_sources.values(): + if "dev/src/support/wasi_heap.cpp" not in sources: + sources.insert(-1, "dev/src/support/wasi_heap.cpp") + sources.insert(-1, "wasi_stack.S") sources = tool_sources["cppgm"] config = (REPO / "obj/generated/cppgm_builtin_host_config.h").read_text() paths = re.search(r"kStandardIncludePaths\[\] = \{(.*?)\};", config, re.S) @@ -159,11 +167,17 @@ def prepare(args): for name in runners: shutil.copyfile(HERE / name, package / name) manifest = {"schema": 1, "sources": sources, "flags": flags, - "link_flags": ["-Wl,-z,stack-size=8388608", "-lc-printscan-long-double"], "files": files, + "link_flags": ["-Wl,-z,stack-size=8388608", "-lc-printscan-long-double", + "--export=__cppgm_wasi_stack_pointer", + "--export=__cppgm_wasi_restore_stack_pointer", + "--export=__cppgm_wasi_heap_break"], "files": files, + "process_reset": {"stack_pointer": "__cppgm_wasi_stack_pointer", + "restore_stack_pointer": "__cppgm_wasi_restore_stack_pointer", + "heap_break": "__cppgm_wasi_heap_break"}, "x86_flags": ["--target=x86_64-linux-gnu", "-std=c++11", "-D_GNU_SOURCE", "-DCPPGM_TELEMETRY_ENABLED=0", "-nostdinc", "-Idev/src", "-Igenerated"] + [flag for name in x86_paths for flag in ["-isystem", name]], - "x86_headers": args.x86_headers, "x86_sources": sources + ["checks/floating.cpp"], + "x86_headers": args.x86_headers, "x86_sources": x86_sources + ["checks/floating.cpp"], "native_sha256": digest((package / "native-compiler").read_bytes()), "bundle_sha256": digest((package / "bundle.bin").read_bytes()), "shim_files": {p.relative_to(package).as_posix(): digest(p.read_bytes()) diff --git a/scripts/experimental/wasi_stack.S b/scripts/experimental/wasi_stack.S new file mode 100644 index 000000000..cb80cb97c --- /dev/null +++ b/scripts/experimental/wasi_stack.S @@ -0,0 +1,16 @@ +// The single-threaded command host restores its initial memory image and this +// pointer between invocations. These leaf functions have no shadow-stack frame. +.globaltype __stack_pointer, i32 +.functype __cppgm_wasi_stack_pointer () -> (i32) +.globl __cppgm_wasi_stack_pointer +__cppgm_wasi_stack_pointer: +.functype __cppgm_wasi_stack_pointer () -> (i32) +global.get __stack_pointer +end_function +.functype __cppgm_wasi_restore_stack_pointer (i32) -> () +.globl __cppgm_wasi_restore_stack_pointer +__cppgm_wasi_restore_stack_pointer: +.functype __cppgm_wasi_restore_stack_pointer (i32) -> () +local.get 0 +global.set __stack_pointer +end_function diff --git a/scripts/tests/wasi_heap_host.cpp b/scripts/tests/wasi_heap_host.cpp index 5958fa8cb..cc2214235 100644 --- a/scripts/tests/wasi_heap_host.cpp +++ b/scripts/tests/wasi_heap_host.cpp @@ -7,6 +7,7 @@ #include extern "C" void* cppgm_test_sbrk(intptr_t); +extern "C" uintptr_t __cppgm_wasi_heap_break(); namespace { const uintptr_t page = 65536; size_t capacity = 128, maximum = 65535; @@ -48,12 +49,14 @@ int main(int argc, char** argv) cppgm_test_sbrk(1); assert(!strcmp(argv[1], "growth")); uintptr_t next = capacity * page; + assert(__cppgm_wasi_heap_break() == next && requests.empty()); assert(reinterpret_cast(cppgm_test_sbrk(0)) == next && requests.empty()); for (unsigned i = 0; i < 2048; ++i) { assert(reinterpret_cast(cppgm_test_sbrk(page)) == next); next += page; assert(reinterpret_cast(cppgm_test_sbrk(0)) == next); + assert(__cppgm_wasi_heap_break() == next); assert(capacity * page >= next && capacity * page - next < 16 * 1024 * 1024); } assert(requests.size() < 32); // Each request must not copy the preceding heap. From 0f60cd3888e4c9800297af14df0596a2321c5ce9 Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 05:39:54 +0000 Subject: [PATCH 3/3] Pass WASI host exports through the linker driver --- scripts/experimental/wasi_inception.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/experimental/wasi_inception.py b/scripts/experimental/wasi_inception.py index 1e0802f3c..60c0e4254 100644 --- a/scripts/experimental/wasi_inception.py +++ b/scripts/experimental/wasi_inception.py @@ -168,9 +168,9 @@ def prepare(args): shutil.copyfile(HERE / name, package / name) manifest = {"schema": 1, "sources": sources, "flags": flags, "link_flags": ["-Wl,-z,stack-size=8388608", "-lc-printscan-long-double", - "--export=__cppgm_wasi_stack_pointer", - "--export=__cppgm_wasi_restore_stack_pointer", - "--export=__cppgm_wasi_heap_break"], "files": files, + "-Wl,--export=__cppgm_wasi_stack_pointer", + "-Wl,--export=__cppgm_wasi_restore_stack_pointer", + "-Wl,--export=__cppgm_wasi_heap_break"], "files": files, "process_reset": {"stack_pointer": "__cppgm_wasi_stack_pointer", "restore_stack_pointer": "__cppgm_wasi_restore_stack_pointer", "heap_break": "__cppgm_wasi_heap_break"},