Singlechip stack use limit evaluation method and device based on real-time interrupt sampling, storage medium and embedded system

By setting the highest priority periodic interrupt source in the bare-metal system, monitoring the instantaneous value of the stack pointer register in real time and updating the historical minimum value, the problem of inaccurate stack usage peak monitoring in the prior art is solved, and stack usage evaluation with low overhead and high accuracy is achieved.

CN121996301APending Publication Date: 2026-05-08FORTIOR TECHNOLOGY (SHENZHEN) CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202511956964.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-12-23
Publication Date
2026-05-08

AI Technical Summary

Technical Problem

Existing technologies struggle to monitor peak stack memory usage in real time and accurately while maintaining extremely low system overhead. This results in high resource consumption, inaccurate measurement results, and non-zero stack fill values ​​that may affect program security.

Method used

Set the highest priority periodic interrupt source, directly read the instantaneous value of the hardware stack pointer register when the interrupt service routine ends, dynamically maintain the historical minimum value of the stack pointer, update the historical minimum value according to the growth direction of stack memory, and calculate the historical peak value of stack memory usage.

Benefits of technology

It enables real-time and accurate monitoring of stack usage peaks under low overhead conditions, avoiding the security risks and accuracy defects introduced by scanning memory contents in traditional methods, and ensuring the accuracy of measurement results and the stability of system performance.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121996301A_ABST
    Figure CN121996301A_ABST
Patent Text Reader

Abstract

The invention discloses a single-chip microcomputer stack use limit evaluation method and device based on real-time interrupt sampling, a storage medium and an embedded system. The method comprises the steps that a periodic interrupt source with the highest interrupt priority is set / called; directly reading an instantaneous value of a hardware stack pointer register when the execution of the service program with the highest priority interruption is finished; comparing the read instantaneous value of the stack pointer with a dynamically maintained historical minimum value of the stack pointer; updating the historical minimum value of the stack pointer according to the growth direction of the stack memory; and based on the updated historical minimum value of the stack pointer and the initial address of the stack memory, calculating to obtain a historical use peak value of the stack memory. According to the method, the instantaneous value of the stack pointer register is read when the interruption occurs, so that an accurate measurement result is obtained, and all security risks introduced by writing and detecting memory contents are eradicated. As only the historical minimum value of the stack pointer needs to be dynamically maintained, an accurate measurement result can be obtained under the condition of low performance resource cost.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of stack usage limit assessment technology, and in particular to a method, apparatus, storage medium and embedded system for assessing the stack usage limit of a microcontroller based on real-time interrupt sampling. Background Technology

[0002] In embedded system design based on low-to-mid-range microcontrollers, a bare-metal (operating system-less) foreground / background software architecture is a widely used, efficient, and reliable solution. The stack plays a crucial role in such systems by storing function return addresses, parameters, local variables, and interrupt context. However, stack usage is not fixed but dynamically changes with the nesting depth of function calls, the triggering of interrupt service routines, and the potential nesting level of interrupts. This strong dynamism and uncertainty make stack overflow a highly insidious and potentially dangerous fault in the system. Once a stack overflow occurs, it will corrupt adjacent critical data areas, leading to abnormal program execution, hardware errors, and even system crashes. Furthermore, such faults are difficult to reproduce and debug.

[0003] Currently, the assessment of stack usage limits mainly relies on two types of techniques. The first is static analysis, which generates stack usage reports for each function during the compilation and linking phase using compiler options and combines this with the memory mapping file output by the linker to estimate the theoretical worst-case call path. The limitation of this method is that its analysis is entirely based on the static control flow of the code, and it cannot effectively simulate and cover the extremely complex runtime scenario of random interrupt triggering and its nesting. This often leads to overly pessimistic estimates or significant deviations from actual runtime conditions, resulting in wasted memory resources or invalid assessment results. The second method is dynamic monitoring, with the "stack filling pattern method" being the most typical. This method fills all the reserved stack space with a specific pattern value (e.g., 0xCD) during system initialization. After the system has undergone sufficient testing and running for a period of time, the entire stack space is scanned to find the boundary between the overwritten and unoverwritten pattern values, thereby inferring the historical maximum stack depth during runtime. While this method is closer to actual operating conditions than static analysis, it still has three inherent drawbacks: First, traversing and scanning the entire reserved stack area is a computationally intensive operation. Even at a low frequency, it continuously consumes valuable CPU cycles of the microcontroller, introducing a significant performance overhead in resource-constrained applications and affecting the system's real-time responsiveness. Second, the accuracy of this method is based on the assumption that "stack memory data, once written, will not change." However, in actual operation, after a stack frame used by a previous function or interrupt service routine exits, the corresponding memory area may be rewritten, overwritten, or even zeroed by subsequent functions or interrupt service routines, thus erasing the previously recorded historical "highest watermark." This makes the scan results unable to reflect the true peak stack usage, potentially providing incorrect safety indications and misleading developers. Secondly, to ensure the accuracy of stack usage trace scanning, choosing a non-zero value for padding is better than 0. However, programmers may define local variables without initializing them before performing operations, such as OR, AND, or increment / decrement operations. Since these variables are habitually assumed to be 0, filling the stack with a non-zero value may lead to unexpected results and affect program safety. If the padding value is 0, local variables will frequently calculate to 0, resulting in the failure to detect stack usage traces. Thirdly, some functions define local variables that are not actually used. Without compiler optimization, these local variables still occupy stack space. In such cases, padding scans may miss them, leading to lower evaluation results.

[0004] Existing technologies struggle to monitor peak stack memory usage in real-time and accurately while maintaining extremely low system overhead. Therefore, a new solution is urgently needed that can achieve real-time, low-overhead, and accurate measurement of peak stack usage to address the problems of high resource consumption, inaccurate measurement results, and the impact of non-zero values ​​on program security inherent in existing technologies. Summary of the Invention

[0005] The main objective of this invention is to provide a method for evaluating the usage limits of a microcontroller stack based on real-time interrupt sampling, aiming to solve the problems of high resource consumption and inaccurate measurement results in the prior art.

[0006] To achieve the above objectives, the present invention proposes a microcontroller stack usage limit evaluation method based on real-time interrupt sampling, which includes: setting / calling a periodic interrupt source with the highest interrupt priority; When the service routine for the highest priority interrupt finishes execution, the instantaneous value of the hardware stack pointer register is read directly. The instantaneous value of the read stack pointer is compared with a dynamically maintained historical minimum value of the stack pointer; and the historical minimum value of the stack pointer is updated according to the growth direction of the stack memory. Based on the updated historical minimum value of the stack pointer and the starting address of the stack memory, the historical peak value of stack memory usage is calculated.

[0007] Optionally, updating the historical minimum value of the stack pointer according to the growth direction of the stack memory specifically includes: If the stack memory grows towards lower addresses, and the instantaneous value of the stack pointer is less than the historical minimum value of the stack pointer, then the instantaneous value is used to update the historical minimum value of the stack pointer.

[0008] Optionally, the microcontroller stack usage limit evaluation method based on real-time interrupt sampling further includes: During system initialization, the historical minimum value of the stack pointer is initialized to the starting address of the stack memory.

[0009] Optionally, the calculation obtains the historical peak usage of stack memory, and then further includes: Compare the historical usage peak with a preset security threshold; If the historical usage peak exceeds the preset security threshold, a stack overflow warning is triggered.

[0010] Optionally, the historical minimum value of the stack pointer is stored in non-volatile memory to retain historical peak information after system reset or wake-up from hibernation.

[0011] Optionally, the period of the periodic interrupt source is not an integer multiple of the period of any other periodic task in the microcontroller system.

[0012] The present invention also proposes a storage medium storing a microcontroller stack usage limit evaluation program based on real-time interrupt sampling. When the program is executed by a microprocessor, it implements the steps corresponding to the microcontroller stack usage limit evaluation method based on real-time interrupt sampling.

[0013] This invention also proposes a microcontroller stack usage limit evaluation device based on real-time interrupt sampling, comprising: The interrupt configuration module is used to set a periodic interrupt source and configure it as the highest priority interrupt in the microcontroller system. The stack pointer sampling module is used to directly read the instantaneous value of the hardware stack pointer register when the service routine of the highest priority interrupt finishes execution; The comparison and update module is used to compare the instantaneous value of the read stack pointer with a dynamically maintained historical minimum value of the stack pointer, and update the historical minimum value of the stack pointer according to the growth direction of the stack memory. The peak calculation module is used to calculate the historical peak usage of stack memory based on the historical minimum value of the stack pointer and the starting address of the stack memory.

[0014] Optionally, the period of the periodic interrupt source configured by the interrupt configuration module is not an integer multiple of the period of any other periodic task in the microcontroller system.

[0015] The present invention also proposes an embedded system, comprising: microprocessor; Memory, used to store program instructions and as stack memory; A hardware timer is configured to generate periodic interrupts; The microprocessor is configured to execute program instructions stored in the memory to implement the microcontroller stack usage limit evaluation method based on real-time interrupt sampling.

[0016] This invention discloses a method for evaluating the stack usage limits of a microcontroller based on real-time interrupt sampling. The method includes: setting a periodic interrupt source and configuring it as the highest priority interrupt in the microcontroller system; directly reading the instantaneous value of the hardware stack pointer register when the service routine of the highest priority interrupt finishes execution; comparing the read instantaneous stack pointer value with a dynamically maintained historical minimum stack pointer value; updating the historical minimum stack pointer value according to the growth direction of the stack memory; and calculating the historical peak usage of the stack memory based on the updated historical minimum stack pointer value and the starting address of the stack memory. This invention obtains accurate measurement results by setting the highest priority periodic interrupt source and reading the instantaneous value of the stack pointer register when an interrupt occurs. Since only the historical minimum stack pointer value needs to be dynamically maintained, accurate measurement results can be obtained with low performance resource consumption. Attached Figure Description

[0017] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on the structures shown in these drawings without creative effort.

[0018] Figure 1 This is a schematic diagram illustrating the steps of an embodiment of the microcontroller stack usage limit evaluation method based on real-time interrupt sampling according to the present invention. Figure 2 This is a schematic diagram of CLK scheduling delay timing coverage; Figure 3 This is a schematic diagram of fixed-period timing sampling; Figure 4 This is a schematic diagram of random time-series sampling.

[0019] The realization of the objective, functional features and advantages of the present invention will be further explained in conjunction with the embodiments and with reference to the accompanying drawings. Detailed Implementation

[0020] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of the present invention, and not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those of ordinary skill in the art without creative effort are within the scope of protection of the present invention.

[0021] It should be noted that all directional indications (such as up, down, left, right, front, back, etc.) in the embodiments of the present invention are only used to explain the relative positional relationship and movement of each component in a certain specific posture (as shown in the figure). If the specific posture changes, the directional indication will also change accordingly.

[0022] In this invention, unless otherwise explicitly specified and limited, the terms "connection," "fixed," etc., should be interpreted broadly. For example, "fixed" can mean a fixed connection, a detachable connection, or an integral part; it can mean a mechanical connection or an electrical connection; it can mean a direct connection or an indirect connection through an intermediate medium; it can mean the internal communication of two components or the interaction between two components, unless otherwise explicitly limited. Those skilled in the art can understand the specific meaning of the above terms in this invention according to the specific circumstances.

[0023] Furthermore, in this invention, descriptions involving "first," "second," etc., are for descriptive purposes only and should not be construed as indicating or implying their relative importance or implicitly specifying the number of technical features indicated. Therefore, a feature defined with "first" or "second" may explicitly or implicitly include at least one of that feature. Additionally, the technical solutions of the various embodiments can be combined with each other, but only on the basis of being achievable by those skilled in the art. When the combination of technical solutions is contradictory or impossible to implement, such a combination of technical solutions should be considered non-existent and not within the scope of protection claimed by this invention.

[0024] Reference Figure 1 This invention provides a method for evaluating the usage limits of a microcontroller stack based on real-time interrupt sampling, comprising: Configure / invoke a periodic interrupt source with the highest interrupt priority; When the service routine for the highest priority interrupt finishes execution, the instantaneous value of the hardware stack pointer register is read directly. The instantaneous value of the read stack pointer is compared with a dynamically maintained historical minimum value of the stack pointer; and the historical minimum value of the stack pointer is updated according to the growth direction of the stack memory. Based on the updated historical minimum value of the stack pointer and the starting address of the stack memory, the historical peak value of stack memory usage is calculated.

[0025] It should be explained that this method is applied to microcontroller systems / embedded systems to monitor the peak usage of stack memory in real time and accurately during bare-metal system operation.

[0026] Step S10: Set / call a periodic interrupt source with the highest interrupt priority.

[0027] It should be explained that the active sampling triggering mechanism constructed and adopted in this invention does not passively wait or perform a full memory scan. Instead, it utilizes existing or specially configured hardware timers to create a sampling pulse sequence evenly distributed along the timeline. This is set to the "highest priority" to ensure that the sampling behavior cannot be preempted. This means that regardless of whether the system is currently deep within the main program loop or in a nested service of a lower-priority interrupt, the sampling interrupt can immediately preempt the CPU, thereby ensuring that the sampling point can "penetrate" any execution state of the system, including the moment of the "deepest interrupt nest," which theoretically consumes the most stack. The highest priority ensures that sampling events are not missed, guaranteeing the capture of stack usage in extreme scenarios. It should also be explained that the sources of periodic interrupts in this invention can be divided into two categories: 1. Active Configuration. Initialize a hardware timer peripheral and configure its overflow interrupt priority to the highest in the system. This is the most direct and controllable method, allowing for free definition of the sampling period.

[0028] 2. Utilize an existing, inherent, high-priority periodic interrupt in the system. For example, the System Tick interrupt in the ARM Cortex-M core, if configured with the highest priority. This invention can "call" or "hook" to the service routine of this existing interrupt, inserting sampling logic. This approach reuses existing resources, eliminates the need for additional hardware timers, and simplifies implementation.

[0029] Furthermore, the sampling behavior in this step is bound to the hardware interrupt mechanism, making it a small task that is automatically triggered by hardware and has a controllable execution time. Compared with traditional software traversal scanning, it has an efficiency advantage in triggering and execution mechanisms. In the interrupt nesting model, low-priority interrupts can be preempted by high-priority interrupts. Setting the sampling interrupt to the highest priority means that this "observation window" is independent of the current software state of the system—whether it is located in a deep function call in the main loop or trapped in a nest of lower-priority interrupts—it can be opened in real time. This ensures that the sampling point can collect the stack image of the system in any possible software state, especially those fleeting "stack usage spikes" formed by complex interrupt nesting. Mechanistically, it utilizes the inherent characteristics of the CPU hardware interrupt controller, elevating the sampling behavior to the hardware scheduling level, making it a mandatory behavior that is not hindered by software flow.

[0030] Periodic interrupt sources construct a uniformly distributed "observation window sequence" across time, much like digital sampling of a continuous signal. A fixed, appropriately frequencyd periodic interrupt discretizes the system's continuous runtime into a series of equally spaced sampling points (t1, t2, t3...). This ensures the systematic and continuous nature of the observations across time. Furthermore, the sampling process itself is constrained within extremely short interrupt service routines, with defined start and end times and constant overhead. This transforms the monitoring activity from "a vague, time-consuming operation" into "a deterministic, minute event," making the total system overhead predictable and quantifiable. Periodicity guarantees uniform coverage of sampling over long periods, enabling a "time-for-space" approach to probabilistically capture all extreme cases. It is crucial to note that, due to its high-priority configuration, it can preempt any other task; the sampled state represents the system's state at that specific instant before the observation process, not the state after being affected by a lengthy scanning process.

[0031] Step S20: When the service routine of the highest priority interrupt finishes execution, directly read the instantaneous value of the hardware stack pointer register.

[0032] It's important to note that the read operation is performed at the end of the highest-priority InterruptServiceRoutine (ISR). This timing has special significance: First, the ISR's own stack frame (including the return address and context register) has been pushed onto the stack; second, any other nested interrupt services with lower priority that might have been triggered during this response cycle have also completed and returned to this ISR. Therefore, the stack pointer register (i.e., the stack pointer SP, SP) at this moment precisely points to the lowest address of the stack space shared by all currently occurring but not yet returned function calls and nested interrupts (for a downward-growing stack), i.e., a snapshot of the current stack usage. Since this interrupt has the highest priority, there are no higher priorities. All interrupts of the same or lower priority that might have been triggered during this interrupt response have also completed their full "trigger-response-return" lifecycle. Because interrupts cannot nest themselves, but other interrupts that are triggered during the execution of this ISR will be responded to immediately before this ISR finishes execution and returns to the main program. Therefore, at the end of the ISR, the system has just completed a full microcycle of "jumping from the main program or a low-priority interrupt state to the highest-priority ISR, possibly nesting other interrupts, and finally all interrupt services being completed." At this point, the SP value precisely points to the bottom boundary of the stack space comprised of all active function call frames and interrupt context frames within this microcycle. This is the golden sampling point that reflects the "most complex instantaneous state."

[0033] "Directly reading hardware registers" means bypassing any intermediate variables or inferences at the software level, obtaining first-hand data directly from the CPU hardware. It acquires the physical stack pointer value directly provided by the CPU hardware, ensuring data accuracy and eliminating software-level latency or errors. Furthermore, sampling at the end of the ISR naturally includes the stack consumption of the highest priority interrupt itself, allowing the measurement model to automatically incorporate the impact of the sampling mechanism itself on the stack, resulting in more rigorous evaluation results. Because it directly reads instantaneous register values, it completely bypasses dependence on volatile RAM memory data, fundamentally eliminating the problem of "loss of historical traces" caused by subsequent operations overwriting stack memory.

[0034] Step S30: Compare the instantaneous value of the read stack pointer with a dynamically maintained historical minimum value of the stack pointer; and update the historical minimum value of the stack pointer according to the growth direction of the stack memory.

[0035] It should be noted that this step introduces a global variable (the historical minimum value of the stack pointer) that persists throughout the entire system's lifecycle. This variable stores the "minimum SP value" observed since system startup (for a downward-growing stack, the smaller the SP value, the deeper the stack is used). The historical minimum value of the stack pointer is independent of the stack memory and is typically stored in the global data area. Its lifecycle is the same as the system's runtime, and its mission is to faithfully record the minimum SP value (corresponding to the maximum stack depth) seen since initialization.

[0036] At each sampling point, the new instantaneous SP value is compared with the historical record. If the current stack is deeper (smaller SP), the record is updated to ensure that the historical minimum stack pointer always records the SP value at the deepest stack usage across all sampling moments. Regardless of how long the system runs or how many sampling points are generated, it only retains that unique "extreme point" information, maintaining a constant memory footprint. This step is crucial for transforming "instantaneous measurement" into "historical peak tracking."

[0037] It is easy to understand that this step dynamically maintains the peak stack usage information of the system so far with constant time complexity through a simple comparison-update logic, with minimal memory usage (only one variable); it only performs one integer comparison and one conditional assignment operation, which is usually completed within a few CPU clock cycles, and has a negligible impact on system performance, making it suitable for resource-constrained environments (microcontroller systems).

[0038] Step S40: Based on the updated historical minimum value of the stack pointer and the starting address of the stack memory, calculate the historical peak value of stack memory usage.

[0039] It's easy to understand that when it's necessary to know the stack usage limit (such as at the end of a system testing phase, during periodic security checks, or when an alert is triggered), a simple calculation is performed based on the stack's growth direction. For the most common downward-growing stack, the formula is: Historical Peak Usage = Stack Start Address - Historical Minimum Stack Pointer. This calculation is based on exact physical addresses, and the result is a precise value in bytes, directly reflecting the maximum capacity of the stack space occupied. Only one subtraction operation is needed to derive the peak usage from the recorded minimum stack pointer (SP) value, making it extremely efficient and supporting real-time alerting functionality.

[0040] Furthermore, the calculations in this step are not performed at each sampling, but only when the results are needed (such as when the test ends, a system report is issued, or an alert is triggered). This "on-demand calculation" model further reduces unnecessary runtime overhead.

[0041] In this invention, steps S10 and S20 together ensure the efficiency of the sampling mechanism itself (hardware interrupt triggering) and the accuracy of the data source (hardware register reading). This invention establishes a pure state observation channel that does not touch, depend on, or interfere with application data. This fundamentally eliminates all security risks (non-zero value interference) and accuracy defects (zero value confusion, missed statistics) introduced by the "stack filling mode method" due to writing and probing memory contents. Step S3 continuously maintains peak information in a near-zero cost manner. The entire process transforms the scanning operation in the traditional dynamic monitoring method into simple register access and comparison operations, reducing complexity and CPU overhead by several orders of magnitude, while ensuring the real-time performance and accuracy of the data. In addition, through the cooperation of step S2 (reading registers) and step S3 (maintaining independent variables), this method completely eliminates the dependence on the data content of the stack memory area. No matter how the stack memory is repeatedly erased and overwritten, the historical peak information recorded in the historical minimum value of the stack pointer remains unchanged, thus solving the most fatal defect of the traditional dynamic monitoring method—unreliable results.

[0042] This invention discloses a method for evaluating the stack usage limits of a microcontroller based on real-time interrupt sampling. The method includes: setting a periodic interrupt source and configuring it as the highest priority interrupt in the microcontroller system; directly reading the instantaneous value of the hardware stack pointer register when the service routine of the highest priority interrupt finishes execution; comparing the read instantaneous stack pointer value with a dynamically maintained historical minimum stack pointer value; updating the historical minimum stack pointer value according to the growth direction of the stack memory; and calculating the historical peak usage of the stack memory based on the updated historical minimum stack pointer value and the starting address of the stack memory. This invention obtains accurate measurement results by setting the highest priority periodic interrupt source and reading the instantaneous value of the stack pointer register when an interrupt occurs, eliminating all security risks introduced by writing to and probing memory contents. Since only the historical minimum stack pointer value needs to be dynamically maintained, accurate measurement results can be obtained with minimal performance resource consumption.

[0043] In one example, updating the historical minimum value of the stack pointer according to the growth direction of the stack memory specifically includes: If the stack memory grows towards lower addresses, and the instantaneous value of the stack pointer is less than the historical minimum value of the stack pointer, then the instantaneous value is used to update the historical minimum value of the stack pointer.

[0044] It's important to explain that this example provides a way to determine the minimum value in the history of updating the stack pointer. The stack model used by most modern microprocessors and microcontrollers (such as the ARM Cortex-M series, AVR, 8051, etc.) follows a pattern where stack memory grows towards lower memory addresses. In this model, the starting address (top of the stack) is a higher memory address, and as data is pushed onto the stack (PUSH, CALL, interrupt responses), the stack pointer value decreases, pointing to lower memory addresses. Therefore, the size of the stack pointer value is inversely proportional to the stack's depth: the smaller the stack pointer value, the further the stack pointer is from the starting point, and the greater the current stack space usage.

[0045] The historical minimum stack pointer value is initialized to the stack top address (maximum value). During system operation, it records the minimum stack pointer value observed so far. If, in a certain sampling, the instantaneous stack pointer value (SP_instant) is smaller than the historical minimum stack pointer value, it means that the current stack pointer points to a memory location lower than the historical record (i.e., a smaller address value). This physically indicates that within the recently experienced microcycle, the stack consumption reached a deeper level than at any previous recorded moment, touching a lower address.

[0046] Once a deeper stack usage is detected, the historical minimum stack pointer value must be immediately updated to this smaller instantaneous stack pointer value.

[0047] In addition, the single-chip microcontroller stack usage limit evaluation method based on real-time interrupt sampling also includes: During system initialization, the historical minimum value of the stack pointer is initialized to the starting address of the stack memory.

[0048] It is readily understood that this operation is performed between jumping from the hardware reset vector to the C language main function entry point or in its very first code segment. This ensures that the monitored state variables are in a known, deterministic logical state before any functional code in the system (including any functions or interrupts that might use the stack) is executed. During system initialization, the historical minimum value of the stack pointer is initialized to the starting address of the stack memory.

[0049] The initialization operation essentially establishes the "origin" for measuring stack depth. All subsequent calculations of "peak stack usage = starting address of stack memory - historical minimum stack pointer value" are then performed. The calculation yields the historical peak usage of stack memory, followed by: Compare the historical usage peak with a preset security threshold; If the historical usage peak exceeds the preset security threshold, a stack overflow warning is triggered.

[0050] It should be noted that the preset security threshold is a byte-based value (which can be set by the developer) pre-set by the developer based on system headroom requirements. It represents the safe upper limit of stack memory that can be used. This threshold is typically smaller than the total configured stack size. For example, if the system is configured with 1KB (1024 bytes) of stack space, the developer can set the security threshold to 800 bytes, reserving 224 bytes (approximately 22%) as a margin to handle undetected extreme cases or future code changes.

[0051] The historical usage peak is compared with a preset security threshold. The triggering scenarios may include at least: periodic checks (such as periodic execution in system idle tasks or low-priority tasks), on-demand queries (manually triggered by testers), or checks immediately after the peak is updated.

[0052] If the historical peak usage exceeds the preset safety threshold, it indicates a stack overflow risk, and a stack overflow warning is issued. The warning occurs before an actual overflow causes a system crash. Developers or system administrators can receive a risk alert before a failure occurs, giving them the opportunity to take preventative measures, such as restarting specific tasks, reducing workload, or scheduling maintenance. In another example, the historical minimum value of the stack pointer is stored in non-volatile memory to retain historical peak information after system reset or wake-up from hibernation.

[0053] This example aims to address the issue of persisting historical monitoring information across operational cycles, ensuring the continuity and long-term effectiveness of the assessment.

[0054] Non-volatile memory (NVM) refers to storage media whose data is not lost after power failure. In microcontroller systems, it typically includes (but is not limited to): 1. On-chip Flash memory: Used to store program code, and some areas can be planned as data storage areas.

[0055] 2. EEPROM: Designed specifically for data storage, it supports byte erasure and writing and has a long lifespan.

[0056] 3. Backup Register: A small number of registers powered by a backup battery in MCUs with an RTC or backup domain.

[0057] 4. External NVM: such as SPIFlash, etc.

[0058] It's easy to understand that when the system restarts due to watchdog reset, power jitter, active shutdown, or entering low-power sleep mode, all RAM data, including historical peak values ​​recorded in CurSPMIN (usually a RAM variable), will be lost. Without this measure, each system restart will be like the first run, monitoring will start from zero, and it will be impossible to obtain the historical maximum stack usage throughout the entire product lifecycle since it left the factory.

[0059] Recording the worst stack usage scenarios encountered throughout a product's entire lifecycle is crucial for analyzing the field operating environment, assessing the impact of code updates, and predicting potential risks. Even after a system reset following a failure, the stored historical peak data can still be retrieved, providing critical evidence for post-incident analysis.

[0060] This example gives the system memory capabilities, enabling it to faithfully retain the history of the most important stack resource usage across power cycles and reset events, greatly enhancing the system's traceability and analyzability.

[0061] It is particularly important to note that the period of the periodic interrupt source is not an integer multiple of the period of any other periodic task in the microcontroller system.

[0062] This example aims to completely eliminate the systematic observation blind spot caused by the synchronization of sampling points with the period of the observed task. Specifically, it establishes phase sliding with other periodic tasks by ensuring that the periods of these tasks are not integer multiples of each other.

[0063] When the periods of two periodic events are not integer multiples of each other, their phase difference will not repeat within each common period (least common multiple period), but will instead traverse all possible values ​​(in a continuous-time model). In discrete clock systems, due to resolution limitations, the phase difference will slide in fixed steps. This means that there is no stable, repeating phase alignment between the sampling point and the start / execution point of any other task. Their relative positions on the time axis will slide continuously and regularly.

[0064] This means that the interrupt cycle has a fixed deviation of at least one system clock (CLK) cycle from the cycles of all other periodic tasks in the system. This cycle design with a fixed deviation causes the triggering time of the sampling interrupt to produce a continuous phase slip relative to the execution time of any other task.

[0065] For example, if the microcontroller's main frequency is set to 100MHz, and the system has interrupt service routines with periods of 1ms and 100us, as well as periodic tasks processed in the main loop (MAIN function) with periods of 2ms, 10ms, and 100ms, and a high-priority timer interrupt ISR_H with a target period of 100μs, to traverse any combination of ordinary tasks and interrupts and the stack usage at any given time, the period of this interrupt is configured to be 99.99us. This deviates from the target period of 100us by (N>=1) main frequency CLKs. Figure 2 As shown, Figure 2 This is a schematic diagram of CLK scheduling delay timing coverage.

[0066] The following is an example of coverage calculation (taking a 100MHz main frequency and a 1CLK deviation as an example): V_slide = 0.01us (i.e., 1 CLK cycle); I. Covering tasks with a 1ms cycle: N_1ms (the number of CLK cycles corresponding to 1ms) = 1ms / 0.01us = 100,000 times T_cover_1ms (time spent on the 1ms task) = 100,000 × 99.99us ≈ 9.999 seconds It only takes about 10 seconds to scan the stack usage of a 1ms task at various moments, and detects its stack usage depth in 0.01us increments.

[0067] II. Covering tasks with a 10ms cycle: N_10ms (the number of CLK cycles corresponding to 10ms) = 10ms / 0.01us = 1,000,000 times T_cover_10ms (time spent on a 10ms task) = 1,000,000 × 99.99us ≈ 99.99 seconds That is, it takes about 100 seconds to ensure that the entire cycle of a 10ms task is fully covered.

[0068] This design ensures that the distribution of sampling trigger points along the timeline is both random and comprehensive, covering any execution state that may occur during system operation without omission, including extreme moments with the deepest interrupt nesting levels and the most complex function call chains. As a counterexample, Figure 3 The diagram illustrates a fixed-period timing sampling method. The sampling points are strictly aligned, but they always appear in the same phase of task execution, resulting in blind spots in the coverage area. Figure 4 This shows a schematic diagram of random time-series sampling, where the sampling points appear randomly, and theoretically can cover various task times.

[0069] As shown in the calculation example above, a sampling interrupt with a small cycle deviation (such as 1 system clock cycle CLK) will, relative to a 1ms task, slide across the entire execution time window of that 1ms task in steps of 0.01us within approximately 10 seconds. This means that as long as the system runtime is long enough (exceeding the time required to cover a complete sliding cycle), the sampling point will inevitably detect the stack state corresponding to every possible execution moment of the task within its cycle.

[0070] In summary, under the method described in this invention, regardless of whether the timing is differential or random, as long as the system runtime is long enough, the sampling points will inevitably traverse every moment within the target task cycle, eliminating any blind spots and achieving complete detection of stack usage depth. This fundamentally guarantees the reliability and completeness of the stack usage depth evaluation results. This design is particularly effective for capturing complex interrupt nesting scenarios. The random triggering and nesting of interrupts of different priorities will form complex timing combinations with periodic tasks and sampled interrupts. The sampling period, which is not an integer multiple, ensures that the sampling points will not always miss certain specific nested combination moments, thereby significantly increasing the probability of capturing the "worst-case stack depth."

[0071] The present invention also proposes a storage medium storing a microcontroller stack usage limit evaluation program based on real-time interrupt sampling. When the program is executed by a microprocessor, it implements the steps corresponding to the microcontroller stack usage limit evaluation method based on real-time interrupt sampling.

[0072] The storage medium refers to any physical or logical entity that can store program instructions (code) and data and be read by a computer (microprocessor).

[0073] For example, semiconductor memories include read-only memory (ROM), programmable read-only memory (PROM), erasable programmable read-only memory (EPROM), electrically erasable programmable read-only memory (EEPROM), and flash memory (such as NOR Flash and NAND Flash).

[0074] Magnetic storage media: such as hard disks and magnetic tapes.

[0075] Optical storage media: such as CD-ROM and DVD-ROM.

[0076] This invention also proposes a microcontroller stack usage limit evaluation device based on real-time interrupt sampling, comprising: The interrupt configuration module is used to set a periodic interrupt source and configure it as the highest priority interrupt in the microcontroller system. The stack pointer sampling module is used to directly read the instantaneous value of the hardware stack pointer register when the service routine of the highest priority interrupt finishes execution; The comparison and update module is used to compare the instantaneous value of the read stack pointer with a dynamically maintained historical minimum value of the stack pointer, and update the historical minimum value of the stack pointer according to the growth direction of the stack memory. The peak calculation module is used to calculate the historical peak usage of stack memory based on the historical minimum value of the stack pointer and the starting address of the stack memory.

[0077] The interrupt configuration module is used to "set a periodic interrupt source and configure it as the highest priority interrupt in the microcontroller system." Specifically, it sets the operating mode (such as up-counting, auto-reload) and period value (reload register ARR) by writing to a specific hardware timer control register, and sets the preemption priority of the timer interrupt to the highest by writing to the priority setting register of the nested vector interrupt controller (NVIC). It creates a periodic sampling event source and grants it the highest system scheduling privileges, laying the time-space foundation for subsequent sampling actions.

[0078] The stack pointer sampling module is used to "directly read the instantaneous value of the hardware stack pointer register when the service routine of the highest priority interrupt finishes execution." Specifically, it typically uses inline assembly instructions (such as MRSR0,MSP or MRSR0,PSP for ARM Cortex-M) or compiler-provided built-in / internal functions (such as __current_sp() supported by some compilers) to directly read the value of the SP register.

[0079] After the system powers on, the interrupt configuration module runs first (during the main function initialization phase), completing the settings for hardware timers and interrupts. The hardware timers periodically trigger interrupts, the CPU responds to the interrupts, and executes the ISR (In-System Reset). At the end of the ISR, the stack pointer sampling module is executed to obtain the current SP (Stack Pointer) value. The sampled SP value is immediately passed to the comparison and update module. This module accesses its maintained historical minimum value variable, compares it, and decides whether to update. When the user or other parts of the system need to know the stack peak value, the peak value calculation module is called. This module reads the historical minimum value variable and the stack start address constant, calculates and returns the peak value.

[0080] In particular, the period of the periodic interrupt source configured by the interrupt configuration module is not an integer multiple of the period of any other periodic task in the microcontroller system.

[0081] The specific structure of the microcontroller stack usage limit evaluation method based on real-time interrupt sampling is as described in the above embodiments. Since this microcontroller stack usage limit evaluation device based on real-time interrupt sampling adopts all the technical solutions of all the above embodiments, it has at least all the beneficial effects brought by the technical solutions of the above embodiments, which will not be elaborated here.

[0082] The present invention also proposes an embedded system, comprising: microprocessor; Memory, used to store program instructions and as stack memory; A hardware timer is configured to generate periodic interrupts; The microprocessor is configured to execute program instructions stored in the memory to implement the microcontroller stack usage limit evaluation method based on real-time interrupt sampling.

[0083] The specific structure of the microcontroller stack use limit evaluation method based on real-time interrupt sampling is as described in the above embodiments. Since this embedded system adopts all the technical solutions of all the above embodiments, it has at least all the beneficial effects brought by the technical solutions of the above embodiments, which will not be elaborated here.

[0084] The above description is merely an optional embodiment of the present invention and does not limit the patent scope of the present invention. All equivalent structural transformations made using the contents of the present invention's specification and drawings under the inventive concept of the present invention, or direct / indirect applications in other related technical fields, are included within the patent protection scope of the present invention.

Claims

1. A method for evaluating the usage limits of a microcontroller stack based on real-time interrupt sampling, characterized in that, include: Configure / invoke a periodic interrupt source with the highest interrupt priority; When the service routine for the highest priority interrupt finishes execution, the instantaneous value of the hardware stack pointer register is read directly. The instantaneous value of the read stack pointer is compared with the historical minimum value of a dynamically maintained stack pointer. And update the historical minimum value of the stack pointer according to the growth direction of the stack memory; Based on the updated historical minimum value of the stack pointer and the starting address of the stack memory, the historical peak value of stack memory usage is calculated.

2. The microcontroller stack usage limit evaluation method based on real-time interrupt sampling as described in claim 1, characterized in that, The step of updating the historical minimum value of the stack pointer according to the growth direction of the stack memory specifically includes: If the stack memory grows towards lower addresses, and the instantaneous value of the stack pointer is less than the historical minimum value of the stack pointer, then the instantaneous value is used to update the historical minimum value of the stack pointer.

3. The single-chip microcontroller stack usage limit evaluation method based on real-time interrupt sampling as described in claim 1, characterized in that, The single-chip microcontroller stack usage limit evaluation method based on real-time interrupt sampling also includes: During system initialization, the historical minimum value of the stack pointer is initialized to the starting address of the stack memory.

4. The single-chip microcontroller stack usage limit evaluation method based on real-time interrupt sampling as described in claim 1, characterized in that, The calculation yields the historical peak usage of stack memory, followed by: Compare the historical usage peak with a preset security threshold; If the historical usage peak exceeds the preset security threshold, a stack overflow warning is triggered.

5. The microcontroller stack usage limit evaluation method based on real-time interrupt sampling as described in claim 1, characterized in that, The historical minimum value of the stack pointer is stored in non-volatile memory to maintain historical peak information after system reset or wake-up from hibernation.

6. The microcontroller stack usage limit evaluation method based on real-time interrupt sampling as described in any one of claims 1 to 5, characterized in that, The period of the periodic interrupt source is not an integer multiple of the period of any other periodic task in the microcontroller system.

7. A storage medium, characterized in that, The storage medium stores a microcontroller stack usage limit evaluation program based on real-time interrupt sampling. When the program is executed by the microprocessor, it implements the steps corresponding to the microcontroller stack usage limit evaluation method based on real-time interrupt sampling as described in any one of claims 1 to 6.

8. A microcontroller stack usage limit evaluation device based on real-time interrupt sampling, characterized in that, include: The interrupt configuration module is used to set a periodic interrupt source and configure it as the highest priority interrupt in the microcontroller system. The stack pointer sampling module is used to directly read the instantaneous value of the hardware stack pointer register when the service routine of the highest priority interrupt finishes execution; The comparison and update module is used to compare the instantaneous value of the read stack pointer with a dynamically maintained historical minimum value of the stack pointer, and update the historical minimum value of the stack pointer according to the growth direction of the stack memory. The peak calculation module is used to calculate the historical peak usage of stack memory based on the historical minimum value of the stack pointer and the starting address of the stack memory.

9. The microcontroller stack usage limit evaluation device based on real-time interrupt sampling as described in claim 8, characterized in that, The period of the periodic interrupt source configured by the interrupt configuration module is not an integer multiple of the period of any other periodic task in the microcontroller system.

10. An embedded system, characterized in that, include: microprocessor; Memory, used to store program instructions and as stack memory; A hardware timer is configured to generate periodic interrupts; The microprocessor is configured to execute program instructions stored in the memory to implement the microcontroller stack usage limit evaluation method based on real-time interrupt sampling as described in any one of claims 1 to 6.