如何编写信号处理程序来捕获 SIGSEGV? [英] How to write a signal handler to catch SIGSEGV?

查看:31
本文介绍了如何编写信号处理程序来捕获 SIGSEGV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个信号处理程序来捕获 SIGSEGV.我使用

I want to write a signal handler to catch SIGSEGV. I protect a block of memory for read or write using

char *buffer;
char *p;
char a;
int pagesize = 4096;

mprotect(buffer,pagesize,PROT_NONE)

这可以保护从缓冲区开始的 pagesize 字节内存免受任何读取或写入.

This protects pagesize bytes of memory starting at buffer against any reads or writes.

其次,我尝试读取内存:

Second, I try to read the memory:

p = buffer;
a = *p 

这将生成一个 SIGSEGV,我的处理程序将被调用.到现在为止还挺好.我的问题是,一旦调用处理程序,我想通过执行

This will generate a SIGSEGV, and my handler will be called. So far so good. My problem is that, once the handler is called, I want to change the access write of the memory by doing

mprotect(buffer,pagesize,PROT_READ);

并继续我的代码的正常运行.我不想退出该功能.在以后写入同一内​​存时,我想再次捕获信号并修改写入权限,然后记录该事件.

and continue normal functioning of my code. I do not want to exit the function. On future writes to the same memory, I want to catch the signal again and modify the write rights and then record that event.

这是代码:

#include <signal.h>
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>

#define handle_error(msg) 
    do { perror(msg); exit(EXIT_FAILURE); } while (0)

char *buffer;
int flag=0;

static void handler(int sig, siginfo_t *si, void *unused)
{
    printf("Got SIGSEGV at address: 0x%lx
",(long) si->si_addr);
    printf("Implements the handler only
");
    flag=1;
    //exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
    char *p; char a;
    int pagesize;
    struct sigaction sa;

    sa.sa_flags = SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = handler;
    if (sigaction(SIGSEGV, &sa, NULL) == -1)
        handle_error("sigaction");

    pagesize=4096;

    /* Allocate a buffer aligned on a page boundary;
       initial protection is PROT_READ | PROT_WRITE */

    buffer = memalign(pagesize, 4 * pagesize);
    if (buffer == NULL)
        handle_error("memalign");

    printf("Start of region:        0x%lx
", (long) buffer);
    printf("Start of region:        0x%lx
", (long) buffer+pagesize);
    printf("Start of region:        0x%lx
", (long) buffer+2*pagesize);
    printf("Start of region:        0x%lx
", (long) buffer+3*pagesize);
    //if (mprotect(buffer + pagesize * 0, pagesize,PROT_NONE) == -1)
    if (mprotect(buffer + pagesize * 0, pagesize,PROT_NONE) == -1)
        handle_error("mprotect");

    //for (p = buffer ; ; )
    if(flag==0)
    {
        p = buffer+pagesize/2;
        printf("It comes here before reading memory
");
        a = *p; //trying to read the memory
        printf("It comes here after reading memory
");
    }
    else
    {
        if (mprotect(buffer + pagesize * 0, pagesize,PROT_READ) == -1)
        handle_error("mprotect");
        a = *p;
        printf("Now i can read the memory
");

    }
/*  for (p = buffer;p<=buffer+4*pagesize ;p++ ) 
    {
        //a = *(p);
        *(p) = 'a';
        printf("Writing at address %p
",p);

    }*/

    printf("Loop completed
");     /* Should never happen */
    exit(EXIT_SUCCESS);
}

问题是只有信号处理程序运行,我在捕获到信号后无法返回到主函数.

The problem is that only the signal handler runs and I can't return to the main function after catching the signal.

推荐答案

当你的信号处理程序返回时(假设它没有调用 exit 或 longjmp 或阻止它实际返回的东西),代码将在该点继续信号发生,重新执行相同的指令.由于此时内存保护没有改变,它只会再次抛出信号,并且您将在无限循环中返回到您的信号处理程序中.

When your signal handler returns (assuming it doesn't call exit or longjmp or something that prevents it from actually returning), the code will continue at the point the signal occurred, reexecuting the same instruction. Since at this point, the memory protection has not been changed, it will just throw the signal again, and you'll be back in your signal handler in an infinite loop.

因此,要使其工作,您必须在信号处理程序中调用 mprotect.不幸的是,正如 Steven Schansker 所指出的,mprotect 不是异步安全的,因此您不能安全地从信号处理程序中调用它.所以,就 POSIX 而言,你完蛋了.

So to make it work, you have to call mprotect in the signal handler. Unfortunately, as Steven Schansker notes, mprotect is not async-safe, so you can't safely call it from the signal handler. So, as far as POSIX is concerned, you're screwed.

幸运的是,在大多数实现中(据我所知,所有现代 UNIX 和 Linux 变体),mprotect 是一个系统调用,从信号处理程序中安全地调用,因此您可以做大部分您想做的事情.问题是,如果您想在读取后更改保护,则必须在读取后在主程序中执行此操作.

Fortunately on most implementations (all modern UNIX and Linux variants as far as I know), mprotect is a system call, so is safe to call from within a signal handler, so you can do most of what you want. The problem is that if you want to change the protections back after the read, you'll have to do that in the main program after the read.

另一种可能性是对信号处理程序的第三个参数做一些事情,它指向一个操作系统和架构特定的结构,其中包含有关信号发生位置的信息.在 Linux 上,这是一个 ucontext 结构,其中包含有关 $PC 地址和其他发生信号的寄存器内容的机器特定信息.如果你修改它,你会改变信号处理程序返回的位置,所以你可以将 $PC 更改为紧跟在错误指令之后,这样它就不会在处理程序返回后重新执行.这很难做到(而且也不便携).

Another possibility is to do something with the third argument to the signal handler, which points at an OS and arch specific structure that contains info about where the signal occurred. On Linux, this is a ucontext structure, which contains machine-specific info about the $PC address and other register contents where the signal occurred. If you modify this, you change where the signal handler will return to, so you can change the $PC to be just after the faulting instruction so it won't re-execute after the handler returns. This is very tricky to get right (and non-portable too).

编辑

ucontext 结构在 中定义.在 ucontext 中,字段 uc_mcontext 包含机器上下文,在 that 中,数组 gregs 包含通用寄存器语境.所以在你的信号处理程序中:

The ucontext structure is defined in <ucontext.h>. Within the ucontext the field uc_mcontext contains the machine context, and within that, the array gregs contains the general register context. So in your signal handler:

ucontext *u = (ucontext *)unused;
unsigned char *pc = (unsigned char *)u->uc_mcontext.gregs[REG_RIP];

会给你发生异常的电脑.你可以阅读它来弄清楚它是什么指令是不是错了,做一些不同的事情.

will give you the pc where the exception occurred. You can read it to figure out what instruction it was that faulted, and do something different.

就在信号处理程序中调用 mprotect 的可移植性而言,任何遵循 SVID 规范或 BSD4 规范的系统都应该是安全的——它们允许调用任何系统调用(手册第 2 节中的任何内容)在信号处理程序中.

As far as the portability of calling mprotect in the signal handler is concerned, any system that follows either the SVID spec or the BSD4 spec should be safe -- they allow calling any system call (anything in section 2 of the manual) in a signal handler.

这篇关于如何编写信号处理程序来捕获 SIGSEGV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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