从自定义系统调用生成段错误 [英] Generating segfault from a custom syscall
问题描述
我正在通过系统调用执行copy_to_user()
.
I'm doing copy_to_user()
from a syscall.
如何获取它以在出错时生成segfault或sigbus,就像用户空间试图访问相同的内存一样?
How can I get it to generate a segfault or sigbus on error, as if userspace was trying to access the same memory?
推荐答案
好吧,一般来说,你做不到.除非您打算重写内核.
Well, generally speaking, you can't. Unless you're planning on rewriting the kernel.
当内核访问用户模式地址时,它使用一种安全形式,通常是copy_from_user
,copy_to_user
,get_user
,...-如前所述.这些宏具有内核检查的返回值,并且在大多数情况下将返回-EFAULT
.
When the kernel accesses user-mode addresses it uses a safe form, usually copy_from_user
, copy_to_user
, get_user
, ... - as you mentioned. These macros have a return value the kernel checks for, and in most cases will return -EFAULT
.
然后,通常会出现libc并调整返回值以适合man
页面-这意味着如果结果错误(取决于调用的是哪个syscall),它将设置errno
.
Then, usually comes libc and adjusts the return value to fit the man
page - meaning it sets errno
if the result is erroneous (depending on which syscall was called).
例如,内核中的常见代码段如下:
For example, a common snippet in the kernel goes as following:
if (unlikely(copy_from_user(&pos, offset, sizeof(loff_t))))
return -EFAULT;
(摘自fs/read_write.c中sendfile64
syscall的实现)
(taken from sendfile64
syscall's implementation at fs/read_write.c)
如您所见,当内核无法从用户模式读取时,它将返回-EFAULT
.
As you see, when the kernel fails to read from usermode, it returns -EFAULT
.
鉴于有可能将多个指针传递给某些系统调用,因此可能无法确定哪个指针导致了-EFAULT
.因此,没有一种通用的用户模式方式可以代表内核在检查无效内存访问后发送SIGSEGV
.
Given that it is possible to pass more than one pointer to some syscalls, it may be impossible to figure out which one caused the -EFAULT
. So there isn't a generic usermode way to send SIGSEGV
s upon a checked invalid memory access on the kernel's behalf.
但是,如果您自己编写内核syscall,并且想要触发信号,那一点都不困难.我对内核的研究还不够,但是您正在寻找send_sig_info
行(或者kernel/signal.c中的另一个合适的函数)之间的内容.
If, however, you're writing a kernel syscall yourself, and you want to trigger a signal, that's not difficult at all. I haven't digged too much in the kernel, but calling something among the lines of send_sig_info
(or another suitable function in kernel/signal.c) is what you're looking for.
这篇关于从自定义系统调用生成段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!