@@ -36,12 +36,17 @@ kcb_t *kcb = &kernel_state;
3636/* Deferred timer work flag to reduce interrupt latency */
3737static volatile bool timer_work_pending = false;
3838
39+ #if CONFIG_STACK_PROTECTION
40+ /* Stack canary checking frequency - check every N context switches */
41+ #define STACK_CHECK_INTERVAL 32
42+
3943/* Magic number written to both ends of a task's stack for corruption detection.
4044 */
4145#define STACK_CANARY 0x33333333U
4246
4347/* Stack check counter for periodic validation (reduces overhead). */
4448static uint32_t stack_check_counter = 0 ;
49+ #endif /* CONFIG_STACK_PROTECTION */
4550
4651/* Simple task lookup cache to accelerate frequent ID searches */
4752static struct {
@@ -74,6 +79,7 @@ static tcb_t *cache_lookup_task(uint16_t id)
7479 return NULL ;
7580}
7681
82+ #if CONFIG_STACK_PROTECTION
7783/* Stack integrity check with reduced frequency */
7884static void task_stack_check (void )
7985{
@@ -104,6 +110,7 @@ static void task_stack_check(void)
104110 panic (ERR_STACK_CHECK );
105111 }
106112}
113+ #endif /* CONFIG_STACK_PROTECTION */
107114
108115/* Updates task delay counters and unblocks tasks when delays expire */
109116static list_node_t * delay_update (list_node_t * node , void * arg )
@@ -308,9 +315,11 @@ void dispatch(void)
308315 if (hal_context_save (((tcb_t * ) kcb -> task_current -> data )-> context ) != 0 )
309316 return ;
310317
318+ #if CONFIG_STACK_PROTECTION
311319 /* Do stack check less frequently to reduce overhead */
312320 if (unlikely ((kcb -> ticks & (STACK_CHECK_INTERVAL - 1 )) == 0 ))
313321 task_stack_check ();
322+ #endif
314323
315324 list_foreach (kcb -> tasks , delay_update , NULL );
316325
@@ -340,7 +349,9 @@ void yield(void)
340349 if (hal_context_save (((tcb_t * ) kcb -> task_current -> data )-> context ) != 0 )
341350 return ;
342351
352+ #if CONFIG_STACK_PROTECTION
343353 task_stack_check ();
354+ #endif
344355
345356 /* In cooperative mode, delays are only processed on an explicit yield. */
346357 if (!kcb -> preemptive )
@@ -363,10 +374,12 @@ static bool init_task_stack(tcb_t *tcb, size_t stack_size)
363374 return false;
364375 }
365376
377+ #if CONFIG_STACK_PROTECTION
366378 /* Only initialize essential parts to reduce overhead */
367379 * (uint32_t * ) stack = STACK_CANARY ;
368380 * (uint32_t * ) ((uintptr_t ) stack + stack_size - sizeof (uint32_t )) =
369381 STACK_CANARY ;
382+ #endif
370383
371384 tcb -> stack = stack ;
372385 tcb -> stack_sz = stack_size ;
0 commit comments