Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

動手做:編譯一個 hello 內核模組並在模擬器中驗證

編輯:Android 開發教學

模組原始碼

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

static int hello_init(void)
{
    printk(KERN_ALERT "Hello, world\n");
    return 0;
}

static void hello_exit(void)
{
    printk(KERN_ALERT "Goodbye, cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);

Makefile

obj-m := hello.o

all:
        make ARCH=arm EXTRA_CFLAGS="-D_CONFIG_ARM_ -fno-pic" -C $(KDIR) M=$(PWD) modules

clean:
        $(MAKE) -C $(KDIR) M=$(PWD) clean

KDIR 指向內核原始碼路徑,也就是先前編譯 goldfish 內核時用的那個目錄。

編譯

make CROSS_COMPILE=arm-linux-androideabi- KDIR=/opt/hackandroid/goldfish_0228

注意:編譯模組所用的內核樹,必須與模擬器啟動時使用的 zImage 完全同一份、同一組設定,否則會因為 vermagic 不符而拒絕載入。這是自編模組最常踩的坑。

在模擬器中測試

啟動模擬器並指定自編內核:

emulator -avd Android4.2.2 -kernel arch/arm/boot/zImage

推送模組:

testhello$ adb push hello.ko /data/local
60 KB/s (2648 bytes in 0.042s)

載入並觀察:

testhello$ adb shell
root@android:/data/local # ls
hello.ko
root@android:/data/local # insmod hello.ko
root@android:/data/local # dmesg -c
<1>Hello,world
root@android:/data/local # lsmod
hello 702 0 - Live 0x00000000 (PO)

卸載並確認:

root@android:/data/local # rmmod hello
root@android:/data/local # dmesg -c
<1>Goodbye, cruel world
root@android:/data/local # lsmod

dmesg 中先出現 Hello, world、insmod 後 lsmod 能看到 hello、rmmod 後又印出 Goodbye 且 lsmod 清空——整個流程就完成了。

補充一點:emulator 需要以 root 身分執行(加上 -shell 或用 userdebug 版本的系統映像),insmod 才會成功。若遇到 Operation not permitted,先檢查這件事,再回頭懷疑模組本身。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved