suoyuanG opened a new pull request, #17054:
URL: https://github.com/apache/nuttx/pull/17054
## Summary
Added nxsched_switch_context for unified context switching.
Base on this, I made a software method for stack overflow detection, which
will detect the sp register and the bottom stack memory of the thread.
## Impact
Add stack overflow detection on context switching. If enable
`STACKCHECK_SOFTWARE`, this check will be turned on. By default, the bottom 16
bytes of the stack will be checked. This parameter can be configured through
`STACKCHECK_MARGIN`
## Testing
```c
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define STACK_SIZE (8192)
static unsigned char stack[STACK_SIZE];
void *thread_func(void *arg) {
puts("haha");
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t thread;
pthread_attr_t attr;
uint32_t stack_color = 0xdeadbeef;
pthread_attr_init(&attr);
pthread_attr_setstack(&attr, stack, STACK_SIZE);
printf("stack: %p\n", stack);
if (pthread_create(&thread, &attr, thread_func, NULL) != 0) {
perror("pthread_create");
return 1;
}
const uintptr_t stack_bottom_align = ((uintptr_t)stack);
uint32_t *start = (uint32_t *)stack_bottom_align;
const uint32_t *end = (uint32_t *)(stack + STACK_SIZE - sizeof(uint32_t));
int found = 0;
for (; start <= end; ++start) {
if (*start == stack_color) {
*start = 0xabcdabcd;
printf("fetch the stack color: %p\n", start);
found = 1;
break;
}
}
pthread_join(thread, NULL);
if (!found) {
fprintf(stderr, "stack color not found\n");
}
pthread_attr_destroy(&attr);
return 0;
}
```
```bash
$ qemu-system-arm -cpu cortex-a7 -nographic -machine virt -kernel build/nuttx
NuttShell (NSH) NuttX-12.10.0
nsh> stack_canarytest
stack: 0x40005278
fetch the stack color: 0x40005288
haha
dump_assert_info: Current Version: NuttX 12.10.0 0d62d83134-dirty Sep 22
2025 14:40:52 arm
dump_assert_info: Assertion failed : at file:
/sched/sched/sched_switchcontext.c:60 task: stack_canarytest process:
stack_canarytest 0x18994
up_dump_register: R0: 400034b0 R1: 00000001 R2: 00000000 R3: 00000000
up_dump_register: R4: 4000bb28 R5: 4000bb28 R6: 400034b0 R7: 00000000
up_dump_register: R8: 000370d2 SB: 40002d50 SL: 00000006 FP: 0000003c
up_dump_register: IP: 40002dc4 SP: 40007130 LR: 00005e50 PC: 00005e50
up_dump_register: CPSR: 600000df
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]