Skip to main content

TECH VEDA

Corporate on-site training - Submit proposal Pick your modulesSharpen your kernel skills: deep dives, drivers, Yocto, CVEs, careers — updated daily. Read the blog →
Tutorials

Rust for Linux: A Beginner’s Guide — Part 2: Rust Module Cleanup Without an Exit Function

The module! macro generates cleanup_module for you and it only drops your struct. Where Rust module cleanup runs on a real Linux 7.3 build, measured.

Rust for Linux: A Beginner’s Guide — Part 2: Rust Module Cleanup Without an Exit Function

The module! macro writes both C entry points itself, init_module and cleanup_module, and the exit path it generates does exactly one thing: it drops your module struct. That is why there is no exit function to write in a Rust kernel module, and why Rust module cleanup belongs in an impl Drop. This part prints the code the macro generates on a Linux 7.3 tree and measures what deleting the Drop implementation removes.

This series builds one Rust kernel module and returns to the same file each part. Part 1, Your First Rust Kernel Module, configured a Linux 7.3 tree with CONFIG_RUST=y and produced a real rust_minimal.ko of 18,992 bytes. This part opens the macro that produced it: you will print the code it generates, find the two C entry points inside, and see where Rust module cleanup runs now that there is no exit function to declare. Every command and output block below was run on a real 7.3 build.

What you need before you start

The tree from Part 1, already built once. Starting fresh you need a Linux 7.3 tree, rustc 1.85.0 or newer, bindgen 0.71.1 or newer, Clang 17.0.1 or newer, and make LLVM=1 rustavailable printing Rust is available! before you configure anything. This run used rustc 1.97.0, Clang 18.1.3 and bindgen 0.71.1 on x86_64.

Three symbols matter in .config: CONFIG_RUST=y, CONFIG_SAMPLES_RUST=y and CONFIG_SAMPLE_RUST_MINIMAL=m. The sample must be a module, not built in, because half of what follows is about that difference. All commands run from the top of the tree.

Printing the code that module! generates

module! is a procedural macro, not a text template you can read off a header, so its expansion is the only honest way to see what it produces. rustc prints it with -Zunpretty=expanded, a nightly option that RUSTC_BOOTSTRAP=1 lets a stable compiler accept. It only succeeds with the exact flag set Kbuild passes, so capture the real command line and edit it.

raghu@techveda.org:~$ cd ~/linux-7.3
raghu@techveda.org:~$ touch samples/rust/rust_minimal.rs
raghu@techveda.org:~$ make LLVM=1 samples/rust/rust_minimal.o V=1 | grep ' rustc ' > /tmp/rustc.cmd
raghu@techveda.org:~$ sed -e 's|; \./tools/objtool.*||' -e 's|--emit=obj=[^ ]* |-Zunpretty=expanded |' -e 's|--emit=dep-info=[^ ]* ||' /tmp/rustc.cmd > /tmp/expand.cmd
raghu@techveda.org:~$ RUSTC_BOOTSTRAP=1 sh /tmp/expand.cmd > /tmp/expanded.rs
raghu@techveda.org:~$ wc -l /tmp/expanded.rs
232 /tmp/expanded.rs

The touch forces a rebuild, because make prints nothing for an object already up to date. The first sed removes the objtool invocation Kbuild appends after a semicolon on the same line; leave it in and the shell runs objtool against an object that was never written. One flag on the captured line decides most of what follows:

raghu@techveda.org:~$ grep -o -- '--cfg MODULE' /tmp/rustc.cmd
--cfg MODULE

Kbuild adds it from KBUILD_RUSTFLAGS_MODULE := --cfg MODULE at line 627 of the top-level Makefile, applied by modkern_rustflags in scripts/Makefile.lib to anything built as a module rather than into vmlinux.

The two C entry points the macro writes for you

In /tmp/expanded.rs, find the doubly nested mod __module_init. Everything to do with Rust module cleanup is inside it, and the nesting makes all of it unreachable from your code.

mod __module_init {
    mod __module_init {
        use pin_init::PinInit;
        #[used(compiler)]
        static __IS_RUST_MODULE: () = ();
        static mut __MOD: ::core::mem::MaybeUninit<super::super::LocalModule>
            =
            ::core::mem::MaybeUninit::uninit();
        #[no_mangle]
        #[link_section = ".init.text"]
        pub unsafe extern "C" fn init_module() -> ::kernel::ffi::c_int {
            unsafe { __init() }
        }
        #[used(compiler)]
        #[link_section = ".init.data"]
        static __UNIQUE_ID___addressable_init_module:
            unsafe extern "C" fn() -> i32 =
            init_module;
        #[no_mangle]
        #[link_section = ".exit.text"]
        pub extern "C" fn cleanup_module() { unsafe { __exit() } }

Those two #[no_mangle] functions are the whole interface to the loader, and the second is where Rust module cleanup ends up. Confirm they reached the module:

raghu@techveda.org:~$ make LLVM=1 -j2 modules
  RUSTC [M] samples/rust/rust_minimal.o
  MODPOST Module.symvers
  LD [M]  samples/rust/rust_minimal.ko
raghu@techveda.org:~$ nm samples/rust/rust_minimal.ko | grep -E ' T (init_module|cleanup_module)$'
0000000000000010 T cleanup_module
0000000000000010 T init_module

In include/linux/module.h, module_init() and module_exit() do nothing but alias those same two names onto functions you wrote:

/* Each module must use one module_init(). */
#define module_init(initfn)					\
	static inline initcall_t __maybe_unused __inittest(void)		\
	{ return initfn; }					\
	int init_module(void) __copy(initfn)			\
		__attribute__((alias(#initfn)));		\
	___ADDRESSABLE(init_module, __initdata);

/* This is only required if you want to be unloadable. */
#define module_exit(exitfn)					\
	static inline exitcall_t __maybe_unused __exittest(void)		\
	{ return exitfn; }					\
	void cleanup_module(void) __copy(exitfn)		\
		__attribute__((alias(#exitfn)));

So the macro is not replacing the loading contract, it is satisfying it. Those are still the only two names the loader resolves. The difference is who writes them: in C you write the bodies and the macros alias the names; here the macro writes the bodies too.

Why Rust module cleanup needs no exit function

Follow cleanup_module inward. It calls __exit(), one line long:

raghu@techveda.org:~$ grep -n 'assume_init_drop' /tmp/expanded.rs
89:        unsafe fn __exit() { unsafe { __MOD.assume_init_drop(); } }

__MOD is the single static the macro declares to hold your module: static mut __MOD: MaybeUninit<LocalModule>. __init() writes your struct into it and __exit() drops it. There is no hook in between, which is why the trait you implement has one method. Its definition in rust/kernel/module.rs says so:

/// The entrypoint to implementing a kernel module.
///
/// For any teardown or cleanup operations, your type may implement [`Drop`].
pub trait Module: Sized + Sync + Send {
    /// Called at module initialization time.
    ///
    /// Use this method to perform whatever setup or registration your module
    /// should do.
    ///
    /// Equivalent to the `module_init` macro in the C API.
    fn init(module: &'static ThisModule) -> crate::error::Result<Self>;
}

That sentence is the design. Rust module cleanup is not a function you register; it is the destructor of the value you returned from init, so a registration held as an owned value deregisters itself.

This is the largest conceptual break from C. A C exit function is a list of calls you keep in step with the init function by hand, and the classic bug is an init path extended while the exit path was not. Here the exit path is generated once and never edited, and teardown order comes from the struct, because Rust drops a struct’s fields in declaration order. Reordering your fields reorders your teardown.

Deleting the Drop implementation and measuring .exit.text

That claim is testable. Back the sample up, note the section sizes, delete Drop and rebuild.

raghu@techveda.org:~$ cp samples/rust/rust_minimal.rs /tmp/rust_minimal.rs.bak
raghu@techveda.org:~$ size -A samples/rust/rust_minimal.o | grep -E '^\.(init|exit)\.text'
.exit.text                      170      0
.init.text                      100      0
raghu@techveda.org:~$ sed -i '/^impl Drop for RustMinimal/,$d' samples/rust/rust_minimal.rs
raghu@techveda.org:~$ make LLVM=1 samples/rust/rust_minimal.o
error: field `numbers` is never read
  --> samples/rust/rust_minimal.rs:26:5
   = note: `-D dead-code` implied by `-D warnings`
   = help: to override `-D warnings` add `#[expect(dead_code)]` or `#[allow(dead_code)]`
error: aborting due to 1 previous error

The error is the point: Drop was the only code reading numbers, and the kernel builds Rust with -D warnings. Silence it and rebuild:

raghu@techveda.org:~$ sed -i 's/^struct RustMinimal {/#[allow(dead_code)]\nstruct RustMinimal {/' samples/rust/rust_minimal.rs
raghu@techveda.org:~$ make LLVM=1 samples/rust/rust_minimal.o
  RUSTC [M] samples/rust/rust_minimal.o
raghu@techveda.org:~$ size -A samples/rust/rust_minimal.o | grep -E '^\.(init|exit)\.text'
.exit.text                       59      0
.init.text                      100      0
raghu@techveda.org:~$ nm samples/rust/rust_minimal.o | grep ' T ' | grep -v __pfx
0000000000000110 T _RNvXCsGeobxOAh4V_12rust_minimalNtB2_11RustMinimalNtNtCs3R38tTcvFoT_6kernel6module6Module4init
0000000000000010 T cleanup_module
0000000000000010 T init_module

The Rust module cleanup body fell from 170 bytes of .exit.text to 59, the mangled Drop::drop symbol is gone, and cleanup_module is still there, still global, still exported to the loader. The exit symbol is not optional; only its contents are, so Rust module cleanup is the half you control. Restore the sample:

raghu@techveda.org:~$ cp /tmp/rust_minimal.rs.bak samples/rust/rust_minimal.rs
raghu@techveda.org:~$ make LLVM=1 -j2 modules
  RUSTC [M] samples/rust/rust_minimal.o
  MODPOST Module.symvers
  LD [M]  samples/rust/rust_minimal.ko

What the C side receives when init returns an error

The init half of the generated code is where the Result you return becomes something the loader understands:

        unsafe fn __init() -> ::kernel::ffi::c_int {
            let initer =
                <super::super::LocalModule as
                        ::kernel::InPlaceModule>::init(::kernel::module::this_module::<super::super::LocalModule>());
            match unsafe {
                    ::pin_init::raw_try_init(__MOD.as_mut_ptr(), initer)
                } {
                Ok(m) => 0,
                Err(e) => e.to_errno(),
            }
        }

to_errno() in rust/kernel/error.rs returns the stored value unchanged, and the error constants are declared negative through the declare_err! macro. A failing numbers.push(72, GFP_KERNEL)? gives an AllocError, which converts to code::ENOMEM, which is -12, which init_module returns directly.

One consequence is where Rust module cleanup does not help you. The macro documents __exit as only ever called after init_module has returned 0, so if init returns Err, __MOD was never initialised and your Drop never runs. The ? operator still releases values the function already owns, because they are dropped as the stack unwinds, but it does nothing for a raw registration made through a C binding that you have not wrapped in an owning type.

The same source compiled as built-in

Remove --cfg MODULE from the captured command and the same source expands into something else. Nothing else changes, so the diff is a clean before and after:

raghu@techveda.org:~$ sed 's| --cfg MODULE | |' /tmp/expand.cmd > /tmp/expand-builtin.cmd
raghu@techveda.org:~$ RUSTC_BOOTSTRAP=1 sh /tmp/expand-builtin.cmd > /tmp/builtin.rs
raghu@techveda.org:~$ diff /tmp/expanded.rs /tmp/builtin.rs | grep -E 'init_module|cleanup_module|initcall|null_mut'
<             unsafe { ::kernel::ThisModule::from_ptr(__this_module.get()) }
>         unsafe { ::kernel::ThisModule::from_ptr(::core::ptr::null_mut()) };
>         global_asm! (".section \".initcall6.init\", \"a\"\n        __rust_minimal_initcall:\n            .long   __rust_minimal_init - .\n            .previous\n        ");
<         pub unsafe extern "C" fn init_module() -> ::kernel::ffi::c_int {
>         pub extern "C" fn __rust_minimal_init() -> ::kernel::ffi::c_int {
<         static __UNIQUE_ID___addressable_init_module:
<             init_module;
<         pub extern "C" fn cleanup_module() { unsafe { __exit() } }
<         static __UNIQUE_ID___addressable_cleanup_module: extern "C" fn() =
<             cleanup_module;
>         pub extern "C" fn __rust_minimal_exit() { unsafe { __exit() } }

There is no init_module and no cleanup_module. In their place are __rust_minimal_init and __rust_minimal_exit, named from the name: key so several built-in modules can coexist, plus a global_asm! block placing a 32-bit relative pointer to the init function in .initcall6.init. THIS_MODULE becomes a null pointer, because a built-in module has no struct module.

Note what is absent from the diff: __exit is identical in both expansions, so the Rust module cleanup code is unchanged. __rust_minimal_exit is generated, but nothing points at it and a built-in module cannot be unloaded, matching the C header’s note that module_exit() has no effect when the driver is statically compiled. The sample’s own !cfg!(MODULE) is folded by the compiler, to !true here and !false there.

Module parameters, and the kernel versions that have them

The params: block is the last thing the macro turns into code. Each entry produces two .modinfo strings and one kernel_param struct in the __param section:

            static __rust_minimal_test_parameter_struct:
                ::kernel::module_param::KernelParam =
                ::kernel::module_param::KernelParam::new(::kernel::bindings::kernel_param {
                        name: kernel::str::as_char_ptr_in_const_context(if true {
                                c"test_parameter"
                            } else { c"rust_minimal.test_parameter" }),
                        mod_: unsafe {
                            core::ptr::from_ref(&::kernel::bindings::__this_module).cast_mut()
                        },
                        ops: core::ptr::from_ref(&::kernel::module_param::PARAM_OPS_I64),
                        perm: 0,
                        level: -1,
                        flags: 0,

perm: 0 arrives with the macro’s own comment, “Will not appear in sysfs”, and no key overrides it, so a Rust module parameter is settable at load time and not readable under /sys/module/. The name is bare for a module and rust_minimal.test_parameter for a built-in. Supported types are the signed and unsigned integers, isize, usize and bool.

raghu@techveda.org:~$ size -A samples/rust/rust_minimal.ko | grep __param
__param                          80      0
raghu@techveda.org:~$ modinfo samples/rust/rust_minimal.ko | grep parm
parm:           test_bool_parameter:This boolean parameter defaults to false (bool)
parm:           test_parameter:This parameter has a default of 1 (i64)

Eighty bytes for two parameters, forty each. Availability is narrow: params: exists only at 7.3. rust/macros/module.rs at v6.18 has no parameter handling at all, and the v6.12 and v6.18 samples carry no params: block.

What changes on the 6.12 LTS kernel

Four differences, each confirmed by fetching the file at the tag rather than inferred. The metadata key is singular, author: "Rust for Linux Contributors", which became authors: ["Rust for Linux Contributors"] at 6.18. The sample’s vector type is Vec<i32> with Vec::new(), which became KVec<i32> with KVec::new() at 6.18. There is no params: key. And the exit path is generated differently. This excerpt is the 6.12 macro’s own format! template, so {{ is an escaped brace and {type_} your module type:

                    static mut __MOD: Option<{type_}> = None;
...
                    unsafe fn __exit() {{
                        // SAFETY: No data race, since `__MOD` can only be accessed by this module
                        // and there only `__init` and `__exit` access it. These functions are only
                        // called once and `__init` was already called.
                        unsafe {{
                            // Invokes `drop()` on `__MOD`, which should be used for cleanup.
                            __MOD = None;
                        }}
                    }}

At 6.12 __MOD is an Option and __exit assigns None, which drops the previous value. From 6.18 it is a MaybeUninit and __exit calls assume_init_drop(). The mechanism is the same on both: Rust module cleanup runs through Drop. The macro is also built from format! strings at 6.12 and 6.18 and from syn and quote at 7.3, so the diagnostics below are 7.3 behaviour and should not be expected verbatim on an LTS tree.

Common wrong turns

Each is correct reasoning from an incomplete model of how Rust module cleanup is generated.

Adding an exit method to the trait implementation. The first thing a C programmer tries, and the reasoning is sound as far as it goes: the trait’s own doc comment calls init the equivalent of module_init, which implies a partner. The trait has one method:

error[E0407]: method `exit` is not a member of trait `kernel::Module`
  --> samples/rust/rust_minimal.rs:50:5
error: aborting due to 1 previous error

The incomplete part of the model is that the exit path is generated rather than declared, so there is nothing for a second method to be called from. Porting from 6.12 produces the same shape of message for the singular author key.

Adding an exit: key to the invocation. Attractive for the same reason plus one more: the invocation reads like a table of module properties, so an exit hook looks like one more property. The macro lists every key it accepts, which makes this the most useful message in the set:

error: unknown key "exit". Valid keys are: ["type", "name", "authors", "description", "license", "alias", "firmware", "imports_ns", "params"].
  --> samples/rust/rust_minimal.rs:13:5
error: aborting due to 1 previous error

Reordering the keys. Every other Rust struct literal takes its fields in any order, so there is no reason to expect this one not to. The macro enforces an order, and names only the keys you used rather than all nine:

error: keys are not ordered as expected. Order them like: ["type", "name", "authors", "description", "license", "params"].
error: aborting due to 1 previous error

Expecting a parameter under /sys/module/. C modules usually pass 0644 to module_param(), so the sysfs entry is the habit. The generated struct hardcodes perm: 0 and exposes no override, so the entry never appears and nothing tells you why. A string parameter fails harder: the macro panics with message: Unsupported parameter type String instead of reporting a clean error.

Verification checklist

Run these against an unmodified 7.3 tree with the sample restored. Each checks the generated Rust module cleanup path rather than your reading of it.

raghu@techveda.org:~$ wc -l /tmp/expanded.rs
232 /tmp/expanded.rs
raghu@techveda.org:~$ grep -c 'fn cleanup_module' /tmp/expanded.rs
1
raghu@techveda.org:~$ nm samples/rust/rust_minimal.ko | grep -cE ' T (init_module|cleanup_module)$'
2
raghu@techveda.org:~$ md5sum samples/rust/rust_minimal.ko
95fde8a2c97dad5fa5fdc90518129cee  samples/rust/rust_minimal.ko
  1. wc -l /tmp/expanded.rs prints 232. A much smaller number means the expansion failed.
  2. grep -c 'fn cleanup_module' /tmp/expanded.rs prints 1: the macro generated an exit function you did not write.
  3. grep assume_init_drop /tmp/expanded.rs returns the one-line __exit body.
  4. nm finds exactly two global text symbols named init_module and cleanup_module.
  5. size -A reports .exit.text as 170 bytes with Drop and 59 without.
  6. md5sum on the module matches the value you recorded before the Drop experiment. The hash above is this run’s toolchain; yours will differ.

Key takeaways

  • module! generates both init_module and cleanup_module. Neither is yours to write, and neither is optional.
  • The generated exit function drops one static, so Rust module cleanup lives in impl Drop and teardown order follows field declaration order.
  • Deleting Drop shrinks .exit.text but does not remove cleanup_module.
  • An Err from init becomes a negative errno and skips Drop, so failure paths inside init must clean up themselves.
  • Removing --cfg MODULE turns the expansion into an initcall with a null THIS_MODULE. On 6.12 the Rust module cleanup path is an Option assignment and params: does not exist.

If you are working through this series as preparation for real driver work, our Linux device drivers training covers the C module and driver model these generated entry points are satisfying.

Was this worth your time?

Frequently asked questions

Can a Rust kernel module run cleanup code at unload time without implementing Drop?
Not through the macro. The generated exit function does nothing except drop the module struct, so the only code that runs at unload time is whatever Drop implementations the struct and its fields have.

Does the exit function disappear if I delete the Drop implementation?
No. The cleanup_module symbol is still present and still global; only its body shrinks. On the 7.3 build measured here .exit.text went from 170 bytes to 59.

Will my Drop implementation run if init returns an error?
No. The macro documents the generated exit path as only ever called after init_module has returned zero, so a failed initialisation never reaches Drop. Clean up inside init on the failure path.

Further reading

RB
Raghu Bharadwaj

Founder, TECH VEDA — 20+ years teaching the Linux kernel, device drivers and embedded systems.

Follow on LinkedIn

Get new posts by email

Kernel, embedded Linux and AI-era engineering — a few sharp reads a month. No spam.

We email occasionally and never share your address.