[BUG] PostgreSQL crashes with ThreadSanitizer during early initialization - Mailing list pgsql-hackers

From Emmanuel Sibi
Subject [BUG] PostgreSQL crashes with ThreadSanitizer during early initialization
Date
Msg-id F7543B04-E56C-4D68-A040-B14CCBAD38F1@gmail.com
Whole thread Raw
Responses Re: [BUG] PostgreSQL crashes with ThreadSanitizer during early initialization
List 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
reachingmain(). 

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
dependencyduring 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
fullyinitialized 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

pgsql-hackers by date:

Previous
From: Ashutosh Sharma
Date:
Subject: Re: Improve pg_sync_replication_slots() to wait for primary to advance
Next
From: David Rowley
Date:
Subject: Re: Fix missing EvalPlanQual recheck for TID scans