Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
2 changes: 2 additions & 0 deletions dev/frontend_source_sets.mk
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
57 changes: 57 additions & 0 deletions dev/src/support/wasi_heap.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#if defined(__wasi__)
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>

// 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<void*>(position);
if (increment < 0 || static_cast<uintptr_t>(increment) % page)
abort();
const uintptr_t amount = static_cast<uintptr_t>(increment);
if (amount > UINTPTR_MAX - position)
{
errno = ENOMEM;
return reinterpret_cast<void*>(-1);
}
const uintptr_t needed = position + amount;
const uintptr_t pages = __builtin_wasm_memory_size(0);
const uint64_t available = static_cast<uint64_t>(pages) * page;
if (needed > available)
{
const uintptr_t required = static_cast<uintptr_t>((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<void*>(-1);
}
}
const uintptr_t before = position;
position = needed;
return reinterpret_cast<void*>(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<uintptr_t>(sbrk(0));
}
#endif
18 changes: 16 additions & 2 deletions scripts/experimental/wasi_inception.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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",
"-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"},
"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())
Expand Down
16 changes: 16 additions & 0 deletions scripts/experimental/wasi_stack.S
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions scripts/export_student_repo.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
42 changes: 42 additions & 0 deletions scripts/tests/test_wasi_heap.py
Original file line number Diff line number Diff line change
@@ -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()
72 changes: 72 additions & 0 deletions scripts/tests/wasi_heap_host.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#include "wasi_heap_mock.h"

#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <string.h>
#include <vector>

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;
std::vector<size_t> 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<void*>(-1));
assert(errno == ENOMEM && cppgm_test_sbrk(0) == before && requests.empty());
return 0;
}
if (!strcmp(argv[1], "negative"))
cppgm_test_sbrk(-static_cast<intptr_t>(page));
if (!strcmp(argv[1], "unaligned"))
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<uintptr_t>(cppgm_test_sbrk(0)) == next && requests.empty());
for (unsigned i = 0; i < 2048; ++i)
{
assert(reinterpret_cast<uintptr_t>(cppgm_test_sbrk(page)) == next);
next += page;
assert(reinterpret_cast<uintptr_t>(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.
maximum = capacity + 1;
const size_t count = requests.size();
const uintptr_t amount = capacity * page - next + page;
assert(reinterpret_cast<uintptr_t>(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<void*>(-1));
assert(errno == ENOMEM && cppgm_test_sbrk(0) == before);
}
5 changes: 5 additions & 0 deletions scripts/tests/wasi_heap_mock.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#pragma once
#include <stddef.h>

extern "C" size_t cppgm_test_memory_size(unsigned);
extern "C" size_t cppgm_test_memory_grow(unsigned, size_t);
Loading