Is Incorrect Thread Stack Allocation Causing System Failures? Here’s How to Solve It!
A common issue for beginners in embedded operating systems is improper thread stack allocation, which can lead to unexpected system failures.
- Locate the problem:
New users of RT-Thread often face the following issue when creating thread:
2. Problem Analysis
From the terminal output, we can extract the following key information:
- The thread where the exception occurred is identified as entry.
2) The stack size of the thread is 0x100.
3) SCB_CFSR_UFSR: 0x01 UNDEFINSTR
The UNDEFINSTR
error typically occurs when the PC pointer attempts to execute an invalid instruction, often due to pointing to an illegal address. Based on point (1), the issue is traced to the entry thread. From point (2), the stack size of the thread appears insufficient, leading to a preliminary diagnosis of a stack overflow in the entry thread.
3. Resolving the Issue
The root cause was identified as a thread stack overflow due to an insufficient stack size. Upon reviewing the thread’s entry function, it was found that a large array was defined within the thread, further confirming the stack overflow issue.
Solving the problem involved a process of analysis and iterative testing, guided by both experience and diagnostic tools:
- Increase the stack size: Adjusting the stack size resolved the issue, allowing the entry thread to run normally.
- Enable kernel stack overflow detection: This feature flagged the problem with the message:
msh > thread: entry stack overflow
.
Ultimately, the stack size was confirmed to be too small, with the large array in the thread exacerbating the overflow — validating the diagnosis.