Skip to content

Docs/Language/Safety Annotations

Safety Annotations

Annotations that check domain rules at compile time: linear values, money conservation, crash-freedom, cost budgets, secrets, and timing.

~8 min read

On this page

Annotations add checks for specific domains. Most are compile-time checks of what a function’s body does; they are not proofs of correctness. fid enforces 17 safety rules, and each has at least one test program the compiler must reject (the rules and their tests). Coverage differs by annotation, as noted below and in Feature Status.

Not a certification. No certification body has assessed the toolchain, and Fid is not suitable for medical, automotive or avionics use. fid qualify reports evidence for a reviewer, and always says NOT_QUALIFIED.

Linear types and conservation

A @linear struct can be used only once:

@linear
struct Token { id: i64 }

fn spend(t: Token) -> i64 { return t.id; }

fn main() -> i64 {
    val t = Token { id: 1 };
    val a = spend(t);
    val b = spend(t);      // second use
    return 0;
}
error: Linear type error (line 9): variable 't' was already consumed (moved).

Using a linear value inside a loop is also rejected. The money module’s Money type is linear.

A @conserve function may not perform IO or network effects, use floating point, mint money, or call a function that is not @conserve:

use money;

@conserve
fn bad_transfer(cents: i64) -> Money {
    return Money_new(cents);   // creates money
}
Conservation error: function 'bad_transfer' is @conserve but calls 'Money_new',
    which is not @conserve.

txn { ... } marks a transaction. The interpreter rolls the block’s writes back if it panics; compiled code runs the block without rollback.

Crash-freedom and bounded cost

@crashfree rejects code that can panic (unwrap, unchecked indexing, overflowing arithmetic) and while loops. @wrapping makes arithmetic wrap instead of panic:

@crashfree
fn next_reading(sensor: i64) -> i64 {
    return sensor + 1;
}
error: Safety error (crashfree) (line 3): function 'next_reading' uses integer `+`/`-`/`*`, which panics on overflow (mark the function @wrapping for two's-complement arithmetic).

With @crashfree @wrapping the same function compiles. @gas(N) limits a static cost estimate of the function body and its callees. Each statement and expression counts once, and the body of a loop with literal bounds counts once per trip (a loop with other bounds counts one trip):

@gas(10)
fn step(a: i64, b: i64) -> i64 {
    val c = a * b + a - b;
    val d = c * c + a;
    return d * 2 + c;
}
Gas error: function 'step' has @gas(10) but total gas cost is 20 (own: 20 + callees: 0).

@no-recursion rejects direct and indirect recursion; @no-unbounded rejects while loops (use for over a range); @bounded-stack requires everything reachable to be non-recursive and called directly, and @bounded-stack(N) also limits the deepest call chain to N frames. @no-alloc rejects allocating calls, Vec::new(), allocating methods such as .push() and string +:

@no-alloc
fn collect(n: i64) -> i64 {
    var v: Vec<i64> = Vec::new();
    v.push(n);
    return v.len();
}
error: Safety error (safety-annotated): function 'collect' is @no-alloc but calls 'Vec_new'.
error: Safety error (safety-annotated): function 'collect' is @no-alloc but uses .push(), which allocates.

@no-indirect rejects calls through a function parameter, a closure or dyn:

error: Safety error (safety-critical): function 'run' is @no-indirect but calls its parameter 'f', a function value.

A safety-annotated function may only call functions and methods that have every safety rule it has.

Regulated-domain presets

AnnotationExpands to
@medical (alias @dal-a)no-alloc, no-recursion, no-unbounded, no-panic, and requires @audit
@safety-criticalno-alloc, no-recursion, no-unbounded, no-panic, no-indirect
@autosarno-alloc, no-recursion, no-unbounded, no-panic

@audit logs each call with its arguments:

@medical @audit
fn dose(weight_kg: f64) -> f64 {
    return weight_kg * 0.5;
}

fn main() -> i64 { println(dose(30.0)); return 0; }

Output: [AUDIT] enter dose(weight_kg=30), [AUDIT] exit dose, 15. Without @audit:

Safety error (medical (IEC 62304 / DAL-A)): function 'dose' is @requires-audit but not @audit.

@realtime rejects IO, Net and Spawn effects, while loops, recursion, and allocating, blocking or dynamically dispatched calls (Real-time error: function 'control' calls 'push'.); deadlines are not checked. @deterministic rejects IO, network and floating point (Determinism error: function 'score' is @deterministic but has effect '!IO'.). @firmware rejects calls to OS-dependent runtime functions such as files, sockets, processes, threads and the environment (function 'boot' is @firmware but calls 'p_file_read').

Contracts

A given precondition is checked at compile time when the call’s arguments are constants. It is not checked at run time.

fn safe_divide(a: i64, b: i64) -> i64 given b != 0 {
    return a / b;
}

fn main() -> i64 {
    println(safe_divide(10, 0));
    return 0;
}
Contract error (F10): precondition violated in call to 'safe_divide'. The 'given' contract is not satisfied with the provided arguments.

Secrets and personal data

A @secret parameter or local cannot reach an output such as println, and a function that returns one must itself be @secret or @declassify:

fn check(@secret token: str) -> bool {
    println(token);
    return str_len(token) == 32;
}
error: Security error (@secret) (line 2): in 'check', a secret value reaches output 'println'
error: Security error (@secret) (line 3): in 'check', returns a secret value; mark the function @secret (callers keep its result secret) or @declassify (an audited release)

@tainted on a parameter makes its function reject IO and Net effects (Taint error: function 'log_input' is @tainted but has effect '!IO' which could leak tainted data).

@sensitive applies the @secret rule to personal data, with one way out: release(consent, value) from the privacy module, which checks consent at run time.

fn send_analytics(@sensitive user_id: i64) {
    println(user_id);
}
error: Security error (@sensitive) (line 2): in 'send_analytics', a sensitive value reaches output 'println'; release it through privacy::release (a consent check) or mark the function @declassify

@zeroize on a local overwrites it (and the bytes of a str or Vec it holds) with zeros at function exit: @zeroize val key = load_key();.

Constant-time code

@constant_time rejects branches, loops, indexing, division and early returns that depend on secret inputs (every parameter not marked @public), and calls to functions that are not @constant_time:

@constant_time
fn same(a: i64, b: i64) -> bool {
    if a == b { return true; }
    return false;
}
error: Security error (constant_time) (line 3): function 'same' has an early return.
error: Security error (constant_time) (line 3): function 'same' branches on secret data (`if`).

fid checks the source only, not the generated code. The frozen fidesc also scans the final machine code on its x86-64 Linux (ELF) path.

Typed strings

The typed_strings module has SQLString, ShellString, HTMLString, JSONString and PathString. A function that takes one will not accept a plain str:

use typed_strings;

fn run_query(q: SQLString) -> str {
    return q.raw();
}

fn main() -> i64 {
    val name = "O'Brien";
    val q = sql_bind(sql_query("SELECT * FROM users WHERE name = '?'"), name);
    println(run_query(q));     // SELECT * FROM users WHERE name = 'O''Brien'
    return 0;
}

Passing "SELECT ... '" + name + "'" to run_query instead is rejected: function 'run_query' parameter 1 expects 'SQLString', got 'str'. The constructors (sql_query, sql_literal) accept any str, so keep user input out of them and pass it through sql_bind or the *_escape helpers.

Always-on checks

Integer overflow and out-of-bounds indexes panic at run time, in release builds too. @wrapping opts a function out of overflow checks; checks inside unsafe { } may be skipped.

@wrapping
fn hash_step(h: i64) -> i64 {
    return h * 31 + 7;                 // wraps on overflow
}

fn main() -> i64 {
    println(hash_step(9223372036854775807));
    var v: Vec<i64> = Vec::new();
    v.push(1);
    println(v[5]);                     // out of bounds
    return 0;
}

Output: 9223372036854775784, then Panic: Vec index out of bounds. Executables built through C get stack canaries and PIE; on Linux also full RELRO and a non-executable stack.

Other annotations

  • @interrupt(N) / interrupt fn mark interrupt handlers (register save and iret); install the IDT entry with p_idt_set_entry and p_lidt. Bare-metal output is experimental.
  • @differentiable, @quantized, @checkpoint, @dp(epsilon=...), @shard and @adapter are accepted and partly checked; see Feature Status.
  • @sync, @test, @bounded, @sanitizer, @sink, @panic_handler and @cpu_local are accepted by the name check and have no effect. Any other unknown annotation is an error, and so is an annotation on the wrong kind of item. Annotations cannot be written on methods inside impl blocks.

The rules and their evidence

IdRuleRejected by (negative tests)
SR-1@no-alloctest_safety_method_alloc_fail, test_medical_fail
SR-2@no-recursiontest_safety_recursion_fail
SR-3@no-unboundedtest_safety_annotations_fail
SR-4@no-panic (@crashfree)test_crashfree_fail, test_crashfree_index_fail, test_crashfree_overflow_fail, test_crashfree_method_fail
SR-5@no-indirecttest_safety_indirect_fail
SR-6@requires-audittest_safety_no_audit_fail
SR-7transitive callstest_medical_fail, test_crashfree_method_fail
SR-8@firmwaretest_firmware_os_fail
SR-9@gas(N)test_gas_fail, test_gas_loop_fail
SR-10@bounded-stacktest_bounded_stack_fail
SR-11@deterministictest_deterministic_fail
SR-12@taintedtest_tainted_param_fail
SR-13@secrettest_secret_output_fail, test_secret_global_fail, test_secret_branch_fail, test_secret_helper_fail, test_secret_return_fail
SR-14@constant_timetest_constant_time_fail, test_constant_time_branch_fail, test_constant_time_index_fail
SR-15sandboxtest_sandbox_fail, test_sandbox_alloc_fail
SR-16@sendtest_spawn_send_fail, test_send_fail
SR-17borrowstest_iter_invalidation_fail, test_field_borrow_fail

Each negative test in tests/bootstrap/ names the error it expects on its first line (// expect-error:), and the test harness fails if the program is accepted. The full table, with each rule’s requirement and the tests that must be accepted, is docs/reference/safety-rules.md in the repository.

fid qualify writes the same table for a program as JSON: the compiler and source hashes, whether the checks passed, every annotated function with its rules, and for each rule its requirement and whether each test file is present.

fid qualify sensor.fd -o evidence.json

The report always ends with "qualification": "NOT_QUALIFIED": it is evidence for a reviewer, not a certificate.

Known limits: a method call is matched to a user method by name, not by the receiver’s type; @gas counts one trip for a loop whose bound is not a literal; fidesc (frozen) checks less than fid.

Report an issue