问题描述
我编写了一个程序,试图读取和写入控制寄存器.
I have written a program which tries to read from and write to the control registers.
程序编译正常,但是当内联汇编即将执行时,它产生了一个分段错误.
The program compiles fine, but when the inline assembly is about to be executed, it produces a segmentation fault.
代码:
void instructions(int val)
{
int i;
int value;
for(i = 0; i < val; i++)
__asm__("mov %cr0, %eax");
}
我使用 GDB 并通过每条装配线,在 mov %cr0,%eax
上发生了分段错误.
I used GDB and stepped through each assembly line and it is on the mov %cr0,%eax
that the segmentation fault is occurring.
谁知道哪里出了问题?
推荐答案
引用自 英特尔® 64 和 IA-32 架构软件开发人员手册 3-650 卷.2A 关于移入和移出控制寄存器:
Quoting from Intel® 64 and IA-32 Architectures Software Developer Manuals 3-650 Vol. 2A on moving to and from control registers:
该指令只有在当前权限级别为0时才能执行.
这意味着指令只能在内核模式下执行.
Which means the instruction can only be executed in kernel mode.
记录 cr0、cr2 和 cr3 内容的最小内核模块可能如下所示(32 位代码路径未经测试):
A minimal kernel module, that logs the contents of cr0, cr2 and cr3 could look something like this (32-bit code path untested):
/* hello.c */
#include <linux/module.h>
#include <linux/kernel.h>
int init_module(void)
{
#ifdef __x86_64__
u64 cr0, cr2, cr3;
__asm__ __volatile__ (
"mov %%cr0, %%rax
"
"mov %%eax, %0
"
"mov %%cr2, %%rax
"
"mov %%eax, %1
"
"mov %%cr3, %%rax
"
"mov %%eax, %2
"
: "=m" (cr0), "=m" (cr2), "=m" (cr3)
: /* no input */
: "%rax"
);
#elif defined(__i386__)
u32 cr0, cr2, cr3;
__asm__ __volatile__ (
"mov %%cr0, %%eax
"
"mov %%eax, %0
"
"mov %%cr2, %%eax
"
"mov %%eax, %1
"
"mov %%cr3, %%eax
"
"mov %%eax, %2
"
: "=m" (cr0), "=m" (cr2), "=m" (cr3)
: /* no input */
: "%eax"
);
#endif
printk(KERN_INFO "cr0 = 0x%8.8X
", cr0);
printk(KERN_INFO "cr2 = 0x%8.8X
", cr2);
printk(KERN_INFO "cr3 = 0x%8.8X
", cr3);
return 0;
}
void cleanup_module(void)
{
}
# Makefile
obj-m += hello.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
test: all
sudo insmod ./hello.ko
sudo rmmod hello
dmesg | tail
这篇关于如何从程序访问控制寄存器 cr0,cr2,cr3?获取分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!