Skip to content

Compilation & Loading

Compilation and Loading

Compiling and loading kernel modules is a foundational skill for Linux sysadmins. This section covers the process of building modules using make, inspecting object files, and dynamically loading/unloading modules with insmod and rmmod.


Compiling Modules with make

Kernel modules are typically built using a Makefile that specifies build rules and dependencies. A minimal Makefile for a module named my_module.ko might look like this:

obj-m += my_module.o

To compile the module, run:

make -C /lib/modules/$(uname -r)/build M=$PWD

This command tells the kernel build system to compile the module in the current directory ($PWD). The output will be a .ko file (e.g., my_module.ko) and a .o object file. The .o file can be inspected further if needed.

Notes:
- Ensure the correct kernel headers are installed (linux-headers-$(uname -r)).
- The make command assumes the kernel source tree is available in /lib/modules/$(uname -r)/build.


Inspecting Object Files

After compilation, you may want to inspect the module’s object file (.o) to analyze its contents. Use tools like objdump or readelf:

objdump -d my_module.o
readelf -a my_module.o

These commands disassemble and display metadata about the object file, including symbols and section headers.

To list symbols in the module:

nm my_module.o

This is useful for verifying exported symbols or debugging linking issues.


Loading Modules with insmod

Use insmod to load a compiled module into the kernel:

sudo insmod my_module.ko

If the module depends on other modules, ensure they are loaded first. Use the -f flag to force load despite errors:

sudo insmod -f my_module.k

Important: insmod is deprecated in favor of modprobe for modern systems. However, it remains useful for legacy or custom modules.


Unloading Modules with rmmod

Unload a module using rmmod:

sudo rmmod my_module

If the module is in use or has dependencies, use the -f flag to force removal:

sudo rmmod -f my_module

Caution: Forcing removal can destabilize the kernel if the module is critical. Always check for dependencies first.


Troubleshooting Tips

  • Version mismatches: Ensure the module is built against the correct kernel version.
  • Symbol errors: Use dmesg to check kernel logs for missing symbols or linking errors.
  • Dependency issues: Use modprobe to automatically handle dependencies when loading modules.

Key takeaways

  • Use make with a proper Makefile to compile kernel modules.
  • Inspect object files with objdump, readelf, or nm for debugging.
  • Load modules with insmod and unload with rmmod, but prefer modprobe for modern workflows.
  • Always verify dependencies and kernel version compatibility before loading modules.
  • Check dmesg output for errors during module loading or unloading.