Commit 0382bda1 authored by jan.koester's avatar jan.koester
Browse files

libc: <execinfo.h> backtrace*, <sys/signalfd.h> signalfd

rustc 1.90's librustc_driver.so (built by rustc, stage 3 of the rust
package) calls backtrace() and backtrace_symbols_fd() from its SIGSEGV
handler and signalfd(); linking rustc-main failed on all three.

backtrace() walks _Unwind_Backtrace (skipping its own frame),
backtrace_symbols()/_fd() print glibc's "module(symbol+0xoff) [0xaddr]"
through dladdr() (_fd without allocating, for signal handlers), signalfd()
is signalfd4 with the kernel's 128-byte signalfd_siginfo.

New e2e_execinfo_signalfd; ctest 171/172 (e2e_uid_r_src: the host runs a
uid_r kernel now and the test expects root).

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 6bb2034b
Loading
Loading
Loading
Loading

include/execinfo.h

0 → 100644
+21 −0
Changes for include/execinfo.h: 21 added lines, 0 removed lines.
Original line number Diff line number Diff line
#pragma once
/* glibc's <execinfo.h>: the return addresses on the calling thread's stack
 * and their symbolic names. Rust's rustc_driver calls backtrace() and
 * backtrace_symbols_fd() from its SIGSEGV handler (stack-overflow report). */

#ifdef __cplusplus
extern "C" {
#endif

/* up to size return addresses, innermost first (backtrace's caller is the
 * first); the number stored */
int backtrace(void **buffer, int size);
/* "module(symbol+0xoff) [0xaddr]" for each, in one malloc()ed block (free
 * the returned pointer only); NULL if out of memory */
char **backtrace_symbols(void *const *buffer, int size);
/* the same lines written to fd, one per frame, without allocating */
void backtrace_symbols_fd(void *const *buffer, int size, int fd);

#ifdef __cplusplus
}
#endif

include/sys/signalfd.h

0 → 100644
+46 −0
Changes for include/sys/signalfd.h: 46 added lines, 0 removed lines.
Original line number Diff line number Diff line
#pragma once
/* Linux signalfd(2): signals read from a file descriptor. */
#include <stdint.h>
#include <signal.h>
#include <fcntl.h>

#define SFD_CLOEXEC  O_CLOEXEC
#define SFD_NONBLOCK O_NONBLOCK

/* what read() returns per signal: the kernel's 128-byte layout */
struct signalfd_siginfo {
    uint32_t ssi_signo;
    int32_t  ssi_errno;
    int32_t  ssi_code;
    uint32_t ssi_pid;
    uint32_t ssi_uid;
    int32_t  ssi_fd;
    uint32_t ssi_tid;
    uint32_t ssi_band;
    uint32_t ssi_overrun;
    uint32_t ssi_trapno;
    int32_t  ssi_status;
    int32_t  ssi_int;
    uint64_t ssi_ptr;
    uint64_t ssi_utime;
    uint64_t ssi_stime;
    uint64_t ssi_addr;
    uint16_t ssi_addr_lsb;
    uint16_t __pad2;
    int32_t  ssi_syscall;
    uint64_t ssi_call_addr;
    uint32_t ssi_arch;
    uint8_t  __pad[28];
};

#ifdef __cplusplus
extern "C" {
#endif

/* fd -1: a new signalfd; else change the mask of that one. flags:
 * SFD_CLOEXEC, SFD_NONBLOCK */
int signalfd(int fd, const sigset_t *mask, int flags);

#ifdef __cplusplus
}
#endif
+1 −0
Changes for src/CMakeLists.txt: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -209,6 +209,7 @@ list(APPEND osSrcs
    "linux/terminate.cpp"
    "linux/unistd.cpp"
    "linux/glibc_compat.cpp"
    "linux/execinfo.cpp"
    "linux/wchar.cpp"
    "linux/stdio.cpp"
    "linux/membarrier.cpp"

src/linux/execinfo.cpp

0 → 100644
+163 −0
Changes for src/linux/execinfo.cpp: 163 added lines, 0 removed lines.
Original line number Diff line number Diff line
/* glibc-only names programs built for *-linux-gnu link against -- above
 * all Rust's std through the libc crate, which calls the LFS "64" variants
 * (open64, stat64, mmap64, ...) on that target. systempp's off_t and struct
 * stat/dirent are 64-bit on every target, so each is the plain function
 * (as in musl). gnu_get_libc_version: std asks for it to decide on glibc
 * bug workarounds; systempp reports a current glibc, none of them apply. */
/*******************************************************************************
Copyright (c) 2026, Jan Koester jan.koester@gmx.net
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
	* Redistributions of source code must retain the above copyright
	  notice, this list of conditions and the following disclaimer.
	* Redistributions in binary form must reproduce the above copyright
	  notice, this list of conditions and the following disclaimer in the
	  documentation and/or other materials provided with the distribution.
	* Neither the name of the <organization> nor the
	  names of its contributors may be used to endorse or promote products
	  derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
/* <execinfo.h> backtrace()/backtrace_symbols*() on the Itanium unwinder
 * (_Unwind_Backtrace, eh_unwind_core.h) and dladdr(); <sys/signalfd.h>
 * signalfd() on signalfd4. */
#include <execinfo.h>
#include <sys/signalfd.h>
#include <dlfcn.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <bits/syscall.h>
#include <bits/sysbits.h>

extern "C" {
enum _Unwind_Reason_Code { _URC_NO_REASON = 0, _URC_END_OF_STACK = 5 };
struct _Unwind_Context;
typedef _Unwind_Reason_Code (*_Unwind_Trace_Fn)(_Unwind_Context*, void*);
_Unwind_Reason_Code _Unwind_Backtrace(_Unwind_Trace_Fn, void*);
uintptr_t _Unwind_GetIP(_Unwind_Context*);
}

namespace {
struct BacktraceState {
    void **buffer;
    int size;
    int count;
    bool skipped;   /* backtrace()'s own frame */
};

_Unwind_Reason_Code backtrace_frame(_Unwind_Context *ctx, void *arg) {
    BacktraceState *st = (BacktraceState*)arg;
    uintptr_t ip = _Unwind_GetIP(ctx);
    if (!st->skipped) {
        st->skipped = true;
        return _URC_NO_REASON;
    }
    if (ip == 0 || st->count >= st->size)
        return _URC_END_OF_STACK;
    st->buffer[st->count++] = (void*)ip;
    return _URC_NO_REASON;
}

/* "module(symbol+0xoff) [0xaddr]" into out (at most cap bytes incl. the
 * NUL, always terminated); the length written */
size_t format_frame(void *addr, char *out, size_t cap) {
    Dl_info info;
    memset(&info, 0, sizeof(info));
    int ok = dladdr(addr, &info);
    size_t n = 0;
    auto put = [&](const char *s) {
        for (; *s && n + 1 < cap; ++s) out[n++] = *s;
    };
    auto puthex = [&](uintptr_t v) {
        char tmp[2 * sizeof(uintptr_t) + 3];
        int i = sizeof(tmp) - 1;
        tmp[i] = 0;
        do { tmp[--i] = "0123456789abcdef"[v & 15]; v >>= 4; } while (v && i > 2);
        tmp[--i] = 'x';
        tmp[--i] = '0';
        put(tmp + i);
    };
    if (ok && info.dli_fname) put(info.dli_fname);
    if (ok && (info.dli_sname || info.dli_fbase)) {
        put("(");
        if (info.dli_sname && info.dli_saddr) {
            put(info.dli_sname);
            put("+");
            puthex((uintptr_t)addr - (uintptr_t)info.dli_saddr);
        } else if (info.dli_fbase) {
            put("+");
            puthex((uintptr_t)addr - (uintptr_t)info.dli_fbase);
        }
        put(")");
    }
    put(" [");
    puthex((uintptr_t)addr);
    put("]");
    out[n] = 0;
    return n;
}
}

extern "C" __attribute__((noinline)) int backtrace(void **buffer, int size) {
    if (!buffer || size <= 0)
        return 0;
    BacktraceState st = { buffer, size, 0, false };
    _Unwind_Backtrace(backtrace_frame, &st);
    return st.count;
}

extern "C" char **backtrace_symbols(void *const *buffer, int size) {
    if (!buffer || size <= 0)
        return nullptr;
    const size_t line = 512;
    char tmp[line];
    size_t total = 0;
    for (int i = 0; i < size; i++)
        total += format_frame(buffer[i], tmp, line) + 1;
    char **res = (char**)malloc(size * sizeof(char*) + total);
    if (!res)
        return nullptr;
    char *p = (char*)(res + size);
    for (int i = 0; i < size; i++) {
        size_t n = format_frame(buffer[i], p, line);
        res[i] = p;
        p += n + 1;
    }
    return res;
}

extern "C" void backtrace_symbols_fd(void *const *buffer, int size, int fd) {
    char tmp[512];
    for (int i = 0; buffer && i < size; i++) {
        size_t n = format_frame(buffer[i], tmp, sizeof(tmp) - 1);
        tmp[n++] = '\n';
        size_t off = 0;
        while (off < n) {
            ssize_t w = write(fd, tmp + off, n - off);
            if (w <= 0) {
                if (w < 0 && errno == EINTR) continue;
                return;
            }
            off += (size_t)w;
        }
    }
}

extern "C" int signalfd(int fd, const sigset_t *mask, int flags) {
    long r = syscall4(__NR_signalfd4, fd, (unsigned long)mask, _NSIG / 8, flags);
    if (r < 0 && r > -4096) {
        errno = (int)-r;
        return -1;
    }
    return (int)r;
}
+20 −0
Changes for src/test/e2e/CMakeLists.txt: 20 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -4093,3 +4093,23 @@ add_dependencies(e2e_thread_guard_page crti Scrt1 crtbeginS crtn systempp)

add_test(NAME e2e_thread_guard_page COMMAND e2e_thread_guard_page)
set_tests_properties(e2e_thread_guard_page PROPERTIES PASS_REGULAR_EXPRESSION "OK: thread guard page")

add_executable(e2e_execinfo_signalfd execinfo_signalfd_test.cpp)
set_target_properties(e2e_execinfo_signalfd PROPERTIES OUTPUT_NAME "execinfo_signalfd_test")
target_compile_options(e2e_execinfo_signalfd PRIVATE -fPIE)
target_link_options(e2e_execinfo_signalfd PRIVATE
    -nostdlib -pie -rdynamic
    -Wl,--hash-style=sysv
    -Wl,--dynamic-linker,$<TARGET_FILE_DIR:systempp>/ld-linux-${CMAKE_SYSTEM_PROCESSOR}.so
    -Wl,-rpath,$<TARGET_FILE_DIR:systempp>
)
target_link_libraries(e2e_execinfo_signalfd PRIVATE
    $<TARGET_OBJECTS:crti>
    $<TARGET_OBJECTS:Scrt1>
    $<TARGET_OBJECTS:crtbeginS>
    $<TARGET_OBJECTS:crtn>
    systempp
)
add_dependencies(e2e_execinfo_signalfd crti Scrt1 crtbeginS crtn systempp)

add_test(NAME e2e_execinfo_signalfd COMMAND e2e_execinfo_signalfd)
Loading