Avoid native aggregate field snapshots and cache validated stack bounds

This commit is contained in:
waozi committed 2026-11-16 15:30:37 -03:00
1 parent 8a3b727cfc
commit 1fd89e81cd
10 files changed
+500 -9

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
## [Unreleased]
- Native code reads individual fields of large records without copying the whole record when snapshot semantics permit it, and repeated native calls reuse validated thread stack bounds.
- Native x86-64 code addresses an element at a constant zero index as its base without computing it: the `Hello, World!` executable's `main` is four machine instructions instead of six, and a record built from a field of another record no longer names an eliminated virtual.
- `zx2native` writes a Linux x86-64 executable for a program that calls host capabilities: it links each capability by name from a registered host library (a `NAME.library` file beside the `.host` players `ziran run` dispatches to, in `ZIRAN_HOST_PATH` or `~/.local/share/ziran/hosts`), with the C ABI the C target declares for it, so a host library built from Ziran through the C target serves both. The ELF names the system dynamic linker and each library, and one System V veneer per capability calls it; bools, integers, pointers, floats, strings and slices cross. A capability no registered library defines is still `assembly.gap.machine-host`, now naming that, and one whose parameters or result the veneer cannot carry is `assembly.gap.machine-host-abi`; a program with no host capabilities stays static. Kryon's `examples/window.zi` lowers to an executable of under 2 KB that opens its window through Kryon's desktop host library.
- Native register allocation gives a block parameter and the parameter it is copied into one register when neither is live where the other is defined, so a loop counter passed around unchanged costs no moves. Sieve drops from about 31 to 24 µs on Omega. An allocation the allocated-code verifier rejects is redone without this.
+2 -2
View File
@@ -1,6 +1,6 @@
ASSEMBLY_C := $(BUILD_DIR)/compiler-assembly
ASSEMBLY_MACHINE_SOURCES := cmd/compiler_target.zi cmd/compiler_machine_image.zi cmd/compiler_abi.zi cmd/compiler_machine_ir.zi \
cmd/compiler_machine_verify.zi cmd/compiler_machine_aggregate.zi cmd/compiler_machine_select.zi cmd/compiler_machine_lower.zi \
cmd/compiler_machine_verify.zi cmd/compiler_machine_aggregate.zi cmd/compiler_machine_fields.zi cmd/compiler_machine_select.zi cmd/compiler_machine_lower.zi \
cmd/compiler_machine_verify_allocated.zi cmd/compiler_regalloc.zi cmd/compiler_x86_bytes.zi cmd/compiler_x86_64.zi cmd/compiler_x86_runtime.zi \
cmd/compiler_x86_win64.zi cmd/compiler_x86_host.zi cmd/compiler_x86_image.zi \
cmd/compiler_aarch64.zi cmd/compiler_armv7.zi \
@@ -59,7 +59,7 @@ $(BUILD_DIR)/obj/assembly-core.o: assembly.mk $(ASSEMBLY_C)/.generated $(BUILD_D
# second copy of those public symbols from assembly-core.o.
ASSEMBLY_NATIVE_MODULES := compiler_abi compiler_machine_image \
compiler_machine_ir compiler_machine_verify \
compiler_machine_aggregate compiler_machine_select compiler_machine_lower compiler_machine_verify_allocated compiler_regalloc \
compiler_machine_aggregate compiler_machine_fields compiler_machine_select compiler_machine_lower compiler_machine_verify_allocated compiler_regalloc \
compiler_target compiler_x86_bytes compiler_x86_64 compiler_x86_runtime compiler_aarch64 compiler_armv7 \
compiler_x86_win64 compiler_x86_host compiler_x86_image \
compiler_arm_bytes \
+142
View File
@@ -0,0 +1,142 @@
using Aggregates :: #import "compiler_machine_aggregate"
using Lir :: #import "compiler_lowered_ir"
using Machine :: #import "compiler_machine_ir"
using Vectors :: #import "std/vec"
// An aggregate load used only to read members need not copy the aggregate.
// This view aliases program memory: every eventual read, including reads
// through nested views, must precede any possible write or call.
MachineFieldsPlan :: struct {
pointer: Vec(s32)
work: s64
root: Vec(s32)
home: Vec(s32)
stamp: Vec(s64)
valid: Vec(bool)
used: Vec(bool)
}
MachineFieldsPlanFree :: (plan: *MachineFieldsPlan) {
VecFree(plan.pointer)
VecFree(plan.root)
VecFree(plan.home)
VecFree(plan.stamp)
VecFree(plan.valid)
VecFree(plan.used)
}
#scope_file
Write :: (op: LirOp) -> bool {
return op == .Store || op == .Copy || op == .Zero || op == .Resize ||
op == .Allocate || op == .Call || op == .CallIndirect || op == .HostCall || op == .Insert
}
Spend :: (plan: *MachineFieldsPlan, count: s64, budget: s64) -> bool {
if count < 0 || count > budget - plan.work { return false }
plan.work += count
return true
}
#scope_export
MachineFieldsPlanBuild :: (plan: *MachineFieldsPlan, function: LirFunction,
aggregates: *MachineAggregatePlan, stack_size: []s64, address_shift: []s32,
enabled: bool, budget: s64, bytes: s64) -> MachineProblem {
count := function.values.count
plan.work = 0
if !VecResizeBounded(plan.pointer, count, bytes) { return .Allocation }
if !Spend(plan, count, budget) { return .Limit }
for value: cast(s64)0..count - 1 { plan.pointer[value] = MachineNoId }
if !enabled { return .None }
if !VecResizeBounded(plan.root, count, bytes) || !VecResizeBounded(plan.home, count, bytes) ||
!VecResizeBounded(plan.stamp, count, bytes) || !VecResizeBounded(plan.valid, count, bytes) ||
!VecResizeBounded(plan.used, count, bytes) { return .Allocation }
for value: cast(s64)0..count - 1 {
plan.root[value] = MachineNoId
plan.home[value] = MachineNoId
plan.stamp[value] = 0
plan.valid[value] = false
plan.used[value] = false
}
// Discover roots before uses, including blocks listed before their
// defining block. A use outside the load's block keeps its snapshot.
for block, home: function.blocks {
if !Spend(plan, block.instructions.count, budget) { return .Limit }
for instruction: block.instructions {
value := instruction.result
if instruction.op != .Load || value < 0 || instruction.operands.count != 1 ||
stack_size[function.values[value]] <= 0 { continue }
pointer := instruction.operands[0]
// A selected memory operand has no standalone address virtual.
if address_shift[pointer] >= 0 { continue }
plan.root[value] = value
plan.pointer[value] = pointer
plan.home[value] = cast(s32)home
plan.valid[value] = true
}
}
for block, home: function.blocks {
stamp: s64
for instruction: block.instructions {
if !Spend(plan, 1 + instruction.operands.count, budget) { return .Limit }
result := instruction.result
if result >= 0 && plan.pointer[result] >= 0 { plan.stamp[result] = stamp }
for value, operand: instruction.operands {
root := plan.root[value]
if root < 0 { continue }
if instruction.op != .Extract || operand != 0 || plan.home[root] != cast(s32)home ||
plan.stamp[root] != stamp {
plan.valid[root] = false
continue
}
plan.used[root] = true
// A member copied out now owns a snapshot. A member read
// in place extends the lifetime of this memory view.
if aggregates.view[result] == .Read { plan.root[result] = root }
}
for edge: instruction.edges {
if !Spend(plan, edge.arguments.count, budget) { return .Limit }
for value: edge.arguments {
root := plan.root[value]
if root >= 0 { plan.valid[root] = false }
}
}
if Write(instruction.op) { stamp += 1 }
}
}
any := false
for value: cast(s32)0..cast(s32)count - 1 {
if plan.pointer[value] < 0 { continue }
if !plan.valid[value] || !plan.used[value] { plan.pointer[value] = MachineNoId; continue }
aggregates.view[value] = .Read
aggregates.root[value] = value
aggregates.address[value] = value
any = true
}
if !any { return .None }
if !Spend(plan, count * 2, budget) { return .Limit }
// Old address sharing referred to frame slots, which can now stand for
// different memory bases. Recompute read addresses; an in-place insert
// still shares the address of the view it changes.
for value: cast(s32)0..cast(s32)count - 1 {
if aggregates.view[value] == .Read { aggregates.address[value] = value }
aggregates.storage[value] = false
}
for block: function.blocks {
if !Spend(plan, block.instructions.count, budget) { return .Limit }
for instruction: block.instructions {
value := instruction.result
if value >= 0 && aggregates.view[value] == .Changed {
aggregates.address[value] = instruction.operands[0]
}
}
}
for value: cast(s32)0..cast(s32)count - 1 {
if stack_size[function.values[value]] >= 0 && !aggregates.split[value] &&
(aggregates.view[value] == .None || aggregates.view[value] == .PutBack) {
aggregates.storage[aggregates.slot[value]] = true
}
}
return .None
}
+19 -2
View File
@@ -1,5 +1,6 @@
using ABI :: #import "compiler_abi"
using Aggregates :: #import "compiler_machine_aggregate"
using Fields :: #import "compiler_machine_fields"
using Lir :: #import "compiler_lowered_ir"
using LirVerifyModule :: #import "compiler_lowered_verify"
using Image :: #import "compiler_machine_image"
@@ -31,6 +32,7 @@ LowerState :: struct {
proven: *LirProvenOwner
frame_raw: *Vec(s32)
aggregates: *AggregateLowering
fields: *MachineFieldsPlan
// The selection plan of the function being lowered (see
// compiler_machine_select), the LIR block and instruction number being
// lowered, and the flags and condition of a compare whose branch follows.
@@ -1570,7 +1572,15 @@ LowerInstruction :: (state: *LowerState, function: *MachineFunction,
if source.op == .Extract { return LowerExtract(state, function, source) }
if source.op == .Insert { return LowerInsert(state, function, source) }
if source.op == .Allocate { return LowerAllocate(state, function, source) }
if source.op == .Load { return LowerMemory(state, function, source, .Load) }
if source.op == .Load {
if state.fields.pointer[source.result] >= 0 {
instruction := BeginInstruction(state, .Move, source.origin)
return VirtualOperand(state, state.aggregates.view_address[source.result], .Define) != MachineNoId &&
VirtualOperand(state, GlobalVirtual(state, function, state.fields.pointer[source.result]), .Use) != MachineNoId &&
FinishInstruction(state, instruction) != MachineNoId
}
return LowerMemory(state, function, source, .Load)
}
if source.op == .Store { return LowerMemory(state, function, source, .Store) }
if source.op == .Copy { return LowerMemory(state, function, source, .Copy) }
if source.op == .Zero { return LowerMemory(state, function, source, .Zero) }
@@ -1617,7 +1627,11 @@ LowerFunction :: (state: *LowerState, function_id: s32) -> bool {
problem = MachineSelectPlanBuild(state.select, state.lir, source, x86, x86 && !state.checks,
state.remaining, state.limits.bytes)
if problem != .None { return Fail(state, problem) }
if !Spend(state, state.select.work) || !CreateVirtuals(state, function_id) { return false }
if !Spend(state, state.select.work) { return false }
problem = MachineFieldsPlanBuild(state.fields, source, *state.aggregates.plan, state.aggregates.stack_size[:],
state.select.address_shift[:], x86 && !state.checks, state.remaining, state.limits.bytes)
if problem != .None { return Fail(state, problem) }
if !Spend(state, state.fields.work) || !CreateVirtuals(state, function_id) { return false }
function = state.owner.functions[function_id]
function.fuel_register = state.options.fuel && MachineAbiFuelRegister(state.target) >= 0 && Loops(source)
if !ViewAddresses(state, *function, source) || !SplitFields(state, *function, source) ||
@@ -1779,6 +1793,9 @@ MachineLower :: (owner: *MachineOwner, program: LirProgram, target: TargetDescri
aggregates: AggregateLowering
defer AggregateLoweringFree(*aggregates)
state.aggregates = *aggregates
fields: MachineFieldsPlan
defer MachineFieldsPlanFree(*fields)
state.fields = *fields
select: MachineSelectPlan
defer MachineSelectPlanFree(*select)
state.select = *select
+32 -4
View File
@@ -93,6 +93,7 @@ void NativeInstanceClose(NativeInstance *instance) { (void)instance; }
#include <link.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <time.h>
#include <unistd.h>
@@ -1319,12 +1320,39 @@ native_stack_limit(void)
{
uintptr_t here = (uintptr_t)__builtin_frame_address(0);
uintptr_t floor = here > NATIVE_STACK_MAXIMUM ? here - NATIVE_STACK_MAXIMUM : 0;
pthread_attr_t attributes;
/* pthread_getattr_np may scan /proc for the main thread. Keep only one
* range per thread, never an instance limit: the depth cap above must
* still follow each entry's frame. A switched/alternate stack misses.
* Linux derives the main stack's bottom from RLIMIT_STACK, which hosts
* may reduce between entries, so validate that inexpensive value too.
* Failed queries and fallback limits are deliberately not cached. */
static _Thread_local struct {
uintptr_t bottom;
size_t size;
rlim_t stack_size;
} cached;
struct rlimit resource;
int have_resource = getrlimit(RLIMIT_STACK, &resource) == 0;
void *low = NULL;
size_t size = 0;
if(pthread_getattr_np(pthread_self(), &attributes) == 0) {
if(pthread_attr_getstack(&attributes, &low, &size) != 0) low = NULL;
pthread_attr_destroy(&attributes);
if(have_resource && cached.size != 0 && cached.stack_size == resource.rlim_cur &&
here > cached.bottom && here - cached.bottom <= cached.size) {
low = (void *)cached.bottom;
size = cached.size;
} else {
pthread_attr_t attributes;
/* Invalidate even on failure, including a changed resource limit. */
cached.size = 0;
if(pthread_getattr_np(pthread_self(), &attributes) == 0) {
if(pthread_attr_getstack(&attributes, &low, &size) != 0) low = NULL;
pthread_attr_destroy(&attributes);
}
if(have_resource && low != NULL && size > NATIVE_STACK_RESERVE &&
here > (uintptr_t)low && here - (uintptr_t)low <= size) {
cached.bottom = (uintptr_t)low;
cached.stack_size = resource.rlim_cur;
cached.size = size;
}
}
uintptr_t bottom = (uintptr_t)low;
if(low != NULL && size > NATIVE_STACK_RESERVE && here > bottom + NATIVE_STACK_RESERVE &&
+120
View File
@@ -0,0 +1,120 @@
using Lir :: #import "compiler_lowered_ir"
using Lower :: #import "compiler_machine_lower"
using Machine :: #import "compiler_machine_ir"
using Verify :: #import "compiler_machine_verify"
using Target :: #import "compiler_target"
#scope_file
Instruction :: (op: Lir.LirOp, result: s32 = -1) -> Lir.LirInstruction {
return .{op = op, result = result, symbol = -1, origin = -1}
}
// A 128 KiB record read by one scalar field, through a nested array, across
// a write/call, through a nested view across a write, across blocks, or
// as a complete escaping snapshot.
Fixture :: (owner: *Machine.MachineOwner, mode: s32, checks: bool) -> bool {
modules := string.["fields"]
fields := s32.[2, 1]
types := Lir.LirType.[.{kind = .Void}, .{kind = .Integer, bits = 32, is_signed = true},
.{kind = .Array, element = 1, count = 32768}, .{kind = .Record, fields = fields[:]},
.{kind = .Pointer, element = 3}, .{kind = .Pointer, element = 1}]
constants := Lir.LirConstant.[.{type = 1, bits = 42}]
globals := Lir.LirGlobal.[.{module = 0, name = "record", type = 3, constant = -1, writable = true}]
values := s32.[4, 5, 1, 3, 1, 1]
instructions: [8]Lir.LirInstruction
address := s32.[0]
storing := s32.[1, 2]
aggregate := s32.[3]
array_index := s32.[4, 2]
answer := s32.[4]
escaping := s32.[3]
instructions[0] = Instruction(.GlobalAddress, 0); instructions[0].symbol = 0
instructions[1] = Instruction(.FieldAddress, 1); instructions[1].operands = address[:]
instructions[1].immediate = 1
instructions[2] = Instruction(.Constant, 2); instructions[2].symbol = 0
instructions[3] = Instruction(.Load, 3); instructions[3].operands = address[:]
instructions[3].effect = 1
at: s64 = 4
count: s64 = 5
if mode == 1 {
instructions[at] = Instruction(.Store); instructions[at].operands = storing[:]
instructions[at].effect = 2; at += 1
} else if mode == 2 {
instructions[at] = Instruction(.Call); instructions[at].symbol = 1
instructions[at].effect = 2; at += 1
}
instructions[at] = Instruction(.Extract, 4)
instructions[at].operands = aggregate[:]; instructions[at].immediate = 1
at += 1
if mode == 3 || mode == 5 {
values[4] = 2
count = 6
instructions[at - 1].immediate = 0
if mode == 5 {
instructions[at] = Instruction(.Store); instructions[at].operands = storing[:]
instructions[at].effect = 2; at += 1
}
instructions[at] = Instruction(.Extract, 5); instructions[at].operands = array_index[:]
at += 1
answer[0] = 5
}
instructions[at] = Instruction(.Return)
instructions[at].operands = ifx mode == 4 then escaping[:] else answer[:]
// Put the consumer first in the block array to exercise discovery of
// load roots before uses, independently of block storage order.
jump := Lir.LirInstruction.[Instruction(.Jump)]
edges := Lir.LirEdge.[.{block = 0}]
jump[0].edges = edges[:]
cross_definition: [5]Lir.LirInstruction
blocks := Lir.LirBlock.[.{instructions = instructions[:at + 1]}, .{}]
block_count: s64 = 1
if mode == 6 {
for index: cast(s64)0..3 { cross_definition[index] = instructions[index] }
cross_definition[4] = jump[0]
blocks[0].instructions = instructions[4:at + 1]
blocks[1].instructions = cross_definition[:]
block_count = 2
}
empty_return := Lir.LirInstruction.[Instruction(.Return)]
empty_blocks := Lir.LirBlock.[.{instructions = empty_return[:]}]
functions := Lir.LirFunction.[
.{module = 0, name = "read", result = ifx mode == 4 then 3 else 1,
values = values[:count], blocks = blocks[:block_count], entry = ifx mode == 6 then 1 else 0, origin = -1},
.{module = 0, name = "barrier", result = 0, blocks = empty_blocks[:], entry = 0, origin = -1}]
program := Lir.LirProgram.{version = Lir.LirVersion, modules = modules[:], types = types[:],
constants = constants[:], globals = globals[:], functions = functions[:], entry = 0, checks = checks}
limits := Machine.MachineDefaultLimits()
lowered := Lower.MachineLower(owner, program, Target.TargetLinuxX64(), Machine.MachineDefaultOptions(), limits)
if lowered.problem != .None {
print("field lowering failed: mode % checks % problem % lir %\n", mode, checks,
cast(s32)lowered.problem, lowered.lir_diagnostic_problem)
return false
}
mir := Lower.MachineProgramView(owner)
if Verify.MachineVerify(mir, limits).problem != .None { return false }
copies: s64
for instruction: mir.instructions {
if instruction.opcode != .Load { continue }
result := mir.operands[instruction.operand_begin]
if result.class == .Stack { copies += 1 }
}
preserve := checks || mode == 1 || mode == 2 || mode == 4 || mode == 5 || mode == 6
if (copies > 0) != preserve || !preserve && mir.stack_objects.count != 0 {
print("field snapshot failed: mode % checks % copies % objects %\n",
mode, checks, copies, mir.stack_objects.count)
return false
}
return true
}
#scope_export
MachineFieldsCases :: () -> bool {
owner: Machine.MachineOwner
defer Lower.MachineFree(*owner)
for mode: cast(s32)0..6 { if !Fixture(*owner, mode, false) { return false } }
if !Fixture(*owner, 0, true) { return false }
print("machine fields: scalar and nested reads avoid aggregate copies; nested writes, calls, cross-block uses, escapes and checks retain snapshots\n")
return true
}
+2
View File
@@ -5,6 +5,7 @@ using Image :: #import "compiler_machine_image"
using Machine :: #import "compiler_machine_ir"
using Verify :: #import "compiler_machine_verify"
using Target :: #import "compiler_target"
using FieldsCases :: #import "machine_fields_cases"
Check :: (condition: bool, message: string) -> bool {
if condition { return true }
@@ -341,6 +342,7 @@ MachineImageContract :: (target: Target.TargetDescription) -> bool {
}
main :: () -> s32 {
if !FieldsCases.MachineFieldsCases() { return 1 }
target := Target.TargetLinuxX64()
if !Check(Target.TargetValid(target), "Linux x86-64 target is valid") ||
!Check(target.allocatable_general == 0xffcf && target.reserved_general == 0x30,
+1 -1
View File
@@ -15,7 +15,7 @@ trap 'rm -rf "$work"' EXIT HUP INT TERM
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS SESSION_MANAGER
export HARMONY_DESKTOP_RECOVERY=0
for entry in Answer Spin Overflow Bump Long Trapper Retain Grow; do
for entry in Answer Spin Overflow Bump Long Trapper Retain Grow Fields; do
"$zi2zx" --root "$repo/tests/spec" -I "$repo/std" --entry "native_bundle:$entry" \
-o "$work/$entry.zx" "$repo/tests/spec/native_bundle.zi"
done
+137
View File
@@ -5,6 +5,15 @@
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#if defined(__linux__)
#include <pthread.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>
#include <ucontext.h>
#endif
#include <string.h>
static char directory[4096];
@@ -169,8 +178,134 @@ state(void)
run(instantiate(retain, BUNDLE_BACKEND_ENGINE, 0, &binding, 1), BUNDLE_EXECUTION_ENGINE, 42);
assert(labels == 4);
BundleClose(retain);
Bundle *fields = open_entry("Fields");
run(instantiate(fields, BUNDLE_BACKEND_NATIVE, 0, NULL, 0), BUNDLE_EXECUTION_NATIVE_X86_64, 42);
run(instantiate(fields, BUNDLE_BACKEND_ENGINE, 0, NULL, 0), BUNDLE_EXECUTION_ENGINE, 42);
BundleClose(fields);
}
#if defined(__x86_64__) && defined(__linux__)
/* Optional measurement uses the constant-return entry: no work or host calls. */
static void
warm_entries(void)
{
Bundle *bundle = open_entry("Answer");
BundleInstance *instance = instantiate(bundle, BUNDLE_BACKEND_NATIVE, 0, NULL, 0);
long long result = 0;
int present = 0;
assert(instance != NULL);
for(int i = 0; i < 1000; i++)
assert(BundleInstanceRun(instance, &result, &present) && present && result == 42);
if(getenv("NATIVE_ENTRY_TIMING") != NULL) {
for(int sample = 0; sample < 7; sample++) {
struct timespec start, end;
assert(clock_gettime(CLOCK_MONOTONIC, &start) == 0);
for(int i = 0; i < 100000; i++)
assert(BundleInstanceRun(instance, &result, &present) && present && result == 42);
assert(clock_gettime(CLOCK_MONOTONIC, &end) == 0);
double ns = (end.tv_sec - start.tv_sec) * 1e9 + end.tv_nsec - start.tv_nsec;
printf("empty warm native entry sample %d: %.2f ns/call (100000 calls)\n", sample, ns / 100000);
}
}
BundleInstanceClose(instance);
BundleClose(bundle);
}
/* Each thread warms its own bounds before trapping another instance. */
static void *
stack_thread(void *unused)
{
(void)unused;
warm_entries();
Bundle *bundle = open_entry("Overflow");
BundleInstance *instance = instantiate(bundle, BUNDLE_BACKEND_NATIVE, 0, NULL, 0);
long long result = 0;
int present = 0;
assert(instance != NULL);
assert(!BundleInstanceRun(instance, &result, &present));
BundleInstanceClose(instance);
BundleClose(bundle);
return NULL;
}
static void
alternate_stack(void)
{
stack_thread(NULL);
}
static void
stack_entries(void)
{
/* Warm main-thread bounds, then reduce RLIMIT_STACK in an isolated child. */
warm_entries();
unsetenv("NATIVE_ENTRY_TIMING");
assert(fflush(NULL) == 0);
pid_t child = fork();
assert(child >= 0);
if(child == 0) {
struct rlimit limit;
assert(getrlimit(RLIMIT_STACK, &limit) == 0);
if(limit.rlim_cur > 1024 * 1024) {
limit.rlim_cur = 1024 * 1024;
assert(setrlimit(RLIMIT_STACK, &limit) == 0);
}
stack_thread(NULL);
_exit(0);
}
int status;
assert(waitpid(child, &status, 0) == child);
assert(WIFEXITED(status) && WEXITSTATUS(status) == 0);
pthread_t threads[2];
pthread_attr_t attributes;
assert(pthread_attr_init(&attributes) == 0);
assert(pthread_attr_setstacksize(&attributes, 1024 * 1024) == 0);
for(int i = 0; i < 2; i++)
assert(pthread_create(&threads[i], &attributes, stack_thread, NULL) == 0);
for(int i = 0; i < 2; i++) assert(pthread_join(threads[i], NULL) == 0);
assert(pthread_attr_destroy(&attributes) == 0);
/* Switching stacks must not reuse a cached pthread range. The established
* fallback permits 1 MiB, so supply 2 MiB for this alternate stack. */
ucontext_t caller, alternate;
assert(getcontext(&alternate) == 0);
alternate.uc_stack.ss_size = 2 * 1024 * 1024;
alternate.uc_stack.ss_sp = malloc(alternate.uc_stack.ss_size);
assert(alternate.uc_stack.ss_sp != NULL);
alternate.uc_stack.ss_flags = 0;
alternate.uc_link = &caller;
makecontext(&alternate, alternate_stack, 0);
assert(swapcontext(&caller, &alternate) == 0);
free(alternate.uc_stack.ss_sp);
stack_thread(NULL);
}
static int
reentrant_label(void *context, const char *module, const char *function,
const HostValue *args, int count, HostValue *result)
{
long long value = 0;
int present = 0;
assert(BundleInstanceRun(context, &value, &present) && present && value == 42);
return label(NULL, module, function, args, count, result);
}
static void
reentrant_entries(void)
{
Bundle *answer = open_entry("Answer");
BundleInstance *inner = instantiate(answer, BUNDLE_BACKEND_NATIVE, 0, NULL, 0);
Bundle *retain = open_entry("Retain");
HostBinding binding = {"native_bundle", "Label", reentrant_label, inner};
run(instantiate(retain, BUNDLE_BACKEND_NATIVE, 0, &binding, 1), BUNDLE_EXECUTION_NATIVE_X86_64, 42);
BundleInstanceClose(inner);
BundleClose(answer);
BundleClose(retain);
}
#endif
int
main(int argc, char **argv)
{
@@ -181,6 +316,8 @@ main(int argc, char **argv)
limits();
state();
checked();
stack_entries();
reentrant_entries();
puts("native ZX: strict, engine and automatic backends, shared code, fuel, stack, globals, host strings and checked pointers");
#else
Bundle *bundle = open_entry("Answer");
+43
View File
@@ -6,6 +6,49 @@ Label :: (round: s64) -> string #foreign host_api;
count: s64;
FieldRecord :: struct { padding: [32768]s32; value: s32 }
field_left: FieldRecord;
field_right: FieldRecord;
FieldRead :: (record: *FieldRecord) -> s32 { return record.value }
FieldPair :: (left: *FieldRecord, right: *FieldRecord) -> s32 { return left.value + right.value }
FieldNestedPair :: (left: *FieldRecord, right: *FieldRecord, index: s64) -> s32 {
return left.padding[index] + right.padding[index]
}
FieldChanged :: (source: *FieldRecord, index: s64) -> s32 {
before := source.value
value := <<source
value.padding[index] = 31
return before + value.padding[index]
}
FieldWrite :: () { field_left.value = 23 }
// Large memory-backed records may be read by field, but a value captured
// before an aliasing write or a call must keep its original contents.
#program_export
Fields :: () -> s32 {
field_left.value = 7
field_right.value = 5
field_left.padding[42] = 3
field_right.padding[42] = 10
nested_pair := FieldNestedPair(*field_left, *field_right, 42)
changed := FieldChanged(*field_left, 42)
nested_snapshot := field_left
inner := nested_snapshot.padding
field_left.padding[42] = 17
before_nested := inner[42]
read := FieldRead(*field_left)
pair := FieldPair(*field_left, *field_right)
snapshot := field_left
field_left.value = 11
before := snapshot.value
call_snapshot := field_left
FieldWrite()
after_call := call_snapshot.value
if nested_pair != 13 || changed != 38 || before_nested != 3 || field_left.padding[42] != 17 { return 2 }
if read != 7 || pair != 12 || before != 7 || after_call != 11 || field_left.value != 23 { return 1 }
return 42
}
#program_export
Answer :: () -> s32 { return 42 }