Module 10 · Lesson 15 of 112

Testing a kernel on the host

Run kernel logic as Rust unit tests on Ubuntu and identify which behaviors require a booted kernel.

  • Beginner to advanced
  • 8 min read
  • 16 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, with Cargo and a Rust toolchain that can build for the Ubuntu host.

Your place in the module
By the end you can 4 objectives
  • Explain why Cargo's default test harness cannot run on a bare-metal kernel target.
  • Place reusable kernel logic in a no_std library with a cfg(test) module.
  • Run library unit tests explicitly for the Ubuntu host target.
  • Distinguish host logic tests from tests that require a booted kernel.
Video coming soonTesting a kernel on the host
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from A leveled log facade
  • The log crate supplies leveled macros, and the registered logger supplies output and target policy.
  • A target defaults to the caller's module path and can be overridden with an explicit string.
  • The macros apply the compile-time and global runtime maxima before dispatching a record.
01

Why the default harness needs an operating system

3 min read

The last lesson built print! and a log facade. Now you build the harness that keeps that code correct as it grows, starting with cfg(test) crates that run pure logic on the host.

Suppose the kernel accepts a line that contains a decimal number. An empty line should be rejected, and so should a number that exceeds the destination type. Both cases can be checked before the kernel boots. The parser needs a byte slice and a rule for interpreting it. A test that verifies how bytes reach the parser from a device has a different requirement. It needs the code that receives those bytes to run in its intended environment.

With the default Rust test harness, cargo test asks the compiler to build a test executable for the selected target. The supplies the executable's entry point. On Ubuntu this is an ordinary user-space program. Linux loads the executable into a process, as described in execve(2). The process can terminate with an exit status that a waiting parent can inspect, as described in wait(2). Cargo uses the test executable's status to determine whether it succeeded.

Target selection matters even when you type the command in an Ubuntu terminal. If your kernel project's Cargo configuration selects riscv64gc-unknown-none-elf, Cargo will try to build the default harness for that bare-metal target. The harness expects a target with OS and standard library support. The operating system it would need does not exist underneath your kernel. The bare-metal target does not provide the standard libtest harness, so this can fail at build time before Cargo has an executable to run. The fact that Ubuntu is running Cargo says where the build command runs. The target says where the resulting executable is meant to run.

Three ways to test kernel codeHost unittestQEMUexit-codetestIn-kernelrunnerExecutionenvironmentUbuntuprocessBooted QEMUguestBooted kernelWhat runsLibrary testfunctionsGuest testimageKernel testfunctionsResult observedHost harnessresultEmulator exitstatusKernel testresult
Choose the test environment according to what the assertion needs to observe

There are three options in this module. Host-side unit tests run selected Rust logic against inputs you supply in an Ubuntu process. QEMU exit-code tests boot an image in QEMU and check the emulator process's exit status for the expected result. A custom in-kernel test runner calls test functions after the kernel boots, using the facilities the kernel provides. The last two can work together. The runner determines what succeeded inside the guest, and the emulator's process status lets an outside script observe the result.

For the decimal parser, the input b"7x" and the expected error are enough to state the test. For a boot check, reaching a particular point after startup is itself the behavior under test. Use the host when you can state the rule in terms of ordinary Rust values. Use a booted guest when the assertion depends on what the kernel does in its target environment.

02

Build the same library logic for the host

4 min read

Put logic you can call with ordinary Rust values in a library target. The kernel can call that library in its bare-metal build. Cargo can also compile the library as an Ubuntu unit-test executable. For an isolated example, run these commands on Ubuntu in a directory where you want to create the package.

bash
cargo new --lib kernel-logic
cd kernel-logic

Replace src/lib.rs with the following code. The parser accepts one or more ASCII decimal digits and returns a u8 when the value fits. Each digit updates the accumulated value by multiplying by ten and adding the digit. The checked operations return None if either operation would exceed the range.

rust
#![no_std]

#[cfg(test)]
extern crate std;

pub fn parse_decimal(bytes: &[u8]) -> Option<u8> {
    if bytes.is_empty() {
        return None;
    }

    let mut value = 0u8;
    for &byte in bytes {
        if !byte.is_ascii_digit() {
            return None;
        }
        value = value.checked_mul(10)?.checked_add(byte - b'0')?;
    }
    Some(value)
}

#[cfg(test)]
mod tests {
    use super::parse_decimal;

    #[test]
    fn accepts_the_maximum() {
        let input = std::format!("{}", u8::MAX);
        assert_eq!(parse_decimal(input.as_bytes()), Some(u8::MAX));
    }

    #[test]
    fn rejects_overflow() {
        assert_eq!(parse_decimal(b"256"), None);
    }

    #[test]
    fn rejects_empty_and_non_digit_input() {
        assert_eq!(parse_decimal(b""), None);
        assert_eq!(parse_decimal(b"7x"), None);
    }
}

#![no_std] applies to the library in both builds. The library retains the core prelude, and #[cfg(test)] extern crate std; explicitly makes std available during unit testing. Only the test uses std::format! to create an owned input string. parse_decimal sees a borrowed slice in both builds. When Cargo compiles the library as an ordinary dependency of the kernel, the cfg(test) import and module are omitted. The parser's source stays the same. Keep cfg(test) on the fixtures and test functions so the assertions exercise the implementation the kernel actually uses.

Two builds of the same library sourceUbuntuunit-testbuildBare-metalkernel buildShared codeSame parserSame parserLibraryattributeno_stdno_stdConditional stdimportIncludedOmittedTest moduleIncludedOmitted
The parser is compiled for both environments, with the test module included only in the host unit-test build shown here

Run the unit tests with the host target selected explicitly.

bash
host_target="$(rustc -vV | sed -n 's/^host: //p')"
cargo test --lib --target "$host_target"

rustc -vV reports the compiler's host triple on its host: line. Using that value avoids assuming Ubuntu is running on a particular CPU architecture. --target overrides a default compilation target configured for the kernel. --lib selects the package's library target, which keeps Cargo from trying to build and run the kernel binary as a test executable when both targets live in the same package. In a project with several packages, run the command from the logic library's package directory or select that package by name using -p.

This is the real result on Ubuntu 24.04 (Rust 1.100.1, x86_64-unknown-linux-gnu):

text
$ cargo test --lib --target "$host_target"
running 3 tests
test tests::rejects_empty_and_non_digit_input ... ok
test tests::rejects_overflow ... ok
test tests::accepts_the_maximum ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

The test order can differ between runs. Now the same package with --target riscv64gc-unknown-none-elf, or with that target set as the default in .cargo/config.toml and a plain cargo test:

text
error[E0463]: can't find crate for `test`
  --> src/lib.rs:37:5
   |
36 |       #[test]
   |       ------- in this attribute macro expansion
...
error: could not compile `kernel-logic` (lib test) due to 5 previous errors

The error comes from the bare-metal target not shipping the test crate, so the harness cannot even be compiled. The plain cargo check --lib --target riscv64gc-unknown-none-elf still succeeded, because the library itself needs no harness.

A successful run here should discover the three annotated test functions. The last function contains two assertions, but it is still one test. If the compiler reports that it cannot find the standard test crate, check the selected target. If Cargo reports that there is no library target, check the package you selected and where its library source is defined. These failures happen before an assertion can evaluate the parser. You can also run cargo check --lib --target "$host_target" to check the ordinary library build on Ubuntu with the test-only import and module omitted. A successful host check gives you evidence about that build. The kernel build still needs to compile the library for its own target.

03

Decide what a passing host test proves

2 min read

The parser tests define three kinds of evidence. The maximum test checks that a valid boundary value remains accepted. The overflow test checks the first decimal value above it. The empty and non-digit tests check two distinct ways the input can violate the format. A suite that only checks b"42" can pass even if the parser accepts an empty slice as zero or silently skips a trailing letter. Choose cases that would fail for a plausible mistake in the implementation.

The same approach works for collections and allocator logic. For a fixed-capacity queue, supply ordinary values and assert that a pop returns them in insertion order. Use a full queue to check what happens when there is no room, and check that the entries already present can still be read afterward. For allocator logic, test the calculation that takes a numeric range, size and alignment and returns a candidate offset. A range of twelve bytes with the current offset at three can fit four bytes aligned to four. The candidate starts at offset four. A request for four bytes starting from offset nine in that same range needs to start at offset twelve after alignment, so it cannot fit. The host process can check both outcomes using integers, without treating those values as physical addresses.

Diagram in production
A host assertion checks the rule using supplied input, while a target test observes the same component in its booted environment

Keep each assertion focused on the behavior you want to claim. If a test uses a host Vec to prepare bytes for a parser, the vector is a fixture. Its successful allocation says the Ubuntu process could allocate memory for that fixture. It supplies no evidence about the kernel heap. Likewise, a correct offset shows that the allocation calculation obeys the rule for those inputs. To test whether the kernel can access the region it hands out, the kernel must run with its target memory setup.

When a host test fails, inspect the input, the expected value and the actual value first. If an overflow assertion fails with an input of b"256", you can reproduce that failure with the same bytes and the same library on Ubuntu. When the host tests pass but a booted kernel rejects valid input, check what bytes actually arrived at the parser and whether the caller handled the return value correctly. The two tests answer different questions, and keeping the parser callable on its own gives you a direct way to narrow down where the behavior changes.

Before choosing where to put a test, state the observation you need in one sentence. “The parser rejects a decimal value above u8::MAX” can be observed by calling a function. “The kernel receives bytes and processes them after boot” depends on the guest. The next lesson, A custom in-kernel test runner, answers how to run test functions when the state they need exists only inside the booted kernel.

Key takeaways

  • Cargo's default Rust test harness expects a target with standard library support.
  • A no_std library can import std under cfg(test) for host test fixtures.
  • The host harness tests the same parser implementation that the kernel can call.
  • A host test can check logic while boot, device access and kernel runtime behavior require a target test.
Reflect
  1. Explain to a colleague, in two sentences: explain why Cargo's default test harness cannot run on a bare-metal kernel target.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close