Compile Linux out-of-tree Module on NixOS in a Nix shell with an FHS Environment
In an earlier post, I talked about how you can build an out-of-tree Linux kernel module in a Nix derivation, i.e., package it in Nix. However, for quick prototyping, sometimes you want to just enter $ make in your shell, for example to check if everything compiles. Out-of-tree module projects following the recommended guidelines use a Makefile, possibly an additional KBuild file, and of course C source and header files. This header file depends on FHS system state.
To be precisely, the following part found in Makefiles doesn’t work out of the box in NixOS:
modules: $(MAKE) -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) modules
However, if we use a Nix shell that opens an FHS environment with the right packages, we end up in an environment where /lib/modules/... exists. The shell.nix might look like this:
let
pkgs = import <nixpkgs> { };
in
(pkgs.buildFHSEnv {
name = "linux-dev-fhs-env";
targetPkgs = pkgs: with pkgs; [
# Linux source tree/build support.
# TODO: Is this the kernel you are using in your NixOS system?
# Otherwise, there will be a version mismatch when you try to
# `insmod` the module.
pkgs.linux_latest.dev # Notice: ".dev" sub attribute brings the magic.
gcc
gnumake
gnupg # warnings when not present when entering the shell
];
}).envYou should also make sure that you are using the right nixpkgs version bringing the right kernel source/version, if you want to insmod the module into your system, so that there is no version mismatch.
Now you can enter the shell and run $ make! Please note that due to the nature of buildFHSEnv (see manual), the user-experience is different from a regular Nix shell.
0 Comments