Files
sakurac/docs/freestanding.md
T

578 lines
29 KiB
Markdown
Raw Permalink Normal View History

2026-10-26 10:14:11 -05:00
# Plan: programs with no operating system
Written 2026-10-20. This is a proposal. The language is yours, so the decisions at the end
are yours to make. Nothing is built yet.
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
`@link` are `extern` sections.
**The std plan is built:** `core/` and `system/` are libraries found beside the
compiler, and `core` needs nothing of a system but memory and `fault`.
**The runtime is a library of its own** since 2026-10-21: `runtime/` (`rt/` for part of
2026-10-26), found beside the compiler as `core/` and `system/` are, whose module is
`runtime`. It needs `core` and
`system`, and nothing of std, so std plays no part in a build that doesn't import it.
**The short answer:**
- **The std plan's `core` makes the source freestanding.** None of its files has a
`when os` section. Its only ties to a platform are intrinsics: the heap's, `fault`'s,
atomics' and lanes'.
- **An executable is more than that source.** Three things tie every native build to
Linux or Windows:
1. **The runtime** the compiler builds into every executable: the module `runtime`,
whose 16 helpers it calls by name.
2. **Code the compiler writes itself:** `_start`, the fault handlers, the trap
stub, thread starts. All of it makes system calls or calls `kernel32`.
3. **What generated code assumes:**
- a thread record at `gs`, read by function prologues;
- an image at `0x400000` addressed absolutely;
- SSE2 and x87 turned on;
- an ELF or console PE.
- **Allocation is the smallest of these.** The heap's algorithm is already plain Sakura:
size classes, chunks, free lists, thread caches. Only taking memory from the system
(`mmap`, `mprotect`, `mremap`, `VirtualAlloc`) and the lock (`futex`, `WaitOnAddress`)
belong to a platform. Split there, the algorithm goes into `core`, and a platform
gives it pages. On bare metal, that's a region of the image, or what the boot memory
map says is free.
- **Alongside the platforms there now, the platform becomes a layer the target chooses.**
- `linux-x86_64` and `windows-x86_64` keep the runtime of `runtime/`.
- A new `none-x86_64` takes the program's own: a module `platform` of up to four
functions, of which only `stop` is required.
- The compiler writes a start for it that needs no system.
- **Operating systems need more than a target:**
- privileged instructions;
- memory the optimizer leaves alone (`volatile`);
- interrupt handlers;
- alignment and packing;
- a kernel in the top 2 GiB.
None of these exists yet.
**Its users:**
- **Kernels and bootloaders,** in ring 0, booted by a loader such as Limine.
- **Programs for an operating system of one's own,** in ring 3, whose platform module
makes that system's calls.
- **UEFI tools,** later, whose platform is the firmware's boot services.
- **Programs on Linux and Windows,** which are unchanged. The heap's split moves code
but not behavior.
**Probed** on 2026-10-20, in the scratchpad's `plans2/f/`, with `x2` (the compiler's fixed
point), and by three searches of the compiler's sources. A program summing a vector, built
at `-O2`:
| | sakurac |
|---|---|
| Executable | 164 KB |
| Kind | ELF `ET_EXEC`, base `0x400000`, segments `.rodata`, `.data`, `.text`, `.lines` |
| Instructions reading through `gs` | 55 |
| `syscall` instructions | 42: `_start`, the heap, its lock, threads, `fail`, `exit`, the trap stub |
| Instructions naming an `xmm` register | 133: formatting, `memcpy`, clearing, comparing |
| RIP-relative operands | 0 |
| Stores below `rsp` (the red zone) | 0 |
- **`core`'s source has no `when` section.** The copy of `core` the std plan probed (11,294
lines) has none, and its intrinsics are only the heap's, `exit` and `abort`, atomics,
lanes, bits, and compile time.
- **Linux lets a program here set its own `gs` base.** `AT_HWCAP2` holds FSGSBASE, and a
C program's `wrgsbase` and `rdgsbase` worked in user mode on this machine. So a
freestanding image can be tested as a Linux process ([Testing](#testing)).
- **There's no QEMU here.** Booting a kernel needs `qemu-system-x86_64`, and UEFI
needs OVMF as well.
## What's there now
### What an executable takes from its platform
| Piece | What it does now | What it needs of the system |
|---|---|---|
| `_start` (`native.sakura:1080-1141` in `sakura-native`) | Points `gs` at the first thread's record, reads the thread's ID, maps a stack, installs a `SIGSEGV` handler, probes the CPU, runs `processor` over the environment, then `<globals>` and `main`, then exits with 0 | `arch_prctl`, `gettid`, `mmap`, `rt_sigaction`, `exit_group`; argc, argv and envp on the first stack. On Windows, `kernel32` throughout (`windows.sakura:306-365`) |
| Stacks | The compiler keeps frames on `rsp`, 32 MiB mapped | `mmap`, or the system's thread stack |
| The thread record | 32 words at `gs`. It holds the stack limit (word 1), the trap frame, the record itself, C-call words, signals, heap caches and format builders | Something must set the `gs` base: `arch_prctl`, or a TLS slot on Windows |
| The 16 helpers, by name in `runtime` (`native.sakura:31-58`) | `fail`, `arguments`, `allocate`, `allocate_untraced`, `release`, `resize`, `equal`, `format_begin`, `format_text`, `format_value`, `format_owned`, `exit`, `abort`, `processor`, `start_thread`, `thread_main`, and `system_start` on Windows | Formatting, `equal` and the heap's logic need nothing. The rest map memory, write, exit, lock or start threads |
| The heap (`runtime/memory.sakura`, 809 lines) | 19 size classes carved from 1 MiB chunks, in up to 64 GiB of reserved address space. Larger blocks are mapped alone. Caches per thread once threaded | `mmap` with `PROT_NONE`, `mprotect`, `munmap`, `mremap`; `VirtualAlloc` on Windows. A `futex` or `WaitOnAddress` lock once threaded |
| Faults | Checks call the trap stub, which calls `fail`. A second trap while reporting exits at once, by `exit_group` written inline. A null read faults in page 0, and the `SIGSEGV` or vectored handler turns it into a report | `fail` allocates from the heap, walks the `rbp` chain over the `.lines` tables, writes to descriptor 2, and exits with 1 |
| Safe points | Only where `std::sys::handle` is used | Signals |
**Generated code assumes:**
- **The stack limit through `gs`.** The compiler checks `rsp - frame` against `gs:[8]`
in every prologue but a small leaf's (`calls.sakura:1039-1047`).
- **SSE2 and x87, always.**
- Floats are scalar SSE2.
- Copies and clears up to 128 bytes, and the prologue's zeroing, go through `xmm`
registers.
- Float `%` is x87's `fprem`.
- AVX is chosen at run time, from the probe.
- **Frame pointers, always,** for traces. **No red zone.**
- **Absolute addresses:**
- `[disp32]` with no base, sign-extended;
- also `mov r32, imm32`, which is zero-extended, and switch tables of `u32`.
So an image runs only where it was linked, in the low 2 GiB.
**The image** (`binary::elf` and `binary::pe`, in `binary`):
- `ET_EXEC` at `0x400000`, or a console PE with its relocations stripped that imports
`kernel32`.
- No `.bss`: `.data` is written whole, zeros and all, so a large zeroed global grows
the file.
- No object files, no flat binaries, no linker.
- An ELF calling C names `/lib64/ld-linux-x86-64.so.2`.
- `build_options.stack` exists, but nothing sets it.
**Targets are a closed list:** the `platform` enum (`entry.sakura:107-110`),
`checker::target_value` (`checker/declare.sakura:146-171` in `sakura-analyzer`), and
`build_options.windows: bool`, tested in about 18 places.
`os` may be `linux`, `macos`, `windows` or `freebsd`, and none of these means "no
system".
### What the language has for systems work
**There:**
- **Raw pointers,** with arithmetic, and `as` between integers and pointers, so a device
register's address can be a pointer.
- **`cfn<F>`** made from an address.
- **Atomics,** with C11's orders. A fence keeps loads and stores from moving across it,
in the optimizer, even where no instruction is emitted.
- **Struct layout as C's:** fields in order, each aligned to itself, never reordered.
It's stated only in the compiler's sources. `@foreign` unions overlay their fields.
**Not there:**
- **Inline assembly,** or any intrinsic for `in`/`out`, `cli`/`sti`/`hlt`, control
registers, MSRs, `lgdt`/`lidt`/`ltr`, `invlpg`, `iretq`, `swapgs`, `rdtsc` or `pause`.
- The encoder emits only `syscall`, `cpuid`, `xgetbv`, `mfence`, `lock`, `rep`,
`ud2`, `vzeroupper` and `fprem` beyond ordinary code.
- The only one a program can reach is Linux's `std::sys::syscall`.
- **Volatile memory.**
- The optimizer reuses a value read through a pointer when nothing between may
write it.
- Its loop passes move such a read out of the loop.
- So a loop polling a device register would read it once.
- **`@align`, `@packed`,** field offsets, sections, placing anything at an address.
- **An entry of one's own.** `main` is `def main(): void` or
`def main(args: span<strview>): void`.
- **Interrupt handlers,** naked functions, a function C or assembly can call outside a C
call, `noreturn` beyond `exit` and `abort`, exported symbols.
**Allocators:**
- Every container's `new` takes a `maybe<&mut allocator>`, and `nothing {}` means the
default heap.
- These always use the default heap: `box`, `rc` and `arc`; a `function` holding more
than 24 bytes; `$"..."`; `to_vector`, `vector::from`, `dict::from` and `to_string`.
- `arena::over(buffer)` serves from memory it's given, then falls back to the heap.
### std with no operating system
| Needs only `core` and a heap | Needs a system |
|---|---|
| `std::math`, `std::json`, `std::yaml`, `std::serial`, `regex`, `uri`, `version` | `std::io`, `std::sys`, `std::args`, `std::time`, `std::thread`, `std::process`, `std::testing` |
## What it needs
1. **A target with no operating system,** beside the two, and a `when` value for it.
2. **The platform as a layer the target chooses:** std's for Linux and Windows, the
program's for none.
3. **The heap's algorithm apart from where its memory comes from.**
4. **A start that needs no system:** the thread record, stacks, SSE, `<globals>`,
`main`.
5. **Faults reported with no system:** a place the platform says the report goes, and a
way for a kernel's own exception handlers to report as a fault does.
6. **An image a loader can place:** its base, the top 2 GiB for kernels, and a `.bss`.
7. **What operating-system code does:**
- privileged instructions;
- volatile memory;
- interrupt handlers;
- alignment and packing.
8. **Testing without hardware,** and on QEMU where it's installed.
## How it fits the rules
- **"Programs run on a virtual machine, or as standalone x86-64 executables for Linux
and Windows that behave identically."**
- A freestanding executable behaves the same wherever it shares a meaning with them:
the same faults, reports and traces.
- Where the report goes, where memory comes from, and how the program stops are the
platform's.
- **Targets:** `os` gains `none`. `--target none-x86_64` is `os == none`,
`arch == x86_64` and `backend == native`. Nothing existing changes name.
- **The VM stays hosted.** `run` refuses `none`. A freestanding program's logic runs in
the VM under the host's target, with its `when os == none` sections set aside.
- **std's system modules aren't read** on `none` unless a program refers to them, under
reading by reference. Where one is, the compiler says it's for other
targets ([std on none](#std-on-none)).
## The design
### The target (decision 1)
- **`none-x86_64`:** no operating system. The program's platform module decides whether
it runs in ring 0, as a kernel, or in ring 3, on a system of its own.
- `check --target none-x86_64` and `build --target none-x86_64`. The language server
takes it as `check` does.
- **The native backend's one switch,** `build_options.windows: bool`, becomes a choice
of three systems.
- **UEFI** comes later ([Later](#later-where-wanted)): a PE for the firmware, with the
Windows calling convention the compiler already has.
### The platform layer (decision 2)
The 16 helpers split three ways:
| Helpers | Where they go | Why |
|---|---|---|
| `format_begin`, `format_text`, `format_value`, `format_owned`, `equal`, and `float`'s and `values`' code | `core` | They're the language's: `$"..."` and comparing values |
| `allocate`, `allocate_untraced`, `release`, `resize` | `core`'s heap, over the platform's pages | The algorithm is the language's, the memory the platform's |
| `fail` | `core` builds the report and walks the trace; the platform writes it and stops | The `.lines` tables are the image's own |
| `arguments`, `processor`, `exit`, `abort`, `start_thread`, `thread_main`, `system_start` | `runtime`'s Linux and Windows sections only | They're the system's. On `none`: no arguments, the probe's features as they are, `exit` stops, and `abort` traps |
**On `none`, the platform is a module `platform`,** given by the program or by a
library, which the compiler looks up by name, as it looks up `runtime` now:
```sakura
module platform;
pub def start(): void; # optional: runs first, before <globals>
pub def pages(count: u64): *mut u8; # optional: count 4 KiB pages for the heap, or null
pub def report(text: strview): void; # optional: where a fault's report goes; dropped if absent
pub def stop(status: i32): void; # required: never returns
```
- **On Linux and Windows,** `system` gives the same four, from the ffi plan. So the
runtime's system parts shrink to those, the lock's wait and wake, and threads.
- **A kernel may write its `platform` as `extern module platform when os == none;`,** so
the structs its loader hands over, as Limine's requests and answers, are laid out as
C's.
### The heap (decision 3)
- **`memory.sakura`'s algorithm moves into `core`.** Its system parts become calls to the
platform: reserving and opening chunks, mapping a large block, giving memory back.
`mremap`'s growth stays Linux's, as an extra the platform may give.
- **On Linux and Windows, nothing changes:** their `pages` are the reservation and
`mprotect` or `VirtualAlloc` of today.
- **On `none`, memory comes from where the program says:**
- `platform::pages`, from what a kernel knows is free;
- or `--heap SIZE`, a region of the image's `.bss` the heap takes first;
- or both, the region first.
- **With neither, there is no default heap.** A build that reaches it fails, naming the
way: "`main` reaches the heap through `vector::append` and `acquire`, and
`none-x86_64` gives no memory: declare `platform::pages`, build with `--heap SIZE`, or
give the vector an allocator."
- The compiler already knows what's reached, since it compiles only that.
- **Allocators given by hand work with no heap at all,** for every container but those
above that always use it. Allocators for `box`, `rc` and `arc` come later.
- **One processor at first.** The heap's lock does nothing until a thread starts, and
`none` has no threads. Several processors come later.
### The start (decision 4)
On `none`, the compiler writes `_start` as it does now, without the system:
1. **Ring 0** (`cs & 3 == 0`):
- turn on x87 and SSE, since every prologue and copy may use them: CR0's EM off and
MP on, CR4's OSFXSR and OSXMMEXCPT on, `fninit`;
- set the `gs` base with `wrmsr` to `IA32_GS_BASE`.
**Ring 3:** set it with `wrgsbase`, which the system must allow, as Linux does.
2. **The stacks:**
- switch `rsp` to a stack in `.bss`, `--stack SIZE`;
- set the limit in the record, and `rbp` to 0.
3. **Probe the CPU** into the record. No `SAKURA_CPU`, since there's no environment.
4. **Run** `platform::start()` if it's declared, then `<globals>`, then `main()`, then
`platform::stop(0)`.
No system calls, no signal handlers, no arguments. `main` stays `def main(): void`. What a
loader hands over, as Limine's answers or a memory map, the platform module reads in its
own way.
### Faults
- **Reporting:**
- The trap stub's second trap calls `platform::stop(1)` rather than `exit_group`.
- `fail` builds "sakura: runtime error: ..." and the trace from `.lines` into a buffer
in `.bss`, not the heap, since the heap may be what failed.
- It hands the buffer to `platform::report`, then calls `platform::stop(1)`.
- **The processor's own faults** are the kernel's, through its interrupt table.
- A null read faults only if the kernel leaves page 0 unmapped.
- A kernel's `@interrupt` handler for a page fault, a division or a general protection
fault calls `core::fault_at(kind, rip, rbp)`. That reports it as the language
reports a fault, with the trace.
- **The stack:** the prologue's compare works as it does on Linux.
### The image (decision 5)
- **ELF `ET_EXEC`, as now,** with:
- `--base ADDR`;
- a `.bss`, so zeroed globals, `--heap` and `--stack` cost nothing in the file;
- `_start` as the entry.
- **The top 2 GiB,** where kernels usually live and where Limine's protocol wants them.
- `[disp32]` already sign-extends and reaches it.
- The compiler's `mov r32, imm32` of an address becomes `mov r64, simm32`, and its
switch tables of `u32` become `i32`.
- So do the handlers' `mov ecx, imm32` of the text's end.
- **Not now:** code that can be placed anywhere (RIP-relative), relocatable PEs, flat
binaries. Multiboot2 enters in 32-bit mode, which the native backend can't write.
### Reaching the hardware (decision 6)
**`core::x86_64`,** a child of `core`, imported where it's used:
| Intrinsics | Instruction |
|---|---|
| `port_in8`, `port_in16`, `port_in32`, `port_out8`, `port_out16`, `port_out32` | `in`, `out` |
| `read_cr0`, `read_cr2`, `read_cr3`, `read_cr4`, `write_cr0`, `write_cr3`, `write_cr4` | `mov` to and from control registers |
| `read_msr`, `write_msr` | `rdmsr`, `wrmsr` |
| `load_gdt`, `load_idt`, `load_task` | `lgdt`, `lidt`, `ltr` |
| `interrupts_off`, `interrupts_on`, `halt`, `pause` | `cli`, `sti`, `hlt`, `pause` |
| `invalidate_page` | `invlpg` |
| `cpuid`, `read_tsc` | `cpuid`, `rdtsc` |
| `read_gs_base`, `write_gs_base` | `rdgsbase`, `wrgsbase` |
| `system_call` | `syscall`, for a platform in ring 3 |
**`volatile_load<T>(p: *T): T` and `volatile_store<T>(p: *mut T, value: T)`,** in
`core` for every target.
- The optimizer treats each as it treats an atomic: touching all memory, so it's
neither removed, merged nor moved.
- An atomic already works this way.
The table holds 28 intrinsics. The encoder gains about 20 instructions, with `fninit`, `fxsave`,
`fxrstor` and `iretq` for the start and interrupts. On the VM, a privileged intrinsic stops
the program, as it can't be run there. `check` is unaffected.
### Interrupt handlers (decision 7)
```sakura
struct interrupt_frame { pub val rip: u64; pub val cs: u64; pub val flags: u64; pub val rsp: u64; pub val ss: u64; }
@interrupt def page_fault(frame: &interrupt_frame, code: u64): void { ... }
@interrupt def timer(frame: &interrupt_frame): void { ... }
```
- **The compiler writes the entry:**
- save every general register and the SSE state (`fxsave`);
- set up what generated code needs, then call the body;
- restore everything, and `iretq`.
A handler taking `code` is one the processor pushes an error code for.
- **Its address,** for the interrupt table, comes from naming it: an `@interrupt`
function's value is a `u64`.
- **The compiler keeps frames on `rsp`,** so a handler's frames go below the interrupted
code's.
### Layout (decision 8)
- **`@align(N)`** on a struct or a global, as a page table's 4096.
- **`@packed`** on a struct: no padding. Its fields may be unaligned, which x86-64 reads
and writes.
- **The README says how structs are laid out,** as the compiler already does it.
### std on `none`
- **What it can use:** `core`, and std's modules that need only a heap.
- **A module whose sections are all for other targets** is reported as such: "`std::io`
is written for `os == linux` and `os == windows`, and this target is `none`."
- Today that case gives "No file declares this module", or a missing `sys::` name
deep inside.
- This helps every target, not only `none`.
## Using it
```sakura
# platform.sakura: what this kernel gives the language
module platform;
import core::x86_64;
pub def report(text: strview): void {
for c in text { x86_64::port_out8(0x3F8, c); } # the first serial port
}
pub def stop(status: i32): void {
x86_64::interrupts_off();
while true { x86_64::halt(); }
}
```
```sakura
# kernel.sakura
def main(): void {
var frames := vector::<u64>::new(); # from --heap
frames.append(0x100000);
platform::report($"{frames.length} frame\n");
}
```
```sh
sakura check --target none-x86_64 kernel.sakura platform.sakura
sakura build --target none-x86_64 --base 0xffffffff80000000 --heap 16M --stack 64K \
-g -o kernel.elf kernel.sakura platform.sakura
qemu-system-x86_64 -cdrom os.iso -serial stdio -s # gdb loads kernel.elf.petal for source lines
```
## How each part works
**The compiler:**
- **Targets:**
- `entry.sakura`'s `platform` gains `none-x86_64`;
- `target_checker` (`program.sakura` in `sakura-server`) sets `os = "none"`;
- `checker::target_value` (`checker/declare.sakura` in `sakura-analyzer`) gains `none`;
- `build_options.windows` becomes a system of three, at its 18 places.
- **The start** (`native.sakura` in `sakura-native`): a third entry beside Linux's and
Windows'. Ring 0 or 3 by `cs`, the stacks from `.bss`, then the `platform` functions
found as `runtime`'s are (`building::prepare`).
- **Faults:**
- the trap stub's second trap calls `stop`;
- on `none` there's no `SIGSEGV` or vectored handler;
- `core::fault_at` enters the trap stub as the Linux handler does now.
- **The image** (`binary::elf`, in `binary`): a `.bss` segment of `PT_LOAD` with a
file size short of its memory size, `--base`, and, for the top 2 GiB, the sign-extended
forms in `binary::amd64`, `calls.sakura` in `sakura-native` and the handlers.
- **Intrinsics:**
- `emitter/intrinsics.sakura` in `sakura-compiler` lowers each to an IR operation;
- `binary::amd64` encodes it;
- the optimizer's table (`intermediate/code.sakura` in `sakura-compiler`) marks the
volatile and privileged ones as touching all memory.
- **`@interrupt`, `@align` and `@packed`:**
- the checker reads them (`checker/attributes.sakura` in `sakura-analyzer`);
- `layouts.sakura` in `sakura-compiler` lays out `@align` and `@packed`;
- `calls.sakura` in `sakura-native` writes the interrupt entry.
**`runtime` and `core`:**
- `runtime/`'s formatting, values, floats and the heap's algorithm move into `core`;
- the four platform functions go into its Linux and Windows sections;
- `core::x86_64` and the volatile intrinsics are added.
## Testing
- **As a Linux process,** without QEMU.
- An image for `none-x86_64` runs on this machine. Linux loads its `ET_EXEC` and
starts it in ring 3, where the start takes `wrgsbase`.
- A test platform module stops and reports through `x86_64::system_call`, as Linux's
`exit_group` and `write`.
- That tests the start, the heap over `pages` and over `--heap`, faults and their
traces, `<globals>`, the stack's limit, volatile memory, and the corpus's programs
that need only `core`.
- **Each build that reaches the heap with none given** fails, naming the way.
- **On QEMU,** where it's installed: a small kernel in `test/kernel/`, booted by Limine.
- It writes to the serial port, which `-serial stdio` gives the test.
- It ends through QEMU's `isa-debug-exit` device, `port_out32(0xF4, code)`, which
gives QEMU's exit status.
- It takes a breakpoint and a page fault through `@interrupt` handlers, and reports
the page fault as a fault, with its trace.
- It reads a timer through volatile memory, and builds at its top-2-GiB base.
- **Layout:** `@packed` and `@align` structs' sizes and offsets, checked by reflection.
- **Linux and Windows unchanged:**
- the corpus in the VM and natively at each level;
- the std suite, and the compiler's unit tests;
- the compiler building itself to its fixed point.
## Phases
1. **The runtime split,** after the std plan's `core`:
- formatting, values and floats into `core`;
- the heap's algorithm into `core` over `pages`;
- `fail` split into building and writing.
Linux and Windows behave as before. About 900 lines of `runtime` moved, and 150 in the
compiler.
2. **`none-x86_64`:** the target and `when os == none`, the start, `platform`, faults,
`.bss`, `--base` (low 2 GiB), `--heap` and `--stack`, and the note for a module of
other targets. Tested as a Linux process. About 600 lines in the compiler.
3. **The hardware:** `core::x86_64` and the volatile intrinsics. About 400 lines in the
compiler.
4. **Layout:** `@align` and `@packed`, and the README's layout. About 250 lines.
5. **Interrupts:** `@interrupt`. About 300 lines.
6. **The top 2 GiB.** About 300 lines.
7. **A kernel booting on QEMU,** in `test/kernel/`. This needs QEMU, and Limine's files,
on the machine running it.
8. **The README:** "Executables and tools", "Pointers and memory", and a section on
programs with no operating system.
## Found along the way
- **A loop polling memory reads it once,** in the optimizer, since nothing in the loop
writes it. Harmless now, wrong for a device register.
- **`.data` is written whole,** so a zeroed global costs its size in the file.
- **`build_options.stack` exists,** and nothing sets it.
- **`arena::over(buffer)` falls back to the heap** when its buffer is full, which on a
target with no heap must fail instead.
## Later, where wanted
- **UEFI:** `uefi-x86_64`, a PE for the firmware (subsystem 10) with its entry under the
Windows calling convention.
- Its platform: pages from `AllocatePages`, reports to `ConOut`, `stop` through
`Exit`.
- A PE with its relocations stripped loads only where its base is free, so it may
need a `.reloc`.
- **Several processors:** a record per processor at `gs`, the heap's lock as a spin, and
starting the others.
- **Programs for one's own system,** in ring 3, with `swapgs` and system calls of its
own.
- **Code that can be placed anywhere,** RIP-relative, for PIE and relocatable PEs.
- **Allocators for `box`, `rc` and `arc`,** and for `$"..."`, so a program with no heap
can use them.
- **`aarch64`,** where the platform layer would carry over unchanged.
- **Object files and exported symbols,** to link with assembly or C.
- **Thread-local variables,** which [later.md](later.md) lists already.
## Decisions for you
1. **Which targets first:**
- **(a) `none-x86_64` alone,** with UEFI later.
- **(b) `none-x86_64` and `uefi-x86_64` together.**
Recommended: **(a)**. It holds everything a kernel needs, and UEFI then reuses its
platform layer.
2. **Where a freestanding program's platform lives:**
- **(a) A module `platform`, given by the program or a library,** whose functions the
compiler finds by name, as it finds `runtime`'s. A platform can be shared as
a package.
- **(b) Attributes on the program's functions,** as `@platform(stop)`.
- **(c) A whole runtime of the program's own** in place of `runtime`, writing all
16 helpers.
Recommended: **(a)**. Four functions, one required, and the language's helpers stay
the language's.
3. **The heap on `none`:**
- **(a) Only where it's given,** by `platform::pages` or `--heap SIZE`. A build that
reaches it otherwise fails, naming the way.
- **(b) Always a region of a fixed size,** unless `--heap` says otherwise.
- **(c) None at all.** Every container takes an allocator, and `box`, `rc`, `arc` and
`$"..."` are refused.
Recommended: **(a)**. A kernel chooses where its memory comes from, and a mistake is
caught at build time, not at boot.
4. **The start:**
- **(a) Written by the compiler,** as now, with no system calls.
- **(b) Written by the program,** with naked functions and the intrinsics.
Recommended: **(a)**. The thread record, the stacks and SSE must be set before any
Sakura code runs, and only the compiler knows their layouts.
5. **Where an image may be placed:**
- **(a) The low 2 GiB,** at `--base`.
- **(b) Also the top 2 GiB,** for kernels.
- **(c) Anywhere,** with RIP-relative code.
Recommended: **(b)**. Kernels live there, and it changes only how addresses are
written as numbers. (c) changes every address the native backend writes.
6. **Reaching the hardware:**
- **(a) Intrinsics in `core::x86_64`,** and `volatile_load` and `volatile_store`.
- **(b) Inline assembly.**
Recommended: **(a)**. 28 intrinsics cover a kernel. The optimizer knows what
each does. And the compiler has no assembler to read text with.
7. **Interrupt handlers:**
- **(a) `@interrupt` functions,** whose entry and exit the compiler writes.
- **(b) Naked functions** the program writes, with the intrinsics.
Recommended: **(a)**, for the same reason as decision 4.
8. **Layout:**
- **(a) `@align(N)` and `@packed`.**
- **(b) `@align(N)` only,** with packed data written as bytes.
Recommended: **(a)**. Descriptor tables' pointers and many on-disk formats are
packed.
9. **The first boot to test on:**
- **(a) Limine,** whose protocol starts a 64-bit ELF in long mode, in the top 2 GiB.
- **(b) UEFI,** which needs decision 1's (b).
Recommended: **(a)**, with decision 5's (b).