Dev.to Security πŸ” Cybersecurity πŸ‘ 2 πŸ“– 10 min read

What If Assembly Had a Type System? Verifying Machine-Code Memory Safety in Lean 4

What if we applied a type system inspired by Rust directly to assembly, enabling us to guarantee memory safety at the machine-code level, and formally proved the soundness of the type checker itself in Lean 4?

What If Assembly Had a Type System? Verifying Machine-Code Memory Safety in Lean 4

What if we applied a type system inspired by Rust directly to assembly, enabling us to guarantee memory safety at the machine-code level, and formally proved the soundness of the type checker itself in Lean 4?

1. Why Do We Need a Type System for Assembly?

Rust has become increasingly popular in recent years, largely because its type system enables memory safety to be checked at compile time.

However, what a CPU actually executes is not Rust source code, but the machine code generated by a compiler. Even if memory safety has been established at the source-code level, a bug in the compilation process could theoretically produce machine code that violates memory safety. And, as with any large and complex software project, compilers are not immune to bugs.

What if we could attach types directly to assembly and guarantee memory safety at the machine-code level? This is one of the motivations behind NoCompiler, an open-source project I am currently developing.

GitHub logo h5i-dev / NoCompiler

Not Only Compiler. Typed RISC-V Assembly for Verified Memory Safety and Equivalence, proved in Lean 4.

NoCompiler

NoCompiler is a typed RISC-V assembly language for statically verifying memory safety and functional equivalence at the machine-code level, with soundness proofs in Lean 4. It enables formally verified machine-code generation and optimization, regardless of whether the code is written by humans, generated by compilers, or produced by AI agents.

Motivation

  • Can we go beyond compilers? AI agents can optimize machine code beyond conventional compiler passes. Formal verification ensures behavioral equivalence and memory safety.
  • Why trust a compiler? Source-level safety guarantees do not automatically extend to executable machine code without trusting the compilation process.
  • Why manually prove machine-code properties? A type system can automate reasoning about memory safety and functional equivalence directly at the machine-code level.
  • Why restrict AI agents to high-level languages? With a formally verified type system, AI agents could generate safe machine code directly, bypassing conventional compilers entirely.

Our answer

  • Typed RISC-V assembly: RV64 assembly with…

NoCompiler is a typed RISC-V assembly where we can formally verify memory safety by adding type annotations to RISC-V assembly. Furthermore, the soundness of its type checker is formally proved in Lean 4 against the formal semantics of RISC-V.

This allows us to verify not only compiler-generated code but also assembly directly written, generated, or modified by humans and AI agents, using the same verification mechanism.

graph TD
    A["Rust / C / C++"] --> B["Compiler"]
    B --> D["Machine Code"]
    C["Human / AI Agent"] --> D
    D --> E["NoCompiler Type Checker"]
    F["Type Annotations"] --> E
    E --> G["Verified Machine Code"]

In this article, I'll walk through a simple function that sums the elements of an array and explain how NoCompiler verifies its memory safety and how the soundness of the type checker itself is formally proved.

2. Typed Assembly

Consider the following Rust function:

fn sum(xs: &[u64]) -> u64 {
    let mut result = 0u64;
    for x in xs {
        result = result.wrapping_add(*x);
    }
    result
}

One possible corresponding RISC-V assembly implementation is:

sum:
    li   a2, 0
    beqz a1, .LBB0_2
.LBB0_1:
    ld   a3, 0(a0)
    add  a2, a3, a2
    addi a1, a1, -1
    addi a0, a0, 8
    bnez a1, .LBB0_1
.LBB0_2:
    mv   a0, a2
    ret

When the function is called, we assume that register a0 contains the starting address of the array and a1 contains the number of elements.

The instruction ld a3, 0(a0) loads eight bytes from the address stored in a0. However, the instruction itself carries no information about the length of the array. If we make a mistake when updating the pointer, the program may read beyond the array's boundaries.

With NoCompiler, we can add the following type annotations to this assembly:

#: fn sum [ρ, n]
#:   in     a0: int(ρ), a1: int(n)
#:   borrow ρ ↦ bytes[8n] ro
#:   where  8 ∣ ρ
#:   out    a0: int
#:   stack  0
sum:
    li   a2, 0
    beqz a1, .LBB0_2
.LBB0_1:
    #: inv [k] a0: int(ρ + 8n βˆ’ 8k), a1: int(k), a2: int where 1 ≀ k ≀ n decreases k
    ld   a3, 0(a0)
    add  a2, a3, a2
    addi a1, a1, -1
    addi a0, a0, 8
    bnez a1, .LBB0_1
.LBB0_2:
    mv   a0, a2
    ret

The lines beginning with #: are NoCompiler's type annotations. To a conventional assembler, these are simply comments, meaning that we can continue using existing RISC-V toolchains without modification.

Let's take a closer look at what these annotations mean.

2.1. Value-Dependent Types

#: fn sum [ρ, n]
#:   in a0: int(ρ), a1: int(n)

Here, ρ and n are symbolic variables. The type int(ρ) means that the value stored in the register is the 64-bit representation of the integer expression ρ .

Unlike conventional integer types, these types allow us to symbolically track the actual values stored in registers, rather than merely establishing that they contain integers.

For example, given a register with type a0: int(ρ), executing the following instruction:

addi a0, a0, 8

allows the type checker to update the type of a0 to int(ρ + 8).

By using such value-dependent types, we can statically reason about the results of pointer arithmetic, even when the concrete addresses are not known until runtime.

2.2. Memory Permissions

#: borrow ρ ↦ bytes[8n] ro

This annotation specifies that the function borrows read permission from its caller for a memory region of 8n bytes starting at address ρ . The accessible region is represented by the following half-open interval:

[ρ,ρ+8n)

We refer to such permissions over memory regions as memory capabilities. The annotation ro denotes read-only permission, while rw denotes read-write permission.

An important distinction here is that knowing a memory address and having permission to access that address are two different things. Assigning an arbitrary integer to a register does not create a new memory capability.

The remaining parts of the function signature specify the required eight-byte alignment of the address (where), the type of the return value (out), and the amount of stack space required by the function (stack).

3. What Does the Type Checker Actually Do?

NoCompiler's type checker reasons about an abstract state at each program point. For explanatory purposes, we can represent this state as follows:

S=(Ξ“,Ξ¨,C)

Here, Ξ“ represents the types of the registers, Ξ¨ represents the arithmetic constraints known to hold, and C represents the set of available memory capabilities.

The actual implementation also maintains additional information, such as the state of the stack and information about values stored in memory.

The type checker updates this abstract state according to the semantics of each instruction and generates logical conditions that must be satisfied to establish safety.

3.1. Checking Memory Accesses

Suppose an instruction reads w bytes from address a , and we have a memory capability with base address b and length l .

b                              b + l
|---------------------------------|
         |------------|
         a            a + w

    Memory access must fit
    inside the capability.

To permit this memory access, the type checker must establish that the following conditions follow from the current arithmetic constraints Ξ¨ :

Ψ⊨b≀a∧a+w≀b+l∧w∣a

The first two conditions ensure that the memory access stays within the capability's boundaries, while the final condition ensures proper alignment. For a store instruction, the type checker must additionally establish that the capability permits writing.

3.2. How Do We Verify Loops?

In our earlier sum example, the length of the array is not known until runtime. Consequently, we cannot simply unroll the loop a concrete number of times to verify it.

Instead, we use a loop invariant.

#: inv [k] a0: int(ρ + 8n βˆ’ 8k), a1: int(k), a2: int where 1 ≀ k ≀ n decreases k

Here, k represents the number of elements that have not yet been processed. Since nβˆ’k elements have already been processed, the current pointer can be expressed as:

a=ρ+8(nβˆ’k)

Furthermore, because we have entered the loop body, the following condition holds:

1≀k≀n

Using this invariant, let's verify the safety of the following instruction:

ld a3, 0(a0)

The available memory capability covers the region [ρ,ρ+8n) . Therefore, the required boundary conditions are:

ρ≀ρ+8(nβˆ’k)
ρ+8(nβˆ’k)+8≀ρ+8n

Simplifying these inequalities gives us k≀n and 1≀k , respectively.

Both conditions follow directly from the loop invariant. The alignment requirement is also satisfied because ρ is a multiple of eight.

We have therefore established that the memory access inside the loop is safe, independently of the concrete length of the array.

Of course, we do not blindly trust the annotated loop invariant itself. The type checker verifies that the invariant holds when execution first enters the loop and that it is preserved by every subsequent iteration.

graph TD
    A["Initial State"] -->|"Check invariant initialization"| B["Loop Invariant"]
    B --> C["Check Memory Access Safety"]
    C --> D["Update Register Types"]
    D -->|"Check invariant preservation"| B
    D -->|"Exit loop"| E["Return"]

Additionally, the annotation decreases k allows the type checker to establish that a nonnegative measure strictly decreases on each iteration. This provides the basis for proving termination of ordinary total functions.

3.3. What Happens If There Is a Bug?

Suppose we introduce a bug by modifying the load instruction as follows:

# Original
ld a3, 0(a0)

# Buggy
ld a3, 8(a0)

The modified instruction reads from an address eight bytes further ahead. Consequently, the required upper-bound condition becomes:

ρ+8(nβˆ’k)+16≀ρ+8n

Simplifying this inequality gives:

2≀k

However, the loop invariant only establishes that 1≀k .

Indeed, when k=1 , the modified instruction attempts to read beyond the last element of the array. Therefore, this implementation cannot pass NoCompiler's type checker under the original function signature.

4. Formally Verifying the Type Checker Itself

So far, we have seen how the type checker establishes the memory safety of assembly programs.

However, what if the type checker itself contains a bug? A buggy type checker could incorrectly accept an unsafe program, undermining the very guarantees we are trying to establish.

To address this problem, NoCompiler formally proves the soundness of its type checker in Lean 4.

4.1. Formal Semantics of RISC-V

First, we define the behavior of RISC-V instructions in Lean. A machine state includes the program counter, registers, memory, and other relevant components.

For example, we define how an addi instruction updates a register and how an ld instruction loads a value from memory, in terms of transitions between machine states.

Abstractly, we can represent such a transition as:

si​sβ€²

This means that executing instruction i in machine state s produces a new machine state sβ€² .

The important point is that the machine-code semantics and the abstract state transformations performed by the type checker are defined separately. We then formally prove that these two definitions are consistent.

4.2. Instruction-Level Soundness

For explanatory purposes, let's write:

s⊨S

to indicate that a concrete machine state s satisfies the conditions represented by an abstract state S .

Suppose the type checker accepts instruction i and produces a new abstract state Sβ€² .

We then prove that the corresponding machine-code execution is safe and that the resulting concrete machine state sβ€² satisfies the conditions represented by the new abstract state Sβ€² .

graph TD
    A["Abstract State S"] -->|"Type Checker"| B["Abstract State S'"]
    A --- C["Concrete Machine State s"]
    B --- D["Concrete Machine State s'"]
    C -->|"RISC-V Execution"| D

In other words, the abstract transformations performed by the type checker must soundly capture the behavior of the actual machine.

For example, NoCompiler includes lemmas such as Fn.arith_sound for arithmetic instructions, Fn.load_sound for memory loads, and Fn.store_sound for memory stores.

By composing these instruction-level soundness results, we can establish soundness guarantees for entire functions.

4.3. We Do Not Need to Trust the Arithmetic Solver Either

Throughout the memory access checks discussed earlier, we frequently encountered logical conditions of the following form:

Ξ¨βŠ¨Ο•

The question is whether the arithmetic constraints currently known to hold, Ξ¨ , logically imply a condition required for safety, Ο• .

NoCompiler uses Presburger arithmetic to reason about such linear integer arithmetic constraints.

However, if an arithmetic solver simply tells us that an implication holds, we would need to trust the correctness of the solver itself. A bug in the solver could otherwise compromise the soundness of the entire verification process.

Instead, NoCompiler uses a certificate-based approach. The proof search procedure generates a certificate, whose validity is independently checked in Lean.

graph TD
    A["Arithmetic Constraints and Target Condition"] --> B["Proof Search"]
    B --> C["Proof Certificate"]
    C --> D["Certificate Checker in Lean"]
    D --> E["Verified Arithmetic Implication"]

The soundness of the certificate checker itself is established by a theorem called Query.check_sound. Consequently, even if there is a bug in the proof search procedure, an invalid certificate cannot be accepted by the sound certificate checker.

4.4. Function-Level Soundness

One of the final soundness theorems is Fn.check_sound. A simplified excerpt of the theorem looks like this:

theorem Fn.check_sound
    (f : Fn) (c : Code) (T : TokEnv)
    (h : f.check c = true)
    -- Conditions on the code region and callees
    ... :
    Meets c D f.entry T f.sig

Here, f is a description of a function, including its type information, while c is the actual machine-code image. The predicate Meets defines what it means for a machine-code function to satisfy its specified function signature.

For ordinary total functions, the theorem guarantees that execution from an initial state satisfying the function signature proceeds without faults, accesses only permitted memory and stack regions, terminates, and satisfies the specified postconditions, subject to the theorem's assumptions.

For programs consisting of multiple functions, these function-level guarantees can be composed using the Prog.check_sound theorem.

5. Conclusion

NoCompiler is still in its early stages, and I would love to hear feedback from anyone working on compilers, programming languages, formal verification, embedded systems, or systems security.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.