How to access the control registers cr0, cr2, cr3 from a program? Getting segmentation error

I wrote a program that tries to read and write to control registers.

The program compiles fine, but when the built-in assembly is about to run, it causes a segmentation error.

the code:

void instructions(int val) { int i; int value; for(i = 0; i < val; i++) __asm__("mov %cr0, %eax"); } 

I used GDB and went through each pipeline line, and a segmentation error occurred on mov %cr0,%eax .

Who knows what's wrong?

+7
source share
1 answer

Quote from Intelยฎ 64 and IA-32 Architect Software Developer's Guide 3-650 Vol. 2A when switching to and from control registers:

This command can only be executed when the current privilege level is 0.

This means that the instruction can only be executed in kernel mode.

The smallest kernel module that records the contents of cr0, cr2, and cr3 might look something like this (32-bit code path not verified):

 /* 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\n\t" "mov %%eax, %0\n\t" "mov %%cr2, %%rax\n\t" "mov %%eax, %1\n\t" "mov %%cr3, %%rax\n\t" "mov %%eax, %2\n\t" : "=m" (cr0), "=m" (cr2), "=m" (cr3) : /* no input */ : "%rax" ); #elif defined(__i386__) u32 cr0, cr2, cr3; __asm__ __volatile__ ( "mov %%cr0, %%eax\n\t" "mov %%eax, %0\n\t" "mov %%cr2, %%eax\n\t" "mov %%eax, %1\n\t" "mov %%cr3, %%eax\n\t" "mov %%eax, %2\n\t" : "=m" (cr0), "=m" (cr2), "=m" (cr3) : /* no input */ : "%eax" ); #endif printk(KERN_INFO "cr0 = 0x%8.8X\n", cr0); printk(KERN_INFO "cr2 = 0x%8.8X\n", cr2); printk(KERN_INFO "cr3 = 0x%8.8X\n", 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 
+14
source

All Articles