A sandbox implementation method and system in a real-time operating system
Patent Information
- Application Number
- CN202611158771.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-31
- Publication Date
- 2026-10-30
AI Technical Summary
此时CPU隐藏了引发异常的应用任务的真实栈指针及状态,传统的错误与异常处理程序(Error & Exception Handler,EEHandler)无法进行异常溯源,无法提取上下文信息
[0022]本发明取得的技术效果是:将ARM Cortex-R架构的CPU遇到异常时的终止模式转换为可控的局部恢复事件;通过任务控制块中的资源链表与影子节点的设计,便于完整统计与彻底清理每个用户任务所申请的资源;将沙盒内所有用户任务作为统一的故障恢复对象。
Smart Images

Figure CN123013077A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to a lightweight sandbox implementation method in a real-time operating system (RTOS). Background Technology
[0002] CPUs used in embedded systems are typically designed with different operating modes in their hardware. These modes are divided into two categories: privileged and unprivileged. The two modes have different levels of control over CPU hardware resources. Privileged CPUs can execute all CPU machine instructions and can read and write the CPU's internal system control registers (also known as privileged registers). Unprivileged CPUs can only execute ordinary calculation, jump, and general data read / write instructions, and cannot directly modify the system control registers that affect the overall operating state of the CPU.
[0003] CPUs used in embedded systems may optionally incorporate a Memory Protection Unit (MPU) in hardware. The MPU is a hardware component within the CPU used to enhance the security and stability of the embedded system. The MPU divides memory into multiple independent regions, assigning privileged and non-privileged read, write, and execute permissions to each region, preventing a task from accidentally modifying data from other tasks or the operating system kernel. In CPUs without an MPU or with the MPU disabled, both privileged and non-privileged users can directly read and write to any peripheral device and access any memory address. In CPUs with an MPU enabled, privileged users can directly read and write to any peripheral device and access any memory address; non-privileged users cannot directly access peripheral devices and can only access memory addresses allocated by the MPU.
[0004] In traditional lightweight RTOS (such as ThreadX), the system kernel code and user application code are usually compiled into a single binary firmware, sharing the same privilege level and memory address space.
[0005] In the OpenCPU scheme, the system kernel code and user application code are compiled into two completely independent binary firmware. The system kernel fills all API (Application Programming Interface) function pointers exposed to users into a jump table at a fixed memory location, allowing application modules to indirectly find API functions. The system kernel also exports a symbol table, which specifies the mapping relationship between symbols and the absolute physical addresses of the jump table, for use by application modules during compilation and linking.
[0006] Existing sandbox implementations in real-time operating systems have the following shortcomings.
[0007] First, if the lightweight RTOS is based on an ARM Cortex-M architecture CPU, when a memory overflow is triggered, the CPU will automatically push the context of the current task (such as the PC and status register) onto the stack of the current task. Developers can then read the PC (Program Counter) pointer that caused the crash from the stack memory.
[0008] If a lightweight RTOS is based on an ARM Cortex-R architecture CPU, when a fatal exception such as a Data Abort or Prefetch Abort occurs, the CPU does not automatically push the stack. Instead, it enters a specific Abort mode and uses dedicated banked registers and specific fault status registers of the coprocessor CP15 to save the error information that caused the exception. In this state, the CPU hides the actual stack pointer and state of the application task that caused the exception. Traditional error and exception handlers (EEHandlers) cannot perform exception tracing or extract context information.
[0009] Second, after a user application crashes in an RTOS, it loses its ability to execute. The mutexes, dynamic memory, and driver sessions it has requested cannot be actively released. The global variables it has requested cannot be cleaned up after a simple in-place restart. After restarting with erroneous values, the application is prone to secondary crashes.
[0010] Third, a user application in an RTOS may contain multiple user tasks. These user tasks share the same application's global variables, private heap, message objects, and driver sessions, while each having its own independent task stack and scheduling state. When any of these tasks experiences out-of-bounds access or an execution flow exception, if only the failed task is restarted, the remaining tasks may still hold pointers to the old instances, queue messages, mutex states, timer callbacks, or driver handles, and continue to access the already corrupted shared memory. Global variables with erroneous values can easily trigger a secondary crash. If the entire system is reset directly, it will cause simultaneous interruptions to system services unrelated to the failed application, such as communication, location, and storage. Therefore, it is necessary to treat a user application and all its contained user tasks, shared writable memory, private heap, and associated kernel resources as a unified fault recovery object, rather than treating a single Task Control Block (TCB) as the fault recovery object. Summary of the Invention
[0011] The technical problem to be solved by this invention is: how to implement a sandbox implementation scheme with low overhead, high stability and application-level isolation for the termination mode of ARM Cortex-R architecture CPU when encountering an exception.
[0012] To address the aforementioned technical problems, this invention proposes a sandbox implementation method in a real-time operating system, comprising the following steps: Step S1: The embedded system employs a real-time operating system (RTOS). The CPU in the embedded system has and enables a memory protection unit (MPU). Tasks in the RTOS are categorized into user tasks and privileged tasks based on their origin. A CPU operating mode and allowed memory access range are set for each type of task. Each task has a corresponding task control block. All running and suspended user tasks constitute a sandbox. Step S2: When the RTOS starts for the first time or switches to a user task, the privileged entry point switches the CPU from privileged mode to non-privileged mode and switches to the user stack of that user task. Step S3: The user task enters the user entry point for execution. Once the user task needs to use the RTOS kernel capabilities, it encodes the request for using the RTOS kernel capabilities into a system call number and parameters, and enters the SVC interrupt service routine and dispatcher via the SVC instruction. The SVC interrupt service routine and dispatcher obtain the task control block corresponding to the user task that triggered the system call from the exception context and verify the system call number, parameter range, and sandbox status. If all checks fail, the SVC interrupt service routine and dispatcher deny the CPU the ability to switch to privileged mode to call the real-time operating system kernel. If all checks pass and it is determined that the user task has no risk of time consumption or blocking, the SVC interrupt service routine and dispatcher allow the CPU to switch to privileged mode to execute the user task, and proceed to step S4. If all checks pass and it is determined that the user task has a risk of time consumption or blocking, the SVC interrupt service routine and dispatcher extract the system call number and parameters from the exception context, encapsulate them into a kernel service request packet, and submit it to the privileged proxy and dispatch task. Step S4: The real-time operating system kernel executes the user task in privileged mode; once the resource creation for the user task is completed, the real-time operating system kernel generates a corresponding shadow node; the shadow node is used to record the created resource type, resource handle, or address; the shadow node is attached to the resource list in the task control block of the user task. Step S5: After the user task finishes calling the privileged mode, the real-time operating system returns to non-privileged mode to execute the user task according to the saved pre-exception state.
[0013] Furthermore, in step S1, tasks from user applications are all user tasks; each user task executes in the CPU's non-privileged mode during normal scheduling; the MPU restricts the memory access scope of a user task to the code segment, shared writable area, private heap, corresponding user stack, and authorized shared window of the user application to which the user task belongs; user tasks access the system kernel and system services through the SVC entry point. Tasks from outside user applications are all privileged tasks; each privileged task executes in the CPU's privileged mode during normal scheduling; the memory access scope of a privileged task is the entire memory address space.
[0014] Furthermore, in step S1, the task control block corresponding to each user task is used to record the resource linked list, mode bit, user entry, user stack top, and permission attributes.
[0015] Furthermore, in step S3, after the user task executes the SVC instruction, the CPU automatically copies the current program status register CPSR into the backup program status register SPSR, and at the same time, the CPU enters the privileged mode handler context; the privileged mode handler context is where hardware interrupts are executed and has the characteristic of being non-blocking.
[0016] Further, in step S3, the SVC interrupt service routine and dispatcher calculate the physical address of the SVC instruction that triggered the interrupt by reading the link register, and parse out the embedded immediate value, which is the system call number. Verifying the system call number involves determining whether the extracted system call number exceeds the maximum index value of the system call dispatch table maintained by the real-time operating system kernel; if it does not exceed this value, the system call number verification passes. Verifying the parameter range refers to determining whether the system call parameters involving memory read / write are between the start and end addresses of the sandbox memory space; if so, the parameter range verification passes. Verifying the sandbox state refers to determining whether the sandbox is in a normal state when the SVC interrupt service routine is triggered; if so, the sandbox state verification passes.
[0017] Furthermore, in step S3, if all verifications pass and it is determined that the user task has a risk of time consumption or blocking, the privileged proxy and dispatch task calls the actual RTOS kernel function in the privileged mode thread mode context, and then returns the result to the corresponding user task; the privileged mode thread mode context is where daily tasks or threads are queued to run, and has the characteristics of allowing blocking and switching.
[0018] Furthermore, in step S5, the CPU automatically copies the current SPSR and stores it in the CPSR, restoring the mode bit and status bit of the previously interrupted task.
[0019] Further, during the execution of steps S3 to S4, the fault handling method of the real-time operating system includes the following steps: Step S31: If the embedded system uses an ARM Cortex-R architecture CPU, after the error and exception handling program in the real-time operating system captures a data termination exception or a prefetch termination exception, it reads the shadow register and a specific register of the coprocessor CP15 in termination mode, and corrects the fault code address by combining the exception type and the status bits before the exception. Step S32: The error and exception handling program comprehensively determines the fault type and repair method by considering the privilege mode before the exception, the mode bits of the current task control block, the code range to which the fault program counter belongs, the fault code address, and the stage at which the exception occurred. If the CPU was in non-privileged mode before the exception occurred, and the task control block that caused the exception belongs to a user task, then it is handled as a sandbox fault, and proceeds to step S33. If the CPU was in privileged mode before the exception occurred, or the fault originated from the system kernel, privileged task, critical driver, or exception handling code, then it is handled as an operating system fault. Step S33: The error and exception handler modifies the memory address in the link register, causing the CPU to execute a preset code in terminate mode. This preset code changes the state of the task control block corresponding to the user task that caused the exception from running to error-suspended, while preventing all user tasks within the sandbox from initiating new SVC instruction requests and sending an error signal to the blocked privileged daemon task. Step S34: The privileged daemon task traverses the resource linked lists of the task control blocks corresponding to all user tasks within the sandbox and cleans them up according to dependency order. Step S35: The privileged daemon task loads all user tasks within the sandbox into the memory space of the corresponding user application, then copies the contents of global variables with initial values from memory back to the memory space of the corresponding user application, clears global variables without initial values, the private heap and shared buffer of the user application corresponding to all user tasks within the sandbox, and the user stacks of all user tasks within the sandbox. Step S36: The real-time operating system recreates all user tasks within the sandbox and restores the entry address, priority, user stack, initial parameters, and MPU configuration of each user task; subsequently, the real-time operating system scheduler runs all user tasks within the sandbox sequentially.
[0020] This invention also proposes a sandbox implementation system in a real-time operating system, including a task classification and sandbox construction module, a user task initialization module, a user task non-privileged execution module, a user task privileged execution module, and a call end return module. The task classification and sandbox construction module classifies tasks in the real-time operating system into user tasks and privileged tasks based on their source, setting the CPU running mode and allowed memory access range for each type of task; each task has a corresponding task control block; all running and suspended user tasks constitute a sandbox. The user task initialization module switches the CPU from privileged mode to non-privileged mode and switches to the user stack of that user task when a user task is first started or switched to. The non-privileged execution module for user tasks is used to execute user tasks at the user entry point. Once a user task needs to use system kernel capabilities, it encodes the request into a system call number and parameters and executes an SVC instruction. It retrieves the task control block corresponding to the user task that triggered the system call from the exception context, and verifies the system call number, parameter range, and sandbox state. If all verifications fail, it rejects the CPU's ability to switch to privileged mode to call the real-time operating system kernel. If all verifications pass and it is determined that the user task has no time-consuming or blocking risk, it allows the CPU to switch to privileged mode to execute the user task, subsequently entering the privileged execution module for user tasks. If all verifications pass and it is determined that the user task has a time-consuming or blocking risk, it extracts the system call number and parameters from the exception context, encapsulates them into a kernel service request packet, and submits it to the privileged proxy and distribution task for processing. The privileged execution module for user tasks is used to execute the user task in privileged mode. Once resource creation is completed for the user task, it generates a resource linked list with a corresponding shadow node attached to the task control block of the user task. The shadow node records the created resource type, resource handle, or address. The call end return module is used to return to non-privileged mode to execute the user task after the user task finishes its call to privileged mode, based on the saved state before the exception.
[0021] Furthermore, in the sandbox implementation system, the user task non-privileged execution module and the user task privileged execution module together constitute the user task execution module. The user task execution module also includes an exception information acquisition unit, a repair method determination unit, a preset code execution unit, a resource cleanup unit, a memory and variable reset unit, and a user task recovery unit for fault handling. The exception information acquisition unit, when the embedded system uses an ARM Cortex-R architecture CPU, captures an exception, reads the error information causing the exception in termination mode, and corrects the fault code address by combining the exception type and the state bits before the exception. The repair method determination unit comprehensively determines the fault type and repair method; if the CPU was in non-privileged mode before the exception occurred, and the task control block that caused the exception belongs to a user task, then it is handled according to sandbox fault handling, and subsequently enters the preset code execution unit; if the CPU was in privileged mode before the exception occurred, or the fault originates from the system kernel, privileged task, critical driver, or exception handling code, then it is handled according to operating system fault handling. The preset code execution unit modifies the memory address in the link register, causing the CPU to execute a preset code in termination mode. This preset code changes the state of the task control block corresponding to the user task that caused the exception from running to error-suspended, while preventing all user tasks within the sandbox from initiating new SVC instruction requests and waking up the resource cleanup unit. The resource cleanup unit traverses the resource linked lists of the task control blocks corresponding to all user tasks within the sandbox and cleans them according to dependency order. The memory and variable reset unit loads all user tasks within the sandbox into the memory space of the corresponding user application, copies the contents of global variables with initial values from memory back to the memory space of the corresponding user application, clears global variables without initial values, the private heap and shared buffer of the user application corresponding to all user tasks within the sandbox, and the user stacks of all user tasks within the sandbox. The user task recovery unit recreates all user tasks within the sandbox and restores the entry address, priority, user stack, initial parameters, and MPU configuration of each user task; subsequently, the real-time operating system scheduler runs all user tasks within the sandbox sequentially.
[0022] The technical effects achieved by this invention are: to transform the termination mode of the ARM Cortex-R architecture CPU when encountering an exception into a controllable local recovery event; to facilitate the complete statistics and thorough cleanup of the resources requested by each user task through the design of the resource linked list and shadow nodes in the task control block; and to treat all user tasks in the sandbox as a unified fault recovery object. Attached Figure Description
[0023] Figure 1 This is a flowchart illustrating the sandbox implementation method in the real-time operating system proposed in this invention.
[0024] Figure 2 yes Figure 1 The flowchart of the fault handling method in steps S3 to S4 is shown.
[0025] Figure 3 This is a schematic diagram of the structure of the sandbox implementation system in the real-time operating system proposed in this invention.
[0026] Figure 4 This is a schematic diagram of the structure of each unit used for fault handling in the user task execution module.
[0027] The attached diagrams are labeled as follows: Task Classification and Sandbox Module 1, User Task Initialization Module 2, User Task Non-Privileged Execution Module 3, User Task Privileged Execution Module 4, Call End Return Module 5, Exception Information Acquisition Unit 31, Repair Method Determination Unit 32, Preset Code Execution Unit 33, Resource Cleanup Unit 34, Memory and Variable Reset Unit 35, User Task Recovery Unit 36. Detailed Implementation
[0028] Please see Figure 1 The sandbox implementation method in the real-time operating system proposed in this invention includes the following steps.
[0029] Step S1: The embedded system employs a real-time operating system. The CPU in the embedded system has and enables a memory protection unit. Tasks in the real-time operating system are categorized into user tasks and privileged tasks based on their origin. The CPU's operating mode and allowed memory access range are set for each type of task. Each task has a corresponding task control block. All running and suspended user tasks constitute a sandbox, and a sandbox contains one or more running and suspended user tasks.
[0030] All tasks originating from user applications are user tasks. Each user task executes in the CPU's non-privileged mode during normal scheduling (i.e., the normal operation phase). This non-privileged CPU mode is, for example, USR mode (User Mode). The memory protection unit restricts the memory access scope of user tasks to the code segment, shared writable area, private heap, corresponding user stack, and authorized shared window of the user application to which the user task belongs. Direct access to kernel memory, privileged mode-specific stacks, private areas of other user applications, and unauthorized peripherals is prohibited. User task access to the system kernel and system services is completed through the SVC (Supervisor Call) entry point.
[0031] Tasks originating from outside user applications—such as those from the system kernel or system services—are privileged tasks. Each privileged task executes in the CPU's privileged mode during normal scheduling. This privileged mode may be, for example, SVC mode. The memory access range of a privileged task is the entire memory address space.
[0032] Each user task's corresponding task control block records a resource list, mode bit, user entry point, user stack top, and permission attributes. The resource list records all resource usage for the user task. The mode bit records whether the CPU running mode for the user task is non-privileged. The user entry point refers to the starting address of the user task's main function. The user stack top is a memory pointer to the user stack allocated independently for the user task, marking the location of the user stack currently in use. The permission attributes define the security level and memory access rules for the user task's runtime.
[0033] Step S2: When the real-time operating system boots for the first time or switches to a user task, the privileged wrapper entry point switches the CPU from privileged mode to non-privileged mode and switches to the user stack of that user task. The privileged wrapper entry point is a piece of kernel boot code running in privileged mode, used to uniformly initialize and prune permissions for the newly created user task, ensuring its operation within a controllable range. The user stack is a contiguous memory area, exclusively for the user task, used to store local variables, function call relationships, and context data at the time of interrupts during the user task's runtime.
[0034] Step S3: The user task enters the user entry point for execution. Once the user task needs to use real-time operating system kernel capabilities such as sleep, message queues, event flags, memory allocation, files, network, and device services, it encodes the request for using the real-time operating system kernel capabilities into a system call number and parameters, and enters the SVC interrupt service routine and dispatcher through the SVC instruction.
[0035] After a user task executes an SVC instruction, the CPU automatically copies the current CPSR (Current Program Status Register) into the SPSR (Backup Program Status Register), and simultaneously enters the privileged handler mode context. The CPSR records the CPU's current running state in real time, including whether it is in privileged or non-privileged mode (mode bit) and whether it is currently executing ARM or Thumb instructions (status bit). The privileged handler mode context, also known as the privileged mode exception context or privileged mode interrupt context, is where hardware interrupts are executed and is non-blocking. At this time, the SVC interrupt service routine and dispatcher act as a proxy layer, severing the user application's direct dependence on the absolute physical addresses of the RTOS API. Even if a system kernel upgrade causes changes in function addresses, the user application does not need to relink.
[0036] The SVC interrupt service routine and dispatcher obtain the task control block corresponding to the user task that triggered the system call from the exception context, and verify the system call number, parameter range, and sandbox status.
[0037] The SVC interrupt service routine and dispatcher calculate the physical address of the SVC instruction that triggered the interrupt by reading the link register, and then parse the embedded immediate value (i.e., the system call number) from it. The real-time operating system kernel maintains a static system call dispatch table, which is an array of function pointers. Verifying the system call number involves checking if the extracted system call number exceeds the maximum index value of this table. If it does, the real-time operating system kernel directly rejects the service and returns an illegal call error code. If it does not exceed the maximum index value, the system call number verification passes.
[0038] Verifying the parameter range involves determining whether system call parameters related to memory read / write operations fall between the start and end addresses of the sandbox memory space. If not, the parameter range verification fails, and an error code is returned. If yes, the parameter range verification passes.
[0039] The sandbox has three states: normal (SANDBOX_NORMAL), fault (SANDBOX_FAULTED), and restart (SANDBOX_RESTARTING). The normal state indicates the sandbox is running healthily. The fault state indicates the sandbox has just triggered an exception, which has been caught and frozen by the error and exception handler, and is awaiting privileged daemons to clean up resources. The restart state indicates the privileged daemons are rewriting the sandbox's memory space. Verifying the sandbox state means determining whether the sandbox is in a normal state when the SVC interrupt service routine is triggered. If it is, the sandbox state verification passes. If not, the sandbox state verification fails.
[0040] If not all checks pass, the SVC interrupt service routine and dispatcher refuse to allow the CPU to switch to privileged mode.
[0041] If all checks pass and it is determined that the user task has no risk of time consumption or blocking, the SVC interrupt service routine and dispatcher allow the CPU to switch to privileged mode to execute the user task, and then proceed to step S4.
[0042] If all checks pass and the user task is determined to have a risk of time consumption or blocking, the SVC interrupt service routine and dispatcher extract the system call number and parameters from the exception context, encapsulate them into a kernel service request packet, and submit it to the privileged proxy and dispatch task. The privileged proxy and dispatch task calls the actual RTOS kernel function within the privileged mode context and then returns the result to the corresponding user task to avoid blocking or triggering scheduler reentry in the exception handling path. The privileged mode context is where routine tasks or threads are queued and run, allowing blocking and switching.
[0043] Step S4: The real-time operating system kernel executes the user task in privileged mode. Once the kernel has created resources such as memory blocks, mutexes, queues, event flags, timers, file or device sessions for the user task, it generates corresponding shadow nodes. Shadow nodes record the type, handle, or address of the created resources. The shadow nodes are attached to the resource list in the user task's task control block. Shadow nodes are synchronously deleted when resources are released normally.
[0044] Step S5: After the user task finishes calling the privileged mode, the real-time operating system returns to the non-privileged mode to execute the user task based on the saved state before the exception. The CPU automatically copies the current SPSR and stores it in the CPSR, restoring the mode and state bits of the previously interrupted task, instead of making the user task stay in the privileged mode permanently.
[0045] Figure 1 During the execution of steps S3 to S4 of the sandbox implementation method shown, the real-time operating system may malfunction. Please refer to... Figure 2 The corresponding troubleshooting methods include the following steps.
[0046] Step S31: If the embedded system uses an ARM Cortex-R architecture CPU, when a fatal exception such as a data termination exception or prefetch termination exception occurs, the CPU enters termination mode and records the error information that caused the exception using dedicated shadow registers (link register, backup program status register) and specific registers of the coprocessor CP15 (data fault address register, data fault status register). After the error and exception handler (EEHandler) in the real-time operating system captures exceptions such as data termination and prefetch termination, it reads the shadow registers and specific registers of the coprocessor CP15 in termination mode, and corrects the fault code address by combining the exception type and the pre-exception status bits (ARM state, Thumb state).
[0047] Because ARM chips have an instruction pipeline hardware mechanism, when an exception occurs and the program counter pointer is recorded in the link register, the address recorded in the link register is not the actual fault code address, but rather a physical offset. For example, in the case of a prefetch termination exception, the actual fault code address in ARM mode is the address recorded in the link register minus 4, while in Thumb mode it is the address recorded in the link register minus 2. Similarly, in the case of a data termination exception, the actual fault code address in ARM mode is the address recorded in the link register minus 8, while in Thumb mode it is the address recorded in the link register minus 4.
[0048] Step S32: The error and exception handling program comprehensively determines the fault type and repair method by considering the privilege mode before the exception (from the backup program status register), the mode bit of the current task control block (privileged mode, non-privileged mode), the code range to which the fault program counter belongs, the fault code address, and the stage at which the exception occurred.
[0049] If the CPU was in non-privileged mode before the exception occurred, and the task control block that caused the exception belonged to a user task, then it was handled as a sandbox fault, and the process proceeded to step S33.
[0050] If the CPU was in privileged mode before the anomaly occurred, or if the fault originated from the system kernel, privileged task, critical driver, or exception handling code, then the fault handling will be performed according to the operating system's fault handling procedures, using existing fault dumping, watchdog reset, or system-wide safe shutdown strategies in the real-time operating system.
[0051] Step S33: The error and exception handler modifies the memory address in the link register, causing the CPU to execute a pre-defined code in terminated mode. This pre-defined code changes the state of the task control block corresponding to the user task that caused the exception from RUNNING to FAULT_PENDING, simultaneously preventing all user tasks within the sandbox from initiating new SVC instruction requests and sending an error signal to the blocked privileged daemon task. The exception entry point only performs context extraction, state switching, and asynchronous notification; it does not perform complex resource releases or image copying within the termination context to reduce the risk of exception reentrancy and kernel state corruption.
[0052] Step S34: The privileged guardian task traverses the resource linked lists of all user tasks' corresponding task control blocks within the sandbox and cleans them up in dependency order. For example, it first disables new callbacks and asynchronous completion events, then unregisters timers, driver callbacks, and device sessions, followed by deleting or revoking synchronization objects such as queues, event flags, semaphores, and mutexes, and finally releases dynamic memory. Different resources are processed through the public interface of the real-time operating system, without directly tampering with the private fields of kernel objects such as mutexes, to avoid disrupting the wait chain and the scheduler's internal consistency.
[0053] Step S35: The privileged guardian task loads all user tasks in the sandbox into the memory space of the user application corresponding to these user tasks, then copies the contents of global variables with initial values in the memory back to the memory space of the corresponding user application, and clears the global variables without initial values, the private heap and shared buffer of the user application corresponding to all user tasks in the sandbox, and the user stack of all user tasks in the sandbox.
[0054] Step S36: The real-time operating system recreates all user tasks within the sandbox and restores the entry address, priority, user stack, initial parameters, and MPU configuration of each user task. Subsequently, the real-time operating system's scheduler runs all user tasks within the sandbox sequentially.
[0055] Please see Figure 3 The sandbox implementation system in the real-time operating system proposed in this invention includes a task classification and sandbox construction module 1, a user task initialization module 2, a user task non-privileged execution module 3, a user task privileged execution module 4, and a call end return module 5. Figure 3 The sandbox implementation system shown corresponds to Figure 1 The sandbox implementation method is shown.
[0056] The task classification and sandbox construction module 1 is used to classify tasks in the real-time operating system into two categories based on their source: user tasks and privileged tasks. It sets the CPU running mode and the allowed memory access range for each type of task. Each task has a corresponding task control block. All running and suspended user tasks constitute a sandbox.
[0057] The user task initialization module 2 is used to switch the CPU from privileged mode to non-privileged mode and switch to the user stack of the user task when a user task is started or switched to for the first time.
[0058] The user task non-privileged execution module 3 is used to execute user tasks at the user entry point. Once a user task needs to use system kernel capabilities, it encodes the request into a system call number and parameters and executes an SVC instruction. It retrieves the task control block corresponding to the user task that triggered the system call from the exception context and verifies the system call number, parameter range, and sandbox status. If all verifications fail, the CPU is denied the ability to switch to privileged mode to call the real-time operating system kernel. If all verifications pass and it is determined that the user task has no risk of time consumption or blocking, the CPU is allowed to switch to privileged mode to execute the user task, and then the user task privileged execution module 4 is entered. If all verifications pass and it is determined that the user task has a risk of time consumption or blocking, the system call number and parameters extracted from the exception context are encapsulated into a kernel service request packet and submitted to the privileged proxy and distribution task for processing.
[0059] The user task privileged execution module 4 is used to execute the user task in privileged mode; once the resource creation for the user task is completed, a corresponding shadow node is generated and attached to the resource list in the task control block of the user task. The shadow node is used to record the type, handle or address of the created resource.
[0060] The call end return module 5 is used to return to the non-privileged mode to execute the user task after the user task finishes calling the privileged mode, based on the saved state before the exception.
[0061] Figure 3 In the sandbox implementation system shown, the user task non-privileged execution module 3 and the user task privileged execution module 4 together constitute the user task execution module. Please refer to... Figure 4 The user task execution module also includes an exception information acquisition unit 31 for fault handling, a repair method determination unit 32, a preset code execution unit 33, a resource cleanup unit 34, a memory and variable reset unit 35, and a user task recovery unit 36. Figure 4 The units shown for fault handling correspond to Figure 2 The fault handling method shown.
[0062] The exception information acquisition unit 31 is used to capture an exception when the embedded system uses an ARM Cortex-R architecture CPU, read the error information that caused the exception in the termination mode, and correct the fault code address by combining the exception type and the state bits before the exception.
[0063] The repair method determination unit 32 is used to comprehensively determine the fault type and repair method. If the CPU was in non-privileged mode before the anomaly occurred, and the task control block that caused the anomaly belongs to a user task, then it is handled as a sandbox fault, and subsequently enters the preset code execution unit 33. If the CPU was in privileged mode before the anomaly occurred, or the fault originated from the system kernel, privileged task, critical driver, or exception handling code, then it is handled as an operating system fault.
[0064] The preset code execution unit 33 is used to modify the memory address in the link register, which causes the CPU to execute a preset code in termination mode. The preset code is used to change the state of the task control block corresponding to the user task that caused the exception from running to error suspended, while preventing all user tasks in the sandbox from initiating new SVC instruction requests, and waking up the resource cleanup unit 34.
[0065] The resource cleanup unit 34 is used to traverse the resource linked list of the task control block corresponding to all user tasks in the sandbox and clean it up in the order of dependency.
[0066] The memory and variable reset unit 35 is used to load all user tasks in the sandbox into the memory space of the corresponding user application, then copy the contents of global variables with initial values in the memory back to the memory space of the corresponding user application, and clear the global variables without initial values, the private heap and shared buffer of the user application corresponding to all user tasks in the sandbox, and the user stack of all user tasks in the sandbox.
[0067] The user task recovery unit 36 is used to recreate all user tasks within the sandbox and restore the entry address, priority, user stack, initial parameters, and MPU configuration of each user task; subsequently, the scheduler of the real-time operating system runs all user tasks within the sandbox in sequence.
[0068] Compared with existing technologies, the sandbox implementation method in the real-time operating system proposed in this invention has the following beneficial effects.
[0069] First, a lightweight dual-privilege mechanism for privileged tasks and user tasks is built within a traditional single-firmware RTOS, balancing isolation security with system compatibility. This invention centralizes all user tasks within a sandbox. Each user task has an independent user stack and MPU-based memory access scope (code segment, shared writable area, private heap, and user stack). Simultaneously, all kernel service requests invoked by user tasks are uniformly aggregated to the SVC instruction entry point. Through the SVC interrupt service routine and dispatcher as a proxy layer, the dependency of user applications on the absolute physical addresses of system kernel APIs is severed. This design allows multiple user tasks within a single user application to run alternately with existing privileged tasks within the same scheduler. It achieves physical-level security sandbox isolation without requiring the reconstruction of existing privileged task invocation methods or forcing system kernel upgrades and relinking, significantly reducing the cost of modifying and upgrading lightweight RTOSs.
[0070] Second, this invention transforms severe exceptions in ARM Cortex-R architecture CPUs into controllable partial recovery events, avoiding system-wide resets. In the terminated mode of an ARM Cortex-R architecture CPU, this invention directly reads the shadow register and specific registers of CP15, and precisely corrects the true fault code address using instruction pipeline physical offset rules based on the status bits. Subsequently, instead of performing complex cleanup directly in the non-blocking exception context, it modifies the memory address in the link register to guide the CPU to execute preset code upon returning to non-privileged mode, setting the faulty task status to error suspension, blocking subsequent SVC requests, and asynchronously notifying privileged guardian tasks. This successfully decouples hardware exception interception from complex resource cleanup, avoiding system kernel state corruption caused by calling blocking interfaces in interrupt contexts, and safely transforming a fatal hard fault that would inevitably lead to system-wide crashes into a controllable partial recovery process in privileged mode context.
[0071] Third, this invention uses all user tasks within the sandbox as a unified recovery object to achieve consistent cold start reconstruction, completely eliminating secondary crashes. When a fault is triggered, the privileged guardian task first follows the resource chain in the task control block corresponding to each user task, and thoroughly cleans up using the system's public interface according to the dependency order (first unregister callbacks / timers, then delete synchronization objects, and finally release dynamic memory), ensuring that the scheduler's waiting chain is not disrupted. Subsequently, the privileged guardian task reloads the original read-only images of all user tasks within the sandbox stored in memory, overwriting the memory space of the corresponding user application, recopying global variables with initial values, and forcibly clearing global variables without initial values, the private heap and shared buffer of the corresponding user application, and all user stacks. This physical-level memory reset principle completely erases historical contaminated data, enabling the entire sandbox to obtain a clean "cold start" environment consistent with the first power-on, cutting off the spread of faults within the sandbox from the source, while the entire process is confined within the physical boundaries of the sandbox, completely without affecting normal system services outside the sandbox.
[0072] Fourth, this invention provides an asymmetric fault identification mechanism that, while introducing sandbox-based local self-healing, does not violate the system's original kernel-level safety shutdown strategy. This invention introduces a comprehensive judgment mechanism into the error and exception handling procedures, combining the pre-exception permission mode in the Backup Program Status Register (SPSR), the mode bit of the task that triggered the exception, and the code segment to which the fault PC pointer belongs for comprehensive judgment. If the fault is confirmed to be caused by a user task, the sandbox recovery process is initiated. If the fault is confirmed to be caused by a non-user task, the system will directly bypass the sandbox recovery logic and use the existing fault dump, watchdog reset, or system-wide safety shutdown strategies in the real-time operating system. This allows this invention to improve application-layer fault tolerance while firmly safeguarding the absolute security baseline of the system kernel.
[0073] The above are merely preferred embodiments of the present invention and are not intended to limit the invention. Various modifications and variations can be made to the present invention by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.
Claims
1. A sandbox implementation method in a real-time operating system, characterized in that, Includes the following steps; Step S1: The embedded system uses a real-time operating system (RTOS). The CPU in the embedded system has and enables a memory protection unit (MPU). Tasks in the real-time operating system are divided into two categories based on their source: user tasks and privileged tasks. The CPU's operating mode and the allowed memory access range are set for each type of task. Each task has a corresponding task control block. All running and suspended user tasks constitute a sandbox; Step S2: When the real-time operating system starts up for the first time or switches to a user task, the privileged wrapper entry switches the CPU from privileged mode to non-privileged mode and switches to the user stack of that user task; Step S3: The user task enters the user entry point for execution; once the user task needs to use the real-time operating system kernel capabilities, the request to use the real-time operating system kernel capabilities is encoded as a system call number and parameters, and enters the SVC interrupt service routine and dispatcher through the SVC instruction; the SVC interrupt service routine and dispatcher obtain the task control block corresponding to the user task that triggered the system call from the exception context, and verify the system call number, parameter range, and sandbox status. If not all checks pass, the SVC interrupt service routine and dispatcher refuse the CPU's ability to switch to privileged mode and call the real-time operating system kernel. If all checks pass and it is determined that the user task has no risk of time consumption or blocking, the SVC interrupt service routine and dispatcher allow the CPU to switch to privileged mode to execute the user task, and then proceed to step S4. If all checks pass and it is determined that the user task has the risk of time consumption or blocking, the SVC interrupt service routine and dispatcher extract the system call number and parameters from the abnormal situation, encapsulate them into a kernel service request packet and submit them to the privileged agent and dispatch task. Step S4: The real-time operating system kernel executes the user task in privileged mode; once the resource creation for the user task is completed, the real-time operating system kernel generates a corresponding shadow node; the shadow node is used to record the type, handle or address of the created resource; the shadow node is attached to the resource list in the task control block of the user task; Step S5: After the user task finishes calling the privileged mode, the real-time operating system returns to the non-privileged mode to execute the user task based on the saved state before the exception.
2. The sandbox implementation method in a real-time operating system according to claim 1, characterized in that, In step S1, all tasks from user applications are user tasks; each user task is executed in the CPU's non-privileged mode during normal scheduling; the MPU restricts the memory access range of user tasks to the code area, shared writable area, private heap, corresponding user stack, and authorized shared window of the user application to which the user task belongs; user tasks access the system kernel and system services through the SVC entry point. Tasks originating from outside the user application are all privileged tasks; each privileged task executes in the CPU's privileged mode during normal scheduling; the memory access range of a privileged task is the entire memory address space.
3. The sandbox implementation method in a real-time operating system according to claim 1, characterized in that, In step S1, the task control block corresponding to each user task is used to record the resource linked list, mode bit, user entry, user stack top, and permission attributes.
4. The sandbox implementation method in a real-time operating system according to claim 1, characterized in that, In step S3, after the user task executes the SVC instruction, the CPU automatically copies the current program status register CPSR into the backup program status register SPSR, and at the same time, the CPU enters the privileged mode handler context. The privileged mode handler context is where hardware interrupts are executed and has the characteristic of being non-blocking.
5. The sandbox implementation method in a real-time operating system according to claim 1, characterized in that, In step S3, the SVC interrupt service routine and dispatcher calculate the physical address of the SVC instruction that triggered the interrupt by reading the link register, and parse out the embedded immediate value, which is the system call number; verifying the system call number is to determine whether the extracted system call number exceeds the maximum index value of the system call dispatch table maintained by the real-time operating system kernel. If the limit is not exceeded, the system call number verification passes; Verifying the parameter range means determining whether the system call parameters involving memory read and write are between the start and end addresses of the sandbox memory space; if so, the parameter range verification passes. Verifying the sandbox status refers to determining whether the sandbox is in a normal state when the SVC interrupt service routine is triggered; if so, the sandbox status verification passes.
6. The sandbox implementation method in a real-time operating system according to claim 1, characterized in that, In step S3, if all verifications pass and it is determined that the user task has the risk of time consumption or blocking, the privileged proxy and dispatch task calls the real RTOS kernel function in the privileged mode thread mode context and then returns the result to the corresponding user task. The privileged mode thread context is where routine tasks or threads are queued and run, and it has the characteristics of allowing blocking and switching.
7. The sandbox implementation method in a real-time operating system according to claim 4, characterized in that, In step S5, the CPU automatically copies the current SPSR and stores it in the CPSR, restoring the mode bit and status bit of the previously interrupted task.
8. The sandbox implementation method in a real-time operating system according to claim 1, characterized in that, During the execution of steps S3 to S4, the fault handling method of the real-time operating system includes the following steps; Step S31: If the embedded system uses an ARM Cortex-R architecture CPU, after the error and exception handler in the real-time operating system captures the data termination exception and the prefetch termination exception, it reads the shadow register and the specific register of the coprocessor CP15 in the termination mode, and corrects the fault code address by combining the exception type and the status bits before the exception. Step S32: The error and exception handling procedure comprehensively determines the fault type and repair method by taking into account the permission mode before the exception, the mode bit of the current task control block, the code range to which the fault program counter belongs, the fault code address, and the stage at which the exception occurred. If the CPU was in non-privileged mode before the exception occurred, and the task control block that caused the exception belonged to a user task, then it was handled as a sandbox fault, and the process proceeded to step S33. If the CPU was in privileged mode before the anomaly occurred, or if the fault originated from the system kernel, privileged task, critical driver, or exception handling code, then it should be handled as an operating system fault. Step S33: The error and exception handler modifies the memory address in the link register, which causes the CPU to execute a preset code in terminate mode; The preset code is used to change the state of the task control block corresponding to the user task that caused the exception from running to error suspended, while preventing all user tasks in the sandbox from initiating new SVC instruction requests, and sending an error signal to the privileged guardian task that is blocked and waiting. Step S34: The privileged guardian task traverses the resource linked list of the task control block corresponding to all user tasks in the sandbox and cleans it up in the order of dependencies; Step S35: The privileged guardian task loads all user tasks in the sandbox into the memory space of the corresponding user application, then copies the contents of global variables with initial values in the storage back to the memory space of the corresponding user application, and clears the global variables without initial values, the private heap and shared buffer of the user application corresponding to all user tasks in the sandbox, and the user stack of all user tasks in the sandbox. Step S36: The real-time operating system recreates all user tasks within the sandbox and restores the entry address, priority, user stack, initial parameters, and MPU configuration of each user task; subsequently, the real-time operating system's scheduler runs all user tasks within the sandbox sequentially.
9. A sandbox implementation system in a real-time operating system, characterized in that, It includes a task classification and sandbox construction module, a user task initialization module, a user task non-privileged execution module, a user task privileged execution module, and a call end return module; The task classification and sandbox construction module is used to classify tasks in the real-time operating system into two categories based on their source: user tasks and privileged tasks. It sets the CPU running mode and the allowed memory access range for each type of task. Each task has a corresponding task control block. All running and suspended user tasks constitute a sandbox; The user task initialization module is used to switch the CPU from privileged mode to non-privileged mode and switch to the user stack of the user task when a user task is first started or switched to. The user task non-privileged execution module is used to execute user tasks at the user entry point; Once a user task needs to use system kernel capabilities, it will encode the request into a system call number and parameters and execute the SVC instruction; retrieve the task control block corresponding to the user task that triggered the system call from the exception context, and verify the system call number, parameter range, and sandbox status; If all checks fail, the CPU's ability to switch to privileged mode and invoke the real-time operating system kernel is denied. If all checks pass and it is determined that the user task has no risk of time consumption or blocking, the CPU is allowed to switch to privileged mode to execute the user task, and then enters the user task privileged execution module; if all checks pass and it is determined that the user task has a risk of time consumption or blocking, the system call number and parameters are extracted from the abnormal situation, encapsulated into a kernel service request packet, and submitted to the privileged proxy and distribution task for processing. The user task privileged execution module is used to execute the user task in privileged mode; once the resource creation for the user task is completed, a corresponding shadow node is generated and attached to the resource list in the task control block of the user task; the shadow node is used to record the type, handle or address of the created resource; The call end return module is used to return to non-privileged mode to execute the user task after the user task finishes its call to privileged mode, based on the saved state before the exception.
10. The sandbox implementation system in a real-time operating system according to claim 9, characterized in that, The user task non-privileged execution module and the user task privileged execution module together constitute the user task execution module; the user task execution module also includes an exception information acquisition unit, a repair method determination unit, a preset code execution unit, a resource cleanup unit, a memory and variable reset unit, and a user task recovery unit for fault handling; The exception information acquisition unit is used to capture an exception when the embedded system uses an ARM Cortex-R architecture CPU, read the error information that caused the exception in the termination mode, and correct the fault code address by combining the exception type and the status bits before the exception. The repair method determination unit is used to comprehensively determine the fault type and repair method; If the CPU was in non-privileged mode before the exception occurred, and the task control block that caused the exception belonged to a user task, then it was handled as a sandbox fault, and the subsequent execution entered the preset code execution unit. If the CPU was in privileged mode before the anomaly occurred, or if the fault originated from the system kernel, privileged task, critical driver, or exception handling code, then it should be handled as an operating system fault. The preset code execution unit is used to modify the memory address in the link register, which causes the CPU to execute a preset code in termination mode. The preset code is used to change the state of the task control block corresponding to the user task that caused the exception from running to error suspension, while preventing all user tasks in the sandbox from initiating new SVC instruction requests, and waking up the resource cleanup unit. The resource cleanup unit is used to traverse the resource linked list of the task control block corresponding to all user tasks in the sandbox and clean them up in the order of dependency. The memory and variable reset unit is used to load all user tasks in the sandbox into the memory space of the corresponding user application, then copy the contents of global variables with initial values in the memory back to the memory space of the corresponding user application, and clear the global variables without initial values, the private heap and shared buffer of the user application corresponding to all user tasks in the sandbox, and the user stack of all user tasks in the sandbox. The user task recovery unit is used to recreate all user tasks within the sandbox and restore the entry address, priority, user stack, initial parameters, and MPU configuration of each user task; subsequently, the scheduler of the real-time operating system runs all user tasks within the sandbox in sequence.
