我尝试在汇编程序中编写内核模块。有一段时间我需要全球变革。我在.data(或.bss)部分中定义了一个dword,在init函数中我尝试将1添加到var。我的程序非常有效,但insmod sey me:
$ sudo insmod ./test.ko
insmod: ERROR: could not insert module ./test.ko: Invalid module format
这是我在nasm中的汇编代码:
[bits 64]
global init
global cleanup
extern printk
section .data
init_mess db "Hello!", 10, 0
g_var dd 0
section .text
init:
push rbp
mov rbp, rsp
inc dword [g_var]
mov rdi, init_mess
xor rax, rax
call printk
xor rax, rax
mov rsp, rbp
pop rbp
ret
cleanup:
xor rax, rax
ret
如果我在C代码中写入,那么所有工作都很好:
static i = 0;
static int __init main_init(void) { i++; return init(); }
但是在这个objdump -d test.ko
中为我写了一个非常实用的代码:
0000000000000000 <init_module>:
0: 55 push %rbp
1: ff 05 00 00 00 00 incl 0x0(%rip) # 7 <init_module+0x7>
7: 48 89 e5 mov %rsp,%rbp
a: e8 00 00 00 00 callq f <init_module+0xf>
f: 5d pop %rbp
10: c3 retq
这是什么意思(包括0x0(%rip))?我怎样才能访问内存?请帮我 :) (我的系统是archlinux x86_64)
我的C代码正确制作模块:
#include <linux/module.h>
#include <linux/init.h>
MODULE_AUTHOR("Actics");
MODULE_DESCRIPTION("Description");
MODULE_LICENSE("GPL");
extern int init(void);
extern int cleanup(void);
static int __init main_init(void) { return init(); }
static void __exit main_cleanup(void) { cleanup(); }
module_init(main_init);
module_exit(main_cleanup);
和我的Makefile:
obj-m := test.o
test-objs := inthan.o module.o
KVERSION = $(shell uname -r)
inthan.o: inthan.asm
nasm -f elf64 -o $@ $^
build:
make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
答案 0 :(得分:3)
内核模式位于地址空间的“负”(即顶部)部分,其中32位绝对地址不能使用(因为它们没有符号扩展)。正如您所注意到的,gcc使用rip-relative地址来解决此问题,该问题从当前指令指针提供偏移量。你可以使用DEFAULT REL
指令让nasm做同样的事情。请参阅relevant section in the nasm documentation。
答案 1 :(得分:1)
您可以随时使用inline assembly
asm("add %3,%1 ; sbb %0,%0 ; cmp %1,%4 ; sbb $0,%0" \
54 : "=&r" (flag), "=r" (roksum) \
55 : "1" (addr), "g" ((long)(size)), \
56 "rm" (limit));