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:
To compile the module, run:
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:
These commands disassemble and display metadata about the object file, including symbols and section headers.
To list symbols in the module:
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:
If the module depends on other modules, ensure they are loaded first. Use the -f flag to force load despite errors:
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:
If the module is in use or has dependencies, use the -f flag to force removal:
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
dmesgto check kernel logs for missing symbols or linking errors. - Dependency issues: Use
modprobeto automatically handle dependencies when loading modules.
Key takeaways¶
- Use
makewith a properMakefileto compile kernel modules. - Inspect object files with
objdump,readelf, ornmfor debugging. - Load modules with
insmodand unload withrmmod, but prefermodprobefor modern workflows. - Always verify dependencies and kernel version compatibility before loading modules.
- Check
dmesgoutput for errors during module loading or unloading.