Mpu-based function level isolation and dynamic heap window memory protection method

By implementing function-level isolation and dynamic heap window protection in embedded systems, the problem of lacking function-level isolation and real-time heap memory protection in existing technologies is solved, enabling fine-grained memory access permission management and improving the security and resource utilization of embedded systems.

CN123179484APending Publication Date: 2026-11-27SICHUAN MEDITATION SOFTWARE CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611683420.3
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-10-29
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

Existing embedded systems lack function-level isolation capabilities and cannot switch permissions in real time based on the internal logic call boundaries of a task. This leads to the over-granting of access permissions to sensitive functions in the task, expanding the attack surface. At the same time, dynamically allocated heap memory lacks real-time protection, and exception handling is rudimentary, affecting system availability and maintainability.

Method used

By dividing the code and static data of protected functions into independent storage sections during the compilation and linking stages, generating a function region table, and dynamically switching the MPU configuration based on function calls during the runtime stage, combined with the heap window allocation and deallocation mechanism, function-level isolation and dynamic heap window protection are achieved.

Benefits of technology

It achieves fine-grained isolation at the function level, defends against buffer overflows and pointer forgery attacks, ensures the consistency of the system's state under task switching and exceptions, and improves the security and resource utilization of embedded systems.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123179484A_ABST
    Figure CN123179484A_ABST
Patent Text Reader

Abstract

The present application relates to a kind of function level isolation and dynamic heap window memory protection method based on MPU, belong to embedded real-time operating system memory protection technical field, solve the problem that the existing technology cannot be switched at function call boundary dynamically, and lack of real-time authorization and abnormal distinguishing ability to heap memory, leading to the problem of coarse granularity of authority, and no protection for heap security. Including in the compilation and linking stage, the code and static data of each protected function are divided into independent storage section and function area table is generated;In the running stage, when task calls protected function, the current MPU configuration is pushed into context stack and saved, and the MPU configuration corresponding to the protected function is loaded according to function area table;When protected function needs to access dynamic heap memory, MPU heap window configuration is dynamically calculated and loaded according to the requested heap memory information and its authorization credentials, and the target heap memory is temporarily authorized. Function level isolation and dynamic heap window memory protection are realized.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of memory protection technology for embedded real-time operating systems, and in particular to a function-level isolation and dynamic heap window memory protection method based on MPU. Background Technology

[0002] With the increasing security requirements of the Internet of Things, industrial control, and smart terminal devices, embedded systems face severe memory security risks, such as buffer overflows, corrupted pointers that damage critical data, and use-after-free issues. Existing technologies generally employ Memory Protection Units (MPUs) as a lightweight hardware isolation method, defining access permissions at the task level to mitigate these risks. However, due to resource constraints in embedded hardware, the granularity and flexibility of this protection remain significant challenges.

[0003] Currently, mainstream MPU protection schemes are mainly divided into two categories. One is the static binding mode, represented by early FreeRTOS MPU implementations. This mode binds a pre-defined fixed memory region (such as the task stack and data segment) to the MPU's physical region once during task creation, and this configuration remains unchanged throughout the task's lifecycle. The other is the task-level dynamic configuration mode, which improves upon this by dynamically reloading the MPU configuration based on the Task Control Block (TCB) during task switching, alleviating the limitation on the number of regions through time reuse. However, both of these schemes stop at the moment of task switching; once a task gains execution rights, all its internal functions share the same access permissions, lacking fine-grained control over the execution flow within the task.

[0004] However, the primary flaw in existing technologies lies in the lack of function-level isolation capabilities. They cannot perform real-time permission switching based on the logical call boundaries within a task, leading to the excessive granting of access permissions to the entire task to only a few sensitive functions (such as encryption and communication protocol parsing). This severely violates the principle of least privilege and significantly expands the attack surface. Secondly, existing mechanisms offer almost no effective real-time protection for dynamically allocated heap memory. Since heap block addresses and lengths are determined at runtime, it is difficult to meet the strict constraints of the MPU regarding powers of 2 and start address alignment. Furthermore, the scarcity of physical heap regions (typically only 8 to 16) results in a lack of lightweight, readily applicable, and easily reversible protection against heap overflow and reuse risks after release.

[0005] Furthermore, existing solutions have serious shortcomings in dynamic state maintenance. On the one hand, when faced with nested function calls, recursion, or interrupt preemption, a single MPU configuration is easily overwritten, leading to disordered permission recovery. Moreover, relying solely on the ordinary pointer and length passed by the caller, the system cannot effectively identify whether the pointer belongs to a valid allocation block of the current task, making it difficult to prevent forged access by old pointers. On the other hand, when an MPU triggers an exception, traditional processing procedures cannot accurately distinguish whether the exception stems from unauthorized function access, heap window out of bounds, or ordinary task-level violations, resulting in a coarse recovery strategy. Typically, it can only simply terminate the task, failing to implement differentiated and precise recovery, severely impacting the system's availability and maintainability. Summary of the Invention

[0006] Based on the above analysis, the embodiments of the present invention aim to provide a function-level isolation and dynamic heap window memory protection method based on MPU, in order to solve the problems that existing methods cannot dynamically switch at function call boundaries and lack the ability to grant real-time authorization and anomaly differentiation for heap memory, resulting in excessively coarse permission granularity and no heap security protection.

[0007] This invention provides a method for function-level isolation and dynamic heap window memory protection based on an MPU, comprising the following steps: During the compilation and linking phases, the code and static data of each protected function are divided into independent storage sections, and a function region table is generated; the function region table includes memory region information for each protected function. During runtime, when a task calls a protected function, the current MPU configuration is pushed onto the context stack for storage, and the MPU configuration corresponding to the protected function is loaded according to the function region table to isolate and switch the memory access permissions of the current task. When the protected function needs to access dynamic heap memory, the MPU heap window configuration is dynamically calculated and loaded according to the requested heap memory information and its authorization credentials, and temporary authorization is granted to the target heap memory. The task's MPU configuration is monitored, and its physical MPU configuration is revoked when the task is switched out, and the physical MPU configuration is restored according to preset conditions when the task is switched in.

[0008] Furthermore, the protected function static data includes private static data, a constant table, and / or a key table; the step of dividing the code and static data of each protected function into independent storage sections includes: Place the code of the protected function in a separate function code section; Place the private static data of the protected functions into a separate writable data section; Place the constant table and / or key table of the protected functions in a separate read-only data section.

[0009] Furthermore, the function region table includes: function identifier or function entry address range, function code segment address range and execution permissions, function read-only data segment address range and read-only permissions, function writable data segment address range and read / write permissions, and upper bound of the function runtime stack window; during the linking stage, code sections, read-only data sections, and writable data sections named according to preset rules are collected by the linker script to generate the function region table.

[0010] Furthermore, during the compilation phase, function entry hooks are inserted at the entry point of the protected function, and function exit hooks are inserted at the return path of the protected function; when a task calls a protected function, the current MPU configuration is pushed onto the context stack for storage, and the MPU configuration corresponding to the protected function is loaded according to the function region table, including: In response to a task calling a protected function, the function is triggered to enter the hook; The function enters the hook to obtain the TCB pointer of the current task and performs a call verification. If the verification passes, the current MPU configuration is pushed onto the context stack. The function region table is searched based on the function identifier to obtain the memory region information of the protected function; The memory region information is converted into MPU register configuration and loaded into the dynamic MPU region; Update the current protected function identifier and nesting depth in TCB.

[0011] Furthermore, the MPU region is divided into a fixed MPU region and a dynamic MPU region; the fixed MPU region is used to protect kernel code, kernel data, the task stack of the current task, and peripheral regions, and remains unchanged while the current task holds the CPU; the dynamic MPU region is used for the temporary configuration of protected functions and heap windows; when the number of dynamic MPU regions is insufficient, two regions to be merged that meet the merging conditions are released; if the merging conditions are not met, the merging is abandoned and a degradation strategy is executed.

[0012] Furthermore, the merging conditions include: The two regions to be merged have identical MPU access permissions, both being read-only; the two regions to be merged are adjacent in the address space, wherein the end address of the region to be merged with the smaller start address is equal to the start address of the region to be merged with the larger start address; The merged region does not overlap with any preset sensitive address range, and the over-authorization rate of the merged region is less than or equal to the preset threshold.

[0013] Furthermore, the call verification includes one or more of the following: function identifier validity verification, task call authorization verification, nesting depth limit verification, dynamic MPU area availability verification, and security stack availability verification. If all required verifications pass, the call verification is deemed successful. If any verification fails, entry into the protected function is refused.

[0014] Furthermore, when the protected function needs to access dynamic heap memory, the process of dynamically calculating and loading the MPU heap window configuration based on the requested heap memory information and its authorization credentials, and temporarily authorizing the target heap memory, includes: The protected function passes the target heap block address, the requested access length, and the handle of the authorization credential provided by the heap allocator through the heap window request interface. It then performs a validity check on the target heap block. If the check passes, it uses the minimum alignment window dynamic calculation algorithm to generate an MPU heap window configuration that meets the MPU hardware constraints. This configuration is then loaded into the reserved dynamic MPU area, granting the current task temporary access to the target heap memory. The temporary access is revoked when a preset termination condition is triggered.

[0015] Furthermore, the step of generating the MPU heap window configuration that satisfies the MPU hardware constraints using the minimum alignment window dynamic calculation algorithm includes: The candidate region size is determined based on the requested access length. The candidate region size is a power of 2 greater than or equal to the requested access length and greater than or equal to the smallest granularity supported by the MPU hardware. The request start address of the target heap block is down-aligned to an integer multiple of the candidate region size to obtain the aligned start address; if the aligned start address plus the candidate region size does not completely cover the request interval, the candidate region size is expanded to twice its size and down-aligned again until the request interval is completely covered. The final aligned starting address and candidate region size are used as the MPU heap window configuration.

[0016] Furthermore, the step of canceling the physical MPU configuration when a task is switched out, and triggering the restoration of the physical MPU configuration according to preset conditions when a task is switched in, includes: When a task is switched out, the general-purpose registers of the current task are saved, the physical configuration of all dynamic MPU regions on the current CPU is cleared, and the context stack and heap window logical states stored in the TCB remain unchanged. When a task is initiated, the general-purpose registers are restored, and the context stack and the current protected function identifier in the TCB are restored. When the task continues to execute and calls the entry hook of the protected function or requests an interface through the heap window again, the physical MPU configuration is recalculated and loaded based on the context stack and the current protected function identifier saved in the TCB.

[0017] Compared with the prior art, the present invention can achieve at least one of the following beneficial effects: This invention provides a function-level isolation and dynamic heap window memory protection method based on MPU. By splitting the code and static data of protected functions into independent storage sections and generating a function region table during the compilation and linking phase, and automatically switching MPU configurations during runtime function entry and exit hooks, each sensitive function exposes only the minimum necessary permissions, effectively reducing the attack surface and achieving fine-grained function-level isolation. Through a dynamic allocation and cancellation mechanism of the heap window, on-demand temporary access authorization is provided for dynamic heap memory with a minimal dynamic MPU area. Combined with dual verification of generation information and software access credentials, it effectively defends against buffer overflows and re-release. This approach addresses typical memory attacks such as pointer forgery and exploitation. Simultaneously, by clearing the physical MPU configuration during task exit and delaying recovery as needed during task entry, it prevents permission remnants and cross-task inheritance, reduces unnecessary MPU overload overhead, and ensures system consistency and rapid recovery under task switching, nested calls, and abnormal disturbances. It achieves fine-grained and dynamic control over memory access permissions for embedded real-time systems at a relatively low hardware cost. Furthermore, it refines MPU protection granularity from the traditional task level to the function level and introduces time-sharing heap windows and generational credential verification mechanisms, significantly improving the security and resource utilization of embedded systems.

[0018] In this invention, the above-described technical solutions can be combined with each other to achieve more preferred combinations. Other features and advantages of this invention will be set forth in the following description, and some advantages may become apparent from the description or be learned by practicing the invention. The objects and other advantages of this invention can be realized and obtained from what is particularly pointed out in the description and drawings. Attached Figure Description

[0019] The accompanying drawings are for illustrative purposes only and are not intended to limit the invention. Throughout the drawings, the same reference numerals denote the same parts.

[0020] Figure 1 This is a flowchart illustrating the function-level isolation and dynamic heap window memory protection method based on MPU provided in Embodiment 1 of the present invention. Figure 2 This is a schematic diagram of sub-region disabling provided in Embodiment 1 of the present invention; Figure 3 This is a schematic diagram of task switching heap window cancellation and delay recovery provided in Embodiment 1 of the present invention; Figure 4 This is a schematic diagram of the anomaly classification process provided in Embodiment 1 of the present invention. Detailed Implementation

[0021] Preferred embodiments of the present invention will now be described in detail with reference to the accompanying drawings, which form part of this application and are used together with the embodiments of the present invention to illustrate the principles of the present invention, but are not intended to limit the scope of the present invention.

[0022] Example 1 A specific embodiment of the present invention discloses a function-level isolation and dynamic heap window memory protection method based on MPU, such as... Figure 1 As shown, it includes the following steps: During the compilation and linking phases, the code and static data of each protected function are divided into independent storage sections, and a function region table is generated; the function region table includes memory region information for each protected function. During runtime, when a task calls a protected function, the current MPU configuration is pushed onto the context stack for storage, and the MPU configuration corresponding to the protected function is loaded according to the function region table to isolate and switch the memory access permissions of the current task. When the protected function needs to access dynamic heap memory, the MPU heap window configuration is dynamically calculated and loaded according to the requested heap memory information and its authorization credentials, and temporary authorization is granted to the target heap memory. The task's MPU configuration is monitored, and its physical MPU configuration is revoked when the task is switched out, and the physical MPU configuration is restored according to preset conditions when the task is switched in.

[0023] It should be noted that this embodiment adds a function-level isolation management module and a heap window management module to the kernel of the Real-Time Operating System (RTOS), and extends the Task Control Block (TCB) to implement the method of this embodiment.

[0024] The function-level isolation management module is responsible for parsing the function region table generated during the compilation and linking stage; when the entry and exit hooks of a protected function are triggered, it performs the stack push saving of the current MPU configuration, the table lookup loading of the physical MPU configuration of the target function, and the stack popping restoration of the previous level configuration; at the same time, it monitors the nesting depth and the number of idle dynamic MPU regions to ensure the atomicity of the switching operation.

[0025] The heap window management module is responsible for maintaining the logical state of the heap window in each task TCB; when executing the heap window request API, it verifies the heap block metadata, generation information and software access credentials; calls the minimum alignment window dynamic calculation algorithm to load the calculated MPU configuration into the reserved dynamic MPU area; and cancels the heap window when the task is cut off or the heap scope is exited.

[0026] The expanded Task Control Block (TCB) adds the following fields: The function region table pointer points to the function region table generated during the compilation and linking stage, which is used to quickly look up the memory region configuration information of the target function at runtime based on the function identifier; The MPU context stack array is used to store snapshots of the MPU configurations that are replaced at each level during the nested calls of protected functions, and supports restoring the permissions of the previous level when the function exits. Current nesting depth records the nesting level of the current protected function call chain, used to detect whether the preset maximum depth has been exceeded to prevent context stack overflow; The currently protected function identifier records the identifier of the currently executing protected function, which is used for permission verification, context consistency check, and accountability when an exception occurs; The heap window logical state record saves the heap window information that the current task has requested but may have its physical configuration revoked due to task switching, including heap block address, length, generation, capability value, occupied dynamic MPU area number and physical open flag, which is used to restore the heap window as needed after the task is re-switched. And an optional recovery context, used to save the stack pointer, return address, error return value location and necessary registers of the function entry point when the system enables function-level exception recovery, so that when a function-level out-of-bounds exception occurs, it can roll back to the function entry point and return an error code.

[0027] The above fields together constitute the MPU permission suspension state of each task during non-running periods, allowing the physical configuration to be completely cleared when the task is switched out, and then restored as needed based on the logical state in the TCB after the task is switched back in.

[0028] During implementation, the MPU area is divided into a fixed MPU area and a dynamic MPU area. The fixed MPU area is used to protect kernel code, kernel data, the task stack of the current task, and peripheral areas, and remains unchanged while the current task holds the CPU. The dynamic MPU area is used for the temporary configuration of protected functions and heap windows. When there are not enough dynamic MPU areas, two areas that meet the merging conditions are released by merging the dynamic MPU areas. If the merging conditions are not met, the merging is abandoned and a degradation strategy is executed.

[0029] Understandably, the task stack of the current task remains unchanged while the current task holds the CPU. During task switching, the scheduler updates the configuration of this region to match the new task stack. The temporary configuration of the heap window is the behavior of configuring a limited dynamic MPU region as a protection window for a specific heap block for a very short time, and then immediately revoking it after use.

[0030] Specifically, if compliance conditions are met, the merge is performed, the two regions to be merged are released in the idle bitmap, the configuration of the merged region is written to one of the physical MPU registers, and the other physical MPU register is marked as idle; the MPU configuration is synchronized through the data synchronization barrier instruction and the instruction synchronization barrier instruction.

[0031] In practice, the conditions for merger include: The two regions to be merged have identical MPU access permissions, both being read-only and not writable; the two regions to be merged are adjacent in the address space, wherein the end address of the region to be merged with the smaller start address is equal to the start address of the region to be merged with the larger start address. The merged region does not overlap with any preset sensitive address range, and the over-authorization rate of the merged region is less than or equal to the preset threshold.

[0032] In practice, the two regions to be merged are merged in the following way: The two regions to be merged are merged into a new region. The starting address of the new region is the smaller base address of the two regions to be merged, and the size of the new region is the sum of the sizes of the two regions. If the size of the new region is not a power of 2, it is rounded up to the next power of 2, and the starting address is down-aligned to that size to obtain the merged region. Down-aligning the starting address to that size means adjusting the starting address to the largest integer address that is no greater than its original value and divisible by that size.

[0033] It should be noted that downward alignment, rather than upward alignment, is used to ensure that the physical coverage after alignment completely includes the entire address range of the original two regions. If upward alignment were used, the first part of the addresses of the original two regions might fall outside the new region and lose MPU protection, resulting in a substantial reduction in the protection scope of the merge operation and violating the security objective of the merge operation.

[0034] For example, the starting address of region A to be merged is 0x00008000, and its size is 512 bytes (2... 9 The coverage address range is 0x00008000~0x000081FF; the starting address of the region B to be merged is 0x00008200, and its size is 128 bytes (2 7 The address range covered is 0x00008200~0x0000827F; the size of the merged region is 512 + 128 = 640 bytes. Since 640 is not a power of 2, it is rounded up to the next power of 2, which is 1024 bytes (2^2 + 128 = 640 bytes). 10Then, the starting address is down-aligned to the 1024-byte boundary. The current smaller starting address is 0x00008000, which is 0 modulo 1024 (0x00008000%1024 = 0), so the starting address remains unchanged at 0x00008000. The merged new region covers an address range of 0x00008000 ~ 0x000083FF and is 1024 bytes in size.

[0035] For example, region A to be merged starts at address 0x00008180 and has a size of 128 bytes; region B to be merged starts at address 0x00008200 and has a size of 128 bytes. The merged region has a size of 256 bytes, which is exactly a power of 2. The starting address 0x00008180 modulo 256 is 128 (0x180%0x100=0x80), which does not meet the alignment requirement. Therefore, the starting address is down-aligned to 0x00008100 (0x00008180 minus 0x80 equals 0x00008100, which is 0 modulo 256).

[0036] Specifically, a sensitive address range refers to a set of memory address ranges predefined by the system during the linking or kernel initialization phase. This set is used to identify critical memory regions in the system that must not be accessed in any form by non-privileged tasks.

[0037] More specifically, the sensitive address range includes one or more of the following: interrupt vector table range, kernel code segment range, kernel global data segment range, peripheral register range, security firmware range, and system reserved range.

[0038] In practice, the over-authorization rate of the merged region = (the area covered by the merged region - the sum of the coverage areas of the two regions to be merged) / the sum of the coverage areas of the two regions to be merged.

[0039] More specifically, the preset threshold is a balanced threshold set based on engineering experience. For example, it is set to 1.5. This value strikes a balance between security and MPU resource utilization. The smaller the value, the less additional exposure there is, but the probability of successful merging decreases. The larger the value, the higher the success rate of merging, but the more unauthorized areas may be exposed.

[0040] During implementation, the degradation strategy will be executed in the following order of priority: First priority: Forcefully close the least recently used heap window using the LRU policy and reclaim the physical area it occupies; Second priority: By using block loading, the read-only data segment of the protected function is split into multiple sub-blocks according to a preset granularity, and only the sub-blocks required by the current function execution path are loaded; Third priority: Deny entry into the protected function, or cause heap window allocation to fail and return an error code to the caller.

[0041] Specifically, the LRU strategy includes: maintaining a timestamp of the most recent access for each dynamic MPU region; and when there are insufficient dynamic MPU regions, forcibly closing and reclaiming the heap window region with the earliest timestamp. It should be noted that the LRU strategy only applies to the dynamic MPU regions occupied by the heap window, and does not apply to the code segment, read-only data segment, or writable data segment regions occupied by currently executing protected functions.

[0042] Specifically, chunk loading includes: dividing the read-only data segment into multiple sub-blocks according to a preset granularity; at the function entry point, loading only the sub-blocks required for the current function execution path and configuring the corresponding MPU region; when the function execution path is switched, unloading the sub-blocks that are no longer needed and loading the sub-blocks required for the new path.

[0043] More specifically, the preset granularity is a power of 2 bytes, and is not less than the minimum region granularity supported by the MPU hardware and not greater than the maximum region size supported by a single physical region of the MPU. Further, the preset granularity is one of 64 bytes, 128 bytes, or 256 bytes.

[0044] Specifically, when entry into a protected function is denied or heap window allocation fails, the system does not commit any MPU register modifications and maintains the original permission state.

[0045] It should be noted that the following behaviors are prohibited as handling situations where dynamic MPU regions are insufficient: merging read-only regions with writable regions or expanding writable permissions in any way is prohibited; skipping MPU configuration loading when regions are insufficient, leaving the target memory region in an unprotected state is prohibited; and submitting only part of the MPU configuration is prohibited, causing protected functions to run with incomplete permissions.

[0046] Specifically, protected function static data includes private static data, constant tables, and / or key tables; among which, private static data refers to local variables defined inside the protected function and bearing the static keyword; they are only visible within the current function and cannot be directly accessed by external functions; they are allocated in the static storage area, exist throughout the program's execution, and their values ​​remain unchanged after the function returns, and are retained for the next call.

[0047] During implementation, during the compilation phase, the code and static data of each protected function are divided into independent storage sections, including: Place the code of the protected function in a separate function code section; Place the private static data of the protected functions into a separate writable data section; Place the constant table and / or key table of the protected functions in a separate read-only data section.

[0048] It should be noted that the parameters and local variables of the protected function are located in the task stack and are protected by a stack window or a dedicated security stack, rather than by static data separation and storage.

[0049] During implementation, during the compilation phase, compiler instrumentation or macro wrapping mechanisms insert function entry hooks at the entry point of the protected function and function exit hooks at the return path of the protected function. The function entry hook is used to pass the function identifier of the current protected function and trigger the switching of the MPU configuration; the function exit hook is used to verify the context consistency of the current protected function and trigger the restoration of the MPU configuration. The function identifier is determined by the compiler at compile time based on the entry index of the function region table and is hard-coded as a constant parameter into the instrumentation code during compilation. It is understandable that heap window allocation and deallocation are handled by independent heap access interfaces and are not forcibly bound to function entry and exit; function-level isolation and heap window authorization can be used independently or in combination within the same protected function.

[0050] Specifically, during the compilation phase, through compiler attributes or specific macro wrapping mechanisms, function entry hooks (such as __enter_protected_func(func_id), where func_id is the function identifier) ​​are automatically inserted at the entry point of the protected function, and function exit hooks (such as __exit_protected_func()) are automatically inserted on the normal or abnormal return path of the function.

[0051] Specifically, the function region table includes: the function identifier or function entry address range, the function code segment address range and execution permissions, the function read-only data segment address range and read-only permissions, the function writable data segment address range and read / write permissions, and the upper bound of the function runtime stack window.

[0052] During implementation, in the linking phase, the linker script collects code sections, read-only data sections, and writable data sections named according to preset rules, generating a function region table. This function region table serves as read-only metadata for system lookup. Understandably, at runtime, when a function enters a hook, it only needs to pass the function identifier of the protected function, and the kernel can then use the function region table to find the complete memory region information for the required code segment, read-only data segment, writable data segment, and stack window.

[0053] Specifically, code sections, read-only data sections, and writable data sections, named according to preset rules, are sections that begin with .text., .rodata., and .data., respectively.

[0054] For example, when protecting an encryption function, the compilation stage places the encryption function's code into a dedicated code section, the key table into a dedicated read-only section, and the function's private static buffer into a dedicated writable section; the linker generates the region table entry for the encryption function based on these sections.

[0055] It is understood that the method in this embodiment centralizes the function region table, MPU context stack, and heap window logical state required for function-level isolation into the TCB or kernel management structure, enabling the scheduler, exception handler, and function entry / exit hooks to jointly maintain the dynamic MPU configuration. Specifically, the MPU context stack only stores the RBAR / RASR register values ​​and context metadata of the dynamic MPU region, excluding the fixed MPU region, to reduce stack space usage and stack push latency.

[0056] In implementation, when a task calls a protected function, the current MPU configuration is pushed onto the context stack for storage, and the MPU configuration corresponding to the protected function is loaded according to the function region table, including: In response to a task calling a protected function, the function is triggered to enter the hook; The function enters the hook to obtain the TCB pointer of the current task and performs a call verification. If the verification passes, the current MPU configuration is pushed onto the context stack. The function region table is searched based on the function identifier to obtain the memory region information of the protected function; The memory region information is converted into MPU register configuration and loaded into the dynamic MPU region; Update the current protected function identifier and nesting depth in TCB.

[0057] In practice, the call verification includes one or more of the following: function identifier validity verification, task call authorization verification, nesting depth limit verification, dynamic MPU area availability verification, and security stack availability verification. If all required verifications pass, the call verification is deemed successful. If any verification fails, entry into the protected function is refused, and no MPU register modifications are committed to maintain system state consistency.

[0058] Specifically, the function identifier validity check is performed by checking whether the input function identifier is less than the total number of entries in the function range table. If so, the check passes.

[0059] Specifically, the task call authorization verification is as follows: verify whether the current task has the authorization to call the protected function. If so, the verification passes. The task TCB has a preset authorization bit mask (such as func_permission_mask). The hook checks whether the permission bit corresponding to the function identifier is 1. If so, the current task has the authorization to call the protected function.

[0060] Specifically, the nesting depth limit check is as follows: check whether the current nesting depth exceeds the preset maximum depth; if not, the check passes. The maximum depth is set based on the capacity of the pre-allocated MPU context stack array in the TCB to prevent stack overflow and data corruption; preferably, it is set to 8 or 16 levels based on system memory resources and typical function call depth.

[0061] Specifically, the availability check of the dynamic MPU area is as follows: scan the idle bitmap of the dynamic MPU area, calculate whether the current number of idle dynamic MPU areas meets the minimum number of MPU areas required by the function; if it meets the requirements, the check passes; if it does not meet the requirements, the insufficient number of dynamic MPU areas is handled; if it is still insufficient after reclamation, the check fails.

[0062] More specifically, the minimum number of MPU regions is determined by the number of independent storage sections that the protected function is split into during the compilation and linking phase. Each protected function contains at least three independent sections: a code section, a read-only data section, and a writable data section, each corresponding to three dynamic MPU regions, so the base count is 3. If the function uses a dedicated security stack, the security stack window is counted as a fourth dynamic MPU region. If the function also contains other independent sections (such as .bss), the minimum number of MPU regions is 3. <func>If a section is added, the count will increase accordingly.

[0063] Optionally, each bit in the dynamic MPU region free bitmap corresponds to an MPU region, with a bit of 1 indicating free and a bit of 0 indicating occupied. When scanning the bitmap, the total number of free bits is counted. If the number of free bits meets the demand, the corresponding MPU region is allocated. The allocation can be in any order. The allocation order can be from low address to high address or from high address to low address.

[0064] In practice, the method of this embodiment also includes: configuring a dedicated security stack for the protected function; When entering a protected function, the current stack pointer is switched to a dedicated safe stack; When exiting a protected function, restore the stack pointer to the task stack before entry.

[0065] Specifically, the allocation methods for dedicated security stacks include static reservation and pooling allocation. Static reservation means that a region is reserved during compilation and linking, labeled as dedicated to functions, and exists throughout the program's execution. Pooling allocation means that the kernel prepares a set of spare stacks (e.g., 8), one is requested when a function enters, and returned after use, and can be reused.

[0066] Specifically, the size of the dedicated security stack is determined by compile-time static analysis. The stack size of the dedicated security stack is ALIGN_UP(CEIL(max_usage×1.5),32); where max_usage represents the maximum stack usage of local variables of the function obtained by the compiler's static analysis; CEIL() represents rounding up; ALIGN_UP(x, 32) represents aligning up to an integer multiple of 32, i.e., ((x+31) / 32)×32.

[0067] Specifically, the security stack availability check verifies whether the security stack is available; if so, the check passes. More specifically, if the function is configured with a dedicated security stack, a security stack block is requested from the security stack free pool; if the request fails, the security stack is unavailable.

[0068] In practice, the context stack adopts a stack-style nested management. Each time a protected function is entered, a snapshot of the current MPU configuration is pushed onto the stack. Each time a protected function is exited, the snapshot of the previous MPU configuration is popped off the stack. When the nesting depth exceeds the preset maximum depth, entry into a new protected function is refused or a protection exception is triggered.

[0069] Optionally, before performing the stack push operation, the function enters the critical section via a hook (e.g., by disabling interrupts or the scheduler) to ensure that the sequence of operations from saving the current configuration on the stack to loading the target configuration is not interrupted or interrupted by task switching; after loading is complete, the function exits the critical section. If a failure is detected during the verification phase, the function does not enter the critical section and returns directly.

[0070] Specifically, the current MPU configuration is pushed onto the context stack, including: Read the register values ​​of the Region Base Address Register (RBAR) and Region Attribute and Size Register (RASR) of all dynamic MPU regions in the current physical MPU, and pack the read values ​​as an MPU configuration snapshot. At the same time, write the current task's stack pointer value, the current protected function identifier, and the current nesting depth as metadata into this snapshot. Copy this snapshot to the [mpu_depth] position of the MPU context stack array in the TCB. Increment mpu_depth by 1. The [mpu_depth] position is the slot of the index mpu_depth corresponding to the current stack top in the MPU context stack array.

[0071] It's important to note that the stack push operation only saves the configuration of the dynamic MPU region, not the fixed MPU region. The fixed MPU region remains unchanged throughout the entire task lifecycle, and saving it increases stack space usage and stack push latency. Taking the ARMv7-M architecture as an example, saving a snapshot of one layer of dynamic MPU region requires only about 16 bytes, while saving the entire region would require more than 96 bytes.

[0072] In practice, the memory region information is converted into MPU register configuration and loaded into the dynamic MPU region, including: Check if the base address of each region meets the alignment constraints required by the size of the memory region; if not, align the base address down to an integer multiple of the region size, and round the region size up to the next power of 2, until the aligned base address meets the alignment requirements and the region can completely cover the original address range; Convert the region size to the encoded value required by the SIZE field in the MPU RASR register (e.g., SIZE = log2(size)-1 in ARMv7-M), and convert the region permissions to the corresponding encoding of the access permission field and the non-executable bit in the MPU RASR register to obtain the physical MPU configuration of the target function, namely the RBAR and RASR register values.

[0073] The physical MPU configuration of the target function is written into the register corresponding to the free dynamic MPU region. If the function is configured with a dedicated security stack, the base address of the security stack block is written as the stack window into the corresponding MPU region, and the CPU stack pointer is switched to the top address of the security stack.

[0074] Specifically, after the physical MPU configuration of the target function is written into the register corresponding to the idle dynamic MPU region, the data synchronization barrier instruction (DSB) and instruction synchronization barrier instruction (ISB) are executed in sequence to ensure that the MPU configuration takes effect immediately, and the subsequent instruction fetching and memory access are constrained by the new MPU configuration.

[0075] Specifically, updating the currently protected function identifier and nesting depth in the TCB involves updating the currently protected function identifier in the TCB to the identifier of the currently passed function, while keeping `mpu_depth` at its pushed-on value. At this point, the function body of the protected function begins execution, and its memory access permissions are strictly limited to the currently loaded code segment, read-only data segment, writable data segment, and stack window.

[0076] Understandably, before a task calls a protected function, its memory access permissions are its basic permissions, typically only including the task's own task stack and basic data area. After entering the protected function, the task's access permissions are shrunk or remapped to the minimum memory range necessary for the function's execution. The switching operation is completed at the function entry point and is transparent to the calling task; the caller needs not be aware of and cannot interfere with the specific configuration of the permission switching.

[0077] In practice, when exiting the protected function, the function exit hook is triggered, and the following is executed: Check if the identifier of the function to be exited matches the current context; if not, trigger a security exception. Pop the previous MPU configuration from the context stack; Restore the configuration of the previous-level MPU to the dynamic MPU region; Update the current protected function identifier and nesting depth in TCB.

[0078] In implementation, when the protected function needs to access dynamic heap memory, the MPU heap window configuration is dynamically calculated and loaded based on the requested heap memory information and its authorization credentials, and temporary authorization is granted to the target heap memory, including: The protected function passes the target heap block address, the requested access length, and the handle of the authorization credential provided by the heap allocator through the heap window request interface. It then performs a validity check on the target heap block. If the check passes, it uses the minimum alignment window dynamic calculation algorithm to generate an MPU heap window configuration that meets the MPU hardware constraints. This configuration is then loaded into the reserved dynamic MPU area, granting the current task temporary access to the target heap memory. The temporary access is revoked when a preset termination condition is triggered.

[0079] It should be noted that the heap window request interface is independent of the function entry hook and function exit hook of the protected function. Function-level isolation and heap window authorization can be used independently or in combination within the same protected function.

[0080] Specifically, the authorization credential handle includes heap block generation information and a software access credential. The heap block generation information is maintained by the heap allocator for each heap block and is incremented or regenerated each time a heap block is released and reallocated. The software access credential is an anti-counterfeiting signature derived by the heap allocator based on heap block metadata, generated as follows: Software Access Credential = HMAC(Kernel Key || Task ID || Heap Block Base Address || Heap Block Length || Generation). The kernel key is a randomly generated symmetric key stored in kernel mode during system startup, which cannot be read or forged by user-mode tasks. The generation is the version number. The software access credential is a software-layer credential, independent of processor hardware capability registers, and does not require CHERI or CHERIoT hardware extension support.

[0081] It should be noted that in this embodiment, the heap allocator maintains metadata for each heap block. This metadata includes the heap block base address, heap block length, associated task, access permissions, generation information, software access credentials, and current status. The heap block status includes: FREE indicates that the heap block has not been allocated and can be used by subsequent allocation requests; ALLOCATED indicates that the block has been allocated and is in normal use. QUARANTINED indicates that the block has been released but is under quarantine observation. It can only be returned to the FREE state and redistributed after the quarantine period is over. WINDOW_OPEN, active heap window, indicates that a heap block has been allocated and there is currently at least one valid heap window authorization, meaning that the heap block is in the active access phase; The transition relationships between heap block states include: FREE is converted to ALLOCATED through an allocation operation; ALLOCATED is converted to QUARANTINED through a release operation; QUARANTINED is automatically converted to FREE after the isolation period expires, at which point the heap block can be reallocated; ALLOCATED is converted to WINDOW_OPEN through a heap window request operation; WINDOW_OPEN is converted back to ALLOCATED through a heap window undo operation.

[0082] Specifically, the WINDOW_OPEN state cannot be directly converted to QUARANTINED. That is, when a heap block is in an active heap window state, the system prohibits performing a free operation on that heap block. The system must first undo all heap windows, returning the heap block state to ALLOCATED, before performing a free operation to enter the isolation period. This constraint ensures that heap blocks are not prematurely freed while the heap window is still in effect, preventing memory access errors and security vulnerabilities caused by window remnants. When a heap block is freed or reallocated, the heap allocator updates its state and generation information accordingly.

[0083] In practice, the target heap block undergoes a validity check, including: Check if the sum of the target heap block address and the requested access length causes an integer overflow; if so, the check fails. The heap allocator metadata is queried based on the target heap block address to verify whether the address points to an allocated heap block; if not, the verification fails. Verify whether the target heap block belongs to the current task; if not, the verification fails. Verify whether the requested access length is less than or equal to the actual allocated size of the target heap block; if not, the verification fails. Verify whether the block generation information in the authorization credential handle is consistent with the latest generation recorded in the heap allocator metadata. If not, the verification fails. The software access credentials are recalculated using the kernel key, and then checked against the software access credentials in the authorization credential handle. If they do not match, the check fails. If all the above checks pass, then the validity check is considered successful. If any of the above checks fails, the validity check is deemed to have failed, no MPU configuration is loaded, the original physical MPU configuration remains unchanged, and the corresponding error code is returned to the caller.

[0084] In practice, a minimum alignment window dynamic calculation algorithm is used to generate an MPU stack window configuration that satisfies the MPU hardware constraints, including: The candidate region size is determined based on the requested access length. The candidate region size is a power of 2 greater than or equal to the requested access length and greater than or equal to the smallest granularity supported by the MPU hardware. The request start address of the target heap block is down-aligned to an integer multiple of the candidate region size to obtain the aligned start address; if the aligned start address plus the candidate region size does not completely cover the request interval, the candidate region size is expanded to twice its size and down-aligned again until the request interval is completely covered. The final aligned starting address and candidate region size are used as the MPU heap window configuration.

[0085] Understandably, the purpose of using downward alignment instead of upward alignment is to ensure that the physical coverage after alignment includes the requested range, so that the block header and all valid data are protected by the MPU.

[0086] In practical implementation, if the hardware supports sub-region disabling, the dynamic MPU region will be divided into multiple equally sized sub-regions. Invalid sub-regions that are over-covered at the front and back ends of the request interval will be calculated. Sub-regions completely outside the request interval will be disabled in the sub-region disabling mask to further tighten the authorization scope. Figure 2 As shown; if the hardware does not support sub-region disabling, or the sub-region disabling mask cannot form a valid configuration, the system degenerates to a minimum aligned dynamic MPU region configuration and does not use sub-region disabling.

[0087] In practice, after the MPU heap window configuration is loaded into the dynamic MPU region, the logical state of the heap window is recorded in the task control block, including: the original address of the target heap block, the requested access length, the actual base address and size after alignment, the generation information, the software access credentials, the number of the occupied dynamic MPU region, the identifier of the protected function, and the physical open flag.

[0088] In practice, the termination of the temporary authorization shall be subject to any of the following conditions: The protected function explicitly calls the heap window undo interface; When a protected function exits, the function exit hook forcibly closes all heap windows opened by the protected function; When the current task is switched off the CPU, the system clears the MPU heap window configuration; When a task terminates or an exception occurs, the system reclaims all heap window resources for that task.

[0089] Specifically, when the function exit hook forcibly closes the heap window, it iterates through all heap window records in the task control block whose protected function identifier is equal to the current protected function identifier, clears the corresponding MPU heap window configuration one by one, and invalidates the physical open flag.

[0090] Furthermore, the number of heap windows opened simultaneously does not exceed the system's preset limit; a dynamic MPU region serves only one heap window request at a time. Even further, the preset limit is 1 to 4.

[0091] During implementation, the physical MPU configuration is revoked when a task is switched out, and restored based on preset conditions when a task is switched in, including: When a task is switched out, the general-purpose registers of the current task are saved, the physical configuration of all dynamic MPU regions on the current CPU is cleared, and the context stack and heap window logical states stored in the TCB remain unchanged. When a task is initiated, the general-purpose registers are restored, and the context stack and the current protected function identifier in the TCB are restored. When the task continues to execute and calls the entry hook of the protected function or requests an interface through the heap window again, the physical MPU configuration is recalculated and loaded based on the context stack and the current protected function identifier saved in the TCB.

[0092] For example, such as Figure 3 As shown, when Task A switches out, the physical window is canceled but the logical state is retained in TCB. When Task B switches in, it cannot inherit the window. When Task A switches in again, it needs to re-apply and verify before the physical window can be restored.

[0093] In implementation, the method of this embodiment also includes exception handling: When the MPU triggers a memory protection exception, obtain the fault address and the current task context; The anomaly type is determined based on the relationship between the fault address, the current task heap window state, and the authorized range of protected functions. Anomaly types include: heap window out of bounds, function-level out of bounds, and ordinary MPU out of bounds. Differentiated recovery strategies are implemented based on different anomaly types.

[0094] Specifically, the exception type is determined in the order of priority: heap window out of bounds, function-level out of bounds, and ordinary MPU out of bounds.

[0095] Specifically, the determination of anomaly types includes: If the fault address falls within the extra coverage area of ​​the current heap window that is expanded due to MPU alignment, and exceeds the original logical range of the requested access, it is determined to be a heap window out of bounds. If the fault address does not belong to the code segment, read-only data segment, writable data segment, or stack window authorized area of ​​the currently protected function, it is determined to be a function-level out-of-bounds error.

[0096] Specifically, differentiated recovery strategies include: If the heap window goes out of bounds, the physical configuration of the heap window for the task is revoked, and the violation address is recorded. If the system has already established a recovery context for the function, an error code is returned to the caller, who then decides on the subsequent handling. If no recovery context has been established, the task is terminated by default. For function-level out-of-bounds errors, first close all heap windows opened by the currently protected function, pop the context stack until returning to the function's entry level, and restore the entry stack pointer; if the recovery context has been saved for the function, jump to the recovery point and return an error code; if the recovery context has not been saved, terminate the task by default to ensure system consistency.

[0097] For example, such as Figure 4 As shown, the exception handler first reads the fault address, the current function ID, and the heap window state. The first-level judgment checks whether the fault address is in the heap window access phase and falls outside the heap block authorization window but is still within the heap block range. If so, it is determined to be a heap window out of bounds, the window is unfurled, and the violation address is recorded. Otherwise, it proceeds to the second-level judgment, which checks whether the fault address exceeds the code segment, read-only data segment, writable data segment, or stack window authorization area of ​​the currently protected function. If so, it is determined to be a function-level out of bounds, cascading undo is performed, and the function entry point is rolled back. If neither of the first two levels can be clearly matched, it is classified as a normal MPU out of bounds and handled as a system-level fault.

[0098] Compared with existing technologies, this embodiment provides a function-level isolation and dynamic heap window memory protection method based on MPU. By splitting the code and static data of protected functions into independent storage sections and generating a function region table during the compilation and linking stage, and combining this with runtime function entry and exit hooks to automatically switch MPU configurations, each sensitive function exposes only the minimum necessary permissions, effectively reducing the attack surface and achieving fine-grained isolation at the function level. Through the dynamic allocation and cancellation mechanism of the heap window, it provides on-demand temporary access authorization to dynamic heap memory with a minimal dynamic MPU area. Combined with dual verification of generation information and software access credentials, it effectively defends against buffer overflows. Typical memory attacks such as reuse after release and pointer forgery are addressed. Simultaneously, by clearing the physical MPU configuration when a task exits and delaying recovery as needed when it enters, the system prevents permission remnants and cross-task inheritance, reduces unnecessary MPU overload overhead, and ensures system consistency and rapid recovery under task switching, nested calls, and abnormal disturbances. This achieves fine-grained and dynamic control over memory access permissions for embedded real-time systems at a relatively low hardware cost. Furthermore, the granularity of MPU protection is refined from the traditional task level to the function level, and time-sharing heap windows and generational credential verification mechanisms are introduced, significantly improving the security and resource utilization of embedded systems.

[0099] Example 2 This invention provides a specific embodiment to illustrate the method process of the embodiment. Assume there are multiple tasks in the system, one of which needs to call the encryption function aes_encrypt() to process sensitive data. This function needs to access: its own code segment; a read-only key table stored in Flash or a read-only data area; the function runtime stack window; and an output buffer located on the heap, passed in as a parameter by the caller.

[0100] Implementation steps: Encryption function marking: Use protection tags to place the aes_encrypt function code into a dedicated code section and the key table into a dedicated read-only data section. The linker automatically generates a region entry for this function.

[0101] The region table is loaded when the task is created: the task TCB's func_region_table points to the protected function region table, which includes aes_encryp.

[0102] Calling the encryption function: When the task executes to aes_encrypt(...), the compiler instrumentation hook function or macro wrapper is automatically triggered, and the entry hook is passed the function identifier corresponding to aes_encrypt.

[0103] Loading function permissions: The kernel pushes the current MPU configuration onto mpu_context_stack and loads the aes_encrypt-specific MPU configuration, such as executable or read-only code segment, read-only key table, writable function data segment, and read-write stack window.

[0104] Requesting heap access: When a function needs to access an output buffer on the heap, it submits the output buffer address, length, generation, and software access credential capability through the heap window request interface. The kernel verifies the heap block metadata, task ownership, access permissions, generation, and capability, and then calculates and loads the heap window.

[0105] Undo heap window: Call exit_heap_scope() before the function ends to undo the heap window.

[0106] Abnormal situations: If an encryption function attempts to access Flash memory outside the key table due to a vulnerability, or writes to the read-only key table, the MPU triggers an exception. The exception handler determines it as a function-level out-of-bounds error based on the context and executes the corresponding policy. If a heap window is requested again using an old pointer, the kernel will refuse to open the heap window due to a mismatch in state, generation, or capability.

[0107] The function returns: __exit_protected_func restores the previous MPU configuration, the task is restored to the permission state before the encryption function was called, and continues to execute normal logic.

[0108] Result: Even if an attacker gains control of the encryption function, their access is limited to the currently authorized region of aes_encrypt and the temporary heap window; the heap window is only temporarily opened when necessary, and the physical window is revoked when exiting the scope or switching tasks.

[0109] Those skilled in the art will understand that all or part of the processes of the methods described in the above embodiments can be implemented by a computer program instructing related hardware, and the program can be stored in a computer-readable storage medium. The computer-readable storage medium may be a disk, optical disk, read-only memory, or random access memory, etc.

[0110] The above description is only a preferred embodiment of the present invention, but the scope of protection of the present invention is not limited thereto. Any changes or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in the present invention should be included within the scope of protection of the present invention.< / func>

Claims

1. A method for function-level isolation and dynamic heap window memory protection based on MPU, characterized in that, Includes the following steps: During the compilation and linking phases, the code and static data of each protected function are divided into independent storage sections, and a function region table is generated. The function region table includes memory region information for each protected function; During the runtime phase, when a task calls a protected function, the current MPU configuration is pushed onto the context stack for storage, and the MPU configuration corresponding to the protected function is loaded according to the function region table to isolate and switch the memory access permissions of the current task; when the protected function needs to access dynamic heap memory, the MPU heap window configuration is dynamically calculated and loaded according to the requested heap memory information and its authorization credentials, and temporary authorization is granted to the target heap memory. Monitor the MPU configuration of the task, cancel its physical MPU configuration when the task is switched out, and trigger the restoration of the physical MPU configuration according to preset conditions when the task is switched in.

2. The method for function-level isolation and dynamic heap window memory protection based on MPU according to claim 1, characterized in that, The protected function static data includes private static data, a constant table, and / or a key table; the step of dividing the code and static data of each protected function into independent storage sections includes: Place the code of the protected function in a separate function code section; Place the private static data of the protected functions into a separate writable data section; Place the constant table and / or key table of the protected functions in a separate read-only data section.

3. The method for function-level isolation and dynamic heap window memory protection based on MPU according to claim 2, characterized in that, The function region table includes: function identifier or function entry address range, function code segment address range and execution permissions, function read-only data segment address range and read-only permissions, function writable data segment address range and read / write permissions, and upper bound of the function runtime stack window; during the linking stage, code sections, read-only data sections, and writable data sections named according to preset rules are collected by the linker script to generate the function region table.

4. The method for function-level isolation and dynamic heap window memory protection based on MPU according to claim 3, characterized in that, During the compilation phase, function entry hooks are inserted at the entry point of the protected function, and function exit hooks are inserted at the return path of the protected function. When a task calls a protected function, the current MPU configuration is pushed onto the context stack for storage, and the MPU configuration corresponding to the protected function is loaded according to the function region table, including: In response to a task calling a protected function, the function is triggered to enter the hook; The function enters the hook to obtain the TCB pointer of the current task and performs a call verification. If the verification passes, the current MPU configuration is pushed onto the context stack. The function region table is searched based on the function identifier to obtain the memory region information of the protected function; The memory region information is converted into MPU register configuration and loaded into the dynamic MPU region; Update the current protected function identifier and nesting depth in TCB.

5. The method for function-level isolation and dynamic heap window memory protection based on MPU according to claim 4, characterized in that, The MPU region is divided into a fixed MPU region and a dynamic MPU region. The fixed MPU region is used to protect kernel code, kernel data, the task stack of the current task, and peripheral regions, and remains unchanged while the current task holds the CPU. The dynamic MPU region is used for the temporary configuration of protected functions and heap windows. When there are not enough dynamic MPU regions, two regions that meet the merging conditions are released by merging the dynamic MPU regions. If the merging conditions are not met, the merging is abandoned and a degradation strategy is executed.

6. The method for function-level isolation and dynamic heap window memory protection based on MPU according to claim 5, characterized in that, The merging conditions include: The two regions to be merged have identical MPU access permissions, both being read-only; the two regions to be merged are adjacent in the address space, wherein the end address of the region to be merged with the smaller start address is equal to the start address of the region to be merged with the larger start address; The merged region does not overlap with any preset sensitive address range, and the over-authorization rate of the merged region is less than or equal to the preset threshold.

7. The method for function-level isolation and dynamic heap window memory protection based on MPU according to claim 5, characterized in that, The call verification includes one or more of the following: function identifier validity verification, task call authorization verification, nesting depth limit verification, dynamic MPU area availability verification, and security stack availability verification. If all required verifications pass, the call verification is deemed successful. If any verification fails, entry into the protected function is refused.

8. The method for function-level isolation and dynamic heap window memory protection based on MPU according to claim 5, characterized in that, When the protected function needs to access dynamic heap memory, the MPU heap window configuration is dynamically calculated and loaded based on the requested heap memory information and its authorization credentials, and temporary authorization is granted to the target heap memory, including: The protected function passes the target heap block address, the requested access length, and the handle of the authorization credential provided by the heap allocator through the heap window request interface. It then performs a validity check on the target heap block. If the check passes, it uses the minimum alignment window dynamic calculation algorithm to generate an MPU heap window configuration that meets the MPU hardware constraints. This configuration is then loaded into the reserved dynamic MPU area, granting the current task temporary access to the target heap memory. The temporary access is revoked when a preset termination condition is triggered.

9. The function-level isolation and dynamic heap window memory protection method based on MPU according to claim 8, characterized in that, The method of generating an MPU heap window configuration that satisfies MPU hardware constraints using a minimum alignment window dynamic calculation algorithm includes: The candidate region size is determined based on the requested access length. The candidate region size is a power of 2 greater than or equal to the requested access length and greater than or equal to the smallest granularity supported by the MPU hardware. The request start address of the target heap block is down-aligned to an integer multiple of the candidate region size to obtain the aligned start address; if the aligned start address plus the candidate region size does not completely cover the request interval, the candidate region size is expanded to twice its size and down-aligned again until the request interval is completely covered. The final aligned starting address and candidate region size are used as the MPU heap window configuration.

10. The method for function-level isolation and dynamic heap window memory protection based on MPU according to claim 5, characterized in that, The step of canceling the physical MPU configuration when a task is switched out and restoring the physical MPU configuration based on preset conditions when a task is switched in includes: When a task is switched out, the general-purpose registers of the current task are saved, the physical configuration of all dynamic MPU regions on the current CPU is cleared, and the context stack and heap window logical states stored in the TCB remain unchanged. When a task is initiated, the general-purpose registers are restored, and the context stack and the current protected function identifier in the TCB are restored. When the task continues to execute and calls the entry hook of the protected function or requests an interface through the heap window again, the physical MPU configuration is recalculated and loaded based on the context stack and the current protected function identifier saved in the TCB.