我想使用 mprotect() 拦截对我的应用程序中特定内存块的所有内存引用,所以我稍微修改了此处找到的 mprotect 示例代码。但是,当我运行修改后的代码时,应用程序不会在捕获的第一个异常之后继续前进。相反,Linux 将继续向我的应用程序发送异常,并且我的应用程序将继续在无限循环中打印出同一行。
现在,我的问题是如何告诉 Linux 继续前进并进入下一条指令。
以下是输出示例:
Got SIGSEGV at address: 0x1556000
value of i is: 8192
Got SIGSEGV at address: 0x1556000
value of i is: 8192
/* Infinitely repeats the above two messages. */
这是代码:
#include <unistd.h>
#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 i;
static void handler(int sig, siginfo_t *si, void *unused)
{
printf("Got SIGSEGV at address: 0x%lx\nvalue of i is: %d\n",
(long) si->si_addr, i);
//exit(EXIT_FAILURE);
}
int
main(int argc, char *argv[])
{
char *p;
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 = sysconf(_SC_PAGE_SIZE);
if (pagesize == -1)
handle_error("sysconf");
/* 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\n", (long) buffer);
if (mprotect(buffer + pagesize * 2, pagesize, PROT_READ) == -1)
handle_error("mprotect");
//for (p = buffer, i = 0 ; i < 10 ; ++i )
// *(p++) = 'a';
for (p = buffer ; i< 8200; ++i )
*(p++) = 'a';
printf("Loop completed\n"); /* Should never happen */
exit(EXIT_SUCCESS);
}