Commit 56ed755
authored
Fix crash caused by race condition in xSemaphoreTake (#173)
* Fix race condition in xSemaphoreTake
This race condition would make infinisim eventually crash with the message "Mutex released without being held" on my machine.
The function `xSemaphoreTake` waits for the semaphore to be available to take by looping + sleeping until there is an element in the `pxQueue->queue`. Then it locks the `pxQueue->mutex` and checks the queuesize again. Since the first check is not done under the mutex, some other thread could remove the element from the queue before the mutex is locked. Then the second check in `xSemaphoreTake` will return false.
The method `DateTimeController::CurrentDateTime()` uses a semaphore as a mutex to guard calls to `UpdateTime()`. But it (and the other methods from `DateTimeController`) do not check if `xSemaphoreTake` actually gave them the semaphore. They will try to give it back even if they failed to take it, which leads to the crash in `xSemaphoreGive`.
The other thread in this crash was calling the watchface refresh method, which also calls `CurrentDateTime()`.
To fix the race condition, lock the mutex guarding `pxQeue->queue` before checking the queue size and unlock before sleeping. When implemented like this, `xSemaphoreTake` from InfiniSim follows the API from FreeRTOS more closely, which waits the full `xTicksToWait` while InfiniSim would abort prematurely in some cases.
With the assumption that `UpdateTime()` will finish within some finite amount of time, this make the methods in `DateTimerController` work even without error handling since they have such long wait times.
* Change to constexpr and use the appropriate type for DELAY_BETWEEN_ATTEMPTS
Since xTicksToWait is TickType_t (uint32) and SDL_Delay takes uint32 as well, we should avoid any chance of funny business due to differences in signedness.1 parent 9893cb7 commit 56ed755
1 file changed
+19
-13
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
5 | 5 | | |
6 | 6 | | |
7 | 7 | | |
| 8 | + | |
8 | 9 | | |
9 | 10 | | |
10 | | - | |
| 11 | + | |
11 | 12 | | |
12 | 13 | | |
13 | 14 | | |
14 | 15 | | |
15 | | - | |
16 | | - | |
17 | | - | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
18 | 24 | | |
19 | | - | |
20 | | - | |
21 | | - | |
22 | | - | |
23 | | - | |
24 | | - | |
25 | | - | |
26 | | - | |
27 | | - | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
28 | 33 | | |
| 34 | + | |
29 | 35 | | |
30 | 36 | | |
31 | 37 | | |
| |||
0 commit comments