Skip to content

Unsafe

Isolate operations whose invariants the type checker cannot prove.

unsafe { ... } authorizes calls and operations marked unsafe. It is an expression, so its tail value can be bound or returned:

import intrinsics

fn main() void {
    size := intrinsics.size_of[int]()
    align := intrinsics.align_of[int]()

    value := unsafe {
        block := intrinsics.alloc(size, align)
        slot := intrinsics.to_raw[int](intrinsics.ptr_cast[u8, int](block))
        intrinsics.store[int](slot, 42)
        read := intrinsics.load[int](slot)
        intrinsics.dealloc(block, size, align)
        read
    }
    println("value ${value}")
}

Without the block, each of those calls is a hard error:

import intrinsics

fn main() void {
    size := intrinsics.size_of[int]()
    align := intrinsics.align_of[int]()
    block := intrinsics.alloc(size, align)
    println("${size} ${align}")
}

ATOLL4010: call to unsafe fn alloc requires an unsafe { ... } block or an enclosing unsafe fn. Note that size_of and align_of are safe — the permission you need is exactly as narrow as the operations you call.

What it changes

Unsafe code may perform operations whose initialization, lifetime, alignment, aliasing, or representation requirements cannot be verified normally. It does not disable parsing, name resolution, generic checking, or type checking, and it does not:

  • make an invalid cast correct;
  • keep an allocation alive;
  • pin a movable buffer;
  • turn a raw pointer into an owned value;
  • let a raw pointer cross a suspension point;
  • guarantee that a host-provided address is inside guest memory.

The permission is lexical. Calling an unsafe operation needs an enclosing unsafe block even when the surrounding function is mostly low-level work, which keeps the proof boundary visible during review.

Pointer kinds

ptr[T] names a block: it carries the block’s size class alongside the address, which is how the allocator answers “which block is this” in constant time. Retain, release and free all need that answer, so a ptr[T] is what a collection keeps in a field and what the allocator hands out and takes back.

A ptr[T] field counts nothing: copying one out of the field retains nothing, and releasing a struct with no Drop frees nothing through it, so a type that owns a block through a ptr gives it back by hand, in its Drop. Today’s compiler still frees a ptr[T] field’s block with a struct that has no Drop.

rawptr[T] reaches bytes: the bare address every load, store, bulk-memory and SIMD operation takes. intrinsics.to_raw is the one conversion between them, and it strips the tag rather than adding a base — it compiles to no instructions at all.

The two rules that follow from the difference are both compiler-enforced:

  • a rawptr may not be live across a suspending call (ATOLL4011);
  • a rawptr may not be written into memory — no struct field, no collection element, no intrinsics.store value (ATOLL4012) — except into a struct field marked unsafe, below.

Neither is about the address going stale. A block never moves. They are about the address not being a reference: nothing counts a rawptr, so nothing keeps its block alive. The second rule is what makes the first checkable — an address that cannot be stored cannot outlive the region that derived it, so its live range is a local’s.

Unsafe fields

Some structures keep a byte address rather than a block: a cursor into the middle of a buffer, a block allocated by hand and given back with drop_in_place and dealloc, memory a host handed over. A ptr[T] names a whole block the allocator handed out, and a plain rawptr field is refused (ATOLL4012). Such a field is marked unsafe and given a rawptr[T] type: it owns nothing, it is set only inside unsafe { ... } (ATOLL4014), and it never leaves the process (ATOLL8016, ATOLL1126).

import intrinsics

struct Routes { names []string }

struct Page {
    title string
    unsafe slot  rawptr[Routes]
}

fn route_count(page &Page) int {
    // SAFETY: `main` keeps the slot alive while any `Page` holds its address.
    routes := unsafe { intrinsics.load[Routes](page.slot) }
    return routes.names.len()
}

fn main() void {
    size := intrinsics.size_of[Routes]()
    align := intrinsics.align_of[Routes]()
    unsafe {
        block := intrinsics.alloc(size, align)
        slot := intrinsics.raw_cast[u8, Routes](intrinsics.to_raw[u8](block))
        intrinsics.store[Routes](slot, Routes { names: ["/", "/about"] })
        page := Page { title: "home", slot: slot }
        println("${page.title}: ${route_count(&page)} routes")
        intrinsics.drop_in_place[Routes](slot)
        intrinsics.dealloc(block, size, align)
    }
}

The field is written unsafe name rawptr[T]; with a visibility it is pub unsafe name rawptr[T], the order pub unsafe fn takes (the parser reads either order). What the marker means:

  • Only a rawptr[T]. unsafe on a field of any other type, a rawptr[T]? or a ptr[T] included, is ATOLL4015. A plain rawptr field is still ATOLL4012, and its help names both routes: a ptr[T], an address nothing counts, or an unsafe field that holds an address you manage yourself. Today’s help still says the ptr[T] owns its block.
  • It owns nothing. Releasing the struct leaves the pointee alone, the cycle collector does not walk through the field, and the field is one address word.
  • Setting it is unsafe. A struct literal that names the field, or an assignment to it, needs an unsafe { ... } block or an enclosing unsafe fn (ATOLL4014) — the struct’s own methods included. Reading it is safe; using the address takes the unsafe intrinsics already.
  • The struct goes wherever a struct goes within one program: into another struct’s field, a list, a closure’s captures, an intrinsics.store. A copy copies the address. ATOLL4012’s other shapes treat the struct as opaque.
  • It never leaves the process. No encoding is derived for a struct that holds an unsafe field, or for one that holds such a struct (ATOLL8016), and a service operation cannot take or answer one (ATOLL1126). There is no check at a crossing between reactors yet; the address would mean nothing in another reactor’s heap either.

Keeping the block alive is the author’s obligation, for as long as any copy of the struct holds the address — and across suspensions too. ATOLL4011 reads the live range of a local, and an address in a field has left every local; the compiler cannot see it held across a suspending call, nor the block behind it freed while a copy still holds it.

import intrinsics

struct Cursor {
    unsafe at   rawptr[u8]
    left usize
}

fn start(block ptr[u8], n usize) Cursor {
    at := unsafe { intrinsics.to_raw[u8](block) }
    return Cursor { at: at, left: n }
}

Enum payloads have no unsafe marker: an address in an enum’s payload is still ATOLL4012.

The unsafe block still owns:

  • valid allocation and alignment;
  • initialized reads;
  • correct element type and size;
  • no use after release or reallocation;
  • compatible aliasing and mutation;
  • balanced ownership when bypassing managed wrappers.

A collection’s block, which as_ptr() points at, is shared until something writes. A copy of a list names the same block, and so does every evaluation of a list literal of constants, whose block is static storage the program never frees, as a string literal’s bytes are. The standard library’s mutators copy a shared block before they write. A write through as_ptr() takes the same step: it goes only into a block this value alone owns, which intrinsics.is_unique_block answers for, or which a reserve of at least one element has just made it own. as_ptr() is an unsafe fn: a list’s and a string’s data, filled and cap are the standard library’s own, and a program reads the two numbers through len() and capacity().

Pointer arithmetic is layout-sensitive. Ask the compiler rather than repeating a constant:

import intrinsics

struct Row { id u32, score u64 }

fn main() void {
    stride := intrinsics.size_of[Row]()
    align := intrinsics.align_of[Row]()

    second := unsafe {
        block := intrinsics.alloc(stride * 2, align)
        first := intrinsics.to_raw[Row](intrinsics.ptr_cast[u8, Row](block))
        intrinsics.store[Row](first, Row { id: 1, score: 10 })

        raw := intrinsics.to_raw[u8](block) + stride
        next := intrinsics.raw_cast[u8, Row](raw)
        intrinsics.store[Row](next, Row { id: 2, score: 20 })
        read := intrinsics.load[Row](next)

        intrinsics.dealloc(block, stride * 2, align)
        read
    }
    println("row ${second.id} scored ${second.score}")
}

Suspension

A raw pointer must not be live across a suspending call. The address itself stays good — a block never moves — but a rawptr is not a reference. to_raw strips the tag that says which block the address is in, so nothing counts it and nothing keeps that block alive. Inside one non-suspending region that is free, because nothing else runs. A suspending call is where the frame parks and the heap goes to whoever is next: another task can allocate, free, grow a collection out of its size class, or trip a cycle collection. The block below is that mistake, and the compiler refuses it with ATOLL4011:

import intrinsics
import time

fn main() void {
    len := 8usize
    align := intrinsics.align_of[u32]()
    unsafe {
        block := intrinsics.alloc(len, align)
        raw := intrinsics.to_raw[u8](block)
        time.sleep(time.Duration.of_millis(1))
        intrinsics.mem_fill(raw, 0u8, len)   // ATOLL4011
        intrinsics.dealloc(block, len, align)
    }
}

The compiler asks about a live range, not about where to_raw is written. An address derived and retired before the call is untouched, and so is one derived inside a loop body that suspends after it — that derivation runs again every iteration. What is refused is an address that has to survive the park.

The fix is structural: finish the raw work inside a non-suspending region and hand back a managed value.

import intrinsics

fn decode_word(view []byte) int? {
    if view.len() < 4 {
        return None
    }

    value := unsafe {
        // SAFETY: the length check above covers all four bytes, and the region
        // does not suspend between taking the address and the load.
        pointer := intrinsics.raw_cast[u8, u32](intrinsics.to_raw[u8](view.as_ptr()))
        intrinsics.load[u32](pointer)
    }
    return Some(value.to_int())
}

fn main() void {
    println("abcd -> ${decode_word("abcd".to_bytes()) ?? -1}")
    println("ab   -> ${decode_word("ab".to_bytes()) ?? -1}")
}

Do not call a suspending file, network, task, stream, or clock operation while a raw pointer is part of the live computation.

Containment

Keep unsafe blocks small and put a total, safe signature around them. The check that justifies the block belongs at the boundary, in front of the caller, not buried inside the implementation:

import intrinsics

struct Header { kind u32, length u32 }

fn read_header(view []byte) Header? {
    size := intrinsics.size_of[Header]().to_int()
    if view.len() < size {
        return None
    }

    header := unsafe {
        // SAFETY: the view holds at least `size_of[Header]` bytes, the wire
        // layout is fixed by the protocol, and nothing here suspends.
        pointer := intrinsics.raw_cast[u8, Header](intrinsics.to_raw[u8](view.as_ptr()))
        intrinsics.load[Header](pointer)
    }
    return Some(header)
}

fn describe(view []byte) string {
    match read_header(view) {
        Some(header) => "kind ${header.kind} length ${header.length}"
        None => "truncated"
    }
}

fn main() void {
    println(describe("abcdefgh".to_bytes()))
    println(describe("ab".to_bytes()))
}

The unsafe region is three lines wide, the precondition is a length test the caller cannot skip, and the failure mode is None rather than a corrupt value. Prefer an existing standard-library wrapper over writing your own, because it already participates in suspension, cleanup, and host ABI rules.

Review checklist

For each unsafe block, a reviewer should be able to answer:

  1. Where did every pointer originate?
  2. What proves the range and alignment?
  3. Which value owns the allocation for the whole access?
  4. Are reads initialized and stores valid for T?
  5. Can mutation reallocate or alias the same storage?
  6. Can control flow suspend, return, or raise an error before cleanup?

If the proof cannot be stated locally, move the operation behind a smaller, well-tested wrapper.

Type to search…

↑↓ navigate↵ selectEsc close