linux - 如何从用户空间访问(如果可能)内核空间?

标签 linux memory-management linux-kernel mmap

在 Linux 内核中用户内存和内核内存究竟是如何区分的(在为内核空间提供安全性方面)?

我可以通过哪些不同的方式从用户空间写入内核地址空间?

我知道的一种方法是通过系统调用。我们可以使用多个系统调用,但最终都是系统调用。即使在系统调用中,我们也会将数据发送到内核空间,它(驱动程序或相应的模块)会调用诸如 copy_from_user() 之类的函数将数据从用户空间复制到内核空间。这里我们完全没有写入地址空间。我们只是传递一个用户指针,其中包含需要复制到内核缓冲区中的数据。

我的问题是有什么方法可以访问内核空间中存在的物理地址并对其执行操作?

其次,除了系统调用之外,还有其他方法可以从用户应用程序写入内核空间吗?

我提到了这个link来自计算器。但我认为我的问题没有在那里得到回答,而是从不同的角度来看的。因此我想问一个不同的问题。

请分享您的知识... 谢谢。

最佳答案

What are the different ways I can write in kernel address space from user space?

我不确定是否还有其他方法,但您可以使用 /dev/mem 和系统调用 mmap() 访问物理内存。

/dev/mem is a character device file that is an image of the main memory of the computer. It may be used, for example, to examine (and even patch) the system. Byte addresses in mem are interpreted as physical memory addresses.

关于 /dev/mem 的更多信息:http://linux.about.com/library/cmd/blcmdl4_mem.htm

关于 mmap() 的更多信息:http://linux.die.net/man/2/mmap

您可以使用mmap() 映射/dev/mem 的一部分并在您的用户程序中使用。一个简短的示例代码:

#define MAPPED_SIZE //place the size here
#define DDR_RAM_PHYS  //place the physical address here

int _fdmem;
int *map = NULL;
const char memDevice[] = "/dev/mem";

/* open /dev/mem and error checking */
_fdmem = open( memDevice, O_RDWR | O_SYNC );

if (_fdmem < 0){
printf("Failed to open the /dev/mem !\n");
return 0;
}
else{
printf("open /dev/mem successfully !\n");
}

/* mmap() the opened /dev/mem */
map= (int *)(mmap(0,MAPPED_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,_fdmem,DDR_RAM_PHYS));

/* use 'map' pointer to access the mapped area! */
for (i=0,i<100;i++)
printf("content: 0x%x\n",*(map+i));

/* unmap the area & error checking */
if (munmap(map,MAPPED_SIZE)==-1){
perror("Error un-mmapping the file");
}

/* close the character device */
close(_fdmem);

但是,请确保您正在映射的区域未被使用,例如未被内核使用,否则它会使您的系统崩溃/挂起,并且您将被迫使用硬件电源按钮重新启动。

希望对你有帮助。

关于linux - 如何从用户空间访问(如果可能)内核空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9662193/

相关文章:

linux - 使用 SVN 保留文件权限

linux - # vs $ 在文章中记录代码时

linux - Bash + 从行中删除空格

iphone - 使用 UIImage 时的内存管理

c - 最近指针不为空时出现空指针取消引用错误

c - linux 内核模块在 100000 次中断后死掉

linux - Linux 中的 "blk_update_request"是什么?

linux - 如何在 Linux 的命令行中使用占位符?

memory-management - 如何在go中释放内存?

c++ - 在这种情况下,可以避免在c++中手动管理内存吗?