On this page
Kernel Modules and no_std
stddepends on the operating system (threads, file I/O, heap allocation), which bare-metal systems and kernel modules do not have.#![no_std]removesstd, keeping only the OS-independentcorecrate, butalloc(heap allocation) andpanic_handler(what to do on panic) must be provided manually. Rust-for-Linux runs Rust code in the Linux kernel by relying onno_std+ the kernel-providedallocimplementation.
Removing std: The no_std Environment
std depends on the operating system—threads, file I/O, networking, heap allocation—all of which assume the presence of an OS. Bare-metal systems, embedded systems, and kernel modules do not have these. #![no_std] removes std, keeping only the OS-independent core crate:
extern crate alloc; // Optional: include when heap allocation is needed
use PanicInfo;
!
core includes: Option, Result, Iterator, Clone, Copy, and basic macros (format_args!, but you need to provide your own write_str implementation to use format!). The alloc crate becomes available once GlobalAlloc is implemented—providing Box, Vec, String, Rc, Arc, HashMap.
Rust-for-Linux (Linux Kernel)
Linux 6.1+ supports Rust kernel modules. Key abstractions:
use *;
module!
;
// Implement file operations
;
The #[vtable] macro generates code for a C-compatible function pointer table for traits—interfacing with the file_operations struct in the kernel's C code. Rust in the kernel has more restrictions than userspace:
- Custom allocator: You cannot use
#[global_allocator]in the kernel; you must use the kernel's allocator (kmalloc/kfree)—accessible viakernel::alloc. - Custom synchronization primitives:
kernel::sync::Mutexis a Rust wrapper around the kernel mutex (struct mutex), notstd::sync::Mutex. - Custom error types:
kernel::error::Errormaps to Linuxerrno. - Panic = BUG(): The kernel cannot unwind—
panic_handlercallsBUG()(prints stack trace + stops the kernel).
References
- Rust-for-Linux: rust-for-linux.com
- Embedded Rust Book: docs.rust-embedded.org
- Phil Opp's blog: os.phil-opp.com
Keywords: no_std, core, alloc, panic_handler, kernel module, Rust-for-Linux, embedded, BUG