A task stack real-time detection and protection method suitable for embedded systems
Patent Information
- Application Number
- CN202611146231.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-30
- Publication Date
- 2026-10-13
AI Technical Summary
[0008]针对现有技术中无法实时检测任务栈是否溢出和定位的技术问题,本发明提出一种适用于嵌入式系统的任务栈实时检测与防护方法
本发明通过读取写入编码和任务栈边界表进行比对,能实时检测栈是否溢出,而非下一次上下文切换,提高了检测的效率;同时通过任务栈边界表可准确识别发生溢出的任务及溢出地址;
Smart Images

Figure CN122903236A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of memory management technology, and in particular to a method for real-time detection and protection of task stacks in embedded systems. Background Technology
[0002] In resource-constrained embedded systems, stack overflow is one of the leading causes of system crashes. Embedded systems typically have only tens to hundreds of kilobytes of storage space, and the stack space for each task is strictly limited (often only a few hundred bytes). Once a task's local variables, function call depth, interrupt nesting, etc., exceed the reserved space, the stack will overflow forward (towards lower addresses), overwriting adjacent memory regions (which could be the stacks of other tasks, global variables, heap memory, or even kernel data structures).
[0003] Stack overflow has the following characteristics, making it one of the most challenging types of failures in embedded development: (1) Strong concealment: Overflow does not necessarily lead to an immediate collapse. It may first manifest as "occasional" data disorder, which is extremely difficult to locate. (2) The damage area is uncertain: the memory area that overflows and tramples depends on the runtime task arrangement and stack usage, and the phenomenon is different each time; (3) Difficult to trace after the fact: The scene is lost after the system is reset, and can only be inferred from the limited logs.
[0004] In existing technologies, FreeRTOS (a real-time operating system) provides two methods for detecting stack overflows (configured via configCHECK_FOR_STACK_OVERFLOW): Method 1 (Stack Pointer Check): Checks whether the current stack pointer is out of the valid range when switching tasks, but it only checks when a task is swapped out. It does not detect runtime overflows and cannot locate the specific overflow location. Method 2 (Canary Check): When a task is created, a marker value is filled at the end of the stack. When switching contexts, it is checked whether the marker has been overwritten. However, this method only checks when the context is switched, which is lagging and overflow may skip the marker area, resulting in missed detections.
[0005] Both of the above methods, upon detecting an overflow, only call the vApplicationStackOverflowHook() hook function, without providing any automatic recovery or isolation mechanism; they simply log the data and then perform a system reset.
[0006] In current technology, some ARM Cortex-M series processors' MPUs (Memory Protection Units) can be configured with stack protection zones. However, embedded systems, due to space constraints, generally do not have stack protection zones for hardware protection; even if stack protection zones are configured, they usually only trigger exceptions and lack adaptive recovery and prevention mechanisms.
[0007] Meanwhile, existing technologies propose stack overflow detection schemes based on read-only memory attributes or isolated regions, but they share common drawbacks: they only perform detection without recovery / isolation / adaptation, and they are not adapted for embedded systems. Alternatively, they are geared towards cloud computing platforms and rely on checkpoint rollback mechanisms, resulting in huge storage and time overhead, making them unsuitable for resource-constrained embedded systems. Summary of the Invention
[0008] To address the technical problem that existing technologies cannot detect and locate task stack overflow in real time, this invention proposes a real-time task stack detection and protection method suitable for embedded systems.
[0009] To achieve the above objectives, the present invention provides the following technical solution: A method for real-time detection and protection of task stacks in embedded systems includes the following steps: S1: Real-time detection of the write code in the first register to determine if it is a stack overflow. If so, write the target address of the stack overflow into the second register; otherwise, continue detection. S2: Read the target address of the stack overflow in the second register, then traverse the preset task stack boundary table, and determine whether the target address of the stack overflow is in the bottom overflow area of the known task stack. If so, it is determined to be a task stack overflow. S3: Isolate the tasks that overflow the task stack, then compare the address of the task stack with the reserved warning area to determine the overflow level, and execute different handling strategies according to the overflow level.
[0010] Preferably, in step S1, the method for determining stack overflow is as follows: The machine mode exception handling mechanism of the embedded system is used as the detection entry point to detect the write code of the first register in real time. If the write code is 0x03, it is determined to be a stack overflow.
[0011] Preferably, the first register is the mcause register.
[0012] Preferably, in step S2, the task stack boundary table records the start address, end address, and bottom overflow area of each task stack.
[0013] Preferably, step S3 includes the following steps: S3-1: Isolate tasks that overflow the task stack; S3-2: Compare the address of the task stack with the reserved warning zone to obtain the overflow level; S3-3: Execute the corresponding handling strategy according to the overflow level.
[0014] Preferably, in step S3-2, the overflow level is determined as follows: When the address of the task stack is within the reserved warning zone, the overflow level is level one; When the address of the task stack exceeds the reserved warning zone but is within the address of an adjacent task stack, the overflow level is level two. When the address of the task stack exceeds the reserved warning area but is within the kernel data or global variable address, the overflow level is three.
[0015] Preferably, in step S3-3, when the overflow level is level one, the corresponding processing strategy is: to isolate the overflowing task, record the log, and let other tasks continue to run; When the overflow level is level 2, the corresponding handling strategy is to isolate the overflowing task from the tasks adjacent to it, record the log, and let other tasks continue to run. When the overflow level is level three, the corresponding handling strategy is to output the diagnostic log and then perform a safe system reset.
[0016] Preferably, it also includes S4: automatically adjusting the task stack allocation strategy based on historical overflow task characteristics.
[0017] Preferably, S4 includes: S4-1: Construct a feature database based on the record features of historical overflow tasks; S4-2: Traverse the feature database based on the type of the task to be assigned, determine whether the same type of task has overflowed, and if so, adjust the size of the task stack; otherwise, continuously check the overflow status of each stack.
[0018] Preferably, in S4-1, the recording characteristics of the overflow task include task type identifier, overflow depth, frequency of occurrence of the same task type, call stack snapshot, and system load context.
[0019] In summary, by adopting the above technical solution, the present invention has at least the following beneficial effects compared with the prior art: This invention compares the read and write encoding with the task stack boundary table to detect stack overflow in real time, rather than the next context switch, thus improving detection efficiency. At the same time, the task stack boundary table can accurately identify the task that overflows and the overflow address. At the same time, when a stack overflow occurs, the overflowing task stack can be isolated and different handling strategies can be implemented to prevent the overflow damage from spreading to other healthy tasks or the kernel. The task stack allocation strategy is automatically adjusted based on historical overflow characteristics to avoid recurrence of similar overflows and achieve adaptive protection adjustment. Attached Figure Description Figure 1 This is a schematic diagram of a real-time task stack detection and protection method applicable to embedded systems according to an exemplary embodiment of the present invention.
[0020] Figure 2 This is a schematic diagram illustrating a task stack overflow handling strategy according to an exemplary embodiment of the present invention.
[0021] Figure 3 This is a schematic diagram of the task stack memory distribution according to an exemplary embodiment of the present invention.
[0022] Figure 4 A schematic diagram illustrating the adjustment of the task stack allocation strategy according to an exemplary embodiment of the present invention. Detailed Implementation
[0023] The present invention will be further described in detail below with reference to embodiments and specific implementation methods. However, this should not be construed as limiting the scope of the above-described subject matter of the present invention to the following embodiments; all technologies implemented based on the content of the present invention fall within the scope of the present invention.
[0024] In the description of this invention, it should be understood that the terms "longitudinal", "lateral", "up", "down", "front", "rear", "left", "right", "vertical", "horizontal", "top", "bottom", "inner", "outer", etc., indicate the orientation or positional relationship based on the orientation or positional relationship shown in the accompanying drawings. They are only for the convenience of describing this invention and simplifying the description, and do not indicate or imply that the device or element referred to must have a specific orientation, or be constructed and operated in a specific orientation. Therefore, they should not be construed as limitations on this invention.
[0025] like Figure 1 As shown, this invention provides a method for real-time detection and protection of task stacks in embedded systems, specifically including the following steps: S1: Real-time detection of the write code in the first register (mcause register) to determine if there is a stack overflow. If so, proceed to S2; otherwise, continue detection.
[0026] In this embodiment, the embedded system can be a RISC-V processor architecture. The architecture uses its own machine-mode exception handling mechanism (Machine-Mode Trap) as the detection entry point to detect the write encoding of the mcause register (which records the exception cause code) in real time and determine the stack state.
[0027] If the written code is 0x03, it is determined to be a stack overflow and proceeds to S2; if the written code is not 0x03, it is determined not to be a stack overflow, but may be other abnormal faults, which can be handled according to the preset exception handling procedure, but this is not the direction of the present invention, and will not be elaborated here.
[0028] S2: Read the target address of the stack overflow in the second register, then traverse the preset task stack boundary table to determine whether the target address of the stack overflow is in the bottom overflow area of the known task stack. If so, it is determined to be a task stack overflow and enters S3. Otherwise, it is handled according to the preset exception handling procedure.
[0029] In this embodiment, the second register is the mtval register, which is used to record the target address of the stack overflow.
[0030] In this embodiment, the task stack boundary table is used to record the start address, end address, and bottom overflow area (the area N bytes down from the end address of the stack) of each task stack, as shown in Table 1.
[0031] Table 1. Task Stack Boundary Table For example, if the target address of the stack overflow is 0x2000 1000, after traversing the task stack boundary table based on the target address of the stack overflow, it is found that the target address of the stack overflow is in the bottom overflow area of the i-th task stack. Then, it can be determined that the i-th task stack is overflowing, and the address of the i-th task stack is written into the third register (mepc register) to achieve accurate location of the overflow stack and assist in subsequent debugging.
[0032] In this embodiment, this step has significant advantages compared to the canary inspection method of FreeRTOS in the prior art, as shown in Table 2.
[0033] Table 2. Advantages of this step compared to the FreeRTOS canary check method. S3: Isolate the tasks that overflow the task stack, then compare the address of the task stack with the reserved warning area to determine the overflow level, and execute different handling strategies according to the overflow level.
[0034] like Figure 2 As shown, step S3 specifically includes the following steps: S3-1: First, isolate the tasks that overflow the task stack.
[0035] In existing technologies, when a task stack overflow is detected, the system is reset directly, affecting all tasks and reducing task processing efficiency.
[0036] In this embodiment, when a task stack overflow is detected, the FreeRTOS kernel API (such as vTaskSuspend()) is called immediately in machine mode to suspend the overflowing task, preventing it from continuing to execute and further spreading and causing damage.
[0037] S3-2: Compare the address of the task stack with the reserved warning zone to obtain the overflow level.
[0038] In this embodiment, the reserved warning area is located at the bottom (low address end) of the task stack allocation space. It is a space that is not actually used, such as 16-32 bytes, and is filled with known flag values (such as 0xA5A5A5A5).
[0039] Furthermore, such as Figure 3 As shown, the reserved warning area is located above the bottom overflow area (at a higher address): the reserved warning area is inside the stack allocation boundary, and the bottom overflow area is outside the stack allocation boundary.
[0040] When the address of the task stack is within the reserved warning zone, the overflow level is level one; When the address of a task stack exceeds the reserved warning zone but is within the address of an adjacent task stack (which can be queried through the task stack boundary table), the entities (tasks, variables) belonging to that adjacent memory are marked as unreliable, with an overflow level of two. When the address of the task stack exceeds the reserved warning area, and is within the range of the constructed memory region table, the overflow level is three.
[0041] In this embodiment, during the compilation and linking process of the embedded system, the linker script (such as linker.ld) defines the start and end addresses of each memory segment. The compiler / linker exports segment boundary symbols in the final binary file, which can be directly used as addresses at runtime, as shown in Table 3.
[0042] Table 3. Common Kernel Data and Global Variable Segments In this embodiment, firstly during the system initialization phase (such as before board_init() or main()), the memory region table can be constructed by reading the segment boundary symbols exported by the linker script using the following code.
[0043] Then, by traversing the memory region table using the following code, it can be determined whether the address of the broken task stack is within the range of the memory region table.
[0044] For example, a memory region table is constructed for the PG2 platform, as shown in Table 4.
[0045] Table 4. Memory Region Table of PG2 Platform When Task A overflows: If mtval = 0x2000_7F80 (within the reserved warning zone of Task A), then the overflow level is determined to be level one; If mtval = 0x2000_8100 (within the stack address of Task B), then the overflow level is determined to be level two; If mtval = 0x2000_5000 (within the .bss segment), since is_in_kernel_or_global() hits the .bss entry after traversing the table, the overflow level is determined to be level three.
[0046] S3-3: Execute the corresponding handling strategy according to the overflow level.
[0047] In this embodiment, when the overflow level is level one, the corresponding handling strategy is to isolate or suspend the overflowing task, record the log, and let other tasks continue to run. When the overflow level is level 2, the corresponding handling strategy is to isolate or suspend the overflowing task and adjacent tasks, log the overflow, and let other tasks continue to run. When the overflow level is level three, the corresponding handling strategy is to output the diagnostic log and then perform a safe system reset.
[0048] In this embodiment, after the overflow task is processed, an adaptive protection strategy is also adopted to prevent the recurrence of similar overflows in the future.
[0049] S4: Automatically adjust the task stack allocation strategy based on historical overflow task characteristics.
[0050] In this embodiment, as Figure 4 As shown, S4 specifically includes the following steps.
[0051] S4-1: Construct a feature database based on historical overflow tasks.
[0052] In this embodiment, all historical overflow tasks are recorded in the system, but can be retrieved directly when needed.
[0053] Therefore, this invention can directly retrieve the record features of the corresponding overflow task from the system to construct a feature database. The record features of the overflow task include task type identifier (function entry / task priority / module), overflow depth (the difference between the actual stack space used and the stack space allocated by the system), occurrence frequency (the frequency of overflows of the same task type), call stack snapshot (the function call chain that triggered the overflow), and system load context (the number of tasks and memory usage when it occurred).
[0054] Furthermore, the greater the overflow depth, the more the stack requirements of this type of task exceed expectations, reflecting the extent to which the actual stack consumption of this type of task exceeds the expected allocation size, requiring a larger stack space to be allocated for subsequent similar tasks.
[0055] S4-2: Traverse the feature database based on the type of the task to be assigned, determine whether the same type of task has overflowed, adjust the task stack size if so, otherwise do not adjust the task stack size, and continuously monitor the running status of each stack.
[0056] In this embodiment, when a task to be assigned is created using xTaskCreate(), the type of the task to be assigned is first determined (including communication tasks, timer tasks, monitoring tasks, ATE test tasks, idle tasks, etc.), which can be determined through the address of the entry function. The entry function pointer (`pxTaskCode`) passed to each task during creation naturally identifies the type of task. Tasks with the same entry function have the same execution logic and similar stack usage patterns. For example, the entry function for an HPLC communication (High-speed Power Line Communications) task is `plc_task()`, the entry function for a CRC (Cyclic redundancy check) calculation task is `crc_task()`, and the entry function for an ATE (Automatic test equipment) test task is `ate_test_task()`.
[0057] In this embodiment, type tags can also be attached to tasks when building the system, including communication tasks, timer tasks, monitoring tasks, ATE test tasks, idle tasks, etc. Alternatively, the FreeRTOS task name (pcName parameter) can be used as the basis for type mapping.
[0058] For example, the task types for the PG2 HPLC communication chip firmware are shown in Table 5.
[0059] Table 5. Task Type Classification Table Then, the adaptive allocator queries the historical feature database using the entry function address as the index key to determine whether the same type of task has ever overflowed.
[0060] (1) If the feature database is traversed and overflow is found in the same type of task, the size of the task stack will be automatically increased: Adjusted stack size = max(user request size, baseline size × K); Where K represents the safety factor. α and β are configurable learning rate parameters.
[0061] (2) If there is no overflow of the same type of task and the space utilization of the task stack is greater than 80% (the space utilization of the task stack can be viewed through the uxTaskGetStackHighWaterMark function), then a warning message will be issued.
[0062] In this embodiment, the stack height watermark of each task is continuously monitored, and the historical feature database is dynamically updated.
[0063] Those skilled in the art will understand that the above embodiments are specific examples of implementing the present invention. In practical applications of persistent media (such as server disks, NAS, and object storage), various changes in form and detail can be made without departing from the spirit and scope of the present invention.
Claims
1. A method for real-time detection and protection of task stacks in embedded systems, characterized in that, Specifically, the following steps are included: S1: Real-time detection of the write code in the first register to determine if it is a stack overflow. If so, write the target address of the stack overflow into the second register; otherwise, continue detection. S2: Read the target address of the stack overflow in the second register, then traverse the preset task stack boundary table, and determine whether the target address of the stack overflow is in the bottom overflow area of the known task stack. If so, it is determined to be a task stack overflow. S3: Isolate the tasks that overflow the task stack, then compare the address of the task stack with the reserved warning area to determine the overflow level, and execute different handling strategies according to the overflow level.
2. The method for real-time detection and protection of task stacks in embedded systems as described in claim 1, characterized in that, In S1, the method for determining stack overflow is as follows: real-time detection of the write code of the first register; if the write code is 0x03, then it is determined to be a stack overflow.
3. The method for real-time detection and protection of task stacks in embedded systems as described in claim 2, characterized in that, The first register is the mcause register.
4. The method for real-time detection and protection of task stacks in embedded systems as described in claim 1, characterized in that, In S2, the task stack boundary table records the start address, end address, and bottom overflow area of each task stack.
5. The method for real-time detection and protection of task stacks in embedded systems as described in claim 1, characterized in that, S3 includes the following steps: S3-1: Isolate tasks that overflow the task stack; S3-2: Compare the address of the task stack with the reserved warning zone to obtain the overflow level; S3-3: Execute the corresponding handling strategy according to the overflow level.
6. The method for real-time detection and protection of task stacks in embedded systems as described in claim 5, characterized in that, In S3-2, the overflow level is determined as follows: When the address of the task stack is within the reserved warning zone, the overflow level is level one; When the address of the task stack exceeds the reserved warning zone but is within the address of an adjacent task stack, the overflow level is level two. When the address of the task stack exceeds the reserved warning area but is within the kernel data or global variable address, the overflow level is three.
7. The method for real-time detection and protection of task stacks in embedded systems as described in claim 5, characterized in that, In S3-3, when the overflow level is level 1, the corresponding handling strategy is: isolate the overflowing task, record the log, and let other tasks continue to run; When the overflow level is level 2, the corresponding handling strategy is to isolate the overflowing task and the tasks adjacent to the overflowing task, record the log, and let other tasks continue to run. When the overflow level is level three, the corresponding handling strategy is to output the diagnostic log and then perform a safe system reset.
8. The method for real-time detection and protection of task stacks in embedded systems as described in claim 1, characterized in that, It also includes S4: automatically adjusting the task stack allocation strategy based on historical overflow task characteristics.
9. A method for real-time detection and protection of task stacks in embedded systems as described in claim 8, characterized in that, S4 includes: S4-1: Construct a feature database based on the record features of historical overflow tasks; S4-2: Traverse the feature database based on the type of the task to be assigned, determine whether the same type of task has overflowed, and if so, adjust the size of the task stack; otherwise, continuously check the overflow status of each stack.
10. A method for real-time detection and protection of task stacks in embedded systems as described in claim 9, characterized in that, In S4-1, the recording characteristics of the overflow task include task type identifier, overflow depth, frequency of occurrence of the same task type, call stack snapshot, and system load context.