cscscscs

記録用

Linux-kernel 4.15.0-42-generic (Ubuntu 18.04)環境でのデバイスドライバーのコンパイル

つまづきポイントを列挙します。

やり方

Makefile:

obj-m := hello.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean

hello.c

#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");

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);

を同じフォルダにいれて、makeする。

つまづきポイント一覧

・error: code model kernel does not support PIC mode

/lib/modules/$(shell uname -r)/build のMakefileに以下のリンクのパッチを当てる。(一応バックアップはしてね)
[xenial/master-next 1/1] UBUNTU: SAUCE: (no-up) disable -pie when gcc has it enabled by default

未経験の人向けに説明すると。
Makefile.patch

 Makefile | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/Makefile b/Makefile
index dda982c..f96b174 100644
--- a/Makefile
+++ b/Makefile
@@ -608,6 +608,12 @@ endif # $(dot-config)
 # Defaults to vmlinux, but the arch makefile usually adds further targets
 all: vmlinux
 
+# force no-pie for distro compilers that enable pie by default
+KBUILD_CFLAGS += $(call cc-option, -fno-pie)
+KBUILD_CFLAGS += $(call cc-option, -no-pie)
+KBUILD_AFLAGS += $(call cc-option, -fno-pie)
+KBUILD_CPPFLAGS += $(call cc-option, -fno-pie)
+
 # The arch Makefile can set ARCH_{CPP,A,C}FLAGS to override the default
 # values of the respective KBUILD_* variables
 ARCH_CPPFLAGS :=

をさっきのMakefileと同じフォルダに入れて、

$ patch < Makefile.patch

する。

Makefile:4: *** missing separator. Stop.

Makefileのタブでなければいけないところが半角スペースになっている。特にVScode userは気をつけてください。

・なんかよくわからないが動かない

Makefileとhello.cを置いているフォルダにある.cache.mk というファイルが悪さをしている可能性がある。make cleanしろ

これのおかげで見えてるファイルにdiffがないのに片方は動いて片方は動かないという最悪のつまりポイントが生成される。
satoru-takeuchi.hatenablog.com