From cd9c35cd64758ff387d9dfdc634af4fe7ae35de1 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Fri, 10 Jul 2026 15:37:03 +1000 Subject: [PATCH] AP_HAL_SITL: fix Semaphore ownership race in give() give() cleared the owner field after releasing the mutex. In the window between the unlock and the owner=-1 assignment another thread could take the lock and set itself as owner; we would then clobber that ownership, causing a spurious "Wrong owner" panic when the victim thread next called check_owner(). owner is now cleared while the lock is still held, so it is only ever mutated under lock protection. This is exercised when two threads share a bus semaphore, e.g. a driver with its own thread and a periodic-callback driver on the same simulated SPI bus. Co-Authored-By: Claude Opus 4.8 (1M context) --- libraries/AP_HAL_SITL/Semaphores.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/AP_HAL_SITL/Semaphores.cpp b/libraries/AP_HAL_SITL/Semaphores.cpp index 0067fd9c148..b68ab31e86a 100644 --- a/libraries/AP_HAL_SITL/Semaphores.cpp +++ b/libraries/AP_HAL_SITL/Semaphores.cpp @@ -22,12 +22,12 @@ Semaphore::Semaphore() bool Semaphore::give() { take_count--; - if (pthread_mutex_unlock(&_lock) != 0) { - AP_HAL::panic("Bad semaphore usage"); - } if (take_count == 0) { owner = (pthread_t)-1; } + if (pthread_mutex_unlock(&_lock) != 0) { + AP_HAL::panic("Bad semaphore usage"); + } return true; }