From f51ae658df5f57056e0ae25f6981f22011c974ff Mon Sep 17 00:00:00 2001 From: shihao zhong Date: Sat, 5 Dec 2026 00:41:32 -0500 Subject: [PATCH] PROTOTYPE: log another process's backtrace from a cloned copy The signal handler only calls clone(), and the copy calls backtrace(). --- src/backend/postmaster/postmaster.c | 4 + src/backend/storage/ipc/Makefile | 1 + src/backend/storage/ipc/meson.build | 1 + src/backend/storage/ipc/procbacktrace.c | 314 ++++++++++++++++++++++++ src/backend/storage/ipc/procsignal.c | 4 + src/include/catalog/pg_proc.dat | 6 + src/include/storage/procbacktrace.h | 18 ++ src/include/storage/procsignal.h | 1 + 8 files changed, 349 insertions(+) create mode 100644 src/backend/storage/ipc/procbacktrace.c create mode 100644 src/include/storage/procbacktrace.h diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 34d1c8ae3f6..c142dd11a13 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -115,6 +115,7 @@ #include "storage/ipc.h" #include "storage/pmsignal.h" #include "storage/proc.h" +#include "storage/procbacktrace.h" #include "storage/shmem_internal.h" #include "tcop/backend_startup.h" #include "tcop/tcopprot.h" @@ -508,6 +509,9 @@ PostmasterMain(int argc, char *argv[]) IsPostmasterEnvironment = true; + /* Load libgcc's unwinder once; children inherit it. */ + LoadBacktraceFunctions(); + /* * Start our win32 signal implementation */ diff --git a/src/backend/storage/ipc/Makefile b/src/backend/storage/ipc/Makefile index f71653bbe48..b52f6d1c54b 100644 --- a/src/backend/storage/ipc/Makefile +++ b/src/backend/storage/ipc/Makefile @@ -18,6 +18,7 @@ OBJS = \ latch.o \ pmsignal.o \ procarray.o \ + procbacktrace.o \ procsignal.o \ shm_mq.o \ shm_toc.o \ diff --git a/src/backend/storage/ipc/meson.build b/src/backend/storage/ipc/meson.build index b8c31e29967..ddb797e4e9c 100644 --- a/src/backend/storage/ipc/meson.build +++ b/src/backend/storage/ipc/meson.build @@ -10,6 +10,7 @@ backend_sources += files( 'latch.c', 'pmsignal.c', 'procarray.c', + 'procbacktrace.c', 'procsignal.c', 'shm_mq.c', 'shm_toc.c', diff --git a/src/backend/storage/ipc/procbacktrace.c b/src/backend/storage/ipc/procbacktrace.c new file mode 100644 index 00000000000..bee3e712dca --- /dev/null +++ b/src/backend/storage/ipc/procbacktrace.c @@ -0,0 +1,314 @@ +/*------------------------------------------------------------------------- + * + * procbacktrace.c + * Log the backtrace of another server process, right now. + * + * PROTOTYPE, not for commit. + * + * The target process may be stuck where it never reaches + * CHECK_FOR_INTERRUPTS(), for example in an LWLock wait, so the request is + * served in the signal handler. backtrace() is not async-signal-safe: once + * a JIT has called __register_frame(), libgcc's unwinder takes a mutex and + * may call malloc(), and it can hang or abort if the signal arrived at the + * wrong instruction. So the handler does not call it. It makes one system + * call, clone(), and the throwaway copy of the process takes the backtrace. + * If the copy hangs or aborts, the request is lost and nothing else. + * + * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group + * + * IDENTIFICATION + * src/backend/storage/ipc/procbacktrace.c + * + *------------------------------------------------------------------------- + */ +#include "postgres.h" + +#ifdef HAVE_EXECINFO_H +#include +#endif +#include +#include +#include +#include +#ifdef __linux__ +#include +#include +#endif + +#include "fmgr.h" +#include "miscadmin.h" +#include "storage/proc.h" +#include "storage/procarray.h" +#include "storage/procbacktrace.h" +#include "storage/procsignal.h" +#include "utils/fmgrprotos.h" + +#if defined(HAVE_BACKTRACE_SYMBOLS) && defined(__linux__) +#define USE_PROC_BACKTRACE 1 +#endif + +#ifdef USE_PROC_BACKTRACE + +/* Set once in the postmaster, inherited by every child. */ +static volatile sig_atomic_t backtrace_loaded = false; + +/* Prototype switches, read from the postmaster's environment. */ +static bool bt_direct = false; /* PG_BT_MODE=direct: call it in the handler */ +static bool bt_timing = false; /* PG_BT_TIMING=1: report clone() time */ + +/* Only static memory is used from the handler and from the copy. */ +static void *bt_frames[100]; +static volatile pid_t bt_child = 0; + +/* Async-signal-safe: append a string / a decimal number to a buffer. */ +static char * +bt_puts(char *p, const char *s) +{ + while (*s) + *p++ = *s++; + return p; +} + +static char * +bt_putnum(char *p, long v) +{ + char tmp[24]; + int n = 0; + + if (v < 0) + { + *p++ = '-'; + v = -v; + } + do + { + tmp[n++] = '0' + (v % 10); + v /= 10; + } while (v > 0); + while (n > 0) + *p++ = tmp[--n]; + return p; +} + +static char bt_text[16384]; + +/* + * Take the backtrace and write it to stderr. + * + * With one_write, the text is first collected in an anonymous memory file + * and then written with a single write(), so that two processes logging at + * the same time do not mix their lines. Only the copy does that. + */ +static void +bt_emit(bool one_write) +{ + char *p = bt_text; + int nframes; + + nframes = backtrace(bt_frames, lengthof(bt_frames)); + + /* MyProcPid is still the pid of the process whose stack this is. */ + p = bt_puts(p, "logging current backtrace of process with PID "); + p = bt_putnum(p, MyProcPid); + p = bt_puts(p, ":\n"); + + if (one_write) + { + int fd = (int) syscall(SYS_memfd_create, "pg_backtrace", 0U); + + if (fd >= 0) + { + ssize_t n; + + backtrace_symbols_fd(bt_frames, nframes, fd); + n = pread(fd, p, bt_text + sizeof(bt_text) - p, 0); + if (n > 0) + p += n; + (void) !write(STDERR_FILENO, bt_text, p - bt_text); + return; + } + } + + (void) !write(STDERR_FILENO, bt_text, p - bt_text); + /* Unlike backtrace_symbols(), this one does not call malloc(). */ + backtrace_symbols_fd(bt_frames, nframes, STDERR_FILENO); +} + +static void +bt_note(const char *what, long v) +{ + char buf[128]; + char *p = buf; + + p = bt_puts(p, "backtrace request in PID "); + p = bt_putnum(p, MyProcPid); + p = bt_puts(p, ": "); + p = bt_puts(p, what); + p = bt_putnum(p, v); + *p++ = '\n'; + (void) !write(STDERR_FILENO, buf, p - buf); +} +#endif /* USE_PROC_BACKTRACE */ + +/* + * Called from procsignal_sigusr1_handler(). + */ +void +HandleLogBacktraceInterrupt(void) +{ +#ifdef USE_PROC_BACKTRACE + int save_errno = errno; + pid_t pid; + struct timespec t0, + t1; + + /* Without the preload the first backtrace() would dlopen() libgcc. */ + if (!backtrace_loaded) + return; + + if (bt_direct) + { + /* What v29 did. Only here to compare. */ + bt_emit(false); + errno = save_errno; + return; + } + + /* + * Reap the previous copy. Wait for that pid only: waitpid(-1) could + * steal the status of a child that system() or popen() is waiting for. If + * the previous copy is still running, drop this request, so there is + * never more than one copy per process. + */ + if (bt_child > 0) + { + int status = 0; + pid_t r = waitpid(bt_child, &status, WNOHANG); + + if (r == 0) + { + if (bt_timing) + bt_note("dropped, previous copy still running, pid ", bt_child); + errno = save_errno; + return; + } + if (r == bt_child && WIFSIGNALED(status)) + bt_note("previous copy was killed by signal ", WTERMSIG(status)); + bt_child = 0; + } + + if (bt_timing) + clock_gettime(CLOCK_MONOTONIC, &t0); + + /* + * Not fork(): that runs atfork handlers registered by libraries, and + * those take locks. The raw system call does nothing in user space. + */ + pid = (pid_t) syscall(SYS_clone, (unsigned long) SIGCHLD, 0UL, 0UL, 0UL, 0UL); + + if (pid != 0) + { + /* Original process (or clone failed): nothing else to do here. */ + if (pid > 0) + bt_child = pid; + if (bt_timing) + { + clock_gettime(CLOCK_MONOTONIC, &t1); + bt_note("clone took usec ", + (t1.tv_sec - t0.tv_sec) * 1000000L + (t1.tv_nsec - t0.tv_nsec) / 1000); + } + errno = save_errno; + return; + } + + /* + * The copy. From here on no PostgreSQL code may run: this process is + * attached to shared memory and looks like the original to everything in + * it, so proc_exit(), elog() or a latch would corrupt the original's + * state. + */ + { + sigset_t mask; + struct sigaction sa; + + /* + * The postmaster signals the whole process group of a backend, so + * this copy gets those signals too, and the inherited handlers write + * to shared memory. Block everything except the alarm below. + */ + sigfillset(&mask); + sigdelset(&mask, SIGALRM); + sigprocmask(SIG_SETMASK, &mask, NULL); + + /* If the unwinder hangs, die after a second. */ + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = SIG_DFL; + sigaction(SIGALRM, &sa, NULL); + alarm(1); + + /* If the unwinder aborts, do not dump shared_buffers into a core. */ + prctl(PR_SET_DUMPABLE, 0); + + bt_emit(true); + + /* Not exit(): no atexit or on_proc_exit callbacks. */ + _exit(0); + } +#endif +} + +/* + * Called once in the postmaster. The first backtrace() call loads libgcc + * with dlopen(), which calls malloc(). Children inherit the loaded library, + * so they pay nothing at startup. + */ +void +LoadBacktraceFunctions(void) +{ +#ifdef USE_PROC_BACKTRACE + void *buf[2]; + const char *mode = getenv("PG_BT_MODE"); + + backtrace(buf, lengthof(buf)); + bt_direct = (mode != NULL && strcmp(mode, "direct") == 0); + bt_timing = (getenv("PG_BT_TIMING") != NULL); + backtrace_loaded = true; +#endif +} + +/* + * pg_log_backend_backtrace + * Signal a backend or an auxiliary process to log its backtrace. + */ +Datum +pg_log_backend_backtrace(PG_FUNCTION_ARGS) +{ +#ifdef USE_PROC_BACKTRACE + int pid = PG_GETARG_INT32(0); + PGPROC *proc; + + proc = BackendPidGetProc(pid); + if (proc == NULL) + proc = AuxiliaryPidGetProc(pid); + + if (proc == NULL) + { + ereport(WARNING, + (errmsg("PID %d is not a PostgreSQL server process", pid))); + PG_RETURN_BOOL(false); + } + + if (SendProcSignal(pid, PROCSIG_LOG_BACKTRACE, GetNumberFromPGProc(proc)) < 0) + { + ereport(WARNING, + (errmsg("could not send signal to process %d: %m", pid))); + PG_RETURN_BOOL(false); + } + + PG_RETURN_BOOL(true); +#else + ereport(WARNING, + (errmsg("backtrace generation is not supported by this installation"))); + PG_RETURN_BOOL(false); +#endif +} diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c index eb0f4d6fcdf..30a9649beae 100644 --- a/src/backend/storage/ipc/procsignal.c +++ b/src/backend/storage/ipc/procsignal.c @@ -32,6 +32,7 @@ #include "storage/ipc.h" #include "storage/latch.h" #include "storage/proc.h" +#include "storage/procbacktrace.h" #include "storage/shmem.h" #include "storage/sinval.h" #include "storage/smgr.h" @@ -715,6 +716,9 @@ procsignal_sigusr1_handler(SIGNAL_ARGS) if (CheckProcSignal(PROCSIG_LOG_MEMORY_CONTEXT)) HandleLogMemoryContextInterrupt(); + if (CheckProcSignal(PROCSIG_LOG_BACKTRACE)) + HandleLogBacktraceInterrupt(); + if (CheckProcSignal(PROCSIG_PARALLEL_APPLY_MESSAGE)) HandleParallelApplyMessageInterrupt(); diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 18b4be838a4..365bb938626 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -8796,6 +8796,12 @@ prorettype => 'bool', proargtypes => 'int4', prosrc => 'pg_log_backend_memory_contexts', proacl => '{POSTGRES=X}' }, +# logging backtrace of the specified server process +{ oid => '9661', descr => 'log backtrace of the specified server process', + proname => 'pg_log_backend_backtrace', provolatile => 'v', + prorettype => 'bool', proargtypes => 'int4', + prosrc => 'pg_log_backend_backtrace', proacl => '{POSTGRES=X}' }, + # non-persistent series generator { oid => '1066', descr => 'non-persistent series generator', proname => 'generate_series', prorows => '1000', diff --git a/src/include/storage/procbacktrace.h b/src/include/storage/procbacktrace.h new file mode 100644 index 00000000000..ee8d9c6ac2a --- /dev/null +++ b/src/include/storage/procbacktrace.h @@ -0,0 +1,18 @@ +/*------------------------------------------------------------------------- + * + * procbacktrace.h + * Log the backtrace of another server process. + * + * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group + * + * src/include/storage/procbacktrace.h + * + *------------------------------------------------------------------------- + */ +#ifndef PROCBACKTRACE_H +#define PROCBACKTRACE_H + +extern void HandleLogBacktraceInterrupt(void); +extern void LoadBacktraceFunctions(void); + +#endif /* PROCBACKTRACE_H */ diff --git a/src/include/storage/procsignal.h b/src/include/storage/procsignal.h index aaa158bfd66..de796d7356a 100644 --- a/src/include/storage/procsignal.h +++ b/src/include/storage/procsignal.h @@ -35,6 +35,7 @@ typedef enum PROCSIG_WALSND_INIT_STOPPING, /* ask walsenders to prepare for shutdown */ PROCSIG_BARRIER, /* global barrier interrupt */ PROCSIG_LOG_MEMORY_CONTEXT, /* ask backend to log the memory contexts */ + PROCSIG_LOG_BACKTRACE, /* ask backend to log its backtrace */ PROCSIG_PARALLEL_APPLY_MESSAGE, /* Message from parallel apply workers */ PROCSIG_SLOTSYNC_MESSAGE, /* ask slot synchronization to stop */ PROCSIG_REPACK_MESSAGE, /* Message from repack worker */ -- 2.37.1 (Apple Git-137.1)