Introduction
This is the reference for Fiducia, the source language consumed by the
fic compiler. A Fiducia source tree
describes a seL4 Microkit system: its
memory regions, protection domains, channels, the per-PD program logic, and
the communication / computation events those programs orchestrate.
Fiducia has two layers. The orchestration layer is written in Fiducia
itself: it says which channel events occur in a protection domain and in what
order, and fic generates the event loop and every Microkit call from it.
The computation layer is foreign code (C or Pancake) that the
orchestration calls from computation events; it holds the data flow.
Orchestration communicates; foreign functions compute. The two meet at a
narrow boundary that the compiler checks and the verifier reads.
The reference is organised after the Rust Reference: each chapter pairs a formal grammar production with the prose semantics that surround it, then expands per syntactic feature with focused subsections and short examples. Where the surface syntax is still in flight, the chapter calls out the incomplete forms with a 🚧 marker so the reference stays honest about what the parser actually accepts today.
Source surfaces
A Fiducia project is one directory holding the files the compiler reads together:
- System description (
.fis) — the static topology: the data layer (structandconstitems), memory regions, protection domains, channels, the system composition. One per project; it is the project. - Program implementations (
.fi) — per-PD orchestration: imports of foreign C / Pancake files, memory mappings, program variable declarations,evtdeclarations, andprocdefinitions. One per protection domain. - Foreign implementations (
.c,.h,.pnk) — the code a.fiimports. Not Fiducia source, but its signatures and contracts are read.
The .fis and the .fi files are linked by name. Each protection domain
p declared in the .fis is implemented by p.fi beside it: a PD without
that file is an error at its declaration, and so is a PD declared twice; a
.fi that no PD names is a warning and is never read. Within a program, a
Mapping refers to a MemoryRegion declared in the .fis; a channel
reference in a process expression resolves against the .fis channel
declarations; a computation event referenced by name from a process is
declared in the same .fi with evt. The Project
Layout chapter gives the full rules.
What the compiler does with a project
fic reads the sources, resolves every name, types the result and runs the
checks, then lowers each protection domain’s orchestration once into a
control-flow graph that every backend reads. From that graph it produces:
- a bootable Microkit image: generated C per protection domain, built with the foreign code and assembled with the generated system description; and
- a system model for UPPAAL, in which each protection domain is one template and each foreign function’s contract stands for its body, so that queries about the whole system (deadlock freedom, ordering, reachability) can be model-checked.
Parsing, name resolution, typing, tail recursion and entry-point binding
run for every output; fic --check runs every check. Running the model checker
and the code verifiers, and building and launching the image, are covered by
the manual; this reference
covers the language those tools read.
🚧 Type checking and well-formedness checking are not yet complete: the chapters on well-formedness and information flow state exactly what is checked today.
How this reference is organised
The chapters follow the project, outside in.
Foundations
- Notation — the BNF dialect the productions use.
- Lexical Structure and Types — tokens, and the types shared by both source surfaces.
System (.fis) items
- Project Layout — which files make a project and how a PD finds its program.
- Data Layer, Memory
Regions, Protection
Domains and
Channels — what the
.fisdeclares.
Program (.fi) items
- Imports and Mappings, Boot
Initialisation and Variable
Declarations — what a
.fibrings in and declares before its events and processes. - Event Declarations —
evtdeclarations for computation events, plus the inline channel and IRQ events used on the left of a process prefix. - Debug Output —
dbg,fic’s own output. - Process Definitions —
procdefinitions for CSP-style processes composed from events, guards, choices, and sequential composition.
Expressions and semantics
- Expressions — the expression language available to carriers, guards, and send payloads.
- Entry Points — how the platform reaches a
process, through
@bind.
Foreign functions
- Foreign Functions — what an import exposes and how calls are checked.
- Contracts — the
requires/ensuressubsetficreads, and what the model assumes of it. - Generated Headers — the layout
ficgenerates for the data layer, shared with the foreign code.
Checks
- Well-Formedness — the rules a system must satisfy before it is accepted, with the messages for each.
- Information Flow — the
High/Lowlattice over regions and mappings.
Where a chapter does not settle a point, the inline /// doc comments in
src/parser/ and src/tast/ are the reference for it.
Conventions
- Production blocks use the BNF dialect documented in Notation — the same conventions as the Rust Reference.
- Examples render in
textblocks; Fiducia is not Rust, andtextkeeps mdBook’s syntax-highlight neutral. - Keywords and identifiers are written with backticks in prose (
evt,eth.send_frame) and as bare tokens inside grammar productions. - An em-dash (—) separates parenthetical asides, matching the existing module-doc style.
- Cross-references to the parser source use repository-relative paths
(
src/parser/event.rs); cross-references to other chapters use plain Markdown links (e.g. Event Declarations).
Notation
This reference uses a BNF dialect for grammar productions. The notation is intentionally close to the Rust Reference so readers familiar with Rust documentation can read it without a separate primer.
Grammar productions
A production has the form LHS ::= RHS, where the right-hand side is a
sequence of terminals, non-terminals, and meta-operators. Productions are
written in text-tagged code blocks:
EventDecl ::= 'evt' ident carriers? ':' (stmt | '{' stmt* '}')
carriers ::= carrier_group+
carrier_group ::= '.' '|' param (',' param)* '|'
param ::= ident ':' type
Meta-operators
| Form | Meaning |
|---|---|
'literal' | A literal token (keyword, symbol). Matches verbatim. |
ident | An identifier: an ASCII letter or _, then letters, digits or _, and not a reserved keyword. |
UIdent | An ident whose first character is an uppercase ASCII letter (UpperCamelCase); process names and references. |
UPPER_IDENT | An ident written in upper case by convention (constants such as SLOT_SIZE); the parser accepts any ident. |
X? | Zero or one of X. |
X* | Zero or more of X. |
X+ | One or more of X. |
X | Y | Either X or Y. Listed alternatives appear on separate lines for readability when the disjunction is long. |
(X Y) | Grouping; otherwise meta-operators bind tighter than juxtaposition. |
Literals in a production are named by their lexical class (the lexical structure has the full rules):
| Name | Matches |
|---|---|
int_lit | A decimal integer (42); digits only, no _ separators. |
hex / hex_lit | 0x then hex digits; _ may separate them (0xFE00_0000). |
bool_lit / bool_literal | true or false. |
string_literal / text_literal | "..." of printable ASCII, with the escapes \\, \", \n and \t. |
Comments inside a production start with --; examples, which are Fiducia
source, use the language’s own // and /* */.
Whitespace between symbols in a production is significant only when called out — most productions allow inter-token whitespace and comments, exactly as the lexer does.
Inline references
- A non-terminal in prose is written in italics (e.g. event, process).
- A literal token in prose is written in backticks (e.g.
evt,->). - A type-level reference into the AST uses backticks plus the Rust path
fragment when it disambiguates (
Event::CPEvent,Process::Choice { branches, default }).
Examples
Examples render in text-tagged code blocks, not rust-tagged: the Fiducia
source language is not Rust, and text keeps mdBook’s syntax-highlighter
neutral. Example:
evt handle_irq:
eth.handle_irq();
Where an example references symbols declared elsewhere (a channel from the
.fis file, a function from an imported .c file, a process declared in
the same section), the surrounding prose names the dependency.
Stability markers
A construct flagged with the 🚧 marker is not yet implemented by the parser. The form appears in the reference because it is part of the designed grammar, but the parser will reject it today:
🚧 Not yet implemented.
Lexical Structure
A .fis and a .fi file are ASCII text read with the same lexer. This
chapter fixes the words the grammars use: what separates
tokens, what a name is, which words are reserved, and how literals are
written.
Whitespace and comments
Spaces, tabs and newlines separate tokens and are otherwise ignored. Comments count as whitespace:
// A line comment runs to the end of the line.
/* A block comment runs to the first closing star-slash. */
Block comments do not nest: /* a /* b */ c */ ends at the first */,
and c */ is then read as source.
Identifiers
ident ::= (letter | '_') (letter | digit | '_')* -- not a reserved word
UIdent ::= ident whose first character is an uppercase letter
letter and digit are ASCII. Case matters. A word that merely starts
with a reserved word is an identifier: irq_count and Mapping_x are
names.
UIdent is what a process is called, in its proc declaration and at
each reference to it (Notified, Drain(x)). Everything else (variables,
events, parameters, mappings, memory regions, protection domains,
channels, structs, constants) takes any ident; the upper and lower case
styles in the other chapters are conventions the parser does not check.
Reserved words
A reserved word is not an identifier, so none can name a variable, event, mapping, region, protection domain, channel, struct or constant.
| Group | Words |
|---|---|
| Security labels | High, Low |
| System items | struct, const, MemoryRegion, ProtectionDomain, System, Chan, Sync, Async, via |
| Program items | import, as, Mapping, irq, evt, proc, default, dbg |
| Process terms | Skip, Div |
| Types | bool, byte, Address, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64 |
| Literals | true, false |
| Reserved, unused | void |
void is reserved so it cannot be read as a struct name; Fiducia has no
void type and no pointers (see Types).
sizeof is not on the list: a variable may be named sizeof. In an
expression, sizeof( followed by a type is the size operator (see
Expressions).
microkit, init and notified are ordinary identifiers; they have
meaning only inside an @bind annotation (see
Entry Points). Likewise packed, inside an
@attr annotation (see Data Layer).
Literals
| Literal | Form | Notes |
|---|---|---|
| Decimal | 0, 42 | Digits only: no _ separators, no leading zeros (07 is an error), no sign. The value must fit an int64. |
| Hexadecimal | 0x1000, 0xFE00_0000 | Lower-case 0x, then hex digits in either case; _ may separate digits after the first. The value must fit a uint64. |
| Boolean | true, false | |
| Text | "..." | Printable ASCII, with the escapes \\, \", \n and \t. Used for mapping permissions and debug output. |
A leading - is never part of a literal: -5 is the unary minus applied
to 5, which the compiler folds to one constant. There are no binary,
octal, character or floating-point literals.
An import path is not a text literal: it
is any characters between the quotes, up to the closing " or the end of
the line.
Punctuation
The process algebra’s operators are -> (event prefix), --> and <->
(channel directions), ||| (interleave), [] (choice), ! (send), ?
(receive) and ; (sequence); @ introduces an annotation. The
expression operators and their precedence are in
Expressions.
Types
Type ::= BaseType ('[' ArrayLen ']')?
BaseType ::= ScalarType | ident -- ident names a declared struct
ScalarType ::= 'bool' | 'byte' | 'Address'
| 'int' | 'int8' | 'int16' | 'int32' | 'int64'
| 'uint' | 'uint8' | 'uint16' | 'uint32' | 'uint64'
ArrayLen ::= int_lit | ident -- ident names a declared constant
Every variable, parameter, carrier, struct field and constant has a type
written this way. Fiducia has no pointer types and no void type.
Scalars
| Type | Meaning |
|---|---|
int8, int16, int32, int64 | Signed integers of that many bits. |
uint8, uint16, uint32, uint64 | Unsigned integers of that many bits. |
int | int64. The type of an integer literal with nothing to give it another. |
uint | uint64. |
byte | uint8, spelled uint8_t in the generated C. |
bool | true or false; not an integer. |
Address | A virtual or physical address, as wide as the platform’s. Arithmetic is defined on it. |
int, uint and byte are other names for int64, uint64 and
uint8: the same types, not conversions of them. The
data layer still rejects int and uint in a
struct field, since they name no fixed size there; use the sized types.
Address is the type of a mapping’s m.vaddr and m.paddr (see
Imports and Mappings).
Structs and arrays
A struct is declared in the .fis’s data layer and is visible to every
program by name. A fixed array T[N] holds N elements of one type;
N is an integer literal or a declared constant, and a type has at most
one array suffix: T[N], never T[N][M].
const LEN: uint = 4;
struct Header {
kind: uint8;
seq: uint8;
flags: uint16;
}
struct Frame {
head: Header;
data: byte[4];
}
done: bool;
raw: byte;
level: int8;
count: uint;
frame: Frame;
codes: uint16[LEN];
sizeof(T) is the size of any type in bytes, a constant: sizeof(Frame),
sizeof(uint16[LEN]). A struct’s fields are laid out as C lays
them out, in declaration order and padded, unless the struct is
@attr(packed) (see Data Layer).
A struct or array variable is assigned whole. A field of a
struct value is read with x.f (frame.head.kind); a field cannot be
assigned to, and there is no indexing of an array element in a .fi.
A channel’s slot type is a struct or a scalar, never an array (see
Channel Declarations).
Conversion
There are no implicit conversions. Both operands of an arithmetic,
bitwise or comparison operator have one type, and a literal takes the
type of the operand beside it. An assignment must match the type of the
variable it assigns exactly: a = raw is an error for an int a and a
byte raw.
The one conversion is the cast e as T:
done = step > 0;
level = step as int8;
count = step as uint + 1;
raw = frame.head.kind as byte;
- The target
Tis an integer type orAddress; the operand is an integer or an address. Abool, a struct and an array can be neither. asbinds tighter than the binary operators and looser than the unary ones, sostep as uint + 1is(step as uint) + 1(see Expressions).- A narrowing cast of a constant is not a constant overflow:
300 as uint8type-checks as auint8, where a bare300would not fit. - Unary
-is defined only on signed types;!only onbool.
Project Layout
A Fiducia project is one directory. The compiler is given that directory and reads these files from it:
datadiode/
datadiode.fis the system: one per project
eth_outer.fi the program of protection domain eth_outer
dd.fi the program of protection domain dd
eth_inner.fi the program of protection domain eth_inner
fire.toml read by fire, not by fic
The .fis
The directory holds exactly one .fis; it is the project. Its name is
free, and a directory with none, or with two, is an error. Everything the
system declares (the data layer, regions, protection
domains, channels and the System composition) is in it.
The .fi files
Each protection domain p is implemented by p.fi, in the same directory
as the .fis: the file name is the binding, and nothing inside either file
names the other. The directory is read for .fi files, not searched below:
- A protection domain with no
p.fiis an error at its declaration in the.fis, and so is a protection domain declared twice. - A
.fithat no protection domain names is a warning, and the file is never parsed. - A
.fiin a subdirectory is not seen.
Imports
An import path is relative to the
project directory, not to the .fi that writes it, so import "include/eth.h" as eth; reads datadiode/include/eth.h from any program in
the project. The extension picks the reader: .c and .h are C, .pnk
is Pancake.
Generated files
Compiling writes under the project directory, and nothing outside it
unless -o says so:
| Path | Written by | Holds |
|---|---|---|
include/gen/types.h | fic, --check included | the data layer as C: structs with _Static_assert layout checks, constants |
include/gen/types.pnk | the same, when a program imports Pancake | the same constants for Pancake |
include/gen/mem.h | the same, when a program imports C | the memory routines of a PD’s runtime, with their contracts |
build/ | --emit=c, fire build | the generated C (build/gen/), the image and the UPPAAL model |
<dir>.xta, <dir>.dot | fic --emit=xta, --emit=dot | the UPPAAL model and the topology graph, named after the project directory <dir> |
Both are generated on every run and are not to be edited or committed.
fire clean removes build/ and include/gen/, and include/ if that
leaves it empty; sources are never touched.
fire adds fire.toml beside the sources and hand-written query files
spec/*.q for verification. Their contents, and the commands, are in the
user manual.
Data Layer: Structs and Constants
StructDecl ::= Attr? 'struct' ident '{' Field* '}'
Attr ::= '@attr' '(' 'packed' (',' 'packed')* ')'
Field ::= ident ':' Type ';'
Type ::= BaseType ('[' ArrayLen ']')?
BaseType ::= ScalarType | ident // ident names a declared struct
ArrayLen ::= integer-literal | ident // ident names a declared constant
ConstDecl ::= 'const' ident ':' Type '=' Expr ';'
The data layer is the system-wide vocabulary of payload struct types
and layout constants. It is shared by every protection domain — and,
through generated type headers, by the external low-level
implementations (C, Pancake) too, so the model and the code agree
on one definition. It lives as flat, top-level items in the .fis file:
like the rest of the system description, declarations are visible to
every .fi program with no import ceremony.
const PACKET_BUFFER_SIZE: int = 2 * 1024;
struct Packet {
length: uint16; // valid bytes in payload (≤ capacity)
payload: byte[PACKET_BUFFER_SIZE]; // fixed-capacity buffer
}
const RING_BYTES: uint = 64 * sizeof(Packet);
Structs
- Names use
UpperCamelCaseby convention. - Fields are flat — primitives, other declared structs, or fixed-size arrays of those; no pointers.
- Fixed-size arrays
T[N]: the lengthNis an integer literal or a declared integerconst(e.g.byte[PACKET_BUFFER_SIZE]), so the size stays statically known:sizeof(T[N]) = N * sizeof(T). - No recursion: a struct may not contain itself, directly or
indirectly. This guarantees
sizeofis computable at compile time by recursive field traversal. - Fields must have fixed-width types so the layout is well-defined:
int,uintandAddresshave no fixed size and are rejected in a struct (uint32, notuint), as is a struct nesting one that has none. An array has one length:T[N], notT[N][M]. - Field names within a struct are distinct.
- Layout is C’s on the target, fields in declaration order: each
field at the next offset that is a multiple of its alignment (a scalar’s
is its size, an array’s its element’s, a struct’s its largest field’s),
and the size rounded up to the struct’s alignment, so
{ a: uint64; b: uint16; }is 16 bytes withbat 8. The generated headers assert it (a_Static_asserton each struct’s size intypes.h), so a C compiler that would lay the struct out differently fails the build. @attr(packed)beforestructpacks it, as C’s__attribute__((packed)): no padding, each field right after the one before, alignment 1, so@attr(packed) struct W { a: uint8; b: uint32; }is 5 bytes withbat 1. A struct nested in it keeps its own padding. Packing is for wire formats: a misaligned field is slower to read, and on device memory or under an atomic, an aarch64 fault.- Struct names are usable wherever a type is expected — variable
declarations, typed channel buffers (
via buf<Packet>), andsizeof.
Constants
- Names use
SCREAMING_SNAKE_CASEby convention (any identifier is accepted); a declared type is required. Unlike a struct field, a constant may have an unsized type such asintoruint. - The right-hand side is a full expression, folded
at compile time (rustc-style, before any lowering). The const
subset covers: literals, references to previously declared
constants,
sizeof(T), and unary/binary arithmetic, bitwise, shift, comparison, and logical operators. - Function calls, runtime variables, and field access are rejected in const position. Forward references between constants are errors — declare in dependency order.
- The folded value must match the declared type (
boolconstants take boolean values; integer-family types take integers).
One home for structs
Every struct is declared in the .fis. A program names them as any
other type, for its locals and body variables, and so do the C and
Pancake files it imports.
fic writes the structs and constants to include/gen/types.h (and, for
Pancake, the constants to include/gen/types.pnk), included as "gen/types.h" with
<project>/include on the include path.
Global state
The data layer declares types and constants, not mutable state. A program’s own variables are its protection domain’s state (see Variable Declarations); state shared across domains is exactly the channel-buffer view: mutable data lives in declared memory regions, mapped explicitly into the PDs that may touch it and labelled for information flow. A shared scalar is a typed slot of a declared region — never an ambient global.
Memory Region Declarations
MemoryRegionDecl ::= SecurityLabel? 'MemoryRegion' ident '(' size (',' page_size?)? (',' phys_addr)? ')' ';'
size ::= hex
page_size ::= hex // '0x1000' (4 KiB) | '0x200000' (2 MiB)
phys_addr ::= hex
SecurityLabel ::= 'High' | 'Low'
A memory region declaration introduces one named region of physical or
virtual memory that protection domains can later map into their
address space. MemoryRegion declarations live in .fis system files;
they are pure topology and carry no per-PD program logic.
Fields
- Security label (optional, defaults to
Low). Tags information-flow level. The one rule is on mappings: a mapping’s label must be at least its region’s, so aHighregion is never mapped atLow; protection domains carry no labels. See Information-flow labels; the Information Flow chapter covers the check. - Name —
snake_caseidentifier; the same name is referenced fromMappingdeclarations in.fifiles. - Size — required, hex literal, in bytes. Must be a multiple of the region’s page size; the parser rejects a size that is not.
- Page size — optional, defaults to
0x1000(4 KiB). The other accepted value is0x200000(2 MiB / Large). The slot may be left empty to give a physical address alone (MemoryRegion mmio(0x1000, , 0xfe000000);), and any other value is not an error: it silently falls back to 4 KiB, so a mistyped page size changes which alignment is checked. - Physical address — optional. When present, must be aligned to the region’s page size. Used for device MMIO regions (clock controller, ethernet registers) where the seL4 loader maps a fixed physical frame rather than allocating one.
Security label and ordering
The label, if present, comes before the MemoryRegion keyword. Omitting
it is equivalent to writing Low:
MemoryRegion ring_buffer_outer(0x1000, 0x1000); // Low (default)
Low MemoryRegion eth0(0x10000, 0x1000, 0x5b040000); // explicit Low
High MemoryRegion ring_buffer_inner(0x1000, 0x1000); // High
High MemoryRegion eth_clk(0x1000, 0x1000, 0x5b200000); // High MMIO
Validation
Two checks run in the parser, each reported at the declaration:
sizeis a multiple ofpage_size.phys_addr(if present) is aligned topage_size.
Resolution then checks that the region name is unique within the system
file. A region is referenced from .fi files by its name; the validator confirms
each Mapping’s mem_region points at a declared MemoryRegion.
Channel buffers
A region named in a channel’s via clause is a
channel buffer. It is mapped into both endpoint PDs implicitly, backs one
channel only, and must not also appear in an explicit Mapping; each of
these is an error otherwise. Any other region may be mapped by several PDs.
Examples
// Anonymous shared buffer, default 4 KiB page, allocator-assigned phys_addr.
MemoryRegion ring_buffer_outer(0x1000, 0x1000);
// 2 MiB region — large pages, allocator-assigned phys_addr.
MemoryRegion packet_buffer_outer(0x200000, 0x200000);
// Memory-mapped device (4 KiB MMIO, fixed physical address).
Low MemoryRegion eth_outer_register(0x1000, 0x1000, 0xf000000);
// 64 KiB device register window, in 4 KiB pages.
Low MemoryRegion eth0(0x10000, 0x1000, 0x5b040000);
// High-side region (a `Low` mapping of it is rejected by the
// information-flow check).
High MemoryRegion eth_clk(0x1000, 0x1000, 0x5b200000);
Protection Domain Declarations
ProtectionDomainDecl ::= 'ProtectionDomain' ident '(' priority (',' irq?)? (',' budget?)? (',' period?)? ')' ';'
priority ::= integer_literal // 0 ≤ p ≤ 254, enforced
irq ::= integer_literal // fits u16; range not enforced
budget ::= integer_literal // microseconds, default 1000
period ::= integer_literal // microseconds, default = budget
A protection-domain declaration introduces one named seL4 Microkit
protection domain (PD): an isolated thread of execution with its own
address space, scheduling parameters, and (optionally) one IRQ binding.
Each ProtectionDomain listed in a .fis system file pairs with one
.fi program file, <name>.fi beside the .fis.
Fields
- Name —
snake_caseidentifier. The matching<name>.fifile holds the PD’s mappings, events, and processes. - Priority — required, range
0..=254(it is read as au8below 255). Out-of-range values are rejected with a parse-time error. Higher numbers run first under the Microkit fixed-priority scheduler. - IRQ — optional; any value fitting a
u16parses (no range check is enforced by the compiler — pick a number the target board’s IRQ controller actually has), but one IRQ may be claimed by only one PD. When present, the PD is wired to receive that hardware interrupt on the reservedirqchannel and can observe it viairq?N/irq!Nevents. - Budget — optional, microseconds; defaults to
1000. Microkit schedules the PD for at mostbudgetmicroseconds out of everyperiod. - Period — optional, microseconds; defaults to whatever
budgetwas set to. Settingperiod > budgetproduces a sub-rate scheduling policy.
The trailing fields are positional, and any of them may be left empty to
set a later one: ProtectionDomain pd(100, , 500); sets the budget with no
IRQ, and ProtectionDomain pd(100, , , 2000); the period alone.
Validation
prioritymust be in0..=254.- A PD name is unique within the system file; a second declaration is an error at the later one.
- An IRQ number belongs to one PD.
- A PD that is referenced from a
Channelor from theSystem =composition must be declared. - A PD without a
<name>.fibeside the.fisis an error when the project is loaded, not when the.fisis parsed. A.fithat no PD names is only a warning, and the file is never opened.
Examples
// Three PDs with distinct priorities; IRQ on the outer driver only.
ProtectionDomain eth_outer(99, 159);
ProtectionDomain dd(150);
ProtectionDomain eth_inner(199, 155);
// A simulator with a low priority and no IRQ binding.
ProtectionDomain simulate(50);
// Explicit budget / period pair (sub-rate scheduling).
ProtectionDomain monitor(120, 0, 200, 1000); // priority 120, IRQ 0, 200 µs / 1 ms
System composition
A .fis file may hold a System = ... clause that names its PDs, joined
by the interleave operator |||, the only composition. The clause is
optional, and every PD it names must be declared:
System = eth_outer ||| dd ||| eth_inner ||| simulate;
The clause is checked for undeclared names only: every declared PD is built,
whether or not System lists it.
Channel Declarations
ChannelDecl ::= SyncChannelDecl | AsyncChannelDecl
SyncChannelDecl ::= 'Sync' 'Chan' ('<' Type '>')? ident '=' ident '-->' ident ';'?
AsyncChannelDecl ::= 'Async'? 'Chan' ident '=' ident '-->' ident ViaClause? ';'?
| 'Async'? 'Chan' ident '=' ident '<->' ident ';'?
ViaClause ::= 'via' ident '<' Type (',' Capacity)? '>'
Capacity ::= int | ident -- a literal or a const
A channel declaration introduces one named communication endpoint between
two protection domains. Channels live in .fis system files; the .fi
files reference them by name only, in the channel events of a process.
A channel is one of two kinds:
- a signalling channel carries no value: a send
c!wakes the other side, and a receivec?waits for it; - a message-passing channel carries values of a type: a send
c!epasses the value ofe, and a receivec?xbinds it tox: the buffered channel, and the synchronised channelSync Chan<T>.
| Declaration | Kind | Direction |
|---|---|---|
Chan c = a --> b; | signalling | a to b |
Chan c = a <-> b; | signalling | both ways; see WF2 |
Sync Chan c = a --> b; | signalling | a to b, a of lower priority |
Sync Chan<T> c = a --> b; | message passing | a to b, a of lower priority, a T per call |
Chan c = a --> b via region<T>; | message passing | a to b, values of T |
The Async keyword may be omitted — a Chan without a leading Sync is
asynchronous. The arrow is always written: Sync channels and buffered
channels take --> only. Only a Sync channel names a type after Chan:
Chan<T> on an async channel is an error, since its values go in a
buffer, via region<T>. The trailing semicolon is optional.
Fields
- Name —
snake_caseidentifier. The same name appears in process expressions on the LHS of?/!. - Endpoints — two distinct protection-domain names. Both must be
declared in the same
.fisfile. ASyncchannel’s sender must have a strictly lower priority than its receiver (seL4 protected procedure calls run low to high). - Buffer (optional, after
via;-->channels only) — theMemoryRegionthat holds the channel’s values and the type of a value:via packet_buffer_outer<int>, a declared data-layer struct (via eth_outer_output<Slot>), or raw bytes,via ring<byte>. The type is a struct or a scalar, never an array, and has at least one byte; it is the value the channel carries,Σ(c). A struct is the channel’s communication type, and the C backend types receive binders from it (o2d?pktdeclaresstatic struct Slot pkt;).viaon a<->orSyncchannel is a parse error.
Signalling channels
A signalling channel is a Microkit notification: a pure synchronisation
point. c! notifies the other end; c? is enabled when the PD was
notified on c. Notifications do not queue: several sends before the
receiver runs wake it once.
A Sync channel is a protected procedure call from the lower-priority
PD to the higher: c! is microkit_ppcall, and the sender waits while
the receiver’s @bind(microkit.protected) process handles c? and runs
to its end (see Entry Points). The
sender’s end is marked pp in the SDF. A Sync Chan<T> carries a value
with the call (see Synchronised channels); the
reply is empty. init makes no such call. In the UPPAAL model a call is
two handshakes: the receiver enters protected from where its notified
waits, the sender waits until protected ends and answers, and the
receiver goes back to where it was.
Examples
// Signalling, one way.
Chan tick = timer --> worker;
// Signalling, both ways — `Async` is the default, can be omitted.
Chan d2i = dd <-> eth_inner;
Async Chan s2o = simulate <-> eth_outer;
// Signalling, synchronous: the lower-priority eth_outer calls dd.
Sync Chan call = eth_outer --> dd;
// Message passing: buffered, a value of a declared struct.
Chan o2d = eth_outer --> dd via eth_outer_output<Slot>;
// Message passing: buffered, raw bytes.
Chan ring = eth_outer --> eth_inner via ring_buffer_outer<byte>;
Buffered channels
A channel declared Chan c = a --> b via region<T>; is a FIFO queue of
T values from a to b, held in region as a ring: Lamport’s
single-producer single-consumer queue, which needs no lock because each
index has one writer (the sender moves the tail, the receiver the head).
- Layout. A 16-byte header holding the two indices and a signal
word, then N slots of
T, packed. N is the channel’s capacity:via r<T, N>declares it (a literal or a const), and it must be at least 1 and fit in the region after the header, else an error at the channel; without it, N is as many as fit, ⌊(size − 16) / sizeof(T)⌋, or 2³¹ − 1 if that is smaller (the indices’ bound), with a warning that the rest of the region is unused. - Order. Values are received in the order they were sent, each once.
- Send,
c!e. Copies the value ofeinto the next slot, and notifies the receiver if the receiver asked. A send to a full ring is lost: the sender goes on and no notification is sent. - Receive,
c?x. Copies the oldest value intox. A receive waits while the ring is empty, and is enabled whenever the ring holds a value, whatever notification woke the PD, so a receiver drains everything that is queued. A receive that finds the ring empty asks to be notified (sDDF’s signalling protocol), so a receiver that is still draining costs the sender no system call. - By copy. Values cross by copy, in both directions; neither PD holds a reference into the region.
- The region. It is mapped into both endpoint PDs by
fic(rw, cached, at addressesficchooses): it must not also appear in aMapping, and it backs one channel only. Only fic’s runtime reaches it: the generated unit exports no symbol for the region.
Synchronised channels
A Sync Chan<T> passes a T in the protected procedure call itself: c!e
copies the value of e into the message registers and calls, and the
receiver’s protected process binds it with c?x. There is no shared
memory and no queue: one value per call, by copy, and the sender waits until
the receiver’s process has run.
struct Req { a: int32; b: int64; }
Sync Chan<Req> ask = client --> server;
// client.fi
evt fill: r = mk.req_make();
@bind(microkit.notified)
proc Notified() { fill -> ask!r -> Skip; }
// server.fi
@bind(microkit.protected)
proc Serve() { ask?q -> show.q -> Serve(); }
- It fits in one seL4 message. The value goes in the message registers,
up to seL4’s
seL4_MsgMaxLength, 120 words of 8 bytes; the kernel passes the first 4 in hardware registers on AArch64 and the rest through the IPC buffer. ATof more than 960 bytes is an error at the channel, naming its size. - A value both ways.
c!eandc?xare required on aSync Chan<T>, and rejected on aSync Chanwith no type, as on any channel that carries no value.
Channel events in process bodies
Inside a process, channel events are written chan_name '?' ident (receive)
and chan_name '!' expr (send) on a message-passing channel, and
chan_name '?' and chan_name '!' on a signalling one. The
names must match exactly; typing resolves each event back to the declared
ChannelDecl and checks that the PD is one of its endpoints, that it may
send or receive there (either end may do both on a <-> channel), and
that the value matches the payload type.
Channel events are the only way to a channel. Imported C or Pancake cannot
call the ring behind a buffered channel: in a .c import the ring is not
yet declared, and a separate driver or Pancake object that calls it fails
to link.
See Event Declarations → Channel events for the inline event grammar and Process Definitions for how channel events sit in a process expression.
WF2 and bidirectional channels
fic checks that the channel dependency graph is acyclic (WF2): a PD that
receives from another waits for it, and a cycle is a circular wait. A
bidirectional channel adds the edge in both directions, so every <->
channel is a cycle. fic --check and the image build warn on one and still
build; --allow-wf2-cycles (or allow_wf2_cycles = true in fire.toml)
silences the warning, deferring deadlock-freedom to an external authority
such as fire verify. The other --emit modes do not run WF2. The demos
pingpong and pingpongpan use <-> this way. See Well-Formedness
for the check and its warning.
Limitations
- The
Syncmodifier rejects bidirectional<->syntactically; sync bidirectional channels would require a richer call/reply protocol than the current implementation supports.
Imports and Mappings
Two declarations sit at the top of every .fi file: import brings an
external C or Pancake source file into scope under a chosen alias, and
Mapping puts a memory region declared in
the .fis into the protection domain’s address space.
Imports
ImportDecl ::= 'import' '"' FilePath '"' 'as' ident ';'
FilePath ::= any text up to the closing quote -- one line, relative to the project
An import declaration names the external implementation that backs the
PD’s computation events. The parser takes the path as written,
up to the closing quote, and decides nothing about it; the front end reads
it relative to the project directory (import "include/eth.h" as eth; is
valid) and picks the reader from the extension: .c and .h are C, .pnk
is Pancake. Any other extension is rejected when the project loads. Every
alias.f(..) call then resolves to a function the file exports, or the
build fails. The alias becomes the prefix on every external call inside
the PD.
What counts as exported depends on the language. For C, fic reads the file
with libclang: every function that is neither static nor inline.
For Pancake it scans the source for export fun declarations, which take
at most four word arguments and return one word; their /@ ... @/
contract blocks are read alongside.
import "include/eth.h" as eth; // C header; src/eth.c is linked
import "pingpong.pnk" as io; // Pancake source — same call shape
Multiple imports are allowed, and they may interleave with mappings — order does not matter for parsing. Each alias must be unique within the file.
Mappings
MappingDecl ::= SecurityLabel? 'Mapping' ident '(' region (',' vaddr)? ',' perms (',' cached)? ')' ';'
region ::= ident -- a MemoryRegion declared in .fis
vaddr ::= hex -- explicit virtual address (optional)
perms ::= string_literal -- 'r', 'rw', 'rx', 'rwx', 'x', 'wx'
cached ::= bool_literal -- default: true
A mapping declaration installs a MemoryRegion into the PD’s address
space. The mapping’s name derives the symbols the generated C defines for
it (<mapping>_vaddr, _size, and _paddr where it is read) — see
Boot Initialisation.
Fields
- Security label —
HighorLowprefix, defaultLow. A mapping’s label must be at least its region’s: aLowmapping of aHighregion is rejected. See Information-flow labels below. - Name — the mapping’s own identifier. Distinct from the region’s name; one region can have multiple mappings under different names.
- Region — the
MemoryRegiondeclared in the.fisfile. - Vaddr (optional) — pin the mapping at a specific virtual address. If
omitted,
ficallocates one. Hex literal. - Permissions — a quoted string of
r/w/xcharacters. Order and case are insensitive:"rw"and"WR"are equivalent. Write-only is rejected; at leastrorxmust be present. The accepted set isr,rw,rx,rwx,x,wx. - Cached (optional, default
true) — whether the mapping is cached in the CPU MMU. Device MMIO regions should be setfalseexplicitly.
Examples
// Anonymous shared buffer at allocator-chosen vaddr, read-write, uncached.
Low Mapping ring_buffer(ring_buffer_outer, "rw", false);
// Same region, default cached flag (true).
Mapping packet_buffer(packet_buffer_outer, "rw");
// Pinned vaddr — useful for debugging or for binding two PDs to a
// shared layout that pre-allocates virtual addresses.
Low Mapping eth0(eth0, 0x2_000_000, "rw");
// High-side mapping of a High MemoryRegion. A Low mapping of that region
// would be rejected.
High Mapping eth_clk(eth_clk, 0x2_200_000, "rw");
// Read-only mapping (data-diode input).
Low Mapping input_buf(eth_outer_output, "r");
Information-flow labels
Both MemoryRegion and Mapping declarations may carry a High or Low
prefix. The two-level lattice is:
flows_to(Low, Low) = true
flows_to(Low, High) = true // upgrade is fine
flows_to(High, Low) = false // downgrade is rejected
flows_to(High, High) = true
In source: Low is the default — omitting the prefix is equivalent to
writing Low. Place the prefix before the MemoryRegion / Mapping
keyword; placing it elsewhere is a parse error.
This is the one information-flow rule: the information-flow check, run
after typing, rejects any mapping that violates
flows_to(region.label, mapping.label), so a High region is never read
through a Low mapping. Protection domains carry no labels of their own.
The data-diode demo uses this to enforce one-way information flow. The
Information Flow chapter has the detail,
and the Memory Region Declarations chapter
states the same rule from the region’s side.
A mapping’s addresses
A mapping is a value only through its addresses:
m.vaddris its virtual address, which fic chose (or you pinned). It compiles to that constant.m.paddris the physical address of its region. It may be known only when the system boots, so it compiles to the symbolm_paddr, which the loader patches. fic declares and patchesm_paddronly in a PD that reads it. On Microkit, a region whosepaddris read must be physically contiguous; Microkit picks its address when the region declares none, and on x86-64 the region must declare one.
Validation
- Each
Mapping’sregionmust reference a declaredMemoryRegion. - Permission strings must contain at least one of
rorx."w"alone is rejected. - A pinned
vaddrmust be aligned to the region’s page size. - Mapping names are unique within the same
.fifile.
Boot Initialisation: the microkit.init Process and Mapping Symbols
Boot-time behaviour of a protection domain is expressed in two ways:
- Address binding is automatic: every
Mappingexports its addresses to the imported C implementation through a naming convention (the mapping symbols below). No syntax is required. - Boot-time logic is modelled by an ordinary
process bound to the platform’s boot entry point
with
@bind(microkit.init)— the model-level counterpart of Microkit’svoid init(void)entrypoint, whichficgenerates.
The boot process
The boot process is the one annotated @bind(microkit.init). Its name
carries no meaning — Init is a common choice, but the binding, not the
name, is what makes it the boot entry point:
@bind(microkit.init)
proc Init() {
setup_eth -> Skip;
}
Microkit calls the PD’s entrypoint exactly once, before any event is
delivered, so the bound process must not contain channel receives or
IRQ awaits; fic does not check this. When it terminates (Skip), control falls through to the
@bind(microkit.notified) event loop — exactly as
the generated C init() runs the boot body and then arms notified().
A @bind(microkit.init) process is mandatory for every PD that has a
.fi program when targeting Microkit (--emit=c or image generation):
the kernel calls init() on every PD at startup. It is mandatory in tandem
with @bind(microkit.notified) — Microkit invokes
both, so a conforming PD binds both (any other platform entry points are
optional). A PD with no boot work still declares a no-op:
@bind(microkit.init)
proc Init() { Skip; }
The @bind(microkit.notified) process, in turn, should be receive-headed if it
receives at all (a warning otherwise);
see Annotations. That both are bound
is checked in every mode, --emit=xta included; see
Entry Points.
Mapping symbols
For every mapping named m, the generated C of the protection domain has
these symbols:
| Symbol | Type | Value |
|---|---|---|
m_vaddr | uintptr_t | Virtual address of the mapping, defined with the address fic laid out (or the one pinned). |
m_size | uint64_t | Region size in bytes, defined with its value. |
m_paddr | uintptr_t | Physical address of the backing region. Declared only in a PD whose program reads m.paddr, and patched by the Microkit loader (a setvar in the SDF) before the PD starts. |
fic defines them; the imported C declares the ones it uses extern:
import "include/eth.h" as eth;
Low Mapping ring_buffer(ring_buffer_outer, "rw");
Low Mapping packet_buffer(packet_buffer_outer, "rw");
/* src/eth.c: defined by the generated C, not here */
extern uintptr_t ring_buffer_vaddr; /* ring_buffer.vaddr */
extern uintptr_t packet_buffer_vaddr; /* packet_buffer.vaddr */
extern uint64_t packet_buffer_size;
Pick mapping names so that <mapping>_vaddr matches the symbol your
implementation uses. A channel’s buffer region has no such symbols: only
fic’s runtime reaches it.
Validation
- Mapping names must be unique within a PD (checked by name resolution); this also guarantees the derived symbols are unique.
m_paddrexists only wherem.paddris read: see A mapping’s addresses.
Variable Declarations
VarDecl ::= ident ':' Type ';'
Type ::= BaseType ('[' ArrayLen ']')?
BaseType ::= PrimitiveType | StructName
A variable declaration introduces one named value at PD-global scope or
inside an event body. The ident: Type; form is
the only shape supported today; an initialiser (ident: Type = expr;) is
reserved but not yet parsed.
🚧 Initialiser syntax (
= expr) is reserved but unparsed. For now, initialise locals from inside the body, and globals in an event run by the@bind(microkit.init)process (see Boot Initialisation).
Scopes
Variables can appear in three positions inside a .fi file:
- Global — at the top level of the file, alongside
Mappingandimportdeclarations. Globals are visible everywhere in the PD, read/write inside event bodies. - Event local — inside a computation event body,
from its declaration to the end of the event body (the statement’s
;, or the closing}). - Process variable — inside a process body: a
parameter (
proc Drain(pkt: Slot), read-only, in scope for the whole body), a declarationx: T;(in scope for the rest of its sequence), or a receive binderc?xon a message-passing channel (in scope for the rest of its prefix).
A name in a body is looked up among that body’s own variables first, then the program’s globals, then the system’s constants:
body variable → global → constant
Event and process variables never see each other: a process value reaches an event only as a carrier. Shadowing a global, a mapping or a constant is a warning; declaring a name twice in one body while the first is still in scope is an error. Carriers are read-only — see Event Declarations.
Primitive types
The primitive types accepted in declarations are:
| Group | Tokens |
|---|---|
| Signed integers | int, int8, int16, int32, int64 |
| Unsigned integers | uint, uint8, uint16, uint32, uint64 |
| Boolean | bool |
| Byte alias | byte (8-bit) |
| Address | Address |
int and uint are aliases of int64 and uint64 on every target.
byte is an alias for uint8. There is no void type — every
declared variable has a concrete, storable type; void is a reserved word,
so v: void; is a parse error.
Struct types and arrays
pkt: Slot // user-defined struct — declared in the .fis data layer
buf: uint8[16] // fixed-size array — length is a literal or const name
Any identifier that isn’t a recognised primitive keyword is treated as a
struct type name, resolved against the .fis struct declarations during
name resolution (unknown names are rejected there, not at parse time).
Fiducia has no pointer types — there is no ptr<T> syntax.
Examples
// Global declarations, top of a .fi file.
counter: int;
ready: bool;
last_irq_ts: uint64;
// Local declarations inside an event body.
evt handle_packet.|size: int|: {
local_buf: int; // local
ok: bool; // local
local_buf = eth.alloc(size); // assignment uses globals/locals/carriers
}
Validation
- A variable name is unique within its enclosing scope (multiple globals with the same name are rejected; a body variable may shadow a global, with a warning).
- The type must be a recognised primitive,
Address, a fixed-size array of one, or a struct name that resolves to a real.fisstruct declaration.
Event Declarations
EventDecl ::= 'evt' ident Carriers? ':' Body
Body ::= Statement | '{' Statement* '}'
Carriers ::= ('.' '|' Param (',' Param)* '|')+
Param ::= ident ':' Type
An event declaration introduces one named atom of computation at the
top level of a .fi file using the evt keyword. Processes reference
it by name on the left of a prefix (my_event -> ...).
evt declarations and proc definitions may appear in any order in a
.fi file: a process can use an event declared below it.
Computation events are one of three event kinds in CoreFi
(paper §4.2);
the other two — channel events (c?x / c!e, or c? / c!) and hardware-interrupt
events (irq?N / irq!N) — are inline atoms that appear in process
bodies and have no top-level declaration.
Computation events
A computation event is a named, atomic block of statements:
assignments and external calls, plus optional carrier parameters. The
block executes as a single transition in the labelled-transition system —
processes can prefix on it (my_event -> ...) but cannot observe it
mid-flight.
Names follow snake_case by convention, which sets a computation event
reference apart from a sub-process reference (UpperCamelCase, with
parentheses). The parser accepts any identifier as an event name.
Body
After the :, the body is either one statement
(a local variable declaration, an assignment, an external function call or
debug output),
ending at its ;, or any number of statements in braces. Either way the
body ends where it says, so what follows it is never read as part of it: a
global declared below an event stays a global.
// One statement: no braces, ends at its ;
evt setup_eth: eth.eth_setup();
// Several statements: braces.
evt handle_packet.|size: int|: {
local_buf: int;
local_buf = eth.alloc(size);
counter = counter + 1;
}
Debug output
A dbg(...) statement prints values from an event body; see
Debug Output.
Carriers
evt handle_packet.|size: int|: // single carrier
evt ack.|chan: int, slot: int|: // grouped carriers
evt ack.|chan: int|.|slot: int|: // chained carriers (equivalent)
Carriers are parameters supplied by the invoking process. The
syntax uses pipes (.|...|) — chosen over parentheses so the visual
boundary is distinct from sub-process parameter lists. Multiple carriers
may be grouped in a single .|x: int, y: int| clause or chained
across multiple .|x: int|.|y: int| clauses; both forms behave
identically.
Inside the body, carriers are read like any other variable: passed to
external calls (eth.handle_rx(idx)) or read in expressions
(local_buf = eth.alloc(size)). They are read-only; assigning one is
an error. Three kinds of variable names can appear in an event body:
| Kind | Declared in | Writable |
|---|---|---|
| Global | Top-level of the .fi file | yes |
| Carrier | The event’s `. | name: type |
| Local | Inside the body via name: Type; | yes |
An event sees its own locals and carriers, then the program’s globals and the system’s constants, never a process variable; lookup and shadowing are in Scopes. To carry mutable state across event invocations, use a global; to carry mutable scratch within one invocation, declare a local variable.
Referencing an event
EventRef ::= ident ('.' ident)*
A process runs an event by naming it, followed by one .ident per
carrier, by convention without whitespace around the dots. The identifiers are
the process’s own variables (a parameter, a receive binder, a declaration
or a global), supplied in the order the event declares its carriers:
evt forward.|pkt: Slot|: { ... }
evt ack.|chan: int, slot: int|: eth.ack_slot(chan, slot);
proc Relay(pkt: Slot, c: int, s: int) {
forward.pkt -> ack.c.s -> Skip;
}
Examples
// No carriers — the event is a fixed call.
evt setup_eth: eth.eth_setup();
// Single carrier, single-statement body — idx is the carrier.
evt read_frame.|idx: int|: eth.handle_rx(idx);
// Several statements, in braces — size carrier passed to alloc.
evt handle_packet.|size: int|: {
local_buf: int;
local_buf = eth.alloc(size);
counter = counter + 1;
}
// Multiple carriers, grouped form.
evt ack.|chan: int, slot: int|: eth.ack_slot(chan, slot);
// Same event, chained carrier form (equivalent).
evt ack.|chan: int|.|slot: int|: eth.ack_slot(chan, slot);
Empty-body events
evt noop: {} is an event with no statements. Useful as a placeholder
while a process expression is being prototyped.
Channel events
ChannelEvent ::= ident '?' ident? // c?x / c? — receive
| ident '!' Expr? // c!e / c! — send
A channel event is an atomic communication action between two protection
domains. The channel name on the LHS is resolved against the Chan
declarations in the surrounding .fis.
Channel events appear inline inside process expressions — they have no top-level declaration.
A message-passing channel carries a value: a
buffered channel (via r<T>) or a Sync Chan<T>, whose type T is the
value’s. On it the receive form
c?x binds the incoming value to x for the rest of that prefix only
(c?x -> P): the binder is gone at the next ;, and a referenced
process does not see it unless it is passed as an argument
(c?x -> Drain(x)). The send form c!e transmits the expression e,
of type T. A signalling channel is a Microkit notification, which
carries no value: its events are c? and c!, and a value or binder on
it is an error (channel 'ball' carries no value),
as is leaving one off a message-passing channel.
No selective receive
The RHS of ? is always a single identifier (a binder), never a value
pattern. Traditional CSP / CSP# accepts c?ACK as “wait only for the
message ACK”, but Fiducia rejects this: it can deadlock when no sender
ever produces the matching value, conflicting with CoreFi’s deadlock-
freedom story (paper §4.1 Wf1). The same expressiveness is recovered by
binding then guarding:
// Recommended.
c?msg -> ([msg == ACK] handle_ack -> Skip [] [msg == NACK] handle_nack -> Skip default Skip)
Send-payload style
The RHS of ! accepts any Expr — the parser does not reject a call
expression there today. The recommended style is still to keep
channel events as pure-communication atoms: bind a call’s result in a
computation event first, then send the bound
variable, rather than calling directly in send position. This keeps
side-effecting work legible as its own step in the process algebra,
even though the grammar itself doesn’t enforce it:
// Discouraged (parses, but buries a side-effecting call in a
// communication event):
// c!eth.get_packet()
// Recommended: bind, then send (pkt is a global variable).
evt get_pkt: pkt = eth.get_packet();
proc P() { get_pkt -> c!pkt -> ... }
Hardware-interrupt events
IRQEvent ::= 'irq' '?' integer_literal // irq?N — await
| 'irq' '!' integer_literal // irq!N — acknowledge
A hardware-interrupt event is a special-cased channel event on the
reserved channel name irq. The integer is the IRQ number declared on
the protection domain. irq?N blocks
until the IRQ fires; irq!N acknowledges the IRQ back to the kernel. The
literal is not checked against the IRQ the protection domain declares: a
mismatch is not reported.
Like channel events, IRQ events appear only inside process expressions and have no top-level declaration:
proc Notified() { irq?159 -> Handle_eth(); irq!159 -> Notified(); }
🚧
self.IRQsyntax is planned —irq?self.IRQ/irq!self.IRQwill resolve the protection domain’s IRQ number without a magic literal.
Debug Output
Dbg ::= 'dbg' '(' (DbgArg (',' DbgArg)*)? ')' ';'
DbgArg ::= text_literal | Expr
dbg prints its arguments in order, then a newline. A text literal is
printable ASCII between double quotes, with the escapes \\, \", \n
and \t. Any other argument is an expression of an integer type, or a
bool, which prints as true or false.
evt tally: {
dbg("round ", rounds);
rounds = io.tally(rounds);
}
dbg is a statement, so it is valid only in an event body: not in a
proc body, a guard or an expression. It is for debugging only. The model
leaves it out, so no argument may call a function: removing the dbg must
not change what the event does.
Put a dbg in an event that does other work, as above. An event that only
prints does nothing in the model, and fic warns about it in every mode,
--check included.
Each line starts with the name of the protection domain that printed it,
then : , so dbg("round ", rounds); in ping prints ping: round 3.
An integer prints in decimal at its full width, a signed one with its
sign: -1 prints -1, and every uint64 prints in full; a bool
prints true or false. fic’s runtime, filib, which every protection
domain links, writes each byte as it comes, so lines from protection
domains running at once can interleave on the shared console.
All output is the .fi’s. By convention, imported C and Pancake use
neither Microkit nor seL4 directly: no microkit.h or sel4/… include,
no microkit_… or seL4_… call, no @microkit_… FFI, in the import or
in the C linked beside it (a header’s source, a Pancake file’s FFI shims).
A channel operation or a print there would be invisible to the model, so
what fire verify proves would not be about the system that runs. fic
does not check this yet.
Process Definitions
ProcessDecl ::= Bind? 'proc' UIdent '(' (Param (',' Param)*)? ')' '{' ProcessBody '}'
Bind ::= '@bind' '(' ident '.' ident (',' ident '.' ident)* ')'
Param ::= ident ':' Type
ProcessBody ::= BodyItem (';' BodyItem)* ';'?
BodyItem ::= VarDecl | ProcessExpr
VarDecl ::= ident ':' Type ';'
ProcessExpr ::= 'Skip'
| 'Div'
| Event '->' ProcessExpr
| '[' Guard ']' ProcessExpr
| ProcessExpr ('[]' ProcessExpr)* ('default' ProcessExpr)?
| ProcessRef
| '(' ProcessExpr (';' ProcessExpr)* ')'
ProcessRef ::= UIdent '(' (ident (',' ident)*)? ')'
Guard ::= Expr -- boolean-shaped: comparison, &&/||/!, boolean
-- variable/call/field access; not arithmetic
A process definition is the orchestration layer of a Fiducia protection
domain — a CSP-style algebraic expression composed from
events, guards, choices, and sequential composition.
Each proc declaration introduces one named process; all proc
declarations in the same .fi file are mutually visible and may reference
each other by name.
proc definitions and evt declarations may appear in any order in the
file.
Following the CoreFi paper §4.2, a process expression is one of:
| Form | Notation | Meaning |
|---|---|---|
| Successful exit | Skip | Terminates normally. |
| Divergence | Div | Divergence (a self-loop, Ω). |
| Event prefix | e -> P | Performs event e, then P. |
| Guard | [b] P | Performs P only if b holds. |
| External choice | P [] Q | Either branch — environment chooses. |
| Default arm | (P [] Q) default R | R runs when no branch is enabled. |
| Sequential | P ; Q | P to completion, then Q. |
| Reference | Name(args) | Calls another process declaration. |
Naming convention
Process names start with an uppercase letter (UpperCamelCase); the parser
requires it. With the parentheses, this sets process references apart from
computation event references:
Reply(pkt)— sub-process call (UpperCamelCase, parentheses required).send_frame.pkt— computation-event reference (snake_caseby convention, dot carrier syntax).
An uppercase name followed by ( is a process reference; any other
identifier before -> is an event.
The boot process is the one bound with @bind(microkit.init); Init is a
conventional name but carries no special meaning (see
Boot Initialisation).
Annotations (@bind)
A process may carry a single @bind(...) annotation mapping it to one or
more platform entry points, without hardcoding kernel terminology into
process names. Group the targets — one platform.entry pair per platform —
on one line:
@bind(microkit.notified, cheri.interrupt_handler)
proc Notified() { o2d?pkt -> d2i!pkt -> Notified(); }
- A process with no
@bindis internal — not directly callable by the kernel. @bindis authoritative for entry-point selection. The C backend and the UPPAAL lowering pick kernel entry points by binding, not by process name: themicrokit.init-bound process becomesinit()(the boot body), themicrokit.notified-bound process becomes thenotified()event loop, and amicrokit.protected-bound process becomesprotected(), which answers aSyncchannel’s call.- The process bound to
microkit.notified, if it receives at all, should be receive-headed (a warning otherwise): every path at its head, through[], the left of;and a helper’s body, begins with a receive (c?x) or an IRQ await (irq?N), with no guard and nodefaultat the top, and no receive sits anywhere else. The kernel invokes it for a message, which the head consumes; a handler that could run without one would never return to the kernel. See Well-Formedness. - Both a
@bind(microkit.init)and a@bind(microkit.notified)process are mandatory for every PD with a program when targeting Microkit — Microkit invokes both on every PD, and the front end reports a PD that lacks one whatever the output (--check,--emit=xta,--emit=c, an image). See Boot Initialisation and Entry Points.microkit.protectedis optional, and bound only where aSyncchannel ends at the PD; its process is receive-headed on those channels and runs to completion (see Well-Formedness). Other platform entry points are optional. - Each entry point binds at most one process. Two processes both
@bind(microkit.notified)is an error — resolution rejects the second rather than silently keeping the first.
Operator precedence
From loosest to tightest:
| Precedence | Operator | Notation | Note |
|---|---|---|---|
| 1 (loosest) | Sequential | ; | Separates body items. |
| 2 | External choice | [] / default | Each branch must carry a discriminator. |
| 3 | Guard | [b] P | Guard binds the next expression only. |
| 4 (tightest) | Event prefix | -> | Right-associative (Hoare CSP, page 4). |
| atoms | Skip, Div, (...), Name(args) |
Concrete consequences:
e -> P() [] e2 -> Q() ≡ Choice([Prefix(e, P()), Prefix(e2, Q())])
e -> P() ; Q() ≡ (e -> P()) ; Q()
[b] e -> P() [] e2 -> Q() ≡ Choice([Guard(b, Prefix(e, P())), Prefix(e2, Q())])
P1() ; P2() [] P3() ≡ P1() ; (P2() [] P3())
[b] (e -> P() [] e2 -> Q()) ≡ Guard(b, Choice(...)) // outer-guard the choice
Parenthesisation cuts through: (...) re-enters at the top of the
precedence chain.
Choice and discriminators
Every branch of a [] choice must carry a discriminator — a
distinguishing prefix that the surrounding environment can pattern-match
on. The parser checks structurally and recurses into a branch’s first
sequential item and into nested choices; a ProcessRef branch is admitted
as it is, and the name is not followed.
Common discriminator shapes:
e -> P() // event prefix
[b] P() // guard
c?x -> ... // channel-event prefix
A branch that is bare Skip, Div or a variable declaration is a parse
error: it is always enabled, so it discriminates nothing. A branch that is
a sequence is judged by its first item.
The optional default arm is taken when no branch’s guard succeeds. It
needs no discriminator of its own. A receive beside a default is a
receive outside the head, and a warning (see
Well-Formedness).
Examples
// Two branches, no default.
proc Dispatch() {
[rx] receive -> Skip [] [!rx] cleanup -> Skip;
}
// Two branches with a fallback.
proc Reply(pkt: int) {
[pass] o2d!pkt -> Skip
[] [!pass] handle_ping -> Skip
default Skip;
}
Guards
Guard ::= Expr -- boolean-shaped: comparison, &&, ||, !, a boolean
-- variable, call or field access; not arithmetic
A guard gates the next process expression on a boolean
expression: [rounds < 3], [!ready],
[io.keep_playing(rounds) != 0]. A guard whose top node is arithmetic ([a + b]),
an integer literal or sizeof is rejected; arithmetic inside a comparison
([a + b == c]) is fine. The guard binds tighter than []:
[b] e -> P [] e2 -> Q ≡ ([b] (e -> P)) [] (e2 -> Q)
The guard applies only to the first branch.
Recursion
A process refers to a process that is already running (itself, or one that called it) only in tail position: as the last thing it does, so the reference is a jump back to that process’s head and the control graph stays finite. Such a reference followed by more work is rejected; a first call to a helper may be followed by more work:
proc Notified() { ball? -> Notified(); tally -> Skip; } // error: non-tail
proc Notified() { ball? -> tally -> Notified(); } // ok
This holds for the entry process too: Notified() at the end of
Notified loops back to its head within the invocation. Only reaching the
end (Skip) returns to the kernel, and the next notification invokes
notified again. A loop whose head receives waits there for the next
message; one that never receives never returns (Skip; Notified() on a
PD’s own CPU budget).
Inside a non-final operand of ;, no enclosing process may be referenced:
its continuation would need a return stack. See
Well-Formedness.
Sequential composition
Inside a {} body, ; separates items. The last item may carry a
trailing ; before }:
proc Notified() {
irq?159 -> Handle_eth();
irq!159 -> Notified();
}
Sub-process calls
ProcessRef ::= UIdent '(' (ident (',' ident)*)? ')'
A sub-process call references another process declared in the same
file. The argument list is currently restricted to identifiers.
Parentheses are always required — even for empty argument lists (Skip
and Div are the only bare uppercase atoms):
proc Notified() { irq?159 -> Handle_eth(); irq!159 -> Notified(); }
proc Handle_eth() { handle_irq -> Dispatch(); }
proc Dispatch() { [rx] receive -> Skip [] [!rx] cleanup -> Skip; }
proc Reply(pkt: int) { o2d!pkt -> Skip; }
The validator confirms each ProcessRef resolves to a declared process
and that the argument count matches.
Empty processes
Skip and Div are atomic and self-contained: Skip is successful
termination, Div is divergence (a self-loop):
proc NoOp() { Skip; }
proc Stuck() { Div; }
Limitations
- Argument lists for
ProcessRefand computation-event references are restricted to identifiers. Onlyirq?Nandirq!Ntake an integer literal. - Currently only variable declarations (
x: int;) are permitted as inline body items alongside process expressions. Assignment statements and external calls must live inevtdeclarations. This restriction is planned to be lifted: future versions will allow statements directly inprocbodies, with flexible interleaving of statements and process expressions. - Recursion is modeled as a sub-process call by name, in tail position only (see Recursion).
- A receive binder does not reach a referenced process: pass it as an
argument,
c?x -> Drain(x)withproc Drain(x: T)(see Scopes). An entry point (@bind) takes no parameters.
Expressions
This chapter describes the expression grammar fic actually parses.
Expressions appear as:
- the right-hand side of assignments inside event bodies;
- the payload of a channel send (
c!e); - the body of a guard (
[b]); - arguments to calls, sub-process calls, and computation-event carriers.
One grammar (Expr) covers literals, variables, calls, sizeof, unary
and binary operators, field access, and casts. There’s no separate arithmetic
vs. logical vs. boolean sub-grammar — a boolean-shaped subset of
Expr is what’s required in guard position (see below), not a
different grammar.
Expr ::= Lit | ident | CExpr | 'sizeof' '(' Type ')'
| '(' Expr ')' -- grouping
| UnOp Expr | Expr BinOp Expr
| FieldBase '.' ident -- field access
| Expr 'as' Type -- cast
FieldBase ::= ident | CExpr | FieldBase '.' ident -- var, call, or field chain
Lit ::= int_lit | hex_lit | bool_lit
-- hex_lit allows '_' (0xFE00_0000); int_lit does not
UnOp ::= '-' | '!' | '~'
BinOp ::= '+' | '-' | '*' | '/' | '%'
| '==' | '!=' | '<' | '<=' | '>' | '>='
| '&&' | '||'
| '&' | '|' | '^' | '<<' | '>>'
Operator precedence
Loosest to tightest:
| Level | Operators |
|---|---|
| 1 | || |
| 2 | && |
| 3 | | |
| 4 | ^ |
| 5 | & |
| 6 | ==, != |
| 7 | <, <=, >, >= |
| 8 | <<, >> |
| 9 | +, - |
| 10 | *, /, % |
| 11 | as |
| 12 | unary -, !, ~ |
| 13 | primary atoms |
Names, mappings and fields
A variable is a program or body variable or a system const. A mapping is
not a value: m alone is an error, and only m.vaddr and m.paddr are
expressions, the two addresses of a mapping.
Any other x.f is field access on a struct value (a variable, a call, or
a chain of fields). Field access binds only to those: a unary operator
does not apply to it directly, so write !(s.ok) and -(s.a), not !s.ok.
A constant subexpression is folded at compile time in the checked arithmetic of its type; a constant that overflows is a compile error, not a wrapped value.
Casts
e as T converts an integer or an address to another integer type or to
Address, explicitly: fic never widens or narrows on its own, so
m.vaddr + w with w: uint32 is an error and m.vaddr + w as uint is the
way to write it. The semantics are Rust’s: widening is lossless, narrowing
is modulo 2ⁿ (300 as uint8 is 44, 200 as uint8 as int8 is -56), and
a constant cast folds at compile time. as binds tighter than every binary
operator and looser than unary: -x as uint is (-x) as uint. A cast to
bool, to a struct or to an array is rejected, as is a cast of one.
Call expressions (CExpr)
CExpr ::= ident '.' ident '(' (Expr (',' Expr)*)? ')'
A call expression invokes a function exported by an imported .c, .h
or .pnk file, prefixed with the import alias chosen at the
import declaration. The alias
is required — there are no local callables in Fiducia, only
externally-implemented functions reached through an alias.
The first ident is the alias; the second is the function name. No
whitespace is permitted around the . or before the (:
eth.send_frame() // OK
eth.send_frame(pkt, len) // OK — arguments are full Expr, comma-separated
drv .start() // rejected — whitespace before '.'
drv. start() // rejected — whitespace after '.'
drv.start () // rejected — whitespace before '('
Guard expressions
A guard ([b] P) requires a
boolean-shaped Expr — arithmetic like [a + b] is rejected at parse
time, since a guard must denote a yes/no decision, not a value. Boolean-shaped means:
a boolean literal, a variable, a call, a field access, a !-negated
boolean-shaped expression, or a comparison/&&/|| combination of
boolean-shaped expressions.
[a + b == c] // OK — comparison of arithmetic is boolean-shaped
[eth.is_forward()] // OK — call
[!flag && ready] // OK — negation + conjunction
[true] // OK
[a + b] // rejected — arithmetic isn't boolean-shaped
A call in a guard must be side-effect free, because the generated C may
evaluate a guard more than once. For a Pancake function with a contract,
fic --check and --emit=xta reject a call whose contract is impure.
Entry Points
A protection domain does nothing until the platform calls it. The handlers
the platform calls are the PD’s entry points, and a proc becomes one
with a @bind annotation:
@bind(microkit.init)
proc Init() { ball! -> Skip; }
@bind(microkit.notified)
proc Notified() {
ball? -> tally -> Skip;
[io.keep_playing(rounds) != 0] ball! -> Notified()
default Skip;
}
@bind(<platform>.<entry>) is platform-neutral: the parser records the
pairs on the process and decides nothing about them. The entry points a
platform has, and what each means, belong to that platform. A process
with no @bind is internal: it runs only when a bound process references
it.
Microkit
Microkit is the platform fic targets, and it has three entry points:
| Entry | Microkit’s | Runs |
|---|---|---|
microkit.init | init() | once, when the PD boots. See Boot Initialisation. |
microkit.notified | notified(channel) | each time the kernel notifies the PD, for a channel message or an interrupt. |
microkit.protected | protected(channel, msginfo) | each time a lower-priority PD calls it on a Sync channel; the caller waits until it returns. |
init and notified are mandatory. Every protection domain binds both, and the front
end reports one that does not, naming the PD and the missing entry, before
any backend runs: fic --check, --emit=xta and --emit=c all stop.
protected is optional. A PD that receives a Sync channel without it
leaves the call to libmicrokit’s default protected(); a PD that binds it
with no Sync channel in is reported, since nothing calls it. Each entry
point binds at most one process.
A notified process that receives should be receive-headed (a warning
otherwise): it starts by consuming
the message or interrupt that woke it (see
Process Definitions). The
generated C makes each receive or interrupt await in the process a
resume point that notified() dispatches to, and init() runs the boot
process. Reaching the end of init or notified returns to the kernel;
the next notification invokes notified again.
The protected process is receive-headed on the PD’s Sync channels and
runs to completion: it starts with a choice of c? over them, and nothing
after the head receives or awaits an interrupt, since its caller waits
while it runs. protected() dispatches on the calling channel, runs to the
process’s end and returns an empty reply. See
Well-Formedness.
A microkit. name other than init, notified and protected is
accepted by the grammar and ignored.
Other platforms
A process may name several platforms on one line,
@bind(microkit.notified, cheri.interrupt_handler). fic compiles the
microkit pairs; the others are kept and not used.
Foreign Functions
A program reaches code written in another language through an
import: import "pingpong.c" as io;
makes every function the file exports callable as io.f(..) from an
event body or a guard. This chapter says what an import exposes, how a
foreign signature becomes a Fiducia one, and where each failure is
reported. Contracts covers the annotations a function may
carry.
What a file exports
fic reads the imported file itself; it does not run the foreign compiler to find out what the file offers.
| File | Language | Read by | Exported functions |
|---|---|---|---|
.c, .h | C | libclang, the real C front end | every function that is neither static nor inline |
.pnk | Pancake | a text scanner, no external tool | every export fun, with at most four word arguments and one word return |
The language is the extension’s: any other extension is rejected when the
project loads (import "x.rs": not a C or Pancake file), and so is a file
that cannot be read. A .c import is compiled into the protection
domain’s unit; a .h import is a driver whose .c is found beside it, or in
src/ for a header under include/ (include/eth.h is backed by
src/eth.c), and is linked; a .pnk import is compiled by CakeML into the image.
Every other .c in the project, outside build/, is compiled into one
archive, build/libproject.a, linked after each PD’s objects: the linker
takes only the files that define something still missing, so a driver
reaches the C it calls (eth.c calls util.c) without the .fi importing
it, and a file nothing calls is left out. If two files define the same
function, the linker takes the first it needs, without an error.
A protection domain has no C library. Its C may call memcpy, memmove,
memset, memcmp and bcmp, which fic’s runtime supplies; anything else
it calls, it brings. The five are C byte loops, linked into every PD, and
include/gen/mem.h declares them with ACSL contracts that Frama-C has
proved of those bodies, so a driver’s proof may call them. The header also
declares fi_memcpy_u8(uint8_t *dst, const uint8_t *src, size_t n): the
five take void *, which Frama-C’s WP follows only for char data, so a
proof about uint8_t buffers copies with this one.
From a foreign signature to a Fiducia one
Each called function’s parameter and return types are lowered to
Fiducia types, on AArch64 LP64 widths:
| C spelling | Fiducia type |
|---|---|
uint8_t, unsigned char, char | uint8 (plain char is unsigned on AArch64) |
uint16_t, unsigned short | uint16 |
uint32_t, unsigned, unsigned int | uint32 |
uint64_t, unsigned long, unsigned long long, size_t | uint64 |
int8_t, signed char | int8 |
int16_t, short | int16 |
int32_t, int | int32 |
int64_t, long, long long, ssize_t, ptrdiff_t | int64 |
bool, _Bool | bool |
uintptr_t, intptr_t, any pointer | Address |
struct S, where the .fis declares a struct S | that struct |
Every Pancake argument and return is one machine word, uint64. A
void return is a function with no value. Anything else (float, an
opaque typedef, a struct the .fis does not declare) has no Fiducia type,
and calling such a function is an error:
error: event 'e': 'io.scale' has a type fic cannot express: parameter 1
('x') has type 'float', which has no fic type
A function that is never called is never lowered, so an unsupported signature elsewhere in the file costs nothing.
Calls
A call alias.f(args) is typed against the lowered signature: the
argument count and types must match, and a result is used at its own type
(an int32_t result is not an int; convert it with as). Failures:
- Unknown function.
io.nothing(1)and astaticfunction alike areforeign function 'io.hidden' is not declared, reported where the call is. - Wrong arity.
'twice' takes 1 argument(s), found 2. - Type mismatch.
expected 'int64', found 'int32'.
A struct passed or returned is the .fis struct of that name, whose
layout both sides share.
When each failure is reported
An unreadable file or an unsupported extension is reported when the
project loads, at the import. An unknown function, a wrong argument
count or type, and a signature with no Fiducia type are reported at the
call. An annotation outside the contract subset, or a call
the contract cannot support, is reported by --check and --emit=xta,
which read the contracts. The foreign compiler’s own errors surface only
when an image is built.
Contracts
A foreign function may carry a contract: requires and ensures clauses
written in the function’s own language. A contract does two jobs, and
only one of them is fic’s.
- The model assumes it.
--emit=xtaturns a contracted function that a protection domain calls into a UPPAAL functionffi_<name>: eachrequiresis anassertat every call (never a guard), and the deterministicensuresis the value the call returns. Anensuresthat only bounds the return value to an interval, comparing it with constants under&&and||(\result == 0 || \result == 1,0 <= \result <= 3), makes the value a choice: in an event, the edge that fires it selects any value the clause allows. That is how a driver’s input enters the model. A call returning a struct takes the fields itsensuresfix (\result.origin == origin), and keeps the rest. - A verifier proves it against the code: Frama-C with
-wpfor C,pancake2viperfor Pancake.fire verifyruns them; see thefire verifychapter of the manual for the tools and their setup.
So the model is only as sound as the contracts, and fic never derives a clause itself: it translates what the annotation states.
The subset fic reads
Both notations are lifted to one neutral form, so one subset applies:
integer and boolean literals, parameters, .fis constants, the return
value and a field of it (\result.f), the parameter’s value on entry,
+ - * / %, the comparisons,
== and !=, ! && ||, and c ? a : b.
| C (ACSL) | Pancake | |
|---|---|---|
| Notation | /*@ ... */ before the function | annotation lines inside the function body |
| Preconditions | requires | requires |
| Postconditions | ensures | ensures |
| Return value | \result | retval |
| Value on entry | \old(x) | old(x) |
| Purity | assigns \nothing; | derived from the body |
/*@ requires 0 <= r && r < ROUNDS;
@ ensures \result == r + 1;
@ assigns \nothing;
@*/
int64_t tally(int64_t r) { return r + 1; }
A constant declared in the .fis may be named in a clause (ROUNDS); the
generated header gives each language its value.
Anything outside the subset is rejected by its name, so a contract never seems read when it was not:
error: cq/ping.fi: ACSL contract error in "pingpong.c": function `tally`:
`ensures \forall integer k; ...` uses the quantifier `\forall`, which is
outside fic's contract subset (arithmetic, comparisons, `! && ||`, `? :`,
`\old`, `\result`, parameters)
In ACSL, quantifiers, memory predicates (\valid, *p), implication,
bit operators and C casts are outside it; in Pancake, so are permissions,
quantifiers, the heap, implication, calls, bit operators and shifts.
Clauses the subset does not cover at all are the verifier’s and are not an
error: in ACSL named behaviours, assumes, terminates and exits, and
in Pancake any annotation other than requires and ensures (a
trusted, an invariant).
What the model needs of a call
For a Pancake function the model checks each call site, because it must produce a value the automaton can use:
- A call whose value is used, rather than made as a bare statement,
needs a deterministic
ensures retval == E. Without one,--checkreports that the function has “no deterministicensures retval == …clause”. - A call in a guard must also be pure, because the generated C may
evaluate a guard more than once. A Pancake function is impure if it
calls a foreign function, stores to memory, reads shared memory, raises,
or writes a
global, directly or through a callee.
An ACSL contract is lifted and rendered the same way. assigns \nothing;
marks a C function pure, and a missing assigns clause counts as
impure, since ACSL’s default permits every effect; the guard check
currently runs for Pancake contracts only.
What fire verify proves
fire verify runs the contract prover first (Frama-C WP for a C import,
pancake2viper for Pancake), then verifyta on the model that assumes
the contracts. Both must pass: a model check over an unproved contract
proves nothing about the code behind it.
Generated Headers
A struct or const declared in the data layer
is the one definition both sides of the foreign boundary use. fic writes
it out for each foreign language, from the typed .fis, before any import
is read.
| File | For | Written when |
|---|---|---|
include/gen/types.h | C imports | the .fis declares a struct or a const |
include/gen/types.pnk | Pancake imports | some program imports a .pnk file |
include/gen/mem.h | C imports | some program imports a .c or .h file; see Foreign Functions |
Both live under <project>/include/gen/; <project>/include is on every
tool’s include path, so a foreign file writes #include "gen/types.h" (or
.pnk). The rest of include/ is yours. Each generated file opens with a
Generated by fic ... Do not edit. marker and is rewritten on every
build. fic refuses to overwrite a file in that place that it did not
write. fire clean removes include/gen/.
types.h
Each struct is written in field order, followed by an assertion on its size:
struct Message {
uint16_t length;
uint16_t kind;
uint32_t offset;
};
_Static_assert(sizeof(struct Message) == 8, "fic: struct Message layout");
struct Slot {
uint16_t flags;
uint16_t seq;
struct Message msg;
};
_Static_assert(sizeof(struct Slot) == 12, "fic: struct Slot layout");
A Fiducia struct has C’s layout on the target: each field at its natural
alignment, padding included; an @attr(packed) struct is declared
struct __attribute__((packed)) Name, with no padding. The assertion makes a C compiler that would
lay the struct out differently fail the build, rather than disagree
silently with the model.
A constant is a #define, except under Frama-C, where it is a static const object so that a contract keeps the constant’s name instead of its
value:
#ifdef __FRAMAC__
static const uint64_t SLOT_SIZE = 2048;
#else
#define SLOT_SIZE 2048
#endif
Fiducia scalars are spelled as the fixed-width C types (int as
int64_t, uint as uint64_t, Address as uintptr_t, bool as
bool). An array field is written with its length: the constant, when
the .fis named one (uint8_t buf[SLOT_SIZE]), else the number.
types.pnk
Pancake has no structs here: types.pnk carries the folded constants as
#defines, which the CakeML preprocessor and pancake2viper both read.
#define ROUNDS 5
Structs are not translated.
Well-Formedness
After typing, fic checks five structural conditions that no typing rule
expresses. Each one is a property the later stages rely on, and each is
reported with the declaration it concerns. They are the checks of the
CoreFi paper’s well-formedness, restricted to what a program text can
violate: WF2 over the whole system, and three conditions on process
bodies. The fifth, where a Sync channel is received, is the platform’s:
Microkit’s protected procedure call. (WF1 and the rest of WF3 are not
checked here.)
A placeholder. Well-formedness checking is still under research. The checks below are what
ficenforces today; which conditions the language needs, and how they are checked, may change.
WF2: the channel dependency graph is acyclic
A protection domain that receives from another waits for it. Draw an edge
from each receiver to the sender it waits for: a cycle is a circular wait,
a deadlock by construction. A unidirectional channel contributes one edge,
receiver to sender; a bidirectional channel (<->) contributes both, so
every bidirectional channel is a cycle. Parallel channels between one
ordered pair of PDs are one edge.
A cycle is a warning, and the program still builds:
warning: WF2 violation: channel dependency graph contains a cycle:
ping → pong → ping (via channels: ball, ball)
--> pingpong.fis:9:1
| Chan ball = ping <-> pong;
The chain of the data-diode demo, eth_outer --> dd --> eth_inner, has no
cycle and passes.
WF2 is a structural over-approximation: it also warns on programs that are
deadlock-free under a fair scheduler. When deadlock-freedom is established
another way, typically by model-checking the UPPAAL model fire build
writes with fire verify, silence the warning with --allow-wf2-cycles (or
allow_wf2_cycles = true under [run.target] in fire.toml). The
pingpong and pingpongpan demos do exactly this, and their
spec/*.q files state the deadlock property instead.
Tail recursion
A reference to a process that is already running (itself, or one that called it) must be the last thing the process does; a first call to a helper may be followed by more work. The reference then compiles to a jump back to a process’s head and the control graph stays finite; a reference to a running process followed by more work would need a return stack.
proc Notified() { ball? -> Notified(); ball! -> Skip; } // rejected
proc Notified() { ball? -> ball! -> Notified(); } // accepted
error: process `Notified` is referenced in non-tail position inside
`Notified` — its continuation would need a return stack
A default branch and receives
The default arm of a choice runs when no branch’s guard holds. A receive
beside a default is a receive outside the head (see the next section) and
a branch with no guard, so the default never runs: two warnings.
proc Pick() { c? -> Skip default Skip; } // warnings: outside the head; no guard
The notified handler is receive-headed
Microkit invokes notified with a message to handle. A process bound to
microkit.notified that receives at all should therefore begin, on every
path, with a receive (c?x) or an interrupt await (irq?N), through [],
the left of ; and a helper process’s body, and with no guard and no
default at the top. Otherwise the handler could run without consuming the
message that woke it and never return to the kernel. A branch of the head is
itself a receive, not a call to a process that receives. A notified that
never receives (a PD that only sends) needs no head.
No receive carries a guard. While a guard is false the message stays queued and the PD sleeps; if every branch of its head is closed, nothing wakes it.
@bind(microkit.notified)
proc Notified() { ball! -> ball? -> Skip; } // warning: starts with a send
@bind(microkit.notified)
proc Notified() { Skip; } // accepted: never receives
@bind(microkit.notified)
proc Notified() { ball? -> ball! -> Notified(); } // accepted
warning: process `Notified` bound to `microkit.notified` is not receive-headed:
each path at its head must begin with an unguarded receive (`c?x`) or IRQ
await (`irq?N`) — the kernel invokes it for a message; a program that
breaks this rule is outside the deadlock freedom fic guarantees
A receive or an IRQ await anywhere but the head is a warning: no notification arrives inside the invocation, so the handler would wait there for the next one, and any other notification meanwhile is dropped.
These are warnings, and the program still builds. Deadlock freedom is proved of programs whose PDs wait only at a head of unguarded receives, so a program with one of these findings is outside that guarantee.
Every choice is decided by its own guards
Outside the head, a choice is decided by its guards: each branch is
guarded, no two guards hold together, and one always holds. A default is
the guard that holds when no other does, and a lone guard is a choice of
one branch, so it must always hold.
Each choice is checked on its own guards, in every state, whatever guards
enclose it. A choice nested directly in a branch is part of that branch’s
choice; one after a ; is a choice of its own:
[b] ([g] a -> Skip [] [!g] e -> Skip) [] [!b] f -> Skip // one choice: fine
[b] (([g] a -> Skip [] [!g || !b] e -> Skip) ; k -> Skip)
[] [!b] f -> Skip // warning: the inner branches overlap when g and not b
A Sync channel is received in protected
A send on a Sync channel is a protected procedure call, which the kernel
answers by invoking the receiver’s protected and makes the caller wait on
until it returns. So these are errors, not warnings: the C has no lowering
for the first three, and the model none for the last.
- The process bound to
microkit.protectedbegins, on every path, with an unguarded receive on aSyncchannel (c?), one branch per channel. - Nothing after its head receives or awaits an interrupt: it runs to its end without waiting.
initandnotifiednever receive aSyncchannel, since its call does not notify.initnever sends on aSyncchannel: it runs before anything else, and the UPPAAL model runs it without interruption, so the callee could not answer.
After the head of protected, as after the head of notified, the guards
decide every choice: each branch is guarded, no two guards hold together,
and one always holds. A finding there is a warning.
@bind(microkit.protected)
proc Serve() { req? -> serve -> Serve(); } // accepted
@bind(microkit.protected)
proc Serve() { req? -> done? -> Skip; } // rejected: waits after the head
@bind(microkit.notified)
proc Notified() { req? -> Notified(); } // rejected: `req` is Sync
@bind(microkit.init)
proc Init() { req! -> Skip; } // rejected: a call from init
Where the checks run
fic --check runs all five after typing, and every backend assumes them.
The other outputs run fewer: WF2 runs only under --check and the image
build.
The process-body checks run first, then the entry-point binding, the
contract read and information flow; WF2 runs last
among them. The Sync receive check reads the graphs, so it runs once they
are built, beside the receive and choice checks.
Information Flow
Memory regions and the mappings that expose them carry a security label,
Low or High, on the two-point lattice Low ≤ High. fic checks one
rule over them.
A placeholder. Information-flow checking is at an initial stage, still under research. The rule below is what
ficchecks today, not a guarantee thatHighdata cannot reachLow: flows through expressions, channels and foreign code are not checked.
A mapping’s label must be at least its memory region’s.
A High region is therefore never read through a Low mapping: High
data cannot reach a context that is allowed to see only Low.
// .fis
High MemoryRegion secret(0x1000);
Low MemoryRegion open(0x1000);
// .fi
High Mapping a(secret, "r"); // accepted: label matches
High Mapping b(open, "rw"); // accepted: upward, Low data seen as High
Low Mapping c(open, "r"); // accepted
Low Mapping d(secret, "r"); // rejected: a High region through a Low mapping
error: information flow violation: High memory region 'secret' is
accessed through Low mapping 'd'
--> p.fi:1:1
| Low Mapping d(secret, "r");
An unlabelled region or mapping is Low. The check reports one error per
offending mapping, at the mapping, in the .fi that declares it.
What the labels do and do not cover
- Labels sit on regions and mappings. A protection domain carries no label of its own: what a PD can see is exactly what it maps.
- A channel buffer’s mapping takes its region’s label, so only a program’s
own
Mappingcan violate the rule. - The check is on mappings only. It does not follow values between variables or across channels, and a channel carries no label.
The data diode
The data-diode demo labels the ring its outer side writes Low and the
ring its inner side reads High, with one forwarding PD between them:
Low MemoryRegion eth_outer_output(0x200000, 0x200000);
High MemoryRegion eth_inner_input(0x200000, 0x200000);
Chan o2d = eth_outer --> dd via eth_outer_output<Slot>;
Chan d2i = dd --> eth_inner via eth_inner_input<Slot>;
Frames enter on the Low side and leave on the High side. The rule
keeps the labelling honest: the High ring can never be mapped with a
Low label, by any program. It does not by itself make the diode one-way.
That direction is the declared topology (-->, outer to inner, and no
channel back), which fic --emit=dot draws and the WF2 check warns of a
cycle in, but which the information-flow check does not inspect.
fic --check runs this check after typing and the
well-formedness checks, WF2 excepted, which runs
after it.