Re: pthread_mutex_trylock crashes because _get_curthread() returns null

From: Konstantin Belousov <kostikbel_at_gmail.com>
Date: Sun, 12 Jan 2025 11:31:08 UTC
On Sat, Jan 11, 2025 at 07:35:51PM -0800, Yuri wrote:
> I am trying to understand this crash:
> 
> 614│ int
> 615│ __Tthr_mutex_trylock(pthread_mutex_t *mutex)
> 616│ {
> 617│         struct pthread *curthread;
> 618│         struct pthread_mutex *m;
> 619│         uint32_t id;
> 620│         int ret, robust;
> 621│
> 622│         ret = check_and_init_mutex(mutex, &m);
> 623│         if (ret != 0)
> 624│                 return (ret);
> 625│         curthread = _get_curthread();
> 626│         id = TID(curthread);
> 627│         if (m->m_flags & PMUTEX_FLAG_PRIVATE)
> 628├───────────────> THR_CRITICAL_ENTER(curthread);
> 
> Program received signal SIGSEGV, Segmentation fault.
> Address not mapped to object.
> __Tthr_mutex_trylock (mutex=<optimized out>) at
> /disk-samsung/freebsd-src/lib/libthr/thread/thr_mutex.c:628
> 628                     THR_CRITICAL_ENTER(curthread);
> 
> The crash occurs at the program startup within the pthread_mutex_trylock()
> function.
> 
> The immediate cause is that _get_curthread() returned null in curthread.
> 
> 
> Testcase: the port databases/qdrant at rev.
> e7cee8d22daf5b6360238cad603ca9f96ecd87fd (at version 1.12.5).
> 
> 
> How can it be that _get_curthread() returns null?
> 
> Shouldn't current thread be always defined?

The following patch should help, please check

commit fb77577e7a4995f038a5d28f42d4c3771e536fdb
Author: Konstantin Belousov <kib@FreeBSD.org>
Date:   Sun Jan 12 13:28:52 2025 +0200

    pthread_mutex_trylock(): init libthr if needed
    
    Sponsored by:   The FreeBSD Foundation
    MFC after:      1 week

diff --git a/lib/libthr/thread/thr_mutex.c b/lib/libthr/thread/thr_mutex.c
index ca8971cc720a..32bdc4afe65f 100644
--- a/lib/libthr/thread/thr_mutex.c
+++ b/lib/libthr/thread/thr_mutex.c
@@ -619,6 +619,7 @@ __Tthr_mutex_trylock(pthread_mutex_t *mutex)
 	uint32_t id;
 	int ret, robust;
 
+	_thr_check_init();
 	ret = check_and_init_mutex(mutex, &m);
 	if (ret != 0)
 		return (ret);