Example of Dynamic Loadable Kernel Module in Android
@ Aeric | Monday, Nov 16, 2020 | 2 minute read | Update at Monday, Nov 16, 2020

Example of dynamic loadable Kernel module in Android

What is kernel module

  1. Mostly use on driver or hardware related
  2. Different to userspace process
  3. Reducing linux kernel, makes linux more flexible
  4. Customize specific functionally system

kernel module fundamental knowledge

Command

> lsmod                   --> List current kernel module (or $ cat /proc/modules)
> insmod ${XXX.ko}        --> Load XXX.ko
> rmmod ${XXX.ko}         --> Remove XXXX.ko

Coding

  1. Include init and exit func at least
  2. Must #include <linux/module.h>
  3. two type of coding architecture

Using “init_module()” and “cleanup_module()”

Using marco

#include <linux/init.h> for using marco “__init” and “__exit”

Makefile

Example case from tracing Qualcomm build flow:

example from : vendor/qcom/opensource/audio-kernel/asoc/codecs/

Three files related to build flow:

1. Android.mk
2. Kbuild
3. AndroidKernelModule.mk

Step1. Create hello.c

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>

static int __init init_my_module(void)
{
	printk(KERN_INFO "Hello, module!\n");
	return 0;
}

static void __exit exit_my_module(void)
{
	printk(KERN_INFO "Bye, module!\n");
}

module_init(init_my_module);
module_exit(exit_my_module);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("BSP");

  1. Create “Android.mk”
# Android makefile for kernel module

LOCAL_PATH := $(call my-dir)

DLKM_DIR := $(TOP)/device/qcom/common/dlkm

# We are actually building *.ko here
KBUILD_OPTIONS += MODNAME=hello_dlkm

###########################################################
include $(CLEAR_VARS)
LOCAL_MODULE              := hello.ko
LOCAL_MODULE_KBUILD_NAME  := hello.ko
LOCAL_MODULE_PATH         := $(KERNEL_MODULES_OUT)
include $(DLKM_DIR)/AndroidKernelModule.mk
###########################################################

  1. Create Kbuild
obj-m += htc_hello.o
  1. build
//After envsetup and lunch device
make hello.ko
  1. Verify
adb root;
adb push hello.ko /data/
adb shell "insmod /data/hello.ko"

Uart should print

Hello, module!

About Me

Hi, my name is Aeric

This is my blog.