gpt4 book ai didi

在 Segmentation Violation 后恢复生机

转载 作者:太空狗 更新时间:2023-10-29 16:34:47 28 4
gpt4 key购买 nike

是否有可能在出现段错误后恢复 C 程序的正常执行流程?

struct A {
int x;
};
A* a = 0;

a->x = 123; // this is where segmentation violation occurs

// after handling the error I want to get back here:
printf("normal execution");
// the rest of my source code....

我想要一种类似于 Java、C# 等中存在的 NullPointerException 的机制。

注意:请不要告诉我 C++ 中有异常处理机制,因为我知道,不要告诉我应该在赋值之前检查每个指针等。

我真正想要实现的是回到上面示例中的正常执行流程。我知道可以使用 POSIX 信号执行某些操作。它应该是什么样子?其他想法?

最佳答案

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <signal.h>
#include <stdlib.h>
#include <ucontext.h>

void safe_func(void)
{
puts("Safe now ?");
exit(0); //can't return to main, it's where the segfault occured.
}

void
handler (int cause, siginfo_t * info, void *uap)
{
//For test. Never ever call stdio functions in a signal handler otherwise*/
printf ("SIGSEGV raised at address %p\n", info->si_addr);
ucontext_t *context = uap;
/*On my particular system, compiled with gcc -O2, the offending instruction
generated for "*f = 16;" is 6 bytes. Lets try to set the instruction
pointer to the next instruction (general register 14 is EIP, on linux x86) */
context->uc_mcontext.gregs[14] += 6;
//alternativly, try to jump to a "safe place"
//context->uc_mcontext.gregs[14] = (unsigned int)safe_func;
}

int
main (int argc, char *argv[])
{
struct sigaction sa;
sa.sa_sigaction = handler;
int *f = NULL;
sigemptyset (&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
if (sigaction (SIGSEGV, &sa, 0)) {
perror ("sigaction");
exit(1);
}
//cause a segfault
*f = 16;
puts("Still Alive");
return 0;
}

$ ./a.out
SIGSEGV raised at address (nil)
Still Alive

不过,如果我在生产代码中看到这样的东西,我会用球棒打人,这是一个丑陋的、为了好玩的 hack。您将不知道段错误是否损坏了您的某些数据,您将没有理智的恢复方法并且知道现在一切正常,没有可移植的方法来执行此操作。您可以做的唯一稍微理智的事情是尝试记录错误(直接使用 write() ,而不是任何 stdio 函数——它们不是信号安全的)并可能重新启动程序。对于这些情况,您最好编写一个 superwisor 进程来监视子进程退出、记录它并启动一个新的子进程。

关于在 Segmentation Violation 后恢复生机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3291382/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com