Drop proven native index checks and read constant text directly

Following the owner's "make sure we oly have guardarils wher ew enede
tehm": a shared fact now carries a pointer's room (the bytes from it to
its root's end that every execution may reach), so a constant text read
through its view is direct too, and x86-64 drops the index check of an
element the shared intervals prove below its bound (ElementAddress with
an immediate bound). Wasm drops proven view checks as well. The machine
verifier proves every PointerDirect where it is defined by walking from
the root down with the same room arithmetic. A checked constant index
past its bound stays a run-time trap instead of a verifier refusal.

On the bench kernels Sieve and Hash now carry no pointer or index
checks. Runtime indices that can leave an array or a view keep their
checks and still trap (tests/proven_pointer_cases.zi).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
waoziandClaude Opus 5.5 committed 2026-11-15 18:43:47 -03:00
1 parent 7ac6643d04
commit 787580628b
10 files changed
+297 -160

No files matched your search

+6 -2
View File
@@ -132,8 +132,12 @@ turns a load, store or zero through a rooted pointer into `PointerDirect`
(the root's raw start plus the token's offset); `MachineVerify` rejects any
memory access whose address is not a `PointerResolve`, fresh `ArenaAllocate`
storage or a `PointerDirect` it re-derives to the same root, and
`zx2wasm` reads the same index proofs. `tests/proven_pointer_cases.zi`
prints the per-fixture counts and holds the hostile twins.
`zx2wasm` reads the same index proofs. A fact carries the pointer's room
(bytes to its root's end that every execution may reach), so a direct read
of a constant text through its view is covered too, and x86-64 drops the
index check of an element proven below its bound (`ElementAddress` with an
immediate bound). `tests/proven_pointer_cases.zi` prints the per-fixture
counts and holds the hostile twins.
M0 integration is done (2026-11-15): the allocator fix, the AArch64
encoder, the native default with checked pointers, the self-hosted C-backend
+1
View File
@@ -2,6 +2,7 @@
## [Unreleased]
- Native x86-64 code drops the index check of an element the shared interval analysis proves in range (fixed arrays and constant-count views such as a string constant's bytes), and reads a constant text directly, so the Sieve and Hash loops carry no pointer or index checks; Wasm drops proven view checks too. A runtime index that can leave the array or view keeps its check and traps.
- A closed C program, linked with `--entry` and built with `--exe` or its own `main`, carries only the code it uses: each module header declares just what another generated file names, the module's `.c` keeps what only it reads, header inline copies stay only for procedures other modules call, and a module whose header would declare nothing has none. For Kryon's examples, headers shrink from 18 to 8.5 KB (window), 288 to 91 KB (hello), 319 to 102 KB (box) and 692 to 420 KB (image).
- Native x86-64 code reaches a global or a frame allocation directly when one shared LIR pass proves the access stays inside a live root, instead of resolving its checked pointer; the machine verifier now checks every load, store, zero and byte comparison and re-derives each direct access, and Wasm takes its index proofs from the same pass. Parameters, loaded pointers and heap blocks keep their resolves, so stale aliases, resized blocks and out-of-range runtime indices still trap. A LIR `zero` is now resolved like a store instead of writing through the raw token.
- Input trust tiers keep memory safety invariant while naming validation failures: bounded environment/argv, binary, file, HTTP and host-byte readers return typed outcomes; local native-cache framing reports why edited entries were refused and recompiles them; the laws inventory stable artifact and host-boundary diagnostics.
+93 -61
View File
@@ -6,17 +6,17 @@
// the frame slot of an `allocate` in the same function. Such a slot is live
// whenever the value can be used: global slots are never retired, a frame
// slot only when its function returns, and neither can be resized or freed
// (resizing needs a heap slot). The fact gives the root's extent and
// writability (a global's flag; frame storage is writable) and the value's
// byte offset from the root: exact when every derivation step is static,
// otherwise bounded by the value's own type, because a field or fixed-array
// element always lies inside its parent and the fixed-array index is checked.
// Parameters, loads, call results, block parameters and heap blocks have no
// root.
// (resizing needs a heap slot). The fact gives the root's writability (a
// global's flag; frame storage is writable) and the value's room: the bytes
// from it to the end of the root that every execution may reach. A field
// moves the pointer by its offset; an element whose index is checked (or
// proven) below a bound moves it by at most bound - 1 elements, the exact
// index when it is a constant. Parameters, loads, call results, block
// parameters and heap blocks have no root.
//
// Index facts. An `element.address` into a fixed array, or a dynamic
// `extract` or `insert`, whose index an interval analysis proves lies inside
// the array, so its bounds check is redundant.
// Index facts. An `element.address` into a fixed array or a view with a
// constant count, or a dynamic `extract` or `insert`, whose index an interval
// analysis proves lies below its bound, so its bounds check is redundant.
//
// The program must already have passed LirVerify: definitions dominate their
// uses and every address step is well typed. A backend drops a check only when
@@ -33,10 +33,9 @@ LirProvenPointer :: struct {
root: LirProvenRoot
// The global's index (Global) or the allocate's result value (Frame).
symbol: s32
// Bytes from the root's start when every step is static, else -1.
offset: s64
// The root's bytes.
extent: s64
// The bytes from the pointer to the root's end that every execution may
// reach.
room: s64
writable: bool
}
@@ -45,9 +44,9 @@ LirProvenOwner :: struct {
valid: bool
value_begin: Vec(s64)
pointers: Vec(LirProvenPointer)
// 1 when the instruction defining the value has its index proven inside
// its fixed array.
index: Vec(u8)
// For the value an indexing instruction defines, the bound its index is
// proven below, or 0.
index: Vec(s64)
}
LirProvenResult :: struct {
@@ -122,7 +121,7 @@ PointeeSize :: (program: LirProgram, type_id: s32) -> s64 {
return TypeSize(program, program.types[type_id].element, 0)
}
Unknown :: () -> LirProvenPointer { return .{root = .Unknown, symbol = LirNoId, offset = -1} }
Unknown :: () -> LirProvenPointer { return .{root = .Unknown, symbol = LirNoId} }
// The value of an integer constant VALUE when it is defined by one, read
// with the constant's signedness.
@@ -151,21 +150,43 @@ ConstantInteger :: (program: LirProgram, function: LirFunction, definition: []s6
return true
}
// FACT moved by at most INDEX elements of SIZE bytes: the room left, or
// Unknown when it could leave the root.
Advance :: (fact: LirProvenPointer, index: s64, size: s64) -> LirProvenPointer {
if index < 0 || size < 0 || size > 0 && index > fact.room / size { return Unknown() }
result := fact
result.room = fact.room - index * size
return result
}
// The largest element index the instruction defining POSITION can reach
// below BOUND: the constant itself, else BOUND - 1. -1 when no index is
// valid.
LargestIndex :: (program: LirProgram, function: LirFunction, definition: []s64, position: s32,
bound: s64) -> s64 {
if bound < 1 { return -1 }
index: s64
if ConstantInteger(program, function, definition, position, *index) {
// A constant at or past the bound traps at the derivation.
return ifx index >= 0 && index < bound then index else -1
}
return bound - 1
}
// The fact for SOURCE's result, given the fact of its first operand.
PointerStep :: (program: LirProgram, function: LirFunction, definition: []s64,
source: LirInstruction, base: LirProvenPointer) -> LirProvenPointer {
if source.op == .GlobalAddress {
if source.symbol < 0 || source.symbol >= program.globals.count { return Unknown() }
global := program.globals[source.symbol]
extent := TypeSize(program, global.type, 0)
if extent < 0 { return Unknown() }
return .{root = .Global, symbol = source.symbol, offset = 0, extent = extent,
writable = global.writable}
room := TypeSize(program, global.type, 0)
if room < 0 { return Unknown() }
return .{root = .Global, symbol = source.symbol, room = room, writable = global.writable}
}
if source.op == .Allocate {
extent := PointeeSize(program, function.values[source.result])
if extent < 0 { return Unknown() }
return .{root = .Frame, symbol = source.result, offset = 0, extent = extent, writable = true}
room := PointeeSize(program, function.values[source.result])
if room < 0 { return Unknown() }
return .{root = .Frame, symbol = source.result, room = room, writable = true}
}
if base.root == .Unknown || source.operands.count < 1 { return Unknown() }
pointer := function.values[source.operands[0]]
@@ -173,31 +194,31 @@ PointerStep :: (program: LirProgram, function: LirFunction, definition: []s64,
target_id := program.types[pointer].element
if target_id < 0 || target_id >= program.types.count { return Unknown() }
target := program.types[target_id]
step: s64 = -1
if source.op == .FieldAddress && source.operands.count == 1 {
if target.kind != .Record || source.immediate >= cast(u64)target.fields.count { return Unknown() }
step = 0
offset: s64
for at: cast(s64)0..cast(s64)source.immediate - 1 {
part := TypeSize(program, target.fields[at], 0)
if part < 0 { return Unknown() }
step += part
offset += part
}
} else if source.op == .ElementAddress && source.operands.count == 2 {
return Advance(base, offset, 1)
}
if source.op != .ElementAddress || source.operands.count < 2 || source.operands.count > 4 { return Unknown() }
element := PointeeSize(program, function.values[source.result])
if element < 0 { return Unknown() }
bound: s64
if source.operands.count == 2 {
// A fixed array's element.
if target.kind != .Array { return Unknown() }
index: s64
if ConstantInteger(program, function, definition, source.operands[1], *index) {
// A constant outside the array traps at the derivation.
if index < 0 || index >= target.count { return Unknown() }
element := TypeSize(program, target.element, 0)
if element < 0 { return Unknown() }
step = index * element
} else { step = -2 }
} else { return Unknown() }
result := base
if base.offset < 0 || step == -2 { result.offset = -1 }
else { result.offset = base.offset + step }
if result.offset > result.extent { return Unknown() }
return result
bound = target.count
} else if !ConstantInteger(program, function, definition, source.operands[source.operands.count - 1], *bound) {
// A view's element (index below count), or the start of a subview
// (low <= high <= count); only a constant count bounds it.
return Unknown()
}
if source.operands.count == 4 { return Advance(base, bound, element) }
return Advance(base, LargestIndex(program, function, definition, source.operands[1], bound), element)
}
// Definitions: value -> block << 32 | instruction, or -1 (a parameter).
@@ -604,10 +625,19 @@ ConditionOf :: (block: LirBlock, value: s32) -> s64 {
}
// Marks an index proven inside its fixed array at SOURCE.
Mark :: (program: LirProgram, function: LirFunction, flow: *Flow, source: LirInstruction, index: []u8) {
Mark :: (program: LirProgram, function: LirFunction, flow: *Flow, source: LirInstruction, index: []s64) {
if source.result < 0 || source.result >= index.count { return }
array_type: s32 = LirNoId
position: s32 = LirNoId
if source.op == .ElementAddress && source.operands.count == 3 {
// A view's element: the index below every value the count can have.
range := WorkGet(flow, source.operands[1])
count := WorkGet(flow, source.operands[2])
if Finite(range) && Finite(count) && range.low >= 0 && range.low <= range.high && range.high < count.low {
index[source.result] = count.low
}
return
}
if source.op == .ElementAddress && source.operands.count == 2 {
pointer := function.values[source.operands[0]]
if program.types[pointer].kind == .Pointer { array_type = program.types[pointer].element }
@@ -619,12 +649,12 @@ Mark :: (program: LirProgram, function: LirFunction, flow: *Flow, source: LirIns
if array_type < 0 || array_type >= program.types.count || program.types[array_type].kind != .Array { return }
range := WorkGet(flow, position)
if Finite(range) && range.low >= 0 && range.low <= range.high && range.high < program.types[array_type].count {
index[source.result] = 1
index[source.result] = program.types[array_type].count
}
}
WalkBlock :: (state: *ProvenState, program: LirProgram, function: LirFunction, flow: *Flow,
block_index: s64, index: []u8, collect: bool) -> bool {
block_index: s64, index: []s64, collect: bool) -> bool {
block := function.blocks[block_index]
entry := block_index == function.entry
if !Spend(state, flow.values + 1) { return false }
@@ -733,7 +763,7 @@ WalkBlock :: (state: *ProvenState, program: LirProgram, function: LirFunction, f
}
Round :: (state: *ProvenState, program: LirProgram, function: LirFunction, flow: *Flow,
index: []u8, collect: bool) -> bool {
index: []s64, collect: bool) -> bool {
flow.changed = false
for block: cast(s64)0..flow.blocks - 1 {
if !WalkBlock(state, program, function, flow, block, index, collect) { return false }
@@ -744,7 +774,7 @@ Round :: (state: *ProvenState, program: LirProgram, function: LirFunction, flow:
// Proves indices for one function. A function whose intervals do not settle
// in the round budget or within FunctionWork keeps every check.
IndexFacts :: (state: *ProvenState, program: LirProgram, function: LirFunction,
flow: *Flow, index: []u8) -> bool {
flow: *Flow, index: []s64) -> bool {
saved := state.remaining
budget := ifx saved < FunctionWork then saved else FunctionWork
state.remaining = budget
@@ -757,7 +787,7 @@ IndexFacts :: (state: *ProvenState, program: LirProgram, function: LirFunction,
}
IndexProof :: (state: *ProvenState, program: LirProgram, function: LirFunction,
flow: *Flow, index: []u8) -> bool {
flow: *Flow, index: []s64) -> bool {
for at: cast(s64)0..index.count - 1 { index[at] = 0 }
if !FlowInit(state, program, function, flow) { return state.problem == .None }
stable := false
@@ -866,21 +896,23 @@ LirProvenPointerOf :: (owner: *LirProvenOwner, function: s64, value: s32) -> Lir
return owner.pointers[at]
}
LirProvenIndex :: (owner: *LirProvenOwner, function: s64, value: s32) -> bool {
// The bound the index of the instruction defining VALUE is proven below,
// or 0 when its check stays.
LirProvenIndexBound :: (owner: *LirProvenOwner, function: s64, value: s32) -> s64 {
if owner == null || !owner.valid || function < 0 || function + 1 >= owner.value_begin.count || value < 0 {
return false
return 0
}
at := owner.value_begin[function] + value
return at < owner.value_begin[function + 1] && owner.index[at] != 0
if at >= owner.value_begin[function + 1] { return 0 }
return owner.index[at]
}
// Whether FACT, the fact of pointer value POINTER, covers an access of WIDTH
// bytes (a write when WRITE): its root is live and the bytes lie inside it.
LirProvenCovers :: (program: LirProgram, function: LirFunction, fact: LirProvenPointer,
pointer: s32, width: s64, write: bool) -> bool {
if fact.root == .Unknown || width < 0 || write && !fact.writable { return false }
if fact.offset >= 0 { return fact.offset <= fact.extent && width <= fact.extent - fact.offset }
if pointer < 0 || pointer >= function.values.count { return false }
pointee := PointeeSize(program, function.values[pointer])
return pointee >= 0 && width <= pointee
LirProvenIndex :: (owner: *LirProvenOwner, function: s64, value: s32) -> bool {
return LirProvenIndexBound(owner, function, value) > 0
}
// Whether FACT covers an access of WIDTH bytes (a write when WRITE): its
// root is live and the bytes lie inside it.
LirProvenCovers :: (fact: LirProvenPointer, width: s64, write: bool) -> bool {
return fact.root != .Unknown && width >= 0 && width <= fact.room && (!write || fact.writable)
}
+18 -3
View File
@@ -621,9 +621,8 @@ LowerMove :: (state: *LowerState, function: *MachineFunction, source: LirInstruc
DirectBase :: (state: *LowerState, function: *MachineFunction, local: s32, width: s64,
write: bool, origin: s32) -> s32 {
if state.target.arch != .X86_64 { return MachineNoId }
lir_function := state.lir.functions[function.lir_function]
fact := LirProvenPointerOf(state.proven, function.lir_function, local)
if !LirProvenCovers(state.lir, lir_function, fact, local, width, write) { return MachineNoId }
if !LirProvenCovers(fact, width, write) { return MachineNoId }
if fact.root == .Frame {
if fact.symbol < 0 || fact.symbol >= state.frame_raw.count { return MachineNoId }
return (<<state.frame_raw)[fact.symbol]
@@ -657,6 +656,22 @@ LowerDirect :: (state: *LowerState, function: *MachineFunction, token: s32, base
return raw
}
// An element whose index the shared facts prove below a bound needs no
// index check: ElementAddress result, base, index, bound.
LowerElement :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
bound: s64
if state.target.arch == .X86_64 && source.operands.count >= 2 && source.operands.count <= 3 {
bound = LirProvenIndexBound(state.proven, function.lir_function, source.result)
}
if bound <= 0 { return LowerMemory(state, function, source, .ElementAddress) }
instruction := BeginInstruction(state, .ElementAddress, source.origin)
if VirtualOperand(state, GlobalVirtual(state, function, source.result), .Define) == MachineNoId ||
VirtualOperand(state, GlobalVirtual(state, function, source.operands[0]), .Use) == MachineNoId ||
VirtualOperand(state, GlobalVirtual(state, function, source.operands[1]), .Use) == MachineNoId ||
ImmediateOperand(state, cast(u64)bound) == MachineNoId { return false }
return FinishInstruction(state, instruction) != MachineNoId
}
LowerMemory :: (state: *LowerState, function: *MachineFunction, source: LirInstruction,
opcode: MachineOpcode) -> bool {
// A load, store or zero goes through the address its checked pointer
@@ -973,7 +988,7 @@ LowerInstruction :: (state: *LowerState, function: *MachineFunction,
if source.op == .Copy { return LowerMemory(state, function, source, .Copy) }
if source.op == .Zero { return LowerMemory(state, function, source, .Zero) }
if source.op == .FieldAddress { return LowerMemory(state, function, source, .FieldAddress) }
if source.op == .ElementAddress { return LowerMemory(state, function, source, .ElementAddress) }
if source.op == .ElementAddress { return LowerElement(state, function, source) }
if source.op == .BytesEqual { return LowerBytesEqual(state, function, source) }
if source.op == .Resize { return LowerResize(state, function, source) }
if source.op == .Call || source.op == .CallIndirect || source.op == .HostCall {
+8 -2
View File
@@ -138,12 +138,14 @@ ValueOf :: (operand: MachineOperand) -> s32 {
// Checked-access counts of a lowered program: pointer resolves left in the
// code, accesses the verifier proved need none (by the root their base
// starts), and fixed-array index checks.
// starts), element index checks left, and element indices the shared facts
// prove.
MachineChecks :: struct {
resolves: s64
direct_global: s64
direct_frame: s64
index_checks: s64
index_proven: s64
}
MachineCheckCount :: (program: MachineProgram) -> MachineChecks {
@@ -160,7 +162,11 @@ MachineCheckCount :: (program: MachineProgram) -> MachineChecks {
}
for instruction: program.instructions {
if instruction.opcode == .PointerResolve { counts.resolves += 1 }
if instruction.opcode == .ElementAddress && instruction.operand_count == 3 { counts.index_checks += 1 }
if instruction.opcode == .ElementAddress {
proven := instruction.operand_count == 4 &&
program.operands[instruction.operand_begin + 3].kind == .Immediate
if proven { counts.index_proven += 1 } else { counts.index_checks += 1 }
}
if instruction.opcode != .PointerDirect || instruction.operand_count < 3 { continue }
base := ValueOf(program.operands[instruction.operand_begin + 2])
if base >= 0 && base < globals.count && globals[base] != 0 { counts.direct_global += 1 }
+136 -84
View File
@@ -543,8 +543,9 @@ FuelFacts :: (state: *VerifyState, program: MachineProgram) -> bool {
// Checked memory. Every load, store and zero reaches memory through an
// address that is checked or proven: a PointerResolve for at least its bytes
// (writable for a write), the fresh storage of an ArenaAllocate, or a
// PointerDirect whose token this re-derives from the root its base starts.
// Byte comparisons read only views resolved for their own counts.
// PointerDirect covering them. Every PointerDirect is proven where it is
// defined: its token re-derives from the root its base starts. Byte
// comparisons read only views resolved for their own counts.
PointeeSize :: (program: MachineProgram, type_id: s32) -> s64 {
if type_id < 0 || type_id >= program.types.count { return -1 }
@@ -597,109 +598,143 @@ Definers :: (state: *VerifyState, program: MachineProgram, limits: MachineLimits
return true
}
// Whether a step from a pointer of type PARENT to one of type RESULT stays
// inside the parent: a record member or fixed-array element (INDEX, or any
// checked index when DYNAMIC) whose bytes hold the result's pointee.
StepInside :: (program: MachineProgram, parent: s32, result: s32, index: u64, dynamic: bool) -> bool {
if PointeeSize(program, parent) < 0 { return false }
target := program.types[program.types[parent].element]
member: s32 = MachineNoId
if target.kind == .Array {
if target.element < 0 || target.element >= program.types.count || target.count < 0 { return false }
element := program.types[target.element].size
if element < 0 || element > 0 && target.count > target.size / element { return false }
if !dynamic && index >= cast(u64)target.count { return false }
member = target.element
} else if target.kind == .Record && !dynamic {
if index >= cast(u64)target.fields_count || target.fields_begin < 0 ||
cast(s64)target.fields_begin + target.fields_count > program.type_ids.count { return false }
member = program.type_ids[target.fields_begin + cast(s64)index]
if member < 0 || member >= program.types.count { return false }
} else { return false }
size := PointeeSize(program, result)
return size >= 0 && size <= program.types[member].size
// The constant a MoveImmediate gives VALUE, when one does.
ConstantOf :: (program: MachineProgram, definer: []s32, value: s32, constant: *u64) -> bool {
if value < 0 || value >= definer.count || definer[value] < 0 { return false }
source := program.instructions[definer[value]]
return source.opcode == .MoveImmediate && source.operand_count == 2 &&
VirtualAt(program, source, 0, .Define) == value && ImmediateAt(program, source, 1, constant)
}
// Whether TOKEN derives, through steps that stay inside their parents, from
// ROOM less INDEX elements of SIZE bytes, or -1 when that leaves the root.
Less :: (room: s64, index: s64, size: s64) -> s64 {
if room < 0 || index < 0 || size < 0 || size > 0 && index > room / size { return -1 }
return room - index * size
}
// The room after STEP, a field or element address, from a pointer with ROOM
// bytes to its root's end, or -1. An element moves by its constant index, or
// by at most bound - 1 elements where its index is checked (or proven) below
// the bound: a fixed array's count, a constant count, or the proven bound.
StepRoom :: (program: MachineProgram, definer: []s32, step: MachineInstruction, room: s64) -> s64 {
parent := VirtualAt(program, step, 1, .Use)
result := VirtualAt(program, step, 0, .Define)
if parent < 0 || result < 0 || PointeeSize(program, program.virtuals[parent].type) < 0 { return -1 }
target := program.types[program.types[program.virtuals[parent].type].element]
if step.opcode == .FieldAddress {
index: u64
if step.operand_count != 3 || !ImmediateAt(program, step, 2, *index) { return -1 }
if target.kind == .Array {
if index >= cast(u64)target.count || target.element < 0 || target.element >= program.types.count { return -1 }
return Less(room, cast(s64)index, program.types[target.element].size)
}
if target.kind != .Record || index >= cast(u64)target.fields_count || target.fields_begin < 0 ||
cast(s64)target.fields_begin + target.fields_count > program.type_ids.count { return -1 }
offset: s64
for at: cast(s64)0..cast(s64)index - 1 {
field := program.type_ids[target.fields_begin + at]
if field < 0 || field >= program.types.count || program.types[field].size < 0 { return -1 }
offset += program.types[field].size
}
return Less(room, offset, 1)
}
if step.opcode != .ElementAddress || step.operand_count < 3 || step.operand_count > 5 { return -1 }
element := PointeeSize(program, program.virtuals[result].type)
if element <= 0 { return -1 }
bound: u64
if step.operand_count == 3 {
if target.kind != .Array || target.count < 0 { return -1 }
bound = cast(u64)target.count
} else if step.operand_count == 4 && !ImmediateAt(program, step, 3, *bound) &&
!ConstantOf(program, definer, VirtualAt(program, step, 3, .Use), *bound) { return -1 }
if step.operand_count == 5 {
// A subview starts at low <= high <= count.
if !ConstantOf(program, definer, VirtualAt(program, step, 4, .Use), *bound) ||
bound > cast(u64)room { return -1 }
return Less(room, cast(s64)bound, element)
}
if bound < 1 || bound > cast(u64)room { return -1 }
largest := cast(s64)bound - 1
index: u64
if ConstantOf(program, definer, VirtualAt(program, step, 2, .Use), *index) {
// A constant at or past a checked bound traps at the step; only the
// proven form, which has no check, must hold it below its bound.
proven := step.operand_count == 4 && program.operands[step.operand_begin + 3].kind == .Immediate
if index < bound { largest = cast(s64)index }
else if proven { return -1 }
}
return Less(room, largest, element)
}
// The room of TOKEN when it derives, through field and element steps, from
// the root whose raw start BASE holds: the PointerCreate on BASE's
// ArenaAllocate, or the token of the global BASE addresses. The root holds
// the token type's pointee, is live for the whole frame, and is writable when
// WRITE.
DirectRoot :: (state: *VerifyState, program: MachineProgram, definer: []s32, start: []s32,
token: s32, base: s32, write: bool) -> bool {
if base < 0 || base >= definer.count || definer[base] < 0 { return false }
// ArenaAllocate, or the token of the global BASE addresses. That root is live
// for the whole frame and writable when WRITE. -1 otherwise.
DirectRoom :: (state: *VerifyState, program: MachineProgram, definer: []s32, start: []s32,
steps: *Vec(s32), token: s32, base: s32, write: bool) -> s64 {
if base < 0 || base >= definer.count || definer[base] < 0 { return -1 }
base_instruction := program.instructions[definer[base]]
if VirtualAt(program, base_instruction, 0, .Define) != base { return false }
if VirtualAt(program, base_instruction, 0, .Define) != base || !VecResize(<<steps, 0) { return -1 }
current := token
steps: s64
while true {
if !Spend(state, 1) { return false }
steps += 1
if steps > program.instructions.count || current < 0 || current >= definer.count ||
definer[current] < 0 { return false }
room: s64 = -1
while room < 0 {
if !Spend(state, 1) { return -1 }
if (<<steps).count > program.instructions.count || current < 0 || current >= definer.count ||
definer[current] < 0 { return -1 }
at := definer[current]
instruction := program.instructions[at]
if VirtualAt(program, instruction, 0, .Define) != current { return false }
type := program.virtuals[current].type
if VirtualAt(program, instruction, 0, .Define) != current { return -1 }
if instruction.opcode == .FieldAddress || instruction.opcode == .ElementAddress {
if instruction.operand_count != 3 { return false }
parent := VirtualAt(program, instruction, 1, .Use)
if parent < 0 { return false }
index: u64
dynamic := instruction.opcode == .ElementAddress
if !dynamic && !ImmediateAt(program, instruction, 2, *index) { return false }
if dynamic && VirtualAt(program, instruction, 2, .Use) < 0 { return false }
if !StepInside(program, program.virtuals[parent].type, type, index, dynamic) { return false }
current = parent
if !VecPush(<<steps, at) { return -1 }
current = VirtualAt(program, instruction, 1, .Use)
continue
}
size := PointeeSize(program, type)
if size < 0 { return false }
if instruction.opcode == .PointerCreate {
// token, raw, size, scratch, flags, chain: frame storage stays
// live until its function returns and is never resized.
// live until its function returns and is never resized. BASE is
// that storage, an ArenaAllocate of at least those bytes earlier
// in the same block, so each run of it reaches the create.
created: u64
flags: u64
arena: u64
if instruction.operand_count != 6 || VirtualAt(program, instruction, 1, .Use) != base ||
!ImmediateAt(program, instruction, 2, *created) || !ImmediateAt(program, instruction, 4, *flags) ||
(flags & cast(u64)MachinePointerHeap) != 0 || (flags & cast(u64)MachinePointerLive) == 0 ||
write && (flags & cast(u64)MachinePointerWritable) == 0 || cast(u64)size > created {
return false
}
// BASE is that storage: an ArenaAllocate of at least those bytes,
// earlier in the same block, so each run of it reaches the create.
arena: u64
if base_instruction.opcode != .ArenaAllocate || base_instruction.operand_count != 3 ||
!ImmediateAt(program, base_instruction, 1, *arena) || arena < created || definer[base] >= at {
return false
}
return start[at] != MachineNoId && start[definer[base]] == start[at]
}
if instruction.opcode == .MoveImmediate {
write && (flags & cast(u64)MachinePointerWritable) == 0 ||
base_instruction.opcode != .ArenaAllocate || base_instruction.operand_count != 3 ||
!ImmediateAt(program, base_instruction, 1, *arena) || arena < created ||
created > 9223372036854775807 || definer[base] >= at || start[at] == MachineNoId ||
start[definer[base]] != start[at] { return -1 }
room = cast(s64)created
} else if instruction.opcode == .MoveImmediate {
// A global's token: slot 1 + G, version 0, offset 0. Globals are
// never retired or resized.
immediate: u64
if instruction.operand_count != 2 || !ImmediateAt(program, instruction, 1, *immediate) { return false }
if instruction.operand_count != 2 || !ImmediateAt(program, instruction, 1, *immediate) { return -1 }
slot := cast(s64)(immediate >> cast(u64)MachinePointerSlotShift)
global := slot - 1
if global < 0 || global >= program.globals.count ||
immediate != MachinePointerToken(slot, 0, 0) { return false }
if global < 0 || global >= program.globals.count || immediate != MachinePointerToken(slot, 0, 0) { return -1 }
entry := program.globals[global]
if write && !entry.writable || entry.type < 0 || entry.type >= program.types.count ||
size > program.types[entry.type].size { return false }
symbol := program.operands[base_instruction.operand_begin + 1]
return base_instruction.opcode == .GlobalAddress && base_instruction.operand_count == 2 &&
symbol.kind == .Global && symbol.id == cast(s32)global
}
return false
if write && !entry.writable || entry.type < 0 || entry.type >= program.types.count ||
base_instruction.opcode != .GlobalAddress || base_instruction.operand_count != 2 ||
symbol.kind != .Global || symbol.id != cast(s32)global { return -1 }
room = program.types[entry.type].size
if room < 0 { return -1 }
} else { return -1 }
}
return false
at := (<<steps).count - 1
while at >= 0 && room >= 0 {
room = StepRoom(program, definer, program.instructions[(<<steps)[at]], room)
at -= 1
}
return room
}
// Whether ADDRESS, operand LOCAL of INSTRUCTION, is checked or proven for
// WIDTH bytes.
CheckedAddress :: (state: *VerifyState, program: MachineProgram, definer: []s32, start: []s32,
instruction: MachineInstruction, local: s32, width: s64, write: bool) -> bool {
steps: *Vec(s32), instruction: MachineInstruction, local: s32, width: s64, write: bool) -> bool {
address := VirtualAt(program, instruction, local, .Use)
if address < 0 || width < 0 || definer[address] < 0 { return false }
source := program.instructions[definer[address]]
@@ -716,19 +751,32 @@ CheckedAddress :: (state: *VerifyState, program: MachineProgram, definer: []s32,
return source.operand_count == 3 && ImmediateAt(program, source, 1, *size) && size >= cast(u64)width
}
if source.opcode == .PointerDirect {
// Proven where it is defined (DirectProven); here it must cover
// the access.
covered: u64
flags: u64
token := VirtualAt(program, source, 1, .Use)
base := VirtualAt(program, source, 2, .Use)
if source.operand_count != 5 || token < 0 || base < 0 ||
!ImmediateAt(program, source, 3, *covered) || !ImmediateAt(program, source, 4, *flags) ||
covered < cast(u64)width || cast(s64)covered > PointeeSize(program, program.virtuals[token].type) ||
write && (flags & 1) == 0 { return false }
return DirectRoot(state, program, definer, start, token, base, (flags & 1) != 0)
return source.operand_count == 5 && ImmediateAt(program, source, 3, *covered) &&
ImmediateAt(program, source, 4, *flags) && covered >= cast(u64)width && (!write || (flags & 1) != 0)
}
return false
}
// Whether DIRECT, a PointerDirect, covers the bytes and writability it
// claims: its token derives from the root its base starts, with that much
// room.
DirectProven :: (state: *VerifyState, program: MachineProgram, definer: []s32, start: []s32,
steps: *Vec(s32), direct: MachineInstruction) -> bool {
covered: u64
flags: u64
token := VirtualAt(program, direct, 1, .Use)
base := VirtualAt(program, direct, 2, .Use)
if direct.operand_count != 5 || VirtualAt(program, direct, 0, .Define) < 0 || token < 0 || base < 0 ||
!ImmediateAt(program, direct, 3, *covered) || !ImmediateAt(program, direct, 4, *flags) ||
covered > 9223372036854775807 || flags > 1 { return false }
room := DirectRoom(state, program, definer, start, steps, token, base, flags == 1)
return room >= 0 && cast(s64)covered <= room
}
// A byte view at operand LOCAL, resolved for the count virtual after it.
ResolvedView :: (program: MachineProgram, definer: []s32, instruction: MachineInstruction, local: s32) -> bool {
address := VirtualAt(program, instruction, local, .Use)
@@ -744,6 +792,8 @@ CheckedMemory :: (state: *VerifyState, program: MachineProgram, limits: MachineL
defer VecFree(definer)
start: Vec(s32)
defer VecFree(start)
steps: Vec(s32)
defer VecFree(steps)
if !Definers(state, program, limits, *definer, *start) { return false }
for instruction_id: cast(s32)0..cast(s32)program.instructions.count - 1 {
if !Spend(state, 1) { return false }
@@ -754,14 +804,16 @@ CheckedMemory :: (state: *VerifyState, program: MachineProgram, limits: MachineL
address := ifx instruction.opcode == .Load then cast(s32)1 else 0
value := VirtualAt(program, instruction, 1 - address,
ifx instruction.opcode == .Load then MachineOperandRole.Define else .Use)
checked = value >= 0 && CheckedAddress(state, program, definer[:], start[:], instruction, address,
checked = value >= 0 && CheckedAddress(state, program, definer[:], start[:], *steps, instruction, address,
program.types[program.virtuals[value].type].size, instruction.opcode == .Store)
} else if instruction.opcode == .Zero {
address := VirtualAt(program, instruction, 0, .Use)
checked = instruction.operand_count == 1 && address >= 0 && CheckedAddress(state, program, definer[:],
start[:], instruction, 0, PointeeSize(program, program.virtuals[address].type), true)
start[:], *steps, instruction, 0, PointeeSize(program, program.virtuals[address].type), true)
} else if instruction.opcode == .BytesEqual {
checked = ResolvedView(program, definer[:], instruction, 1) && ResolvedView(program, definer[:], instruction, 3)
} else if instruction.opcode == .PointerDirect {
checked = DirectProven(state, program, definer[:], start[:], *steps, instruction)
}
if state.diagnostic.problem != .None { return false }
if !checked { return Fail(state, .Unchecked, instruction = instruction_id) }
+2
View File
@@ -1165,6 +1165,8 @@ ElementAddress :: (state: *State) -> bool {
count := state.program.types[source_pointer.element].count
X86CompareImmediate(*state.writer, low, count)
TrapUnless(state, X86Below, MachineX64TrapReserved - 1)
} else if instruction.operand_count == 4 && OperandAt(state, 3).kind == .Immediate {
// The shared facts prove the index below this bound: no check.
} else if instruction.operand_count == 4 {
count := Register(state, 3, .Use)
if count == MachineNoId { return false }
+4 -2
View File
@@ -2021,13 +2021,15 @@ lower_convert(Fn *fn, const LirInstruction *instruction)
}
/* Leaves the byte offset `index * size` as i32 on the stack after checking
* index < count; index and count are integer values or count is constant. */
* index < count; index and count are integer values or count is constant.
* An index the shared facts prove below every count it can meet needs no
* check. */
static void
checked_index(Fn *fn, int32_t index, int32_t count_value, int64_t count_constant, int64_t size)
{
int32_t owner = fn->instruction && fn->instruction->result >= 0 &&
fn->instruction->result < fn->function->values.length ? fn->instruction->result : -1;
if(owner >= 0 && fn->proven && fn->proven[owner] && count_value < 0) {
if(owner >= 0 && fn->proven && fn->proven[owner]) {
get_i64(fn, index, 0);
if(size != 1) { i64_const(fn, size); op(fn, 0x7e); }
op(fn, 0xa7);
+6
View File
@@ -28,6 +28,12 @@ three places, each for a reason:
record through a parameter (any caller's pointer, possibly stale), and the 5
platform-call string arguments carry a run-time count. Both keep their
checks. The fixture prints `resolves=13 direct-frame=4`.
- Following the owner's "make sure we oly have guardarils wher ew enede
tehm", native code also drops index checks the intervals prove (not only
Wasm), and Wasm drops proven view checks. On the bench kernels Sieve and
Hash have no pointer or index checks left; Records' 15 proven
`extract`/`insert` indices are left to the native Records lane, which owns
those encoders.
## Verdicts
+23 -6
View File
@@ -39,8 +39,9 @@ Counts :: (test: *NativeTest, path: string, counts: *Pipeline.MachineChecks) ->
defer Proven.LirProvenFree(*facts)
proved := Proven.LirProvenBuild(*facts, Link.ZxExecReadProgram(*owner), Lir.LirDefaultLimits())
if !NativeAssert(test, proved.problem == .None, CheckConcat("the shared facts failed for ", path)) { return false }
print("% rooted=% proven-indices=% resolves=% direct-global=% direct-frame=% index-checks=%\n", PathName(path),
proved.rooted, proved.indices, counts.resolves, counts.direct_global, counts.direct_frame, counts.index_checks)
print("% rooted=% proven-indices=% resolves=% direct-global=% direct-frame=% index-checks=% index-proven=%\n",
PathName(path), proved.rooted, proved.indices, counts.resolves, counts.direct_global, counts.direct_frame,
counts.index_checks, counts.index_proven)
return true
}
@@ -181,8 +182,8 @@ main :: (argc: s32, argv: **u8) -> s32 {
direct := Bundle(*test, tools, test.work, "direct",
"table: [4]s64 = .{10, 20, 30, 40};\nMark :: (value: *s64) { <<value += 1 }\n#program_export\nmain :: () -> s64 {\n local: [8]s64\n Mark(*local[0])\n for i: 0..7 { local[i] += cast(s64)i * 3 }\n total := table[2] + local[5]\n for i: 0..3 { total += table[i] }\n table[1] = 7\n return total + table[1]\n}\n")
if test.failed || !Counts(*test, direct, *counts) { return 1 }
if !NativeAssert(*test, counts.resolves == 2 && counts.direct_global == 5 && counts.direct_frame == 3,
"global and frame array accesses are not all direct") ||
if !NativeAssert(*test, counts.resolves == 2 && counts.direct_global == 5 && counts.direct_frame == 3 &&
counts.index_checks == 0 && counts.index_proven == 7, "global and frame array accesses are not all direct") ||
!Runs(*test, tools, direct, "152\n") || !WasmRuns(*test, tools, direct, "152\n") ||
!Tampered(*test, direct) { return 1 }
@@ -191,8 +192,8 @@ main :: (argc: s32, argv: **u8) -> s32 {
index := Bundle(*test, tools, test.work, "index",
"limit: s64 = 9;\nMark :: (value: *s64) { <<value += 1 }\n#program_export\nmain :: () -> s64 {\n local: [4]s64\n Mark(*local[0])\n local[limit] = 1\n return local[limit]\n}\n")
if test.failed || !Counts(*test, index, *counts) { return 1 }
if !NativeAssert(*test, counts.resolves == 2 && counts.direct_frame == 2 && counts.index_checks == 3,
"the runtime-index accesses are not direct behind their index checks") ||
if !NativeAssert(*test, counts.resolves == 2 && counts.direct_frame == 2 && counts.index_checks == 2 &&
counts.index_proven == 1, "the runtime-index accesses are not direct behind their index checks") ||
!Runs(*test, tools, index, "") || !WasmRuns(*test, tools, index, "") { return 1 }
// A heap block moved by growth: the stale element pointer has no root,
@@ -212,6 +213,22 @@ main :: (argc: s32, argv: **u8) -> s32 {
"the escaped frame pointer's read is not the one resolve") ||
!Runs(*test, tools, stale, "") { return 1 }
// A constant text read as a view: the loop's index is proven below the
// text's count and the bytes are read directly; a runtime index past the
// count reads directly behind its kept check, which traps.
text := Bundle(*test, tools, test.work, "text",
"TEXT :: \"the quick brown fox\";\n#program_export\nmain :: () -> s64 {\n total: s64\n for i: 0..cast(s64)TEXT.count - 1 { total += cast(s64)TEXT[i] }\n return total\n}\n")
if test.failed || !Counts(*test, text, *counts) { return 1 }
if !NativeAssert(*test, counts.resolves == 0 && counts.direct_global == 1 && counts.index_checks == 0,
"the text loop's read is not direct behind a proven index") ||
!Runs(*test, tools, text, "1843\n") || !WasmRuns(*test, tools, text, "1843\n") { return 1 }
past_text := Bundle(*test, tools, test.work, "past_text",
"TEXT :: \"the quick brown fox\";\nlimit: s64 = 40;\n#program_export\nmain :: () -> s64 {\n return cast(s64)TEXT[limit]\n}\n")
if test.failed || !Counts(*test, past_text, *counts) { return 1 }
if !NativeAssert(*test, counts.resolves == 0 && counts.direct_global >= 1 && counts.index_checks == 1,
"the read past the text is not direct behind its index check") ||
!Runs(*test, tools, past_text, "") || !WasmRuns(*test, tools, past_text, "") { return 1 }
// Indices a loop bounds: the shared intervals prove both sieve indices
// inside the array, so Wasm drops their checks; the same loop one step
// past the end keeps its check and traps on both routes.