Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ Browse the documentation on [GitHub Pages](https://kernelite.github.io/milo/) or
* [docs/06-hardware-and-interrupts.md](docs/06-hardware-and-interrupts.md) — Exception vectors, GICv2 interrupt routing, ARM Generic Timer, PL011 UART, `fw_cfg`/`ramfb`, and VirtIO-MMIO drivers.
* [docs/07-contributing-and-debugging.md](docs/07-contributing-and-debugging.md) — QEMU + GDB debugging workflow, panic/fault diagnostics, commit/license rules, and checklists for adding syscalls, drivers, or host tests.
* [docs/08-testing-and-ci.md](docs/08-testing-and-ci.md) — Host `snitch` ASan/UBSan test harness, `gcovr` coverage, quality gates, on-target `milo>` tests, and GitHub Actions CI workflows.
* [docs/09-design-patterns-and-best-practices.md](docs/09-design-patterns-and-best-practices.md) — Freestanding C++20 patterns, RAII/Rule of Five, HAL & DDK isolation, dual-target testing, forensic logging, and quality gates with external references.
* [docs/reference.md](docs/reference.md) — Detailed feature summary, repository directory layout, toolchain/host prerequisites, build/shell commands, and roadmap.
* [docs/adr/0001-unit-testing-framework.md](docs/adr/0001-unit-testing-framework.md) — Architectural decision record for the `snitch` host test runner, HAL mocks, and QEMU test coexistence.

Expand Down
101 changes: 101 additions & 0 deletions docs/09-design-patterns-and-best-practices.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<!--
SPDX-License-Identifier: GPL-3.0-only
Copyright (c) 2026 Marco Buschini <marco.buschini@gmail.com>
-->

# 09 — Engineering Patterns & Best Practices

**Milo** is written in freestanding C++20 for AArch64 (`-ffreestanding -fno-exceptions -fno-rtti`) with a host-testable core (`HOST_TEST`). Rather than relying on ad-hoc C idioms or runtime-heavy abstractions, the codebase enforces a small set of deterministic systems-engineering patterns across `kernel/`, `include/ddk/`, `drivers/`, and `tests/host/`.

---

## 1. Freestanding C++20 Without Exceptions, RTTI, or `atexit`

### How Milo Uses It
* **Compiler & ABI flags (`Makefile`, `drivers/ddk.mk`):** All kernel and driver translation units compile with `-std=c++20 -ffreestanding -fno-exceptions -fno-rtti -fno-threadsafe-statics -fno-use-cxa-atexit`.
* **Value-based error handling (`include/ddk/Status.hpp`, `kernel/core/traits.hpp`):** Fallible operations return `Kernel::DDK::Result<T>` (paired with `Kernel::DDK::Status`) or kernel `Result<T, E>` instead of throwing exceptions. Callers inspect `.is_ok()` / `.is_err()` explicitly, enforced by `[[nodiscard]]`.
* **Static-storage placement & `atexit`-free singletons (`drivers/dummy/DummyDriver.cpp`, `kernel/ddk/KernelPlatformServices.cpp`):** Out-of-tree DDK drivers must not assume kernel `kmalloc`/`kfree` or `__cxa_atexit`. `DummyDriver` uses aligned static storage with placement `new` (`new (g_dummy_storage) DummyDriver()`) and explicit destructor invocation (`drv->~Driver()`), while `kernel_platform_services()` returns a namespace-scope instance rather than a function-local `static` with a non-trivial destructor (which would emit a `__cxa_atexit` reference).

### Why & References
* Eliminates exception tables (`.eh_frame`), RTTI typeinfo bloat, and hidden heap allocations or `atexit` teardown chains in bare-metal EL1 code.
* [C++ Core Guidelines — E.1: Develop a strategy for error handling](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-errors)
* [ISO C++ Freestanding Proposal / Hosted vs. Freestanding](https://en.cppreference.com/w/cpp/freestanding)
* [Itanium C++ ABI — `__cxa_atexit` / DSO Object Destruction](https://itanium-cxx-abi.github.io/cxx-abi/abi.html#dso-dtor)

---

## 2. RAII & Rule of Five for Deterministic Resource Ownership

### How Milo Uses It
* **Move-only DDK resource handles (`include/ddk/Resources.hpp`, `include/ddk/Services.hpp`):** `MmioRegion`, `DmaBuffer`, `IrqHandle`, `IrqLock`, and `EventHandle` delete copy construction/assignment, implement move construction/assignment that null out the source handle, and deterministically release backing kernel resources via `PlatformServices*` in `reset()` / `~T()`.
* **Scoped kernel guards:**
* `Kernel::Sync::IrqGuard` (`kernel/sync/IrqGuard.hpp`) saves `DAIF` interrupt state on entry and restores it on scope exit.
* `Kernel::Log::ScopedLevel` (`kernel/core/log.hpp`) temporarily adjusts console log verbosity and restores the previous threshold when leaving scope.
* `Kernel::Shell::Tests::TestSession` (`kernel/shell/tests/test_common.hpp`) manages compact dot-progress output, console muting, and summary/failure reporting on scope exit.

### Why & References
* Prevents resource leaks on early returns or OOM rollback paths (for example, `DummyDriver::init()` automatically unmaps `MmioRegion` if `alloc_dma()` fails) without needing exceptions.
* [C++ Core Guidelines — R.1: Manage resources automatically using resource handles and RAII](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-raii)
* [C++ Core Guidelines — C.21: If you define or `=delete` any copy, move, or destructor function, define or `=delete` them all (Rule of Five)](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-five)

---

## 3. Hardware Isolation, HAL, and Compiler-Enforced DDK Boundaries

### How Milo Uses It
* **Arch-agnostic core vs. HAL (`arch/aarch64-linux-gnu/`, `kernel/hal/targets/qemu_virt/`):** Architecture-specific assembly, MMU page-table manipulation, and GIC/timer/board wiring live behind `kernel/hal/*.hpp` interfaces, keeping `kernel/mm/`, `kernel/fs/`, `kernel/ipc/`, `kernel/net/`, `kernel/loader/`, and `kernel/process/` hardware-agnostic.
* **Capability injection (`include/ddk/Services.hpp`, `kernel/ddk/KernelPlatformServices.*`):** Modular drivers under `drivers/` never touch global kernel symbols (`alloc_frames`, `HAL::get_cpu()`, `WaitQueue`). Instead, they receive `Kernel::DDK::PlatformServices&` and probe devices via `Kernel::DDK::DeviceDescriptor` (`include/ddk/Bus.hpp`).
* **Compiler-enforced header boundary (`drivers/ddk.mk`, `Makefile`):** Driver translation units compile with `DDK_CXXFLAGS` passing only `-I$(MILO_DDK_DIR)/include`—omitting `-Ikernel` and `-Iarch/...`—so any accidental private kernel include fails immediately at compile time. `make export-ddk` packages `include/ddk/` and `drivers/ddk.mk` into `build/ddk/` so external out-of-tree driver builds use the exact same workflow.

### Why & References
* Decouples drivers from kernel internals (Dependency Inversion), enabling out-of-tree builds and host-side mocking without QEMU.
* [Dependency Inversion Principle (SOLID)](https://en.wikipedia.org/wiki/Dependency_inversion_principle)
* [Fuchsia Driver Framework (DFv2) — Driver Isolation & Capability Injection](https://fuchsia.dev/fuchsia-src/concepts/drivers/driver_framework)
* [Windows Driver Frameworks (WDF) — Driver Model & Resource Ownership](https://learn.microsoft.com/en-us/windows-hardware/drivers/wdf/)

---

## 4. Dual-Target Testing & Zero-Leak Memory Invariants

### How Milo Uses It
* **Host-native `snitch` + Sanitizers (`tests/host/`, `Makefile`):** Architecture-agnostic kernel modules and DDK drivers compile natively on the host with `-DHOST_TEST` against `tests/host/mocks/host_hal.cpp` (a 16 MiB simulated RAM arena + mock MMU/CPU/console/IRQ HAL), running under AddressSanitizer and UndefinedBehaviorSanitizer (`-fsanitize=address,undefined`) and `gcovr` line/branch coverage (`make test-host`).
* **On-target kernel & EL0 verification (`kernel/shell/tests/`, `user/test_milo.c`):** `test all` runs 250+ in-kernel assertions in QEMU, and `/bin/test_milo` verifies the EL0 musl/syscall/VFS/devfs ABI end-to-end inside `milo-sh` or `milo-bash`.
* **Zero-leak PFA baseline invariants:** Tests such as `test_ddk.cpp`, `test_lazy_mm_suite.cpp`, and `test_loader_pipeline.cpp` snapshot `Kernel::MM::pfa_free_pages_count()` before and after instantiation/teardown (including OOM rollback paths) and assert exact frame conservation.

### Why & References
* Catching memory-safety, UB, and refcount bugs under ASan/UBSan on the host gives fast feedback before booting QEMU, while `pfa_free_pages_count()` invariants ensure zero physical page leaks across CoW, demand paging, and driver lifecycles.
* [AddressSanitizer (Clang Documentation)](https://clang.llvm.org/docs/AddressSanitizer.html)
* [UndefinedBehaviorSanitizer (Clang Documentation)](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html)
* [gcovr User Guide](https://gcovr.com/en/stable/)
* [Linux Kernel Memory Management — Page Reference Counting (`get_page` / `put_page`)](https://docs.kernel.org/core-api/mm-api.html)

---

## 5. Observability: Structured Forensic Logging Decoupled from Console UX

### How Milo Uses It
* **Decoupled console vs. capture thresholds (`kernel/core/log.{hpp,cpp}`):** `Kernel::Log::set_level()` controls what prints to the UART console (kept quiet at `Warn` during boot and `Off` + muted console during compact `TestSession` dot-progress runs), while `set_capture_level()` (default `Level::Trace`) continuously records every event—including `seq`, monotonic `ts_ns`, `level`, `tag`, and `msg`—into an `IrqGuard`-protected 512-entry ring buffer.
* **Standard machine-readable export (`kernel/shell/shell.cpp`, `kernel/fs/devfs/devfs.cpp`):** Operators and test scripts can inspect captured logs on demand via `logs` / `dmesg` (`--json`, `--tail N`, `--level L`) or read `/dev/kmsg` from EL0 userspace as **JSON Lines (`.jsonl`)** without cluttering interactive console output.

### Why & References
* Keeps interactive boot and `test all` output concise (`.` for passes, detailed diagnostics only on failures) while preserving full forensic traces for post-mortem debugging and CI log parsing.
* [JSON Lines (NDJSON) Format Specification](https://jsonlines.org/)
* [Linux Kernel `/dev/kmsg` Ring Buffer Interface](https://www.kernel.org/doc/Documentation/ABI/testing/dev-kmsg)

---

## 6. Automated Quality Gates & Repository Hygiene

### How Milo Uses It
* **Unified `make quality` gate (`Makefile`, `scripts/`):** Runs four automated checks before commits:
1. `format-check` (`clang-format --dry-run --Werror`)
2. `license-check` (`scripts/check_license_headers.py --check` enforcing `SPDX-License-Identifier: GPL-3.0-only`)
3. `lint-report` (`clang-tidy` across `compile_commands.json` generated by `scripts/generate_compile_commands.py`)
4. `test-host` (`snitch` ASan/UBSan suite + `gcovr` coverage reports)
* **Commit enforcement (`.githooks/pre-commit`, `Makefile`):** `make commit` runs `quality` and sets `MILO_MAKE_COMMIT=1`, preventing unformatted, unlicensed, or failing code from being committed. Commit titles follow Conventional Commits (`feat(...)`, `fix(...)`, `test(...)`, `docs(...)`).

### Why & References
* Automating formatting, static analysis, licensing, and sanitizer checks locally prevents regressions from reaching CI.
* [Clang-Tidy Documentation](https://clang.llvm.org/extra/clang-tidy/)
* [SPDX License Identifiers](https://spdx.dev/learn/handling-license-info/)
* [Conventional Commits Specification](https://www.conventionalcommits.org/)
Loading