在多线程环境中捕获信号

6

我有一个要尽可能提高韧性的大型程序,其中包含大量线程。

我需要捕获SIGBUS SIGSEGV信号,并在必要时重新初始化问题线程,或禁用线程以继续使用降低的功能。

我的第一个想法是执行setjump,然后设置信号处理程序,可以记录问题,然后进行longjump返回到线程中的恢复点。问题在于,信号处理程序需要确定信号来自哪个线程,以使用适当的跳转缓冲区,否则跳回错误的线程将毫无意义。

有没有人有任何想法如何在信号处理程序中确定有问题的线程?


1
您应该使用sigsetjump()/siglongjmp()而不是setjmp()/longjmp(),这样就不需要重置信号处理程序。 - Andrew Henle
信号处理程序访问静态或线程存储的对象,并调用标准库函数?听起来像是未定义行为。 - autistic
3个回答

4
我会假设您已经仔细考虑过此事并有非常好的理由相信,通过尝试在SIGSEGV后重试,您的程序将变得更加弹性化——请记住,segfault突出显示了悬空指针和其他可能在不引起segfault情况下破坏进程地址空间中不可预测位置的滥用问题。
既然您已经非常认真地考虑过这个问题,并且已经确定(以某种方式)您的应用程序segfault的特定方式绝对不能掩盖用于取消和重新启动线程的会计数据的损坏,并且您具有完美的取消逻辑用于这些线程(也是非常罕见的),那么让我们解决这个问题吧。
Linux上的SIGSEGV处理程序在失败指令的线程中执行(man 7 signal)。我们无法调用pthread_self(),因为它不是异步信号安全的,但互联网普遍认为syscall (man 2 syscall) 是安全的,因此我们可以通过syscall SYS_gettid获取线程ID。因此,我们需要维护一个pthread_t(pthread_self)到pid(gettid())的映射。由于write()也是安全的,因此我们可以陷阱SEGV,将当前线程ID写入管道,然后暂停,直到pthread_cancel结束。
我们还需要一个监视线程来监视何时出现问题。监视线程监视已终止线程的管道读端口,并可能重新启动它。
因为我认为假装处理SIGSEGV是愚蠢的,所以我将称这里执行此操作的结构为daft_thread_t等。someone_please_fix_me代表您的错误代码。监视器线程是main()。当线程segfault时,它会被信号处理程序捕获,将其ID写入管道;监视器读取管道,取消具有pthread_cancel和pthread_join的线程,并重新启动它。
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>

#define MAX_DAFT_THREADS (1024) // arbitrary

#define CHECK_OSCALL(call, onfail) { \
    if ((call) == -1) { \
        char buf[512]; \
        strerror_r(errno, buf, sizeof(buf)); \
        fprintf(stderr, "%s@%d failed: %s\n", __FILE__, __LINE__, buf); \
        onfail; \
    } \
}

/*********************** daft thread accounting *****************/
typedef void* (*threadproc_t)(void* arg);

struct daft_thread_t {
    threadproc_t start_routine;
    void* start_routine_arg;
    pthread_t pthread;
    pid_t tid;
};

struct daft_thread_accounting_info_t {
    int monitor_pipe[2];
    pthread_mutex_t info_lock;
    size_t daft_thread_count;
    struct daft_thread_t daft_threads[MAX_DAFT_THREADS];
};

static struct daft_thread_accounting_info_t g_thread_accounting;

void daft_thread_accounting_info_init(struct daft_thread_accounting_info_t* inf)
{
    memset(inf, 0, sizeof(*inf));
    pthread_mutex_init(&inf->info_lock, NULL);
    CHECK_OSCALL(pipe(inf->monitor_pipe), abort());
}

struct daft_thread_wrapper_data_t {
    struct daft_thread_t* thread_info;
};

static void* daft_thread_wrapper(void* arg)
{
    struct daft_thread_t* wrapper = arg;
    wrapper->tid = gettid();
    return (*wrapper->start_routine)(wrapper->start_routine_arg);
}

static void start_daft_thread(threadproc_t proc, void* arg)
{
    struct daft_thread_t*  info;
    pthread_mutex_lock(&g_thread_accounting.info_lock);
    assert (g_thread_accounting.daft_thread_count < MAX_DAFT_THREADS);
    info = &g_thread_accounting.daft_threads[g_thread_accounting.daft_thread_count++];
    pthread_mutex_unlock(&g_thread_accounting.info_lock);
    info->start_routine = proc;
    info->start_routine_arg = arg;
    CHECK_OSCALL(pthread_create(&info->pthread, NULL, daft_thread_wrapper, info), abort());
}

static struct daft_thread_t* find_thread_by_tid(pid_t thread_id)
{
    int k;
    struct daft_thread_t* info = NULL;
    pthread_mutex_lock(&g_thread_accounting.info_lock);
    for (k = 0; k < g_thread_accounting.daft_thread_count; ++k) {
        if (g_thread_accounting.daft_threads[k].tid == thread_id) {
            info = &g_thread_accounting.daft_threads[k];
            break;
        }
    }
    pthread_mutex_unlock(&g_thread_accounting.info_lock);
    return info;
}

static void restart_daft_thread(struct daft_thread_t* info)
{
    void* unused;
    CHECK_OSCALL(pthread_cancel(info->pthread), abort());
    CHECK_OSCALL(pthread_join(info->pthread, &unused), abort());
    info->tid = 0;
    CHECK_OSCALL(pthread_create(&info->pthread, NULL, daft_thread_wrapper, info), abort());
}

/************* signal handling stuff **************/
struct sigdeath_notify_info {
    int signum;
    pid_t tid;
};

static void sigdeath_handler(int signum, siginfo_t* info, void* ctx)
{
    int z;
    struct sigdeath_notify_info inf = {
        .signum = signum,
        .tid = gettid()
    };
    z = write(g_thread_accounting.monitor_pipe[1], &inf, sizeof(inf));
    assert (z == sizeof(inf)); // or else SIGABRT. Are we handling that too? Hope     not.
    pause(); // returning doesn't do us any good.
}

static void register_signal_handlers()
{
    struct sigaction sa = {};
    sa.sa_sigaction = sigdeath_handler;
    sa.sa_flags = SA_SIGINFO;
    CHECK_OSCALL(sigaction(SIGSEGV, &sa, NULL), abort());
    CHECK_OSCALL(sigaction(SIGBUS, &sa, NULL), abort());
}

pid_t gettid() { return (pid_t) syscall(SYS_gettid); }

/** This is the code that segfaults randomly. Kwality with a 'k'. */
static void* someone_please_fix_me(void* arg)
{
    char* i_think_this_address_looks_nice = (char*) 42;
    sleep(1 + rand() % 200);
    i_think_this_address_looks_nice[0] = 'q'; // ugh
    return NULL;
}

// main() will serve as the monitor thread here
int main()
{
    int k;
    struct sigdeath_notify_info death;
    daft_thread_accounting_info_init(&g_thread_accounting);
    register_signal_handlers();
    for (k = 0; k < 200; ++k) {
        start_daft_thread(someone_please_fix_me, (void*) k);
    }
    while (read(g_thread_accounting.monitor_pipe[0], &death, sizeof(death)) == sizeof(death)) {
        struct daft_thread_t* info = find_thread_by_tid(death.tid);
        if (info == NULL) {
            fprintf(stderr, "*** thread_id %u not found\n", death.tid);
            continue;
        }
        fprintf(stderr, "Thread %u (%d) died of %d, restarting.\n",
            death.tid, (int) info->start_routine_arg, death.signum);
        restart_daft_thread(info);
    }
    fprintf(stderr, "Shouldn't get here.\n");
    return 0;
}

如果你没有考虑过: 尝试从SIGSEGV错误中恢复是非常危险的 - 我强烈建议不要这样做。线程共享一个地址空间。导致段错误的线程可能还会破坏其他线程数据或全局记账数据,例如malloc()的记账。一种更安全的方法 - 假设失败的代码已经无法修复但必须使用 - 是将失败的代码隔离在进程边界之后,例如在调用损坏的代码之前进行fork()。然后,您必须捕获SIGCLD并处理进程崩溃或正常终止,以及其他许多问题,但至少您不必担心随机损坏。当然,最好的选择是修复该可怜的代码,以便您不会观察到段错误。

以上所有内容中最重要的一行是最后一行。线程不会自己“崩溃” - 你必须编写糟糕的代码。如果你添加某种类型的“监视器”线程,那么这只是你需要测试、调试、维护的另一件事情,当然还有一个可能会出问题的额外线程:( - Martin James
破损的代码应该被修复,像这样的问题应该被记录下来,虽然在磁盘空间不足时写入内存映射文件可能会导致一个可恢复的段错误。故障也可能发生在关闭的库中。 - camelccc
@camelccc 全都正确。请注意,尽管我提醒了你,但我还是提供了一个可行的解决方案来解决你的问题 :) 一个封闭的库完全有可能破坏你的进程地址空间,但无法读取其源代码并不能保护你。因此,在这种情况下,我仍然建议使用“fork”。关于 mmap:我认为 mmap 失败会导致 SIGBUS,但可能我记错了。 - lyngvi
@MartinJames非常正确。我试图给我的回复一个“这是个糟糕的想法,这是你如何去做”的感觉 - 在原始问题的限制内工作。我怀疑OP有一个损坏的第三方库,因为他的评论暗示了这一点。如果你处于这种情况下,保持运行有问题的代码在单独的进程中是最好的选择。 - lyngvi

2

在我的Linux系统上,使用syscall(SYS_gettid)可以正常工作:gcc pt.c -lpthread -Wall -Wextra

//pt.c
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <setjmp.h>
#include <signal.h>
#include <string.h>
#include <ucontext.h>
#include <stdlib.h>

static sigjmp_buf jmpbuf[65536];

static void handler(int sig, siginfo_t *siginfo, void *context)
{
    //ucontext_t *ucontext = context;
    pid_t tid = syscall(SYS_gettid);

    printf("Thread %d in handler, signal %d\n", tid, sig);
    siglongjmp(jmpbuf[tid], 1);
}

static void *threadfunc(void *data)
{
    int index, segvindex = *(int *)data;
    pid_t tid = syscall(SYS_gettid);

    for(index = 0; index < 500; index++) {
        if (sigsetjmp(jmpbuf[tid], 1) == 1) {
            printf("Recovery of thread %d\n", tid); 
            continue;
        }
        printf("Thread %d, index %d\n", tid, index);
        if (index % 5 == segvindex) {
            printf("%zu\n", strlen((char *)2)); // SIGSEGV
        }
        pthread_yield();
    }
    return NULL;
}

int main(void)
{
    pthread_t thread1, thread2, thread3;
    int segvindex1 = rand() % 5;
    int segvindex2 = rand() % 5;
    int segvindex3 = rand() % 5;
    struct sigaction sact;

    memset(&sact, 0, sizeof sact);
    sact.sa_sigaction = handler;
    sact.sa_flags = SA_SIGINFO;
    if (sigaction(SIGSEGV, &sact, NULL) < 0) {
        perror("sigaction");
        return 1;
    }
    pthread_create(&thread1, NULL, &threadfunc, (void *) &segvindex1);
    pthread_create(&thread2, NULL, &threadfunc, (void *) &segvindex2);
    pthread_create(&thread3, NULL, &threadfunc, (void *) &segvindex3);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_join(thread3, NULL);
    return 0;
}

为了更具可移植性,可以使用pthread_self。它是异步信号安全的。
但是收到SIGSEGV的线程应该通过异步信号安全的方式启动一个新线程,而不应该执行siglongjmp,因为这可能会导致调用非异步信号安全的函数。

在信号处理程序中使用syscall是否安全? - incompetent
@user252127 Linux特有的syscall(SYS_gettid)是异步信号安全的。它满足所有异步信号安全规则。由于它是Linux特有的,因此不在异步信号安全函数的POSIX列表上。几乎相同的getpid()在列表上。 - 4566976

0
根据我的经验,当一个线程程序接收到同步信号时——例如由程序引起的信号,比如解除引用坏指针——导致问题的线程会接收到该信号。
我曾使用过一个明确保证这种行为的系统,但我不知道它是否普遍存在。当然,如果有问题的线程已经阻塞了信号,就像在一个范例中只有一个线程处理所有信号的情况下,那么信号将传递给信号处理线程。

这需要成立才能正常工作,但是接下来怎么办 - 你需要跳出处理程序,并确定去哪里。我看不到使用堆栈帧来帮助的任何方法。 - camelccc
Linux的signal(7)手册页面(http://linux.die.net/man/7/signal)似乎暗示引起SIGSEGV等信号的线程将是处理该信号的线程: "一个信号可以被生成(因此处于挂起状态)对于整个进程(例如,当使用kill(2)发送时),或者针对特定线程(例如,某些信号,如由于执行特定机器语言指令而生成的SIGSEGV和SIGFPE是线程定向的,以及使用pthread_kill(3)针对特定线程的信号)。" - Andrew Henle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接