Android中kernel核心模組編譯執行

2021-08-15 17:17:31 字數 2830 閱讀 5858

author: geneblue

核心驅動是漏洞的高發區,了解android驅動**的編寫是分析、利用驅動漏洞的基礎。本文以乙個「hello」驅動為例,簡單介紹核心驅動編寫、編譯的基本過程,包括核心模組的內建編譯和動態載入方式的編譯。

在./goldsifh/drivers資料夾下新建hello目錄,在hello目錄中新建hello.c檔案:

#include #include #include #include module_license("gpl");  

module_author("geneblue");

module_description("hello kernel device");

module_version("1.0");

#define cmd_command 0x1336

long hello_ioctl(struct file *filp, //ioctl函式

unsigned int cmd,

unsigned long arg)

return 0;

} struct file_operations hello_fops = ;

static struct miscdevice hello_device = ;

static int __init hello_begin(void)

static void __exit hello_exit(void)

module_init(hello_begin); //模組初始化函式

module_exit(hello_exit); //模組解除安裝函式

寫驅動模組時都要包含module.h標頭檔案,該標頭檔案定義了一些編寫模組時常用巨集或函式;kernel.h提供常用的核心函式,如printk();fs.h提供檔案表和檔案結構,如file_operations;miscdevice.h提供註冊為misc裝置的常用函式。

在hello目錄中要增加makefile配置檔案用於編譯。在makefile中新增:

obj-y +=  hello.o
表示內建編譯,即直接編譯到核心檔案zimage中。然後在goldfish/drivers/makefile中包含新建的驅動裝置

obj-y += hello/
這樣,再次編譯核心後,驅動裝置即可包含在核心中。

有的時候,我們需要在手機中編寫可動態載入的驅動模組,可動態載入模組非常便於除錯,在kmsg中可直接看到除錯資訊,這個時候需要重新編譯手機核心,開啟核心的動態載入屬性。在編譯的核心的時候,使用

make menuconfig
命令,並在menuconfig中做如下配置:

如果不開啟該選項就直接insmod載入hello.ko,一般情況下都會報如下錯誤:

insmod: init_module 'hello.ko' failed (function not implemented)
編譯完核心之後,還需要將核心拷貝到aosp的原始碼中,替換掉預設的核心檔案,在我的android原始碼中預設的核心檔案存放在如下路徑中:

/android-4.4.4_r1/device/lge/hammerhead-kernel/zimage-dtb
編譯android原始碼生成新的boot.img檔案,然後只將boot.img刷入到手機即可。

完成核心的準備工作之後,下面就要編譯動態載入模組hello.ko,依然是上述的hello.c檔案,在任意位置建乙個目錄,拷貝hello.c並編寫makefile如下:

obj-m := hello.o  

kerneldir := /home/geneblue/android/source/kernel/msm/

pwd :=$(shell pwd)

arch=arm

cross_compile=/home/geneblue/android/source/tsinghua_aosp/android-4.4.4_r1/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.6/bin/arm-linux-androideabi-

cc=$(cross_compile)gcc

ld=$(cross_compile)ld

cflags_module=-fno-pic

modules:

make -c $(kerneldir) arch=$(arch) cross_compile=$(cross_compile) m=$(pwd) modules

clean:

rm *.o *.ko *.mod.c *.order *.symvers

注意,makefile中要加上cflags_module=-fno-pic選項,不然編譯好的hello.ko relocation節會錯誤:

insmod: init_module 'hello.ko' failed (exec format error)  

kmsg:

<3>[ 1646.589131] hello: unknown relocation: 27

最後,使用make命令即可編譯正確的hello.ko檔案。

使用模擬器來載入新編好的核心,並在adb shell中檢視新編的驅動:

這樣,乙個最簡單的裝置驅動已經可以正確執行了。

將hello.ko檔案push的手機中,用insmod來載入即可。

矩陣的核(kernel)與象(image)

本文介紹矩陣論中一對非常重要的概念 核 kernel 與象 image 這部分內容有助於我們從更加深入的層次去審視矩陣與線性變換的關係,對於更進一步地學習和領會泛函分析中的內容也很有幫助。在閱讀本文前,強烈建議讀者了解前文 所介紹的知識。首先,假設有乙個如下所示的 n m 的矩陣,我們其實可以把它看...

git獲取Android最新kernel核心

git clone git kernel git branch a 在我的電腦上面可以看到下面的內容,前面帶星號是當前的分支 android 2.6.36 remotes origin archive android 2.6.32 remotes origin head origin android...

Android 啟動效能優化 kernel篇

題目有點大,其實kernel的啟動效能調整和android基本沒什麼關係,我想應該適用所有使用linux的嵌入式裝置 時間測量 說到效能調整,第一件該幹的的事就是看下時間到底消耗在 俗話說的好 知己知彼,百戰百勝 過度優化,萬惡之首 因此手頭上要有稱心如意的時間測試工具,方法。其實我是不太喜歡工具的...