C SIGSEGV处理程序和保卫 [英] C SIGSEGV Handler & Mprotect

查看:183
本文介绍了C SIGSEGV处理程序和保卫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个程序,该程序使用mprotect()限制对内存块的访问.请求内存时,会抛出SIGSEGV,我使用signal()调用进行监听.

I'm constructing a program which uses mprotect() to restrict a block of memory from accessing. When the memory is requested, a SIGSEGV is thrown which I listen for using a signal() call.

一旦检测到SIGSEGV,我就需要以某种方式访问​​指向所请求的内存(引发故障)的指针以及所请求的段的大小.这可能吗?

Once the SIGSEGV has been detected, I need to somehow access the pointer to the memory that was requested (that threw the fault) and the size of the segment requested. Is this possible?

void fifoSigHandler(){

    // Needs to only remove protection from requested block of virtual memory
    mprotect(fifoVm,(size_t)fifoVm_size,PROT_WRITE);
    printf("Caught Seg Fault");
}

void fifo_init(void* vm, int vm_size, int n_frames, int page_size)
{
    fifoVm = vm;
    fifoVm_size = vm_size;
    fifoFrames = n_frames;
    fifoPageSize = page_size;

    mprotect(fifoVm,(size_t)fifoVm_size,PROT_NONE);

    signal(SIGSEGV, fifoSigHandler);
}

此外,是否有办法确定当前分配的内存块(PROT_NONE,PROT_READ等)的mprotect()级别?

Additionally, is there a way to determine the level of mprotect() a block of memory is currently assigned (PROT_NONE,PROT_READ, etc..)?

推荐答案

您必须将sigactionSA_SIGINFO一起使用,而不是signal来建立您的处理程序,然后您将在一个siginfo_t,包括si_addr.

You have to use sigaction with SA_SIGINFO instead of signal to establish your handler, and then you will get called back with useful information in a siginfo_t, including si_addr.

si_addr将包含地址.至于长度,那么,除非您愿意解析指令,否则您很不走运.最好的办法是对si_addr中报告的页面采取措施,然后,如果这还不够,您将很快收到另一个信号.至少,这就是我们在ObjectStore中所做的事情.

si_addr, as explained in sigaction(2), will contain the address. As for the length, well, you're out of luck unless you're willing to parse instructions. Best you can do is take action for the page reported in si_addr, and then if that's not enough, you'll get another signal soon enough. At least, that's how we did things in ObjectStore.

这篇关于C SIGSEGV处理程序和保卫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆