[BUG] PostgreSQL crashes with ThreadSanitizer during early initialization

From: Emmanuel Sibi <emmanuelsibi(dot)mec(at)gmail(dot)com>
To: pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: [BUG] PostgreSQL crashes with ThreadSanitizer during early initialization
Date: 2025-09-08 04:45:49
Message-ID: F7543B04-E56C-4D68-A040-B14CCBAD38F1@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi hackers, I've found a bug that causes PostgreSQL to crash during startup when built with ThreadSanitizer (-fsanitize=thread).

My environment
Ubuntu 24.04.1 LTS (kernel 6.14.0-29-generic)
clang 18
PostgreSQL 17.2
Build Configuration: ./configure --enable-debug --enable-cassert CFLAGS="-fsanitize=thread -g"

PostgreSQL compiled with ThreadSanitizer (-fsanitize=thread) crashes with SIGSEGV during program initialization, before reaching main().

Steps to Reproduce

1. Configure PostgreSQL with ThreadSanitizer
2. ./configure --enable-debug CFLAGS="-fsanitize=thread -g"
3. make
4. Run any PostgreSQL command: ./postgres --version

Expected Behavior: Program should start normally and display version information.
Actual Behavior: Segmentation fault during early initialization

Root Cause: The __ubsan_default_options() function in main.c is compiled with TSan instrumentation, creating a circular dependency during sanitizer runtime initialization.
1. TSan initialization calls __ubsan_default_options()
2. TSan tries to instrument the function
3. Instrumentation requires initialized ThreadState
4. ThreadState isn't ready because TSan init isn't complete
5. Segfault/crash occurs

Proposed Fix: Move __ubsan_default_options() to a separate compilation unit built without sanitizer instrumentation.
The below attached patch moves the function to a separate compilation unit with a custom Makefile rule that uses -fno-sanitize=thread,address,undefined. The reached_main check is preserved to avoid calling getenv() before libc is fully initialized and to handle cases where set_ps_display() breaks /proc/$pid/environ.

Please let me know if you have any questions or would like further details.
Thanks & Regards,
Emmanuel Sibi

Attachment Content-Type Size
tsan_segfault.patch application/x-patch 4.2 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message David Rowley 2025-09-08 04:51:08 Re: Fix missing EvalPlanQual recheck for TID scans
Previous Message Ashutosh Sharma 2025-09-08 04:33:20 Re: Improve pg_sync_replication_slots() to wait for primary to advance