Skip to content

Commit 54c3e97

Browse files
committed
Fix undefined behavior in uxSchedulerCoreMask initialization and clamping logic
1 parent 4f32c35 commit 54c3e97

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

tasks.c

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -515,8 +515,14 @@ PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandles[ configNUMBER_OF_CORES ];
515515
/* Global scheduler core mask. Bit N = 1 means core N is allowed to run
516516
* non-idle tasks. Defaults to all cores enabled. Use
517517
* vTaskSetSchedulerCoreMask() / uxTaskGetSchedulerCoreMask() to change it
518-
* at run time. */
519-
PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerCoreMask = ( UBaseType_t ) ( ( 1UL << configNUMBER_OF_CORES ) - 1UL );
518+
* at run time.
519+
*
520+
* The mask is derived by right-shifting ~0 rather than left-shifting 1,
521+
* because left-shifting by a value equal to the type width is undefined
522+
* behaviour in C (C11 §6.5.7). Using UBaseType_t throughout also avoids
523+
* the assumption that unsigned long is at least as wide as UBaseType_t. */
524+
PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerCoreMask =
525+
( ( UBaseType_t ) ( ~( UBaseType_t ) 0U ) >> ( ( sizeof( UBaseType_t ) * ( size_t ) 8U ) - ( size_t ) configNUMBER_OF_CORES ) );
520526
#endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_SCHEDULER_CORE_MASK == 1 ) ) */
521527

522528
/* Improve support for OpenOCD. The kernel tracks Ready tasks via priority lists.
@@ -3141,8 +3147,12 @@ static void prvInitialiseNewTask( TaskFunction_t pxTaskCode,
31413147
{
31423148
uxOldMask = uxSchedulerCoreMask;
31433149

3144-
/* Clamp to the number of physical cores so stray bits are ignored. */
3145-
uxSchedulerCoreMask = uxCoreMask & ( UBaseType_t ) ( ( 1UL << configNUMBER_OF_CORES ) - 1UL );
3150+
/* Clamp to the number of physical cores so stray bits are ignored.
3151+
* The valid-core mask is derived by right-shifting ~0 to avoid
3152+
* left-shift UB and unsigned long width assumptions (see the
3153+
* uxSchedulerCoreMask initialiser for a full explanation). */
3154+
uxSchedulerCoreMask = uxCoreMask &
3155+
( ( UBaseType_t ) ( ~( UBaseType_t ) 0U ) >> ( ( sizeof( UBaseType_t ) * ( size_t ) 8U ) - ( size_t ) configNUMBER_OF_CORES ) );
31463156

31473157
if( xSchedulerRunning != pdFALSE )
31483158
{

0 commit comments

Comments
 (0)