Compile Linux out-of-tree Module on NixOS in a Nix shell with an FHS Environment

Published by Philipp Schuster on

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
  ];
}).env

You 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.


Philipp Schuster

Hi, I'm Philipp and interested in Computer Science. I especially like low level development, making ugly things nice, and de-mystify "low level magic".

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *