Try   HackMD

Add System Call to Arm64 Linux kernel with M2 Chip

Environment

  • MBP with M2 chip (2023)
  • MacOS 13.3 (22E252)
  • Vmware with Ubuntu 64bit 22.04.3 arm-64 architecture

Prepare

Download the Linux Kernel Archives (https://www.kernel.org) or using

wget -P ~/ https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.15.137.tar.xz

Get into root mode

sudo su // or sudo -i

Decompress files to /usr/src

tar -xvf linux-5.15.137.tar.xz -C /usr/src

Update apt

sudo apt update && sudo apt upgrade -y

Install package which can help us to build kernel

sudo apt install build-essential libncurses-dev libssl-dev libelf-dev bison flex -y

Install vim

sudo apt install vim -y

Clear package

sudo apt clean && sudo apt autoremove -y

Add system calls hello

Create directory

cd /usr/src/linux-5.15.137
mkdir hello
cd hello

Create hello.c

vim hello.c

Content of hello.c

#include <linux/kernel.h> 
#include <linux/syscalls.h> 

SYSCALL_DEFINE0(hello){ 
	printk("Hello world!\n"); 
	return 0; 
}

Create Makefile under the same dir

vim Makefile

Content of Makefile

obj-y := hello.o

Back to previous dir and open makefile

# 回上個目錄

cd ..

# 打開此目錄下的 Makefile

vim Makefile

Find core-y and append the hello/ into it

core-y := kernel/ certs/ mm/ fs/ ipc/ security/ crypto/ hello/

Add system call to table and note the system call number

- For ARM64 -

/usr/src/linux-5.15.137/include/uapi/asm-generic/unistd.h

// add your syscall
#define __NR_hello 441 
__SYSCALL(__NR_hello, sys_hello)

...

// modify the total number 441 -> 442
#define __NR_syscalls 442 

/arch/arm64/include/asm/unistd.h

#define __NR_compat_syscalls number+1 

Add asmlinkage long sys_hello(void); to syscalls.h

# 把目錄轉回去
cd /usr/src/linux-5.15.137

vim include/linux/syscalls.h

#加入一行(這行直接加在檔案的最下面就好)

註: 在vim編輯檔案的時候 可以按shift+G就會跳到最後一行

asmlinkage long sys_hello(void);

Compile Kernel

make localmodconfig

make localmodconfig

#這邊會跳出一大堆問你要不要裝的套件,全部按enter跳過就好

Check processor number

nproc

用幾核心去編譯

make -j12

如果要重新make,請先使用

make clean
make -j12

Install Kernel

sudo make modules_install -j12
sudo make install -j12

Update boot loader and rboot

sudo update-grub
reboot

Check kernel version

uname -r

Issues

If kernel version doesn't update

vim /etc/default/grub

GRUB_TIMEOUT_STYLE: hidden -> menu
GRUB_TIMEOUT: 0 -> -1

update-grub
reboot

Make Failed > Modify .config

can't read modules.order: No such file or directory
make:*** [Makefile:1544 __modinstpre] Error2 
sudo vim .config

CONFIG_SYSTEM_TRUSTED_KEYS = ""
CONFIG_SYSTEM_REVOCATION_KEYS = ""

Make modules failed > Install dwarves

.tmp_vmlinux.btf: pahole(pahole) is not available
Failed to generate BTF for vmlinux
Try to disable CONFIG_DEBUG_INFO_BTF
make:***[Makefile:1227:vmlinux] Error1
sudo apt-get install dwarves

Ref