From 9dda4781a43fa2ed43305f57102c0ab3f3795db1 Mon Sep 17 00:00:00 2001 From: arctic-alpaca <67190338+arctic-alpaca@users.noreply.github.com> Date: Wed, 2 Apr 2025 12:42:05 +0200 Subject: [PATCH] Fix race in POSIX port `vPortEndScheduler` The `vPortEndScheduler` checks whether it's a FreeRTOS thread after signalling the scheduler thread to stop. This creates a race between the check and the destruction of the thread key. By moving the signal to the scheduler thread after the check, the race is prevented. --- portable/ThirdParty/GCC/Posix/port.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/portable/ThirdParty/GCC/Posix/port.c b/portable/ThirdParty/GCC/Posix/port.c index dd7ca1a9a..1f23ba27a 100644 --- a/portable/ThirdParty/GCC/Posix/port.c +++ b/portable/ThirdParty/GCC/Posix/port.c @@ -329,12 +329,17 @@ void vPortEndScheduler( void ) xTimerTickThreadShouldRun = false; pthread_join( hTimerTickThread, NULL ); + /* Check whether the current thread is a FreeRTOS thread. + * This has to happen before the scheduler is signaled to exit + * its loop to prevent data races on the thread key. */ + BaseType_t is_freertos_thread = prvIsFreeRTOSThread(); + /* Signal the scheduler to exit its loop. */ xSchedulerEnd = pdTRUE; ( void ) pthread_kill( hMainThread, SIG_RESUME ); /* Waiting to be deleted here. */ - if( prvIsFreeRTOSThread() == pdTRUE ) + if( is_freertos_thread == pdTRUE ) { pxCurrentThread = prvGetThreadFromTask( xTaskGetCurrentTaskHandle() ); event_wait( pxCurrentThread->ev );