LoginSignup
5
3

More than 3 years have passed since last update.

WSL2でカーネルのビルドとデバイスドライバの作成

Last updated at Posted at 2020-09-05

Linux実機が手元になかったので(実際にデバイスを制御しない)デバイスドライバ作成のための環境構築をUbuntu20.04 on WSL2上で行った。

  1. システムのカーネルのバージョンの確認する。

    $ uname -r
    4.19.104-microsoft-standard
    
  2. Githubのmicrosoft/WSL2-Linux-Kernelから対応するバージョンのカーネルのソースコードを落とす。

    $ wget https://github.com/microsoft/WSL2-Linux-Kernel/archive/$(uname -r).zip
    $ unzip $(uname -r).zip
    
  3. README-Microsoft.WSL2に従ってカーネルをビルドする。並列コンパイルのためmake -jにしたらメモリが足らなくなったので注意。

    $ sudo install build-essential flex bison libssl-dev libelf-dev
    $ cd path/to/WSL2-Linux-Kernel-$(shell uname -r)
    $ make KCONFIG_CONFIG=Microsoft/config-ws
    
  4. 試しにinsmod/rmmod時にログに出力するだけの簡単なデバイスドライバを作ってみる。デフォルトのログレベルが1 (KERN_ALERT)だったのでここでは0 (KERN_EMERG)でメッセージを出力した。

hello.c
#include <linux/module.h>

static int hello_init(void) {
    printk(KERN_EMERG "hello init\n");

    return 0;
}

static void hello_exit(void) {
    printk(KERN_EMERG "hello exit\n");
}

module_init(hello_init);
module_exit(hello_exit)
Makefile
obj-m := hello.o

all:
    make -C path/to/WSL2-Linux-Kernel-$(shell uname -r) M=$(PWD) modules

clean:
    make -C path/to/WSL2-Linux-Kernel-$(shell uname -r) M=$(PWD) clean
$ make
$ sudo insmod hello.ko
$ sudo rmmod hello
$ dmesg | tail
...
[ 1313.975997] hello init
[ 1320.991808] hello exit
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3