|
6 | 6 | */ |
7 | 7 |
|
8 | 8 | #include <hal.h> |
| 9 | +#include <lib/libc.h> |
9 | 10 | #include <lib/queue.h> |
10 | 11 | #include <sys/task.h> |
11 | 12 |
|
@@ -41,10 +42,6 @@ static volatile uint32_t timer_work_generation = 0; /* counter for coalescing */ |
41 | 42 | /* Stack canary checking frequency - check every N context switches */ |
42 | 43 | #define STACK_CHECK_INTERVAL 32 |
43 | 44 |
|
44 | | -/* Magic number written to both ends of a task's stack for corruption detection. |
45 | | - */ |
46 | | -#define STACK_CANARY 0x33333333U |
47 | | - |
48 | 45 | /* Stack check counter for periodic validation (reduces overhead). */ |
49 | 46 | static uint32_t stack_check_counter = 0; |
50 | 47 | #endif /* CONFIG_STACK_PROTECTION */ |
@@ -153,12 +150,12 @@ static void task_stack_check(void) |
153 | 150 | uint32_t *hi_canary_ptr = (uint32_t *) ((uintptr_t) self->stack + |
154 | 151 | self->stack_sz - sizeof(uint32_t)); |
155 | 152 |
|
156 | | - if (unlikely(*lo_canary_ptr != STACK_CANARY || |
157 | | - *hi_canary_ptr != STACK_CANARY)) { |
| 153 | + if (unlikely(*lo_canary_ptr != self->canary || |
| 154 | + *hi_canary_ptr != self->canary)) { |
158 | 155 | printf("\n*** STACK CORRUPTION: task %u base=%p size=%u\n", self->id, |
159 | 156 | self->stack, (unsigned int) self->stack_sz); |
160 | 157 | printf(" Canary values: low=0x%08x, high=0x%08x (expected 0x%08x)\n", |
161 | | - *lo_canary_ptr, *hi_canary_ptr, STACK_CANARY); |
| 158 | + *lo_canary_ptr, *hi_canary_ptr, self->canary); |
162 | 159 | panic(ERR_STACK_CHECK); |
163 | 160 | } |
164 | 161 | } |
@@ -544,10 +541,16 @@ static bool init_task_stack(tcb_t *tcb, size_t stack_size) |
544 | 541 | } |
545 | 542 |
|
546 | 543 | #if CONFIG_STACK_PROTECTION |
547 | | - /* Only initialize essential parts to reduce overhead */ |
548 | | - *(uint32_t *) stack = STACK_CANARY; |
| 544 | + /* Generate random canary for this task */ |
| 545 | + tcb->canary = (uint32_t) random(); |
| 546 | + /* Ensure canary is never zero */ |
| 547 | + if (tcb->canary == 0) |
| 548 | + tcb->canary = 0xDEADBEEFU; |
| 549 | + |
| 550 | + /* Write canary to both ends of stack */ |
| 551 | + *(uint32_t *) stack = tcb->canary; |
549 | 552 | *(uint32_t *) ((uintptr_t) stack + stack_size - sizeof(uint32_t)) = |
550 | | - STACK_CANARY; |
| 553 | + tcb->canary; |
551 | 554 | #endif |
552 | 555 |
|
553 | 556 | tcb->stack = stack; |
|
0 commit comments