Switch to CoercePointee macro, with examples by dingxiangfei2009 · Pull Request #1130 · Rust-for-Linux/linux (original) (raw)
Target audience: first timers to build kernel with Rust support
This patch demonstrates the new capability from the current Rust Nightly, which now supports the #[derive(CoercePointee)]
macro to derive the key trait implementations, in place of use of unstable language features such as Unsize
and DispatchFromDyn
.
An illustrative example is attached for more details in the Rust sample kernel module.
How to test this
As usual, you shall follow the guide to set up the toolchain: https://docs.kernel.org/rust/quick-start.html. This demonstration can be executed through virtualization. In this case, during configuration through make LLVM=1 menuconfig, be sure to select Enable Paravirtualization code and KVM Guest support under Processor type and features/Linux guest support; also select Printing Macros as modularised under Kernel hacking/Sample kernel code/Rust samples. Initiate build with make LLVM=1 optionally with -j for parallelism.
Meanwhile, you will need busybox from https://www.busybox.net/downloads/binaries/1.35.0-x86_64-linux-musl/busybox. I am running a x86_64 box, so the demo uses qemu-system-x86_64 as the emulator. I will use the usr/gen_init_cpio script for generating the initramfs image initram.img. Here is the description I used.
dir /bin 0755 0 0
dir /sys 0755 0 0
dir /dev 0755 0 0
file /bin/busybox <path to busybox> 0755 0 0
slink /bin/sh /bin/busybox 0755 0 0
slink /bin/mount /bin/busybox 0755 0 0
slink /bin/insmod /bin/busybox 0755 0 0
slink /bin/rmmod /bin/busybox 0755 0 0
slink /bin/cut /bin/busybox 0755 0 0
slink /bin/cat /bin/busybox 0755 0 0
slink /bin/cd /bin/busybox 0755 0 0
slink /bin/ls /bin/busybox 0755 0 0
file /init init 0755 0 0
file /rust_print.ko <path to linux>/linux/samples/rust/rust_print.ko 0755 0 0
I used this command to launch the emulation and it dropped to a shell.
qemu-system-x86_64 \
-kernel arch/x86_64/boot/bzImage \
-initrd <path to initram.img> \
-M pc \
-m 4G \
-cpu Cascadelake-Server \
-smp 4 \
-nographic \
-vga none \
-no-reboot \
-accel kvm \
-append 'console=ttyS0'
In the shell I executed insmod rust_print.ko
.
What would you see
Upon successful launch, a quick insmod rust_print.ko
will generate some kernel log. You may watch out for the following log stanza, especially the lines containing the text Arc<dyn Display>
.
...
[ 36.255440] rust_print: "hello, world"
[ 36.255627] rust_print: [samples/rust/rust_print.rs:35:5] c = "hello, world"
[ 36.256245] rust_print: Arc<dyn Display> says 42
[ 36.256267] rust_print: Arc<dyn Display> says hello, world
[ 36.256579] rust_print: "hello, world"
...
TODO(@wieDasDing): work on the patch epilogue a bit more