diff --git a/TeensyThreads.cpp b/TeensyThreads.cpp
index d86397b..74f4b59 100644
--- a/TeensyThreads.cpp
+++ b/TeensyThreads.cpp
@@ -48,6 +48,13 @@ extern "C" {
}
}
+extern "C" void stack_overflow_default_isr() {
+ currentThread->flags = Threads::ENDED;
+}
+extern "C" void stack_overflow_isr(void) __attribute__ ((weak, alias("stack_overflow_default_isr")));
+
+// extern unsigned long _estack; // the main thread 0 stack
+
Threads::Threads() : current_thread(0), thread_count(0), thread_error(0) {
// initilize thread slots to empty
for(int i=0; i<MAX_THREADS; i++) {
@@ -65,6 +72,8 @@ Threads::Threads() : current_thread(0), thread_count(0), thread_error(0) {
currentActive = FIRST_RUN;
threadp[0]->flags = RUNNING;
threadp[0]->ticks = DEFAULT_TICKS;
+ // threadp[0]->stack = (uint8_t*)&_estack - DEFAULT_STACK_SIZE;
+ // threadp[0]->stack_size = DEFAULT_STACK_SIZE;
currentUseSystick = 1;
}
@@ -103,6 +112,11 @@ void Threads::getNextThread() {
// First, save the currentSP set by context_switch
threadp[current_thread]->sp = currentSP;
+ // did we overflow the stack (don't check thread 0)?
+ if (current_thread && ((uint8_t*)currentThread->sp - currentThread->stack <= 8)) {
+ stack_overflow_isr();
+ }
+
// Find any priority threads
int priority_thread = -1;
for(int i=0; i < MAX_THREADS; i++) {
diff --git a/TeensyThreads.h b/TeensyThreads.h
index 8ea7d7b..7dc7017 100644
--- a/TeensyThreads.h
+++ b/TeensyThreads.h
@@ -77,6 +77,7 @@ extern "C" {
void context_switch_pit_isr(void);
void systick_isr(void);
void loadNextThread();
+ void stack_overflow_isr(void);
}
// The stack frame saved by the interrupt